Merge vk-gl-cts/opengl-es-cts-3.2.5 into vk-gl-cts/master
[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 "tcuStringTemplate.hpp"
52
53 #include "vktSpvAsmCrossStageInterfaceTests.hpp"
54 #include "vktSpvAsm8bitStorageTests.hpp"
55 #include "vktSpvAsm16bitStorageTests.hpp"
56 #include "vktSpvAsmUboMatrixPaddingTests.hpp"
57 #include "vktSpvAsmConditionalBranchTests.hpp"
58 #include "vktSpvAsmIndexingTests.hpp"
59 #include "vktSpvAsmImageSamplerTests.hpp"
60 #include "vktSpvAsmComputeShaderCase.hpp"
61 #include "vktSpvAsmComputeShaderTestUtil.hpp"
62 #include "vktSpvAsmFloatControlsTests.hpp"
63 #include "vktSpvAsmGraphicsShaderTestUtil.hpp"
64 #include "vktSpvAsmVariablePointersTests.hpp"
65 #include "vktSpvAsmVariableInitTests.hpp"
66 #include "vktSpvAsmPointerParameterTests.hpp"
67 #include "vktSpvAsmSpirvVersionTests.hpp"
68 #include "vktTestCaseUtil.hpp"
69 #include "vktSpvAsmLoopDepLenTests.hpp"
70 #include "vktSpvAsmLoopDepInfTests.hpp"
71 #include "vktSpvAsmCompositeInsertTests.hpp"
72 #include "vktSpvAsmVaryingNameTests.hpp"
73 #include "vktSpvAsmWorkgroupMemoryTests.hpp"
74 #include "vktSpvAsmSignedIntCompareTests.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] = 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 = 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 testWithNan)
436 {
437         const string                                    nan                             = testWithNan ? "_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              = testWithNan ? "OpExtension \"SPV_KHR_float_controls\"\n" : "";
444         string                                                  capabilities    = testWithNan ? "OpCapability SignedZeroInfNanPreserve\n" : "";
445         string                                                  exeModes                = testWithNan ? "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           = testWithNan ? &compareFUnord<true> : &compareFUnord<false>;
540
541                 if (testWithNan)
542                 {
543                         spec.extensions.push_back("VK_KHR_shader_float_controls");
544                         spec.requestedVulkanFeatures.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat32 = DE_TRUE;
545                 }
546
547                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
548         }
549
550         return group.release();
551 }
552
553 struct OpAtomicCase
554 {
555         const char*             name;
556         const char*             assembly;
557         const char*             retValAssembly;
558         OpAtomicType    opAtomic;
559         deInt32                 numOutputElements;
560
561                                         OpAtomicCase(const char* _name, const char* _assembly, const char* _retValAssembly, OpAtomicType _opAtomic, deInt32 _numOutputElements)
562                                                 : name                          (_name)
563                                                 , assembly                      (_assembly)
564                                                 , retValAssembly        (_retValAssembly)
565                                                 , opAtomic                      (_opAtomic)
566                                                 , numOutputElements     (_numOutputElements) {}
567 };
568
569 tcu::TestCaseGroup* createOpAtomicGroup (tcu::TestContext& testCtx, bool useStorageBuffer, int numElements = 65535, bool verifyReturnValues = false)
570 {
571         std::string                                             groupName                       ("opatomic");
572         if (useStorageBuffer)
573                 groupName += "_storage_buffer";
574         if (verifyReturnValues)
575                 groupName += "_return_values";
576         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Test the OpAtomic* opcodes"));
577         vector<OpAtomicCase>                    cases;
578
579         const StringTemplate                    shaderTemplate  (
580
581                 string("OpCapability Shader\n") +
582                 (useStorageBuffer ? "OpExtension \"SPV_KHR_storage_buffer_storage_class\"\n" : "") +
583                 "OpMemoryModel Logical GLSL450\n"
584                 "OpEntryPoint GLCompute %main \"main\" %id\n"
585                 "OpExecutionMode %main LocalSize 1 1 1\n" +
586
587                 "OpSource GLSL 430\n"
588                 "OpName %main           \"main\"\n"
589                 "OpName %id             \"gl_GlobalInvocationID\"\n"
590
591                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
592
593                 "OpDecorate %buf ${BLOCK_DECORATION}\n"
594                 "OpDecorate %indata DescriptorSet 0\n"
595                 "OpDecorate %indata Binding 0\n"
596                 "OpDecorate %i32arr ArrayStride 4\n"
597                 "OpMemberDecorate %buf 0 Offset 0\n"
598
599                 "OpDecorate %sumbuf ${BLOCK_DECORATION}\n"
600                 "OpDecorate %sum DescriptorSet 0\n"
601                 "OpDecorate %sum Binding 1\n"
602                 "OpMemberDecorate %sumbuf 0 Coherent\n"
603                 "OpMemberDecorate %sumbuf 0 Offset 0\n"
604
605                 "${RETVAL_BUF_DECORATE}"
606
607                 + getComputeAsmCommonTypes("${BLOCK_POINTER_TYPE}") +
608
609                 "%buf       = OpTypeStruct %i32arr\n"
610                 "%bufptr    = OpTypePointer ${BLOCK_POINTER_TYPE} %buf\n"
611                 "%indata    = OpVariable %bufptr ${BLOCK_POINTER_TYPE}\n"
612
613                 "%sumbuf    = OpTypeStruct %i32arr\n"
614                 "%sumbufptr = OpTypePointer ${BLOCK_POINTER_TYPE} %sumbuf\n"
615                 "%sum       = OpVariable %sumbufptr ${BLOCK_POINTER_TYPE}\n"
616
617                 "${RETVAL_BUF_DECL}"
618
619                 "%id        = OpVariable %uvec3ptr Input\n"
620                 "%minusone  = OpConstant %i32 -1\n"
621                 "%zero      = OpConstant %i32 0\n"
622                 "%one       = OpConstant %u32 1\n"
623                 "%two       = OpConstant %i32 2\n"
624
625                 "%main      = OpFunction %void None %voidf\n"
626                 "%label     = OpLabel\n"
627                 "%idval     = OpLoad %uvec3 %id\n"
628                 "%x         = OpCompositeExtract %u32 %idval 0\n"
629
630                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
631                 "%inval     = OpLoad %i32 %inloc\n"
632
633                 "%outloc    = OpAccessChain %i32ptr %sum %zero ${INDEX}\n"
634                 "${INSTRUCTION}"
635                 "${RETVAL_ASSEMBLY}"
636
637                 "             OpReturn\n"
638                 "             OpFunctionEnd\n");
639
640         #define ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, NUM_OUTPUT_ELEMENTS) \
641         do { \
642                 DE_ASSERT((NUM_OUTPUT_ELEMENTS) == 1 || (NUM_OUTPUT_ELEMENTS) == numElements); \
643                 cases.push_back(OpAtomicCase(#NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, NUM_OUTPUT_ELEMENTS)); \
644         } while (deGetFalse())
645         #define ADD_OPATOMIC_CASE_1(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, 1)
646         #define ADD_OPATOMIC_CASE_N(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, numElements)
647
648         ADD_OPATOMIC_CASE_1(iadd,       "%retv      = OpAtomicIAdd %i32 %outloc %one %zero %inval\n",
649                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IADD );
650         ADD_OPATOMIC_CASE_1(isub,       "%retv      = OpAtomicISub %i32 %outloc %one %zero %inval\n",
651                                                                 "             OpStore %retloc %retv\n", OPATOMIC_ISUB );
652         ADD_OPATOMIC_CASE_1(iinc,       "%retv      = OpAtomicIIncrement %i32 %outloc %one %zero\n",
653                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IINC );
654         ADD_OPATOMIC_CASE_1(idec,       "%retv      = OpAtomicIDecrement %i32 %outloc %one %zero\n",
655                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IDEC );
656         if (!verifyReturnValues)
657         {
658                 ADD_OPATOMIC_CASE_N(load,       "%inval2    = OpAtomicLoad %i32 %inloc %one %zero\n"
659                                                                         "             OpStore %outloc %inval2\n", "", OPATOMIC_LOAD );
660                 ADD_OPATOMIC_CASE_N(store,      "             OpAtomicStore %outloc %one %zero %inval\n", "", OPATOMIC_STORE );
661         }
662
663         ADD_OPATOMIC_CASE_N(compex, "%even      = OpSMod %i32 %inval %two\n"
664                                                                 "             OpStore %outloc %even\n"
665                                                                 "%retv      = OpAtomicCompareExchange %i32 %outloc %one %zero %zero %minusone %zero\n",
666                                                                 "                         OpStore %retloc %retv\n", OPATOMIC_COMPEX );
667
668
669         #undef ADD_OPATOMIC_CASE
670         #undef ADD_OPATOMIC_CASE_1
671         #undef ADD_OPATOMIC_CASE_N
672
673         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
674         {
675                 map<string, string>                     specializations;
676                 ComputeShaderSpec                       spec;
677                 vector<deInt32>                         inputInts               (numElements, 0);
678                 vector<deInt32>                         expected                (cases[caseNdx].numOutputElements, -1);
679
680                 specializations["INDEX"]                                = (cases[caseNdx].numOutputElements == 1) ? "%zero" : "%x";
681                 specializations["INSTRUCTION"]                  = cases[caseNdx].assembly;
682                 specializations["BLOCK_DECORATION"]             = useStorageBuffer ? "Block" : "BufferBlock";
683                 specializations["BLOCK_POINTER_TYPE"]   = useStorageBuffer ? "StorageBuffer" : "Uniform";
684
685                 if (verifyReturnValues)
686                 {
687                         const StringTemplate blockDecoration    (
688                                 "\n"
689                                 "OpDecorate %retbuf ${BLOCK_DECORATION}\n"
690                                 "OpDecorate %ret DescriptorSet 0\n"
691                                 "OpDecorate %ret Binding 2\n"
692                                 "OpMemberDecorate %retbuf 0 Offset 0\n\n");
693
694                         const StringTemplate blockDeclaration   (
695                                 "\n"
696                                 "%retbuf    = OpTypeStruct %i32arr\n"
697                                 "%retbufptr = OpTypePointer ${BLOCK_POINTER_TYPE} %retbuf\n"
698                                 "%ret       = OpVariable %retbufptr ${BLOCK_POINTER_TYPE}\n\n");
699
700                         specializations["RETVAL_ASSEMBLY"] =
701                                 "%retloc    = OpAccessChain %i32ptr %ret %zero %x\n"
702                                 + std::string(cases[caseNdx].retValAssembly);
703
704                         specializations["RETVAL_BUF_DECORATE"]  = blockDecoration.specialize(specializations);
705                         specializations["RETVAL_BUF_DECL"]              = blockDeclaration.specialize(specializations);
706                 }
707                 else
708                 {
709                         specializations["RETVAL_ASSEMBLY"]              = "";
710                         specializations["RETVAL_BUF_DECORATE"]  = "";
711                         specializations["RETVAL_BUF_DECL"]              = "";
712                 }
713
714                 spec.assembly                                                   = shaderTemplate.specialize(specializations);
715
716                 if (useStorageBuffer)
717                         spec.extensions.push_back("VK_KHR_storage_buffer_storage_class");
718
719                 spec.inputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_INPUT)));
720                 spec.outputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_EXPECTED)));
721                 if (verifyReturnValues)
722                         spec.outputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_ATOMIC_RET)));
723                 spec.numWorkGroups = IVec3(numElements, 1, 1);
724
725                 if (verifyReturnValues)
726                 {
727                         switch (cases[caseNdx].opAtomic)
728                         {
729                                 case OPATOMIC_IADD:
730                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IADD>;
731                                         break;
732                                 case OPATOMIC_ISUB:
733                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_ISUB>;
734                                         break;
735                                 case OPATOMIC_IINC:
736                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IINC>;
737                                         break;
738                                 case OPATOMIC_IDEC:
739                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IDEC>;
740                                         break;
741                                 case OPATOMIC_COMPEX:
742                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_COMPEX>;
743                                         break;
744                                 default:
745                                         DE_FATAL("Unsupported OpAtomic type for return value verification");
746                         }
747                 }
748                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
749         }
750
751         return group.release();
752 }
753
754 tcu::TestCaseGroup* createOpLineGroup (tcu::TestContext& testCtx)
755 {
756         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opline", "Test the OpLine instruction"));
757         ComputeShaderSpec                               spec;
758         de::Random                                              rnd                             (deStringHash(group->getName()));
759         const int                                               numElements             = 100;
760         vector<float>                                   positiveFloats  (numElements, 0);
761         vector<float>                                   negativeFloats  (numElements, 0);
762
763         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
764
765         for (size_t ndx = 0; ndx < numElements; ++ndx)
766                 negativeFloats[ndx] = -positiveFloats[ndx];
767
768         spec.assembly =
769                 string(getComputeAsmShaderPreamble()) +
770
771                 "%fname1 = OpString \"negateInputs.comp\"\n"
772                 "%fname2 = OpString \"negateInputs\"\n"
773
774                 "OpSource GLSL 430\n"
775                 "OpName %main           \"main\"\n"
776                 "OpName %id             \"gl_GlobalInvocationID\"\n"
777
778                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
779
780                 + string(getComputeAsmInputOutputBufferTraits()) +
781
782                 "OpLine %fname1 0 0\n" // At the earliest possible position
783
784                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
785
786                 "OpLine %fname1 0 1\n" // Multiple OpLines in sequence
787                 "OpLine %fname2 1 0\n" // Different filenames
788                 "OpLine %fname1 1000 100000\n"
789
790                 "%id        = OpVariable %uvec3ptr Input\n"
791                 "%zero      = OpConstant %i32 0\n"
792
793                 "OpLine %fname1 1 1\n" // Before a function
794
795                 "%main      = OpFunction %void None %voidf\n"
796                 "%label     = OpLabel\n"
797
798                 "OpLine %fname1 1 1\n" // In a function
799
800                 "%idval     = OpLoad %uvec3 %id\n"
801                 "%x         = OpCompositeExtract %u32 %idval 0\n"
802                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
803                 "%inval     = OpLoad %f32 %inloc\n"
804                 "%neg       = OpFNegate %f32 %inval\n"
805                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
806                 "             OpStore %outloc %neg\n"
807                 "             OpReturn\n"
808                 "             OpFunctionEnd\n";
809         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
810         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
811         spec.numWorkGroups = IVec3(numElements, 1, 1);
812
813         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpLine appearing at different places", spec));
814
815         return group.release();
816 }
817
818 bool veryfiBinaryShader (const ProgramBinary& binary)
819 {
820         const size_t    paternCount                     = 3u;
821         bool paternsCheck[paternCount]          =
822         {
823                 false, false, false
824         };
825         const string patersns[paternCount]      =
826         {
827                 "VULKAN CTS",
828                 "Negative values",
829                 "Date: 2017/09/21"
830         };
831         size_t                  paternNdx               = 0u;
832
833         for (size_t ndx = 0u; ndx < binary.getSize(); ++ndx)
834         {
835                 if (false == paternsCheck[paternNdx] &&
836                         patersns[paternNdx][0] == static_cast<char>(binary.getBinary()[ndx]) &&
837                         deMemoryEqual((const char*)&binary.getBinary()[ndx], &patersns[paternNdx][0], patersns[paternNdx].length()))
838                 {
839                         paternsCheck[paternNdx]= true;
840                         paternNdx++;
841                         if (paternNdx == paternCount)
842                                 break;
843                 }
844         }
845
846         for (size_t ndx = 0u; ndx < paternCount; ++ndx)
847         {
848                 if (!paternsCheck[ndx])
849                         return false;
850         }
851
852         return true;
853 }
854
855 tcu::TestCaseGroup* createOpModuleProcessedGroup (tcu::TestContext& testCtx)
856 {
857         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opmoduleprocessed", "Test the OpModuleProcessed instruction"));
858         ComputeShaderSpec                               spec;
859         de::Random                                              rnd                             (deStringHash(group->getName()));
860         const int                                               numElements             = 10;
861         vector<float>                                   positiveFloats  (numElements, 0);
862         vector<float>                                   negativeFloats  (numElements, 0);
863
864         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
865
866         for (size_t ndx = 0; ndx < numElements; ++ndx)
867                 negativeFloats[ndx] = -positiveFloats[ndx];
868
869         spec.assembly =
870                 string(getComputeAsmShaderPreamble()) +
871                 "%fname = OpString \"negateInputs.comp\"\n"
872
873                 "OpSource GLSL 430\n"
874                 "OpName %main           \"main\"\n"
875                 "OpName %id             \"gl_GlobalInvocationID\"\n"
876                 "OpModuleProcessed \"VULKAN CTS\"\n"                                    //OpModuleProcessed;
877                 "OpModuleProcessed \"Negative values\"\n"
878                 "OpModuleProcessed \"Date: 2017/09/21\"\n"
879                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
880
881                 + string(getComputeAsmInputOutputBufferTraits())
882
883                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
884
885                 "OpLine %fname 0 1\n"
886
887                 "OpLine %fname 1000 1\n"
888
889                 "%id        = OpVariable %uvec3ptr Input\n"
890                 "%zero      = OpConstant %i32 0\n"
891                 "%main      = OpFunction %void None %voidf\n"
892
893                 "%label     = OpLabel\n"
894                 "%idval     = OpLoad %uvec3 %id\n"
895                 "%x         = OpCompositeExtract %u32 %idval 0\n"
896
897                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
898                 "%inval     = OpLoad %f32 %inloc\n"
899                 "%neg       = OpFNegate %f32 %inval\n"
900                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
901                 "             OpStore %outloc %neg\n"
902                 "             OpReturn\n"
903                 "             OpFunctionEnd\n";
904         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
905         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
906         spec.numWorkGroups = IVec3(numElements, 1, 1);
907         spec.verifyBinary = veryfiBinaryShader;
908         spec.spirvVersion = SPIRV_VERSION_1_3;
909
910         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpModuleProcessed Tests", spec));
911
912         return group.release();
913 }
914
915 tcu::TestCaseGroup* createOpNoLineGroup (tcu::TestContext& testCtx)
916 {
917         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnoline", "Test the OpNoLine instruction"));
918         ComputeShaderSpec                               spec;
919         de::Random                                              rnd                             (deStringHash(group->getName()));
920         const int                                               numElements             = 100;
921         vector<float>                                   positiveFloats  (numElements, 0);
922         vector<float>                                   negativeFloats  (numElements, 0);
923
924         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
925
926         for (size_t ndx = 0; ndx < numElements; ++ndx)
927                 negativeFloats[ndx] = -positiveFloats[ndx];
928
929         spec.assembly =
930                 string(getComputeAsmShaderPreamble()) +
931
932                 "%fname = OpString \"negateInputs.comp\"\n"
933
934                 "OpSource GLSL 430\n"
935                 "OpName %main           \"main\"\n"
936                 "OpName %id             \"gl_GlobalInvocationID\"\n"
937
938                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
939
940                 + string(getComputeAsmInputOutputBufferTraits()) +
941
942                 "OpNoLine\n" // At the earliest possible position, without preceding OpLine
943
944                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
945
946                 "OpLine %fname 0 1\n"
947                 "OpNoLine\n" // Immediately following a preceding OpLine
948
949                 "OpLine %fname 1000 1\n"
950
951                 "%id        = OpVariable %uvec3ptr Input\n"
952                 "%zero      = OpConstant %i32 0\n"
953
954                 "OpNoLine\n" // Contents after the previous OpLine
955
956                 "%main      = OpFunction %void None %voidf\n"
957                 "%label     = OpLabel\n"
958                 "%idval     = OpLoad %uvec3 %id\n"
959                 "%x         = OpCompositeExtract %u32 %idval 0\n"
960
961                 "OpNoLine\n" // Multiple OpNoLine
962                 "OpNoLine\n"
963                 "OpNoLine\n"
964
965                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
966                 "%inval     = OpLoad %f32 %inloc\n"
967                 "%neg       = OpFNegate %f32 %inval\n"
968                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
969                 "             OpStore %outloc %neg\n"
970                 "             OpReturn\n"
971                 "             OpFunctionEnd\n";
972         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
973         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
974         spec.numWorkGroups = IVec3(numElements, 1, 1);
975
976         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpNoLine appearing at different places", spec));
977
978         return group.release();
979 }
980
981 // Compare instruction for the contraction compute case.
982 // Returns true if the output is what is expected from the test case.
983 bool compareNoContractCase(const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
984 {
985         if (outputAllocs.size() != 1)
986                 return false;
987
988         // Only size is needed because we are not comparing the exact values.
989         size_t byteSize = expectedOutputs[0].getByteSize();
990
991         const float*    outputAsFloat   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
992
993         for(size_t i = 0; i < byteSize / sizeof(float); ++i) {
994                 if (outputAsFloat[i] != 0.f &&
995                         outputAsFloat[i] != -ldexp(1, -24)) {
996                         return false;
997                 }
998         }
999
1000         return true;
1001 }
1002
1003 tcu::TestCaseGroup* createNoContractionGroup (tcu::TestContext& testCtx)
1004 {
1005         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
1006         vector<CaseParameter>                   cases;
1007         const int                                               numElements             = 100;
1008         vector<float>                                   inputFloats1    (numElements, 0);
1009         vector<float>                                   inputFloats2    (numElements, 0);
1010         vector<float>                                   outputFloats    (numElements, 0);
1011         const StringTemplate                    shaderTemplate  (
1012                 string(getComputeAsmShaderPreamble()) +
1013
1014                 "OpName %main           \"main\"\n"
1015                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1016
1017                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1018
1019                 "${DECORATION}\n"
1020
1021                 "OpDecorate %buf BufferBlock\n"
1022                 "OpDecorate %indata1 DescriptorSet 0\n"
1023                 "OpDecorate %indata1 Binding 0\n"
1024                 "OpDecorate %indata2 DescriptorSet 0\n"
1025                 "OpDecorate %indata2 Binding 1\n"
1026                 "OpDecorate %outdata DescriptorSet 0\n"
1027                 "OpDecorate %outdata Binding 2\n"
1028                 "OpDecorate %f32arr ArrayStride 4\n"
1029                 "OpMemberDecorate %buf 0 Offset 0\n"
1030
1031                 + string(getComputeAsmCommonTypes()) +
1032
1033                 "%buf        = OpTypeStruct %f32arr\n"
1034                 "%bufptr     = OpTypePointer Uniform %buf\n"
1035                 "%indata1    = OpVariable %bufptr Uniform\n"
1036                 "%indata2    = OpVariable %bufptr Uniform\n"
1037                 "%outdata    = OpVariable %bufptr Uniform\n"
1038
1039                 "%id         = OpVariable %uvec3ptr Input\n"
1040                 "%zero       = OpConstant %i32 0\n"
1041                 "%c_f_m1     = OpConstant %f32 -1.\n"
1042
1043                 "%main       = OpFunction %void None %voidf\n"
1044                 "%label      = OpLabel\n"
1045                 "%idval      = OpLoad %uvec3 %id\n"
1046                 "%x          = OpCompositeExtract %u32 %idval 0\n"
1047                 "%inloc1     = OpAccessChain %f32ptr %indata1 %zero %x\n"
1048                 "%inval1     = OpLoad %f32 %inloc1\n"
1049                 "%inloc2     = OpAccessChain %f32ptr %indata2 %zero %x\n"
1050                 "%inval2     = OpLoad %f32 %inloc2\n"
1051                 "%mul        = OpFMul %f32 %inval1 %inval2\n"
1052                 "%add        = OpFAdd %f32 %mul %c_f_m1\n"
1053                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
1054                 "              OpStore %outloc %add\n"
1055                 "              OpReturn\n"
1056                 "              OpFunctionEnd\n");
1057
1058         cases.push_back(CaseParameter("multiplication", "OpDecorate %mul NoContraction"));
1059         cases.push_back(CaseParameter("addition",               "OpDecorate %add NoContraction"));
1060         cases.push_back(CaseParameter("both",                   "OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"));
1061
1062         for (size_t ndx = 0; ndx < numElements; ++ndx)
1063         {
1064                 inputFloats1[ndx]       = 1.f + std::ldexp(1.f, -23); // 1 + 2^-23.
1065                 inputFloats2[ndx]       = 1.f - std::ldexp(1.f, -23); // 1 - 2^-23.
1066                 // Result for (1 + 2^-23) * (1 - 2^-23) - 1. With NoContraction, the multiplication will be
1067                 // conducted separately and the result is rounded to 1, or 0x1.fffffcp-1
1068                 // So the final result will be 0.f or 0x1p-24.
1069                 // If the operation is combined into a precise fused multiply-add, then the result would be
1070                 // 2^-46 (0xa8800000).
1071                 outputFloats[ndx]       = 0.f;
1072         }
1073
1074         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
1075         {
1076                 map<string, string>             specializations;
1077                 ComputeShaderSpec               spec;
1078
1079                 specializations["DECORATION"] = cases[caseNdx].param;
1080                 spec.assembly = shaderTemplate.specialize(specializations);
1081                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1082                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1083                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1084                 spec.numWorkGroups = IVec3(numElements, 1, 1);
1085                 // Check against the two possible answers based on rounding mode.
1086                 spec.verifyIO = &compareNoContractCase;
1087
1088                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
1089         }
1090         return group.release();
1091 }
1092
1093 bool compareFRem(const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1094 {
1095         if (outputAllocs.size() != 1)
1096                 return false;
1097
1098         vector<deUint8> expectedBytes;
1099         expectedOutputs[0].getBytes(expectedBytes);
1100
1101         const float*    expectedOutputAsFloat   = reinterpret_cast<const float*>(&expectedBytes.front());
1102         const float*    outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1103
1104         for (size_t idx = 0; idx < expectedBytes.size() / sizeof(float); ++idx)
1105         {
1106                 const float f0 = expectedOutputAsFloat[idx];
1107                 const float f1 = outputAsFloat[idx];
1108                 // \todo relative error needs to be fairly high because FRem may be implemented as
1109                 // (roughly) frac(a/b)*b, so LSB errors can be magnified. But this should be fine for now.
1110                 if (deFloatAbs((f1 - f0) / f0) > 0.02)
1111                         return false;
1112         }
1113
1114         return true;
1115 }
1116
1117 tcu::TestCaseGroup* createOpFRemGroup (tcu::TestContext& testCtx)
1118 {
1119         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opfrem", "Test the OpFRem instruction"));
1120         ComputeShaderSpec                               spec;
1121         de::Random                                              rnd                             (deStringHash(group->getName()));
1122         const int                                               numElements             = 200;
1123         vector<float>                                   inputFloats1    (numElements, 0);
1124         vector<float>                                   inputFloats2    (numElements, 0);
1125         vector<float>                                   outputFloats    (numElements, 0);
1126
1127         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1128         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats2[0], numElements);
1129
1130         for (size_t ndx = 0; ndx < numElements; ++ndx)
1131         {
1132                 // Guard against divisors near zero.
1133                 if (std::fabs(inputFloats2[ndx]) < 1e-3)
1134                         inputFloats2[ndx] = 8.f;
1135
1136                 // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1137                 outputFloats[ndx] = std::fmod(inputFloats1[ndx], inputFloats2[ndx]);
1138         }
1139
1140         spec.assembly =
1141                 string(getComputeAsmShaderPreamble()) +
1142
1143                 "OpName %main           \"main\"\n"
1144                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1145
1146                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1147
1148                 "OpDecorate %buf BufferBlock\n"
1149                 "OpDecorate %indata1 DescriptorSet 0\n"
1150                 "OpDecorate %indata1 Binding 0\n"
1151                 "OpDecorate %indata2 DescriptorSet 0\n"
1152                 "OpDecorate %indata2 Binding 1\n"
1153                 "OpDecorate %outdata DescriptorSet 0\n"
1154                 "OpDecorate %outdata Binding 2\n"
1155                 "OpDecorate %f32arr ArrayStride 4\n"
1156                 "OpMemberDecorate %buf 0 Offset 0\n"
1157
1158                 + string(getComputeAsmCommonTypes()) +
1159
1160                 "%buf        = OpTypeStruct %f32arr\n"
1161                 "%bufptr     = OpTypePointer Uniform %buf\n"
1162                 "%indata1    = OpVariable %bufptr Uniform\n"
1163                 "%indata2    = OpVariable %bufptr Uniform\n"
1164                 "%outdata    = OpVariable %bufptr Uniform\n"
1165
1166                 "%id        = OpVariable %uvec3ptr Input\n"
1167                 "%zero      = OpConstant %i32 0\n"
1168
1169                 "%main      = OpFunction %void None %voidf\n"
1170                 "%label     = OpLabel\n"
1171                 "%idval     = OpLoad %uvec3 %id\n"
1172                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1173                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1174                 "%inval1    = OpLoad %f32 %inloc1\n"
1175                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1176                 "%inval2    = OpLoad %f32 %inloc2\n"
1177                 "%rem       = OpFRem %f32 %inval1 %inval2\n"
1178                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1179                 "             OpStore %outloc %rem\n"
1180                 "             OpReturn\n"
1181                 "             OpFunctionEnd\n";
1182
1183         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1184         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1185         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1186         spec.numWorkGroups = IVec3(numElements, 1, 1);
1187         spec.verifyIO = &compareFRem;
1188
1189         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1190
1191         return group.release();
1192 }
1193
1194 bool compareNMin (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1195 {
1196         if (outputAllocs.size() != 1)
1197                 return false;
1198
1199         const BufferSp&                 expectedOutput                  (expectedOutputs[0].getBuffer());
1200         std::vector<deUint8>    data;
1201         expectedOutput->getBytes(data);
1202
1203         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1204         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1205
1206         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float); ++idx)
1207         {
1208                 const float f0 = expectedOutputAsFloat[idx];
1209                 const float f1 = outputAsFloat[idx];
1210
1211                 // For NMin, we accept NaN as output if both inputs were NaN.
1212                 // Otherwise the NaN is the wrong choise, as on architectures that
1213                 // do not handle NaN, those are huge values.
1214                 if (!(tcu::Float32(f1).isNaN() && tcu::Float32(f0).isNaN()) && deFloatAbs(f1 - f0) > 0.00001f)
1215                         return false;
1216         }
1217
1218         return true;
1219 }
1220
1221 tcu::TestCaseGroup* createOpNMinGroup (tcu::TestContext& testCtx)
1222 {
1223         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnmin", "Test the OpNMin instruction"));
1224         ComputeShaderSpec                               spec;
1225         de::Random                                              rnd                             (deStringHash(group->getName()));
1226         const int                                               numElements             = 200;
1227         vector<float>                                   inputFloats1    (numElements, 0);
1228         vector<float>                                   inputFloats2    (numElements, 0);
1229         vector<float>                                   outputFloats    (numElements, 0);
1230
1231         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1232         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1233
1234         // Make the first case a full-NAN case.
1235         inputFloats1[0] = TCU_NAN;
1236         inputFloats2[0] = TCU_NAN;
1237
1238         for (size_t ndx = 0; ndx < numElements; ++ndx)
1239         {
1240                 // By default, pick the smallest
1241                 outputFloats[ndx] = std::min(inputFloats1[ndx], inputFloats2[ndx]);
1242
1243                 // Make half of the cases NaN cases
1244                 if ((ndx & 1) == 0)
1245                 {
1246                         // Alternate between the NaN operand
1247                         if ((ndx & 2) == 0)
1248                         {
1249                                 outputFloats[ndx] = inputFloats2[ndx];
1250                                 inputFloats1[ndx] = TCU_NAN;
1251                         }
1252                         else
1253                         {
1254                                 outputFloats[ndx] = inputFloats1[ndx];
1255                                 inputFloats2[ndx] = TCU_NAN;
1256                         }
1257                 }
1258         }
1259
1260         spec.assembly =
1261                 "OpCapability Shader\n"
1262                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1263                 "OpMemoryModel Logical GLSL450\n"
1264                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1265                 "OpExecutionMode %main LocalSize 1 1 1\n"
1266
1267                 "OpName %main           \"main\"\n"
1268                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1269
1270                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1271
1272                 "OpDecorate %buf BufferBlock\n"
1273                 "OpDecorate %indata1 DescriptorSet 0\n"
1274                 "OpDecorate %indata1 Binding 0\n"
1275                 "OpDecorate %indata2 DescriptorSet 0\n"
1276                 "OpDecorate %indata2 Binding 1\n"
1277                 "OpDecorate %outdata DescriptorSet 0\n"
1278                 "OpDecorate %outdata Binding 2\n"
1279                 "OpDecorate %f32arr ArrayStride 4\n"
1280                 "OpMemberDecorate %buf 0 Offset 0\n"
1281
1282                 + string(getComputeAsmCommonTypes()) +
1283
1284                 "%buf        = OpTypeStruct %f32arr\n"
1285                 "%bufptr     = OpTypePointer Uniform %buf\n"
1286                 "%indata1    = OpVariable %bufptr Uniform\n"
1287                 "%indata2    = OpVariable %bufptr Uniform\n"
1288                 "%outdata    = OpVariable %bufptr Uniform\n"
1289
1290                 "%id        = OpVariable %uvec3ptr Input\n"
1291                 "%zero      = OpConstant %i32 0\n"
1292
1293                 "%main      = OpFunction %void None %voidf\n"
1294                 "%label     = OpLabel\n"
1295                 "%idval     = OpLoad %uvec3 %id\n"
1296                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1297                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1298                 "%inval1    = OpLoad %f32 %inloc1\n"
1299                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1300                 "%inval2    = OpLoad %f32 %inloc2\n"
1301                 "%rem       = OpExtInst %f32 %std450 NMin %inval1 %inval2\n"
1302                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1303                 "             OpStore %outloc %rem\n"
1304                 "             OpReturn\n"
1305                 "             OpFunctionEnd\n";
1306
1307         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1308         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1309         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1310         spec.numWorkGroups = IVec3(numElements, 1, 1);
1311         spec.verifyIO = &compareNMin;
1312
1313         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1314
1315         return group.release();
1316 }
1317
1318 bool compareNMax (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1319 {
1320         if (outputAllocs.size() != 1)
1321                 return false;
1322
1323         const BufferSp&                 expectedOutput                  = expectedOutputs[0].getBuffer();
1324         std::vector<deUint8>    data;
1325         expectedOutput->getBytes(data);
1326
1327         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1328         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1329
1330         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float); ++idx)
1331         {
1332                 const float f0 = expectedOutputAsFloat[idx];
1333                 const float f1 = outputAsFloat[idx];
1334
1335                 // For NMax, NaN is considered acceptable result, since in
1336                 // architectures that do not handle NaNs, those are huge values.
1337                 if (!tcu::Float32(f1).isNaN() && deFloatAbs(f1 - f0) > 0.00001f)
1338                         return false;
1339         }
1340
1341         return true;
1342 }
1343
1344 tcu::TestCaseGroup* createOpNMaxGroup (tcu::TestContext& testCtx)
1345 {
1346         de::MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "opnmax", "Test the OpNMax instruction"));
1347         ComputeShaderSpec                               spec;
1348         de::Random                                              rnd                             (deStringHash(group->getName()));
1349         const int                                               numElements             = 200;
1350         vector<float>                                   inputFloats1    (numElements, 0);
1351         vector<float>                                   inputFloats2    (numElements, 0);
1352         vector<float>                                   outputFloats    (numElements, 0);
1353
1354         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1355         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1356
1357         // Make the first case a full-NAN case.
1358         inputFloats1[0] = TCU_NAN;
1359         inputFloats2[0] = TCU_NAN;
1360
1361         for (size_t ndx = 0; ndx < numElements; ++ndx)
1362         {
1363                 // By default, pick the biggest
1364                 outputFloats[ndx] = std::max(inputFloats1[ndx], inputFloats2[ndx]);
1365
1366                 // Make half of the cases NaN cases
1367                 if ((ndx & 1) == 0)
1368                 {
1369                         // Alternate between the NaN operand
1370                         if ((ndx & 2) == 0)
1371                         {
1372                                 outputFloats[ndx] = inputFloats2[ndx];
1373                                 inputFloats1[ndx] = TCU_NAN;
1374                         }
1375                         else
1376                         {
1377                                 outputFloats[ndx] = inputFloats1[ndx];
1378                                 inputFloats2[ndx] = TCU_NAN;
1379                         }
1380                 }
1381         }
1382
1383         spec.assembly =
1384                 "OpCapability Shader\n"
1385                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1386                 "OpMemoryModel Logical GLSL450\n"
1387                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1388                 "OpExecutionMode %main LocalSize 1 1 1\n"
1389
1390                 "OpName %main           \"main\"\n"
1391                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1392
1393                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1394
1395                 "OpDecorate %buf BufferBlock\n"
1396                 "OpDecorate %indata1 DescriptorSet 0\n"
1397                 "OpDecorate %indata1 Binding 0\n"
1398                 "OpDecorate %indata2 DescriptorSet 0\n"
1399                 "OpDecorate %indata2 Binding 1\n"
1400                 "OpDecorate %outdata DescriptorSet 0\n"
1401                 "OpDecorate %outdata Binding 2\n"
1402                 "OpDecorate %f32arr ArrayStride 4\n"
1403                 "OpMemberDecorate %buf 0 Offset 0\n"
1404
1405                 + string(getComputeAsmCommonTypes()) +
1406
1407                 "%buf        = OpTypeStruct %f32arr\n"
1408                 "%bufptr     = OpTypePointer Uniform %buf\n"
1409                 "%indata1    = OpVariable %bufptr Uniform\n"
1410                 "%indata2    = OpVariable %bufptr Uniform\n"
1411                 "%outdata    = OpVariable %bufptr Uniform\n"
1412
1413                 "%id        = OpVariable %uvec3ptr Input\n"
1414                 "%zero      = OpConstant %i32 0\n"
1415
1416                 "%main      = OpFunction %void None %voidf\n"
1417                 "%label     = OpLabel\n"
1418                 "%idval     = OpLoad %uvec3 %id\n"
1419                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1420                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1421                 "%inval1    = OpLoad %f32 %inloc1\n"
1422                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1423                 "%inval2    = OpLoad %f32 %inloc2\n"
1424                 "%rem       = OpExtInst %f32 %std450 NMax %inval1 %inval2\n"
1425                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1426                 "             OpStore %outloc %rem\n"
1427                 "             OpReturn\n"
1428                 "             OpFunctionEnd\n";
1429
1430         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1431         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1432         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1433         spec.numWorkGroups = IVec3(numElements, 1, 1);
1434         spec.verifyIO = &compareNMax;
1435
1436         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1437
1438         return group.release();
1439 }
1440
1441 bool compareNClamp (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1442 {
1443         if (outputAllocs.size() != 1)
1444                 return false;
1445
1446         const BufferSp&                 expectedOutput                  = expectedOutputs[0].getBuffer();
1447         std::vector<deUint8>    data;
1448         expectedOutput->getBytes(data);
1449
1450         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1451         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1452
1453         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float) / 2; ++idx)
1454         {
1455                 const float e0 = expectedOutputAsFloat[idx * 2];
1456                 const float e1 = expectedOutputAsFloat[idx * 2 + 1];
1457                 const float res = outputAsFloat[idx];
1458
1459                 // For NClamp, we have two possible outcomes based on
1460                 // whether NaNs are handled or not.
1461                 // If either min or max value is NaN, the result is undefined,
1462                 // so this test doesn't stress those. If the clamped value is
1463                 // NaN, and NaNs are handled, the result is min; if NaNs are not
1464                 // handled, they are big values that result in max.
1465                 // If all three parameters are NaN, the result should be NaN.
1466                 if (!((tcu::Float32(e0).isNaN() && tcu::Float32(res).isNaN()) ||
1467                          (deFloatAbs(e0 - res) < 0.00001f) ||
1468                          (deFloatAbs(e1 - res) < 0.00001f)))
1469                         return false;
1470         }
1471
1472         return true;
1473 }
1474
1475 tcu::TestCaseGroup* createOpNClampGroup (tcu::TestContext& testCtx)
1476 {
1477         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnclamp", "Test the OpNClamp instruction"));
1478         ComputeShaderSpec                               spec;
1479         de::Random                                              rnd                             (deStringHash(group->getName()));
1480         const int                                               numElements             = 200;
1481         vector<float>                                   inputFloats1    (numElements, 0);
1482         vector<float>                                   inputFloats2    (numElements, 0);
1483         vector<float>                                   inputFloats3    (numElements, 0);
1484         vector<float>                                   outputFloats    (numElements * 2, 0);
1485
1486         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1487         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1488         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats3[0], numElements);
1489
1490         for (size_t ndx = 0; ndx < numElements; ++ndx)
1491         {
1492                 // Results are only defined if max value is bigger than min value.
1493                 if (inputFloats2[ndx] > inputFloats3[ndx])
1494                 {
1495                         float t = inputFloats2[ndx];
1496                         inputFloats2[ndx] = inputFloats3[ndx];
1497                         inputFloats3[ndx] = t;
1498                 }
1499
1500                 // By default, do the clamp, setting both possible answers
1501                 float defaultRes = std::min(std::max(inputFloats1[ndx], inputFloats2[ndx]), inputFloats3[ndx]);
1502
1503                 float maxResA = std::max(inputFloats1[ndx], inputFloats2[ndx]);
1504                 float maxResB = maxResA;
1505
1506                 // Alternate between the NaN cases
1507                 if (ndx & 1)
1508                 {
1509                         inputFloats1[ndx] = TCU_NAN;
1510                         // If NaN is handled, the result should be same as the clamp minimum.
1511                         // If NaN is not handled, the result should clamp to the clamp maximum.
1512                         maxResA = inputFloats2[ndx];
1513                         maxResB = inputFloats3[ndx];
1514                 }
1515                 else
1516                 {
1517                         // Not a NaN case - only one legal result.
1518                         maxResA = defaultRes;
1519                         maxResB = defaultRes;
1520                 }
1521
1522                 outputFloats[ndx * 2] = maxResA;
1523                 outputFloats[ndx * 2 + 1] = maxResB;
1524         }
1525
1526         // Make the first case a full-NAN case.
1527         inputFloats1[0] = TCU_NAN;
1528         inputFloats2[0] = TCU_NAN;
1529         inputFloats3[0] = TCU_NAN;
1530         outputFloats[0] = TCU_NAN;
1531         outputFloats[1] = TCU_NAN;
1532
1533         spec.assembly =
1534                 "OpCapability Shader\n"
1535                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1536                 "OpMemoryModel Logical GLSL450\n"
1537                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1538                 "OpExecutionMode %main LocalSize 1 1 1\n"
1539
1540                 "OpName %main           \"main\"\n"
1541                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1542
1543                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1544
1545                 "OpDecorate %buf BufferBlock\n"
1546                 "OpDecorate %indata1 DescriptorSet 0\n"
1547                 "OpDecorate %indata1 Binding 0\n"
1548                 "OpDecorate %indata2 DescriptorSet 0\n"
1549                 "OpDecorate %indata2 Binding 1\n"
1550                 "OpDecorate %indata3 DescriptorSet 0\n"
1551                 "OpDecorate %indata3 Binding 2\n"
1552                 "OpDecorate %outdata DescriptorSet 0\n"
1553                 "OpDecorate %outdata Binding 3\n"
1554                 "OpDecorate %f32arr ArrayStride 4\n"
1555                 "OpMemberDecorate %buf 0 Offset 0\n"
1556
1557                 + string(getComputeAsmCommonTypes()) +
1558
1559                 "%buf        = OpTypeStruct %f32arr\n"
1560                 "%bufptr     = OpTypePointer Uniform %buf\n"
1561                 "%indata1    = OpVariable %bufptr Uniform\n"
1562                 "%indata2    = OpVariable %bufptr Uniform\n"
1563                 "%indata3    = OpVariable %bufptr Uniform\n"
1564                 "%outdata    = OpVariable %bufptr Uniform\n"
1565
1566                 "%id        = OpVariable %uvec3ptr Input\n"
1567                 "%zero      = OpConstant %i32 0\n"
1568
1569                 "%main      = OpFunction %void None %voidf\n"
1570                 "%label     = OpLabel\n"
1571                 "%idval     = OpLoad %uvec3 %id\n"
1572                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1573                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1574                 "%inval1    = OpLoad %f32 %inloc1\n"
1575                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1576                 "%inval2    = OpLoad %f32 %inloc2\n"
1577                 "%inloc3    = OpAccessChain %f32ptr %indata3 %zero %x\n"
1578                 "%inval3    = OpLoad %f32 %inloc3\n"
1579                 "%rem       = OpExtInst %f32 %std450 NClamp %inval1 %inval2 %inval3\n"
1580                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1581                 "             OpStore %outloc %rem\n"
1582                 "             OpReturn\n"
1583                 "             OpFunctionEnd\n";
1584
1585         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1586         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1587         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
1588         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1589         spec.numWorkGroups = IVec3(numElements, 1, 1);
1590         spec.verifyIO = &compareNClamp;
1591
1592         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1593
1594         return group.release();
1595 }
1596
1597 tcu::TestCaseGroup* createOpSRemComputeGroup (tcu::TestContext& testCtx, qpTestResult negFailResult)
1598 {
1599         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsrem", "Test the OpSRem instruction"));
1600         de::Random                                              rnd                             (deStringHash(group->getName()));
1601         const int                                               numElements             = 200;
1602
1603         const struct CaseParams
1604         {
1605                 const char*             name;
1606                 const char*             failMessage;            // customized status message
1607                 qpTestResult    failResult;                     // override status on failure
1608                 int                             op1Min, op1Max;         // operand ranges
1609                 int                             op2Min, op2Max;
1610         } cases[] =
1611         {
1612                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    0,              65536,  0,              100 },
1613                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  -65536, 65536,  -100,   100 },  // see below
1614         };
1615         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1616
1617         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1618         {
1619                 const CaseParams&       params          = cases[caseNdx];
1620                 ComputeShaderSpec       spec;
1621                 vector<deInt32>         inputInts1      (numElements, 0);
1622                 vector<deInt32>         inputInts2      (numElements, 0);
1623                 vector<deInt32>         outputInts      (numElements, 0);
1624
1625                 fillRandomScalars(rnd, params.op1Min, params.op1Max, &inputInts1[0], numElements);
1626                 fillRandomScalars(rnd, params.op2Min, params.op2Max, &inputInts2[0], numElements, filterNotZero);
1627
1628                 for (int ndx = 0; ndx < numElements; ++ndx)
1629                 {
1630                         // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1631                         outputInts[ndx] = inputInts1[ndx] % inputInts2[ndx];
1632                 }
1633
1634                 spec.assembly =
1635                         string(getComputeAsmShaderPreamble()) +
1636
1637                         "OpName %main           \"main\"\n"
1638                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1639
1640                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1641
1642                         "OpDecorate %buf BufferBlock\n"
1643                         "OpDecorate %indata1 DescriptorSet 0\n"
1644                         "OpDecorate %indata1 Binding 0\n"
1645                         "OpDecorate %indata2 DescriptorSet 0\n"
1646                         "OpDecorate %indata2 Binding 1\n"
1647                         "OpDecorate %outdata DescriptorSet 0\n"
1648                         "OpDecorate %outdata Binding 2\n"
1649                         "OpDecorate %i32arr ArrayStride 4\n"
1650                         "OpMemberDecorate %buf 0 Offset 0\n"
1651
1652                         + string(getComputeAsmCommonTypes()) +
1653
1654                         "%buf        = OpTypeStruct %i32arr\n"
1655                         "%bufptr     = OpTypePointer Uniform %buf\n"
1656                         "%indata1    = OpVariable %bufptr Uniform\n"
1657                         "%indata2    = OpVariable %bufptr Uniform\n"
1658                         "%outdata    = OpVariable %bufptr Uniform\n"
1659
1660                         "%id        = OpVariable %uvec3ptr Input\n"
1661                         "%zero      = OpConstant %i32 0\n"
1662
1663                         "%main      = OpFunction %void None %voidf\n"
1664                         "%label     = OpLabel\n"
1665                         "%idval     = OpLoad %uvec3 %id\n"
1666                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1667                         "%inloc1    = OpAccessChain %i32ptr %indata1 %zero %x\n"
1668                         "%inval1    = OpLoad %i32 %inloc1\n"
1669                         "%inloc2    = OpAccessChain %i32ptr %indata2 %zero %x\n"
1670                         "%inval2    = OpLoad %i32 %inloc2\n"
1671                         "%rem       = OpSRem %i32 %inval1 %inval2\n"
1672                         "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
1673                         "             OpStore %outloc %rem\n"
1674                         "             OpReturn\n"
1675                         "             OpFunctionEnd\n";
1676
1677                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts1)));
1678                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts2)));
1679                 spec.outputs.push_back  (BufferSp(new Int32Buffer(outputInts)));
1680                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1681                 spec.failResult                 = params.failResult;
1682                 spec.failMessage                = params.failMessage;
1683
1684                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1685         }
1686
1687         return group.release();
1688 }
1689
1690 tcu::TestCaseGroup* createOpSRemComputeGroup64 (tcu::TestContext& testCtx, qpTestResult negFailResult)
1691 {
1692         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsrem64", "Test the 64-bit OpSRem instruction"));
1693         de::Random                                              rnd                             (deStringHash(group->getName()));
1694         const int                                               numElements             = 200;
1695
1696         const struct CaseParams
1697         {
1698                 const char*             name;
1699                 const char*             failMessage;            // customized status message
1700                 qpTestResult    failResult;                     // override status on failure
1701                 bool                    positive;
1702         } cases[] =
1703         {
1704                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    true },
1705                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  false },        // see below
1706         };
1707         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1708
1709         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1710         {
1711                 const CaseParams&       params          = cases[caseNdx];
1712                 ComputeShaderSpec       spec;
1713                 vector<deInt64>         inputInts1      (numElements, 0);
1714                 vector<deInt64>         inputInts2      (numElements, 0);
1715                 vector<deInt64>         outputInts      (numElements, 0);
1716
1717                 if (params.positive)
1718                 {
1719                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements, filterNonNegative);
1720                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterPositive);
1721                 }
1722                 else
1723                 {
1724                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements);
1725                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterNotZero);
1726                 }
1727
1728                 for (int ndx = 0; ndx < numElements; ++ndx)
1729                 {
1730                         // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1731                         outputInts[ndx] = inputInts1[ndx] % inputInts2[ndx];
1732                 }
1733
1734                 spec.assembly =
1735                         "OpCapability Int64\n"
1736
1737                         + string(getComputeAsmShaderPreamble()) +
1738
1739                         "OpName %main           \"main\"\n"
1740                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1741
1742                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1743
1744                         "OpDecorate %buf BufferBlock\n"
1745                         "OpDecorate %indata1 DescriptorSet 0\n"
1746                         "OpDecorate %indata1 Binding 0\n"
1747                         "OpDecorate %indata2 DescriptorSet 0\n"
1748                         "OpDecorate %indata2 Binding 1\n"
1749                         "OpDecorate %outdata DescriptorSet 0\n"
1750                         "OpDecorate %outdata Binding 2\n"
1751                         "OpDecorate %i64arr ArrayStride 8\n"
1752                         "OpMemberDecorate %buf 0 Offset 0\n"
1753
1754                         + string(getComputeAsmCommonTypes())
1755                         + string(getComputeAsmCommonInt64Types()) +
1756
1757                         "%buf        = OpTypeStruct %i64arr\n"
1758                         "%bufptr     = OpTypePointer Uniform %buf\n"
1759                         "%indata1    = OpVariable %bufptr Uniform\n"
1760                         "%indata2    = OpVariable %bufptr Uniform\n"
1761                         "%outdata    = OpVariable %bufptr Uniform\n"
1762
1763                         "%id        = OpVariable %uvec3ptr Input\n"
1764                         "%zero      = OpConstant %i64 0\n"
1765
1766                         "%main      = OpFunction %void None %voidf\n"
1767                         "%label     = OpLabel\n"
1768                         "%idval     = OpLoad %uvec3 %id\n"
1769                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1770                         "%inloc1    = OpAccessChain %i64ptr %indata1 %zero %x\n"
1771                         "%inval1    = OpLoad %i64 %inloc1\n"
1772                         "%inloc2    = OpAccessChain %i64ptr %indata2 %zero %x\n"
1773                         "%inval2    = OpLoad %i64 %inloc2\n"
1774                         "%rem       = OpSRem %i64 %inval1 %inval2\n"
1775                         "%outloc    = OpAccessChain %i64ptr %outdata %zero %x\n"
1776                         "             OpStore %outloc %rem\n"
1777                         "             OpReturn\n"
1778                         "             OpFunctionEnd\n";
1779
1780                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts1)));
1781                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts2)));
1782                 spec.outputs.push_back  (BufferSp(new Int64Buffer(outputInts)));
1783                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1784                 spec.failResult                 = params.failResult;
1785                 spec.failMessage                = params.failMessage;
1786
1787                 spec.requestedVulkanFeatures.coreFeatures.shaderInt64 = VK_TRUE;
1788
1789                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1790         }
1791
1792         return group.release();
1793 }
1794
1795 tcu::TestCaseGroup* createOpSModComputeGroup (tcu::TestContext& testCtx, qpTestResult negFailResult)
1796 {
1797         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsmod", "Test the OpSMod instruction"));
1798         de::Random                                              rnd                             (deStringHash(group->getName()));
1799         const int                                               numElements             = 200;
1800
1801         const struct CaseParams
1802         {
1803                 const char*             name;
1804                 const char*             failMessage;            // customized status message
1805                 qpTestResult    failResult;                     // override status on failure
1806                 int                             op1Min, op1Max;         // operand ranges
1807                 int                             op2Min, op2Max;
1808         } cases[] =
1809         {
1810                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    0,              65536,  0,              100 },
1811                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  -65536, 65536,  -100,   100 },  // see below
1812         };
1813         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1814
1815         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1816         {
1817                 const CaseParams&       params          = cases[caseNdx];
1818
1819                 ComputeShaderSpec       spec;
1820                 vector<deInt32>         inputInts1      (numElements, 0);
1821                 vector<deInt32>         inputInts2      (numElements, 0);
1822                 vector<deInt32>         outputInts      (numElements, 0);
1823
1824                 fillRandomScalars(rnd, params.op1Min, params.op1Max, &inputInts1[0], numElements);
1825                 fillRandomScalars(rnd, params.op2Min, params.op2Max, &inputInts2[0], numElements, filterNotZero);
1826
1827                 for (int ndx = 0; ndx < numElements; ++ndx)
1828                 {
1829                         deInt32 rem = inputInts1[ndx] % inputInts2[ndx];
1830                         if (rem == 0)
1831                         {
1832                                 outputInts[ndx] = 0;
1833                         }
1834                         else if ((inputInts1[ndx] >= 0) == (inputInts2[ndx] >= 0))
1835                         {
1836                                 // They have the same sign
1837                                 outputInts[ndx] = rem;
1838                         }
1839                         else
1840                         {
1841                                 // They have opposite sign.  The remainder operation takes the
1842                                 // sign inputInts1[ndx] but OpSMod is supposed to take ths sign
1843                                 // of inputInts2[ndx].  Adding inputInts2[ndx] will ensure that
1844                                 // the result has the correct sign and that it is still
1845                                 // congruent to inputInts1[ndx] modulo inputInts2[ndx]
1846                                 //
1847                                 // See also http://mathforum.org/library/drmath/view/52343.html
1848                                 outputInts[ndx] = rem + inputInts2[ndx];
1849                         }
1850                 }
1851
1852                 spec.assembly =
1853                         string(getComputeAsmShaderPreamble()) +
1854
1855                         "OpName %main           \"main\"\n"
1856                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1857
1858                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1859
1860                         "OpDecorate %buf BufferBlock\n"
1861                         "OpDecorate %indata1 DescriptorSet 0\n"
1862                         "OpDecorate %indata1 Binding 0\n"
1863                         "OpDecorate %indata2 DescriptorSet 0\n"
1864                         "OpDecorate %indata2 Binding 1\n"
1865                         "OpDecorate %outdata DescriptorSet 0\n"
1866                         "OpDecorate %outdata Binding 2\n"
1867                         "OpDecorate %i32arr ArrayStride 4\n"
1868                         "OpMemberDecorate %buf 0 Offset 0\n"
1869
1870                         + string(getComputeAsmCommonTypes()) +
1871
1872                         "%buf        = OpTypeStruct %i32arr\n"
1873                         "%bufptr     = OpTypePointer Uniform %buf\n"
1874                         "%indata1    = OpVariable %bufptr Uniform\n"
1875                         "%indata2    = OpVariable %bufptr Uniform\n"
1876                         "%outdata    = OpVariable %bufptr Uniform\n"
1877
1878                         "%id        = OpVariable %uvec3ptr Input\n"
1879                         "%zero      = OpConstant %i32 0\n"
1880
1881                         "%main      = OpFunction %void None %voidf\n"
1882                         "%label     = OpLabel\n"
1883                         "%idval     = OpLoad %uvec3 %id\n"
1884                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1885                         "%inloc1    = OpAccessChain %i32ptr %indata1 %zero %x\n"
1886                         "%inval1    = OpLoad %i32 %inloc1\n"
1887                         "%inloc2    = OpAccessChain %i32ptr %indata2 %zero %x\n"
1888                         "%inval2    = OpLoad %i32 %inloc2\n"
1889                         "%rem       = OpSMod %i32 %inval1 %inval2\n"
1890                         "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
1891                         "             OpStore %outloc %rem\n"
1892                         "             OpReturn\n"
1893                         "             OpFunctionEnd\n";
1894
1895                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts1)));
1896                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts2)));
1897                 spec.outputs.push_back  (BufferSp(new Int32Buffer(outputInts)));
1898                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1899                 spec.failResult                 = params.failResult;
1900                 spec.failMessage                = params.failMessage;
1901
1902                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1903         }
1904
1905         return group.release();
1906 }
1907
1908 tcu::TestCaseGroup* createOpSModComputeGroup64 (tcu::TestContext& testCtx, qpTestResult negFailResult)
1909 {
1910         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsmod64", "Test the OpSMod instruction"));
1911         de::Random                                              rnd                             (deStringHash(group->getName()));
1912         const int                                               numElements             = 200;
1913
1914         const struct CaseParams
1915         {
1916                 const char*             name;
1917                 const char*             failMessage;            // customized status message
1918                 qpTestResult    failResult;                     // override status on failure
1919                 bool                    positive;
1920         } cases[] =
1921         {
1922                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    true },
1923                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  false },        // see below
1924         };
1925         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1926
1927         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1928         {
1929                 const CaseParams&       params          = cases[caseNdx];
1930
1931                 ComputeShaderSpec       spec;
1932                 vector<deInt64>         inputInts1      (numElements, 0);
1933                 vector<deInt64>         inputInts2      (numElements, 0);
1934                 vector<deInt64>         outputInts      (numElements, 0);
1935
1936
1937                 if (params.positive)
1938                 {
1939                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements, filterNonNegative);
1940                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterPositive);
1941                 }
1942                 else
1943                 {
1944                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements);
1945                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterNotZero);
1946                 }
1947
1948                 for (int ndx = 0; ndx < numElements; ++ndx)
1949                 {
1950                         deInt64 rem = inputInts1[ndx] % inputInts2[ndx];
1951                         if (rem == 0)
1952                         {
1953                                 outputInts[ndx] = 0;
1954                         }
1955                         else if ((inputInts1[ndx] >= 0) == (inputInts2[ndx] >= 0))
1956                         {
1957                                 // They have the same sign
1958                                 outputInts[ndx] = rem;
1959                         }
1960                         else
1961                         {
1962                                 // They have opposite sign.  The remainder operation takes the
1963                                 // sign inputInts1[ndx] but OpSMod is supposed to take ths sign
1964                                 // of inputInts2[ndx].  Adding inputInts2[ndx] will ensure that
1965                                 // the result has the correct sign and that it is still
1966                                 // congruent to inputInts1[ndx] modulo inputInts2[ndx]
1967                                 //
1968                                 // See also http://mathforum.org/library/drmath/view/52343.html
1969                                 outputInts[ndx] = rem + inputInts2[ndx];
1970                         }
1971                 }
1972
1973                 spec.assembly =
1974                         "OpCapability Int64\n"
1975
1976                         + string(getComputeAsmShaderPreamble()) +
1977
1978                         "OpName %main           \"main\"\n"
1979                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1980
1981                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1982
1983                         "OpDecorate %buf BufferBlock\n"
1984                         "OpDecorate %indata1 DescriptorSet 0\n"
1985                         "OpDecorate %indata1 Binding 0\n"
1986                         "OpDecorate %indata2 DescriptorSet 0\n"
1987                         "OpDecorate %indata2 Binding 1\n"
1988                         "OpDecorate %outdata DescriptorSet 0\n"
1989                         "OpDecorate %outdata Binding 2\n"
1990                         "OpDecorate %i64arr ArrayStride 8\n"
1991                         "OpMemberDecorate %buf 0 Offset 0\n"
1992
1993                         + string(getComputeAsmCommonTypes())
1994                         + string(getComputeAsmCommonInt64Types()) +
1995
1996                         "%buf        = OpTypeStruct %i64arr\n"
1997                         "%bufptr     = OpTypePointer Uniform %buf\n"
1998                         "%indata1    = OpVariable %bufptr Uniform\n"
1999                         "%indata2    = OpVariable %bufptr Uniform\n"
2000                         "%outdata    = OpVariable %bufptr Uniform\n"
2001
2002                         "%id        = OpVariable %uvec3ptr Input\n"
2003                         "%zero      = OpConstant %i64 0\n"
2004
2005                         "%main      = OpFunction %void None %voidf\n"
2006                         "%label     = OpLabel\n"
2007                         "%idval     = OpLoad %uvec3 %id\n"
2008                         "%x         = OpCompositeExtract %u32 %idval 0\n"
2009                         "%inloc1    = OpAccessChain %i64ptr %indata1 %zero %x\n"
2010                         "%inval1    = OpLoad %i64 %inloc1\n"
2011                         "%inloc2    = OpAccessChain %i64ptr %indata2 %zero %x\n"
2012                         "%inval2    = OpLoad %i64 %inloc2\n"
2013                         "%rem       = OpSMod %i64 %inval1 %inval2\n"
2014                         "%outloc    = OpAccessChain %i64ptr %outdata %zero %x\n"
2015                         "             OpStore %outloc %rem\n"
2016                         "             OpReturn\n"
2017                         "             OpFunctionEnd\n";
2018
2019                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts1)));
2020                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts2)));
2021                 spec.outputs.push_back  (BufferSp(new Int64Buffer(outputInts)));
2022                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
2023                 spec.failResult                 = params.failResult;
2024                 spec.failMessage                = params.failMessage;
2025
2026                 spec.requestedVulkanFeatures.coreFeatures.shaderInt64 = VK_TRUE;
2027
2028                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
2029         }
2030
2031         return group.release();
2032 }
2033
2034 // Copy contents in the input buffer to the output buffer.
2035 tcu::TestCaseGroup* createOpCopyMemoryGroup (tcu::TestContext& testCtx)
2036 {
2037         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opcopymemory", "Test the OpCopyMemory instruction"));
2038         de::Random                                              rnd                             (deStringHash(group->getName()));
2039         const int                                               numElements             = 100;
2040
2041         // 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.
2042         ComputeShaderSpec                               spec1;
2043         vector<Vec4>                                    inputFloats1    (numElements);
2044         vector<Vec4>                                    outputFloats1   (numElements);
2045
2046         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats1[0], numElements * 4);
2047
2048         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2049         floorAll(inputFloats1);
2050
2051         for (size_t ndx = 0; ndx < numElements; ++ndx)
2052                 outputFloats1[ndx] = inputFloats1[ndx] + Vec4(0.f, 0.5f, 1.5f, 2.5f);
2053
2054         spec1.assembly =
2055                 string(getComputeAsmShaderPreamble()) +
2056
2057                 "OpName %main           \"main\"\n"
2058                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2059
2060                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2061                 "OpDecorate %vec4arr ArrayStride 16\n"
2062
2063                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2064
2065                 "%vec4       = OpTypeVector %f32 4\n"
2066                 "%vec4ptr_u  = OpTypePointer Uniform %vec4\n"
2067                 "%vec4ptr_f  = OpTypePointer Function %vec4\n"
2068                 "%vec4arr    = OpTypeRuntimeArray %vec4\n"
2069                 "%buf        = OpTypeStruct %vec4arr\n"
2070                 "%bufptr     = OpTypePointer Uniform %buf\n"
2071                 "%indata     = OpVariable %bufptr Uniform\n"
2072                 "%outdata    = OpVariable %bufptr Uniform\n"
2073
2074                 "%id         = OpVariable %uvec3ptr Input\n"
2075                 "%zero       = OpConstant %i32 0\n"
2076                 "%c_f_0      = OpConstant %f32 0.\n"
2077                 "%c_f_0_5    = OpConstant %f32 0.5\n"
2078                 "%c_f_1_5    = OpConstant %f32 1.5\n"
2079                 "%c_f_2_5    = OpConstant %f32 2.5\n"
2080                 "%c_vec4     = OpConstantComposite %vec4 %c_f_0 %c_f_0_5 %c_f_1_5 %c_f_2_5\n"
2081
2082                 "%main       = OpFunction %void None %voidf\n"
2083                 "%label      = OpLabel\n"
2084                 "%v_vec4     = OpVariable %vec4ptr_f Function\n"
2085                 "%idval      = OpLoad %uvec3 %id\n"
2086                 "%x          = OpCompositeExtract %u32 %idval 0\n"
2087                 "%inloc      = OpAccessChain %vec4ptr_u %indata %zero %x\n"
2088                 "%outloc     = OpAccessChain %vec4ptr_u %outdata %zero %x\n"
2089                 "              OpCopyMemory %v_vec4 %inloc\n"
2090                 "%v_vec4_val = OpLoad %vec4 %v_vec4\n"
2091                 "%add        = OpFAdd %vec4 %v_vec4_val %c_vec4\n"
2092                 "              OpStore %outloc %add\n"
2093                 "              OpReturn\n"
2094                 "              OpFunctionEnd\n";
2095
2096         spec1.inputs.push_back(BufferSp(new Vec4Buffer(inputFloats1)));
2097         spec1.outputs.push_back(BufferSp(new Vec4Buffer(outputFloats1)));
2098         spec1.numWorkGroups = IVec3(numElements, 1, 1);
2099
2100         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector", "OpCopyMemory elements of vector type", spec1));
2101
2102         // The following case copies a float[100] variable from the input buffer to the output buffer.
2103         ComputeShaderSpec                               spec2;
2104         vector<float>                                   inputFloats2    (numElements);
2105         vector<float>                                   outputFloats2   (numElements);
2106
2107         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats2[0], numElements);
2108
2109         for (size_t ndx = 0; ndx < numElements; ++ndx)
2110                 outputFloats2[ndx] = inputFloats2[ndx];
2111
2112         spec2.assembly =
2113                 string(getComputeAsmShaderPreamble()) +
2114
2115                 "OpName %main           \"main\"\n"
2116                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2117
2118                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2119                 "OpDecorate %f32arr100 ArrayStride 4\n"
2120
2121                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2122
2123                 "%hundred        = OpConstant %u32 100\n"
2124                 "%f32arr100      = OpTypeArray %f32 %hundred\n"
2125                 "%f32arr100ptr_f = OpTypePointer Function %f32arr100\n"
2126                 "%f32arr100ptr_u = OpTypePointer Uniform %f32arr100\n"
2127                 "%buf            = OpTypeStruct %f32arr100\n"
2128                 "%bufptr         = OpTypePointer Uniform %buf\n"
2129                 "%indata         = OpVariable %bufptr Uniform\n"
2130                 "%outdata        = OpVariable %bufptr Uniform\n"
2131
2132                 "%id             = OpVariable %uvec3ptr Input\n"
2133                 "%zero           = OpConstant %i32 0\n"
2134
2135                 "%main           = OpFunction %void None %voidf\n"
2136                 "%label          = OpLabel\n"
2137                 "%var            = OpVariable %f32arr100ptr_f Function\n"
2138                 "%inarr          = OpAccessChain %f32arr100ptr_u %indata %zero\n"
2139                 "%outarr         = OpAccessChain %f32arr100ptr_u %outdata %zero\n"
2140                 "                  OpCopyMemory %var %inarr\n"
2141                 "                  OpCopyMemory %outarr %var\n"
2142                 "                  OpReturn\n"
2143                 "                  OpFunctionEnd\n";
2144
2145         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
2146         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
2147         spec2.numWorkGroups = IVec3(1, 1, 1);
2148
2149         group->addChild(new SpvAsmComputeShaderCase(testCtx, "array", "OpCopyMemory elements of array type", spec2));
2150
2151         // The following case copies a struct{vec4, vec4, vec4, vec4} variable from the input buffer to the output buffer.
2152         ComputeShaderSpec                               spec3;
2153         vector<float>                                   inputFloats3    (16);
2154         vector<float>                                   outputFloats3   (16);
2155
2156         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats3[0], 16);
2157
2158         for (size_t ndx = 0; ndx < 16; ++ndx)
2159                 outputFloats3[ndx] = inputFloats3[ndx];
2160
2161         spec3.assembly =
2162                 string(getComputeAsmShaderPreamble()) +
2163
2164                 "OpName %main           \"main\"\n"
2165                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2166
2167                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2168                 //"OpMemberDecorate %buf 0 Offset 0\n"  - exists in getComputeAsmInputOutputBufferTraits
2169                 "OpMemberDecorate %buf 1 Offset 16\n"
2170                 "OpMemberDecorate %buf 2 Offset 32\n"
2171                 "OpMemberDecorate %buf 3 Offset 48\n"
2172
2173                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2174
2175                 "%vec4      = OpTypeVector %f32 4\n"
2176                 "%buf       = OpTypeStruct %vec4 %vec4 %vec4 %vec4\n"
2177                 "%bufptr    = OpTypePointer Uniform %buf\n"
2178                 "%indata    = OpVariable %bufptr Uniform\n"
2179                 "%outdata   = OpVariable %bufptr Uniform\n"
2180                 "%vec4stptr = OpTypePointer Function %buf\n"
2181
2182                 "%id        = OpVariable %uvec3ptr Input\n"
2183                 "%zero      = OpConstant %i32 0\n"
2184
2185                 "%main      = OpFunction %void None %voidf\n"
2186                 "%label     = OpLabel\n"
2187                 "%var       = OpVariable %vec4stptr Function\n"
2188                 "             OpCopyMemory %var %indata\n"
2189                 "             OpCopyMemory %outdata %var\n"
2190                 "             OpReturn\n"
2191                 "             OpFunctionEnd\n";
2192
2193         spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
2194         spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
2195         spec3.numWorkGroups = IVec3(1, 1, 1);
2196
2197         group->addChild(new SpvAsmComputeShaderCase(testCtx, "struct", "OpCopyMemory elements of struct type", spec3));
2198
2199         // The following case negates multiple float variables from the input buffer and stores the results to the output buffer.
2200         ComputeShaderSpec                               spec4;
2201         vector<float>                                   inputFloats4    (numElements);
2202         vector<float>                                   outputFloats4   (numElements);
2203
2204         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats4[0], numElements);
2205
2206         for (size_t ndx = 0; ndx < numElements; ++ndx)
2207                 outputFloats4[ndx] = -inputFloats4[ndx];
2208
2209         spec4.assembly =
2210                 string(getComputeAsmShaderPreamble()) +
2211
2212                 "OpName %main           \"main\"\n"
2213                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2214
2215                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2216
2217                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2218
2219                 "%f32ptr_f  = OpTypePointer Function %f32\n"
2220                 "%id        = OpVariable %uvec3ptr Input\n"
2221                 "%zero      = OpConstant %i32 0\n"
2222
2223                 "%main      = OpFunction %void None %voidf\n"
2224                 "%label     = OpLabel\n"
2225                 "%var       = OpVariable %f32ptr_f Function\n"
2226                 "%idval     = OpLoad %uvec3 %id\n"
2227                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2228                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
2229                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
2230                 "             OpCopyMemory %var %inloc\n"
2231                 "%val       = OpLoad %f32 %var\n"
2232                 "%neg       = OpFNegate %f32 %val\n"
2233                 "             OpStore %outloc %neg\n"
2234                 "             OpReturn\n"
2235                 "             OpFunctionEnd\n";
2236
2237         spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
2238         spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
2239         spec4.numWorkGroups = IVec3(numElements, 1, 1);
2240
2241         group->addChild(new SpvAsmComputeShaderCase(testCtx, "float", "OpCopyMemory elements of float type", spec4));
2242
2243         return group.release();
2244 }
2245
2246 tcu::TestCaseGroup* createOpCopyObjectGroup (tcu::TestContext& testCtx)
2247 {
2248         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opcopyobject", "Test the OpCopyObject instruction"));
2249         ComputeShaderSpec                               spec;
2250         de::Random                                              rnd                             (deStringHash(group->getName()));
2251         const int                                               numElements             = 100;
2252         vector<float>                                   inputFloats             (numElements, 0);
2253         vector<float>                                   outputFloats    (numElements, 0);
2254
2255         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
2256
2257         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2258         floorAll(inputFloats);
2259
2260         for (size_t ndx = 0; ndx < numElements; ++ndx)
2261                 outputFloats[ndx] = inputFloats[ndx] + 7.5f;
2262
2263         spec.assembly =
2264                 string(getComputeAsmShaderPreamble()) +
2265
2266                 "OpName %main           \"main\"\n"
2267                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2268
2269                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2270
2271                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2272
2273                 "%fmat     = OpTypeMatrix %fvec3 3\n"
2274                 "%three    = OpConstant %u32 3\n"
2275                 "%farr     = OpTypeArray %f32 %three\n"
2276                 "%fst      = OpTypeStruct %f32 %f32\n"
2277
2278                 + string(getComputeAsmInputOutputBuffer()) +
2279
2280                 "%id            = OpVariable %uvec3ptr Input\n"
2281                 "%zero          = OpConstant %i32 0\n"
2282                 "%c_f           = OpConstant %f32 1.5\n"
2283                 "%c_fvec3       = OpConstantComposite %fvec3 %c_f %c_f %c_f\n"
2284                 "%c_fmat        = OpConstantComposite %fmat %c_fvec3 %c_fvec3 %c_fvec3\n"
2285                 "%c_farr        = OpConstantComposite %farr %c_f %c_f %c_f\n"
2286                 "%c_fst         = OpConstantComposite %fst %c_f %c_f\n"
2287
2288                 "%main          = OpFunction %void None %voidf\n"
2289                 "%label         = OpLabel\n"
2290                 "%c_f_copy      = OpCopyObject %f32   %c_f\n"
2291                 "%c_fvec3_copy  = OpCopyObject %fvec3 %c_fvec3\n"
2292                 "%c_fmat_copy   = OpCopyObject %fmat  %c_fmat\n"
2293                 "%c_farr_copy   = OpCopyObject %farr  %c_farr\n"
2294                 "%c_fst_copy    = OpCopyObject %fst   %c_fst\n"
2295                 "%fvec3_elem    = OpCompositeExtract %f32 %c_fvec3_copy 0\n"
2296                 "%fmat_elem     = OpCompositeExtract %f32 %c_fmat_copy 1 2\n"
2297                 "%farr_elem     = OpCompositeExtract %f32 %c_farr_copy 2\n"
2298                 "%fst_elem      = OpCompositeExtract %f32 %c_fst_copy 1\n"
2299                 // Add up. 1.5 * 5 = 7.5.
2300                 "%add1          = OpFAdd %f32 %c_f_copy %fvec3_elem\n"
2301                 "%add2          = OpFAdd %f32 %add1     %fmat_elem\n"
2302                 "%add3          = OpFAdd %f32 %add2     %farr_elem\n"
2303                 "%add4          = OpFAdd %f32 %add3     %fst_elem\n"
2304
2305                 "%idval         = OpLoad %uvec3 %id\n"
2306                 "%x             = OpCompositeExtract %u32 %idval 0\n"
2307                 "%inloc         = OpAccessChain %f32ptr %indata %zero %x\n"
2308                 "%outloc        = OpAccessChain %f32ptr %outdata %zero %x\n"
2309                 "%inval         = OpLoad %f32 %inloc\n"
2310                 "%add           = OpFAdd %f32 %add4 %inval\n"
2311                 "                 OpStore %outloc %add\n"
2312                 "                 OpReturn\n"
2313                 "                 OpFunctionEnd\n";
2314         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2315         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2316         spec.numWorkGroups = IVec3(numElements, 1, 1);
2317
2318         group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "OpCopyObject on different types", spec));
2319
2320         return group.release();
2321 }
2322 // Assembly code used for testing OpUnreachable is based on GLSL source code:
2323 //
2324 // #version 430
2325 //
2326 // layout(std140, set = 0, binding = 0) readonly buffer Input {
2327 //   float elements[];
2328 // } input_data;
2329 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
2330 //   float elements[];
2331 // } output_data;
2332 //
2333 // void not_called_func() {
2334 //   // place OpUnreachable here
2335 // }
2336 //
2337 // uint modulo4(uint val) {
2338 //   switch (val % uint(4)) {
2339 //     case 0:  return 3;
2340 //     case 1:  return 2;
2341 //     case 2:  return 1;
2342 //     case 3:  return 0;
2343 //     default: return 100; // place OpUnreachable here
2344 //   }
2345 // }
2346 //
2347 // uint const5() {
2348 //   return 5;
2349 //   // place OpUnreachable here
2350 // }
2351 //
2352 // void main() {
2353 //   uint x = gl_GlobalInvocationID.x;
2354 //   if (const5() > modulo4(1000)) {
2355 //     output_data.elements[x] = -input_data.elements[x];
2356 //   } else {
2357 //     // place OpUnreachable here
2358 //     output_data.elements[x] = input_data.elements[x];
2359 //   }
2360 // }
2361
2362 tcu::TestCaseGroup* createOpUnreachableGroup (tcu::TestContext& testCtx)
2363 {
2364         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opunreachable", "Test the OpUnreachable instruction"));
2365         ComputeShaderSpec                               spec;
2366         de::Random                                              rnd                             (deStringHash(group->getName()));
2367         const int                                               numElements             = 100;
2368         vector<float>                                   positiveFloats  (numElements, 0);
2369         vector<float>                                   negativeFloats  (numElements, 0);
2370
2371         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
2372
2373         for (size_t ndx = 0; ndx < numElements; ++ndx)
2374                 negativeFloats[ndx] = -positiveFloats[ndx];
2375
2376         spec.assembly =
2377                 string(getComputeAsmShaderPreamble()) +
2378
2379                 "OpSource GLSL 430\n"
2380                 "OpName %main            \"main\"\n"
2381                 "OpName %func_not_called_func \"not_called_func(\"\n"
2382                 "OpName %func_modulo4         \"modulo4(u1;\"\n"
2383                 "OpName %func_const5          \"const5(\"\n"
2384                 "OpName %id                   \"gl_GlobalInvocationID\"\n"
2385
2386                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2387
2388                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2389
2390                 "%u32ptr    = OpTypePointer Function %u32\n"
2391                 "%uintfuint = OpTypeFunction %u32 %u32ptr\n"
2392                 "%unitf     = OpTypeFunction %u32\n"
2393
2394                 "%id        = OpVariable %uvec3ptr Input\n"
2395                 "%zero      = OpConstant %u32 0\n"
2396                 "%one       = OpConstant %u32 1\n"
2397                 "%two       = OpConstant %u32 2\n"
2398                 "%three     = OpConstant %u32 3\n"
2399                 "%four      = OpConstant %u32 4\n"
2400                 "%five      = OpConstant %u32 5\n"
2401                 "%hundred   = OpConstant %u32 100\n"
2402                 "%thousand  = OpConstant %u32 1000\n"
2403
2404                 + string(getComputeAsmInputOutputBuffer()) +
2405
2406                 // Main()
2407                 "%main   = OpFunction %void None %voidf\n"
2408                 "%main_entry  = OpLabel\n"
2409                 "%v_thousand  = OpVariable %u32ptr Function %thousand\n"
2410                 "%idval       = OpLoad %uvec3 %id\n"
2411                 "%x           = OpCompositeExtract %u32 %idval 0\n"
2412                 "%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
2413                 "%inval       = OpLoad %f32 %inloc\n"
2414                 "%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
2415                 "%ret_const5  = OpFunctionCall %u32 %func_const5\n"
2416                 "%ret_modulo4 = OpFunctionCall %u32 %func_modulo4 %v_thousand\n"
2417                 "%cmp_gt      = OpUGreaterThan %bool %ret_const5 %ret_modulo4\n"
2418                 "               OpSelectionMerge %if_end None\n"
2419                 "               OpBranchConditional %cmp_gt %if_true %if_false\n"
2420                 "%if_true     = OpLabel\n"
2421                 "%negate      = OpFNegate %f32 %inval\n"
2422                 "               OpStore %outloc %negate\n"
2423                 "               OpBranch %if_end\n"
2424                 "%if_false    = OpLabel\n"
2425                 "               OpUnreachable\n" // Unreachable else branch for if statement
2426                 "%if_end      = OpLabel\n"
2427                 "               OpReturn\n"
2428                 "               OpFunctionEnd\n"
2429
2430                 // not_called_function()
2431                 "%func_not_called_func  = OpFunction %void None %voidf\n"
2432                 "%not_called_func_entry = OpLabel\n"
2433                 "                         OpUnreachable\n" // Unreachable entry block in not called static function
2434                 "                         OpFunctionEnd\n"
2435
2436                 // modulo4()
2437                 "%func_modulo4  = OpFunction %u32 None %uintfuint\n"
2438                 "%valptr        = OpFunctionParameter %u32ptr\n"
2439                 "%modulo4_entry = OpLabel\n"
2440                 "%val           = OpLoad %u32 %valptr\n"
2441                 "%modulo        = OpUMod %u32 %val %four\n"
2442                 "                 OpSelectionMerge %switch_merge None\n"
2443                 "                 OpSwitch %modulo %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
2444                 "%case0         = OpLabel\n"
2445                 "                 OpReturnValue %three\n"
2446                 "%case1         = OpLabel\n"
2447                 "                 OpReturnValue %two\n"
2448                 "%case2         = OpLabel\n"
2449                 "                 OpReturnValue %one\n"
2450                 "%case3         = OpLabel\n"
2451                 "                 OpReturnValue %zero\n"
2452                 "%default       = OpLabel\n"
2453                 "                 OpUnreachable\n" // Unreachable default case for switch statement
2454                 "%switch_merge  = OpLabel\n"
2455                 "                 OpUnreachable\n" // Unreachable merge block for switch statement
2456                 "                 OpFunctionEnd\n"
2457
2458                 // const5()
2459                 "%func_const5  = OpFunction %u32 None %unitf\n"
2460                 "%const5_entry = OpLabel\n"
2461                 "                OpReturnValue %five\n"
2462                 "%unreachable  = OpLabel\n"
2463                 "                OpUnreachable\n" // Unreachable block in function
2464                 "                OpFunctionEnd\n";
2465         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
2466         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
2467         spec.numWorkGroups = IVec3(numElements, 1, 1);
2468
2469         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpUnreachable appearing at different places", spec));
2470
2471         return group.release();
2472 }
2473
2474 // Assembly code used for testing decoration group is based on GLSL source code:
2475 //
2476 // #version 430
2477 //
2478 // layout(std140, set = 0, binding = 0) readonly buffer Input0 {
2479 //   float elements[];
2480 // } input_data0;
2481 // layout(std140, set = 0, binding = 1) readonly buffer Input1 {
2482 //   float elements[];
2483 // } input_data1;
2484 // layout(std140, set = 0, binding = 2) readonly buffer Input2 {
2485 //   float elements[];
2486 // } input_data2;
2487 // layout(std140, set = 0, binding = 3) readonly buffer Input3 {
2488 //   float elements[];
2489 // } input_data3;
2490 // layout(std140, set = 0, binding = 4) readonly buffer Input4 {
2491 //   float elements[];
2492 // } input_data4;
2493 // layout(std140, set = 0, binding = 5) writeonly buffer Output {
2494 //   float elements[];
2495 // } output_data;
2496 //
2497 // void main() {
2498 //   uint x = gl_GlobalInvocationID.x;
2499 //   output_data.elements[x] = input_data0.elements[x] + input_data1.elements[x] + input_data2.elements[x] + input_data3.elements[x] + input_data4.elements[x];
2500 // }
2501 tcu::TestCaseGroup* createDecorationGroupGroup (tcu::TestContext& testCtx)
2502 {
2503         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "decoration_group", "Test the OpDecorationGroup & OpGroupDecorate instruction"));
2504         ComputeShaderSpec                               spec;
2505         de::Random                                              rnd                             (deStringHash(group->getName()));
2506         const int                                               numElements             = 100;
2507         vector<float>                                   inputFloats0    (numElements, 0);
2508         vector<float>                                   inputFloats1    (numElements, 0);
2509         vector<float>                                   inputFloats2    (numElements, 0);
2510         vector<float>                                   inputFloats3    (numElements, 0);
2511         vector<float>                                   inputFloats4    (numElements, 0);
2512         vector<float>                                   outputFloats    (numElements, 0);
2513
2514         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats0[0], numElements);
2515         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats1[0], numElements);
2516         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats2[0], numElements);
2517         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats3[0], numElements);
2518         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats4[0], numElements);
2519
2520         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2521         floorAll(inputFloats0);
2522         floorAll(inputFloats1);
2523         floorAll(inputFloats2);
2524         floorAll(inputFloats3);
2525         floorAll(inputFloats4);
2526
2527         for (size_t ndx = 0; ndx < numElements; ++ndx)
2528                 outputFloats[ndx] = inputFloats0[ndx] + inputFloats1[ndx] + inputFloats2[ndx] + inputFloats3[ndx] + inputFloats4[ndx];
2529
2530         spec.assembly =
2531                 string(getComputeAsmShaderPreamble()) +
2532
2533                 "OpSource GLSL 430\n"
2534                 "OpName %main \"main\"\n"
2535                 "OpName %id \"gl_GlobalInvocationID\"\n"
2536
2537                 // Not using group decoration on variable.
2538                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2539                 // Not using group decoration on type.
2540                 "OpDecorate %f32arr ArrayStride 4\n"
2541
2542                 "OpDecorate %groups BufferBlock\n"
2543                 "OpDecorate %groupm Offset 0\n"
2544                 "%groups = OpDecorationGroup\n"
2545                 "%groupm = OpDecorationGroup\n"
2546
2547                 // Group decoration on multiple structs.
2548                 "OpGroupDecorate %groups %outbuf %inbuf0 %inbuf1 %inbuf2 %inbuf3 %inbuf4\n"
2549                 // Group decoration on multiple struct members.
2550                 "OpGroupMemberDecorate %groupm %outbuf 0 %inbuf0 0 %inbuf1 0 %inbuf2 0 %inbuf3 0 %inbuf4 0\n"
2551
2552                 "OpDecorate %group1 DescriptorSet 0\n"
2553                 "OpDecorate %group3 DescriptorSet 0\n"
2554                 "OpDecorate %group3 NonWritable\n"
2555                 "OpDecorate %group3 Restrict\n"
2556                 "%group0 = OpDecorationGroup\n"
2557                 "%group1 = OpDecorationGroup\n"
2558                 "%group3 = OpDecorationGroup\n"
2559
2560                 // Applying the same decoration group multiple times.
2561                 "OpGroupDecorate %group1 %outdata\n"
2562                 "OpGroupDecorate %group1 %outdata\n"
2563                 "OpGroupDecorate %group1 %outdata\n"
2564                 "OpDecorate %outdata DescriptorSet 0\n"
2565                 "OpDecorate %outdata Binding 5\n"
2566                 // Applying decoration group containing nothing.
2567                 "OpGroupDecorate %group0 %indata0\n"
2568                 "OpDecorate %indata0 DescriptorSet 0\n"
2569                 "OpDecorate %indata0 Binding 0\n"
2570                 // Applying decoration group containing one decoration.
2571                 "OpGroupDecorate %group1 %indata1\n"
2572                 "OpDecorate %indata1 Binding 1\n"
2573                 // Applying decoration group containing multiple decorations.
2574                 "OpGroupDecorate %group3 %indata2 %indata3\n"
2575                 "OpDecorate %indata2 Binding 2\n"
2576                 "OpDecorate %indata3 Binding 3\n"
2577                 // Applying multiple decoration groups (with overlapping).
2578                 "OpGroupDecorate %group0 %indata4\n"
2579                 "OpGroupDecorate %group1 %indata4\n"
2580                 "OpGroupDecorate %group3 %indata4\n"
2581                 "OpDecorate %indata4 Binding 4\n"
2582
2583                 + string(getComputeAsmCommonTypes()) +
2584
2585                 "%id   = OpVariable %uvec3ptr Input\n"
2586                 "%zero = OpConstant %i32 0\n"
2587
2588                 "%outbuf    = OpTypeStruct %f32arr\n"
2589                 "%outbufptr = OpTypePointer Uniform %outbuf\n"
2590                 "%outdata   = OpVariable %outbufptr Uniform\n"
2591                 "%inbuf0    = OpTypeStruct %f32arr\n"
2592                 "%inbuf0ptr = OpTypePointer Uniform %inbuf0\n"
2593                 "%indata0   = OpVariable %inbuf0ptr Uniform\n"
2594                 "%inbuf1    = OpTypeStruct %f32arr\n"
2595                 "%inbuf1ptr = OpTypePointer Uniform %inbuf1\n"
2596                 "%indata1   = OpVariable %inbuf1ptr Uniform\n"
2597                 "%inbuf2    = OpTypeStruct %f32arr\n"
2598                 "%inbuf2ptr = OpTypePointer Uniform %inbuf2\n"
2599                 "%indata2   = OpVariable %inbuf2ptr Uniform\n"
2600                 "%inbuf3    = OpTypeStruct %f32arr\n"
2601                 "%inbuf3ptr = OpTypePointer Uniform %inbuf3\n"
2602                 "%indata3   = OpVariable %inbuf3ptr Uniform\n"
2603                 "%inbuf4    = OpTypeStruct %f32arr\n"
2604                 "%inbufptr  = OpTypePointer Uniform %inbuf4\n"
2605                 "%indata4   = OpVariable %inbufptr Uniform\n"
2606
2607                 "%main   = OpFunction %void None %voidf\n"
2608                 "%label  = OpLabel\n"
2609                 "%idval  = OpLoad %uvec3 %id\n"
2610                 "%x      = OpCompositeExtract %u32 %idval 0\n"
2611                 "%inloc0 = OpAccessChain %f32ptr %indata0 %zero %x\n"
2612                 "%inloc1 = OpAccessChain %f32ptr %indata1 %zero %x\n"
2613                 "%inloc2 = OpAccessChain %f32ptr %indata2 %zero %x\n"
2614                 "%inloc3 = OpAccessChain %f32ptr %indata3 %zero %x\n"
2615                 "%inloc4 = OpAccessChain %f32ptr %indata4 %zero %x\n"
2616                 "%outloc = OpAccessChain %f32ptr %outdata %zero %x\n"
2617                 "%inval0 = OpLoad %f32 %inloc0\n"
2618                 "%inval1 = OpLoad %f32 %inloc1\n"
2619                 "%inval2 = OpLoad %f32 %inloc2\n"
2620                 "%inval3 = OpLoad %f32 %inloc3\n"
2621                 "%inval4 = OpLoad %f32 %inloc4\n"
2622                 "%add0   = OpFAdd %f32 %inval0 %inval1\n"
2623                 "%add1   = OpFAdd %f32 %add0 %inval2\n"
2624                 "%add2   = OpFAdd %f32 %add1 %inval3\n"
2625                 "%add    = OpFAdd %f32 %add2 %inval4\n"
2626                 "          OpStore %outloc %add\n"
2627                 "          OpReturn\n"
2628                 "          OpFunctionEnd\n";
2629         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats0)));
2630         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
2631         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
2632         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
2633         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
2634         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2635         spec.numWorkGroups = IVec3(numElements, 1, 1);
2636
2637         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "decoration group cases", spec));
2638
2639         return group.release();
2640 }
2641
2642 struct SpecConstantTwoIntCase
2643 {
2644         const char*             caseName;
2645         const char*             scDefinition0;
2646         const char*             scDefinition1;
2647         const char*             scResultType;
2648         const char*             scOperation;
2649         deInt32                 scActualValue0;
2650         deInt32                 scActualValue1;
2651         const char*             resultOperation;
2652         vector<deInt32> expectedOutput;
2653         deInt32                 scActualValueLength;
2654
2655                                         SpecConstantTwoIntCase (const char* name,
2656                                                                                         const char* definition0,
2657                                                                                         const char* definition1,
2658                                                                                         const char* resultType,
2659                                                                                         const char* operation,
2660                                                                                         deInt32 value0,
2661                                                                                         deInt32 value1,
2662                                                                                         const char* resultOp,
2663                                                                                         const vector<deInt32>& output,
2664                                                                                         const deInt32   valueLength = sizeof(deInt32))
2665                                                 : caseName                              (name)
2666                                                 , scDefinition0                 (definition0)
2667                                                 , scDefinition1                 (definition1)
2668                                                 , scResultType                  (resultType)
2669                                                 , scOperation                   (operation)
2670                                                 , scActualValue0                (value0)
2671                                                 , scActualValue1                (value1)
2672                                                 , resultOperation               (resultOp)
2673                                                 , expectedOutput                (output)
2674                                                 , scActualValueLength   (valueLength)
2675                                                 {}
2676 };
2677
2678 tcu::TestCaseGroup* createSpecConstantGroup (tcu::TestContext& testCtx)
2679 {
2680         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
2681         vector<SpecConstantTwoIntCase>  cases;
2682         de::Random                                              rnd                             (deStringHash(group->getName()));
2683         const int                                               numElements             = 100;
2684         const deInt32                                   p1AsFloat16             = 0x3c00; // +1(fp16) == 0 01111 0000000000 == 0011 1100 0000 0000
2685         vector<deInt32>                                 inputInts               (numElements, 0);
2686         vector<deInt32>                                 outputInts1             (numElements, 0);
2687         vector<deInt32>                                 outputInts2             (numElements, 0);
2688         vector<deInt32>                                 outputInts3             (numElements, 0);
2689         vector<deInt32>                                 outputInts4             (numElements, 0);
2690         const StringTemplate                    shaderTemplate  (
2691                 "${CAPABILITIES:opt}"
2692                 + string(getComputeAsmShaderPreamble()) +
2693
2694                 "OpName %main           \"main\"\n"
2695                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2696
2697                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2698                 "OpDecorate %sc_0  SpecId 0\n"
2699                 "OpDecorate %sc_1  SpecId 1\n"
2700                 "OpDecorate %i32arr ArrayStride 4\n"
2701
2702                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2703
2704                 "${OPTYPE_DEFINITIONS:opt}"
2705                 "%buf     = OpTypeStruct %i32arr\n"
2706                 "%bufptr  = OpTypePointer Uniform %buf\n"
2707                 "%indata    = OpVariable %bufptr Uniform\n"
2708                 "%outdata   = OpVariable %bufptr Uniform\n"
2709
2710                 "%id        = OpVariable %uvec3ptr Input\n"
2711                 "%zero      = OpConstant %i32 0\n"
2712
2713                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
2714                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
2715                 "%sc_final  = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n"
2716
2717                 "%main      = OpFunction %void None %voidf\n"
2718                 "%label     = OpLabel\n"
2719                 "${TYPE_CONVERT:opt}"
2720                 "%idval     = OpLoad %uvec3 %id\n"
2721                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2722                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
2723                 "%inval     = OpLoad %i32 %inloc\n"
2724                 "%final     = ${GEN_RESULT}\n"
2725                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2726                 "             OpStore %outloc %final\n"
2727                 "             OpReturn\n"
2728                 "             OpFunctionEnd\n");
2729
2730         fillRandomScalars(rnd, -65536, 65536, &inputInts[0], numElements);
2731
2732         for (size_t ndx = 0; ndx < numElements; ++ndx)
2733         {
2734                 outputInts1[ndx] = inputInts[ndx] + 42;
2735                 outputInts2[ndx] = inputInts[ndx];
2736                 outputInts3[ndx] = inputInts[ndx] - 11200;
2737                 outputInts4[ndx] = inputInts[ndx] + 1;
2738         }
2739
2740         const char addScToInput[]               = "OpIAdd %i32 %inval %sc_final";
2741         const char addSc32ToInput[]             = "OpIAdd %i32 %inval %sc_final32";
2742         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_final %inval %zero";
2743         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_final %zero %inval";
2744
2745         cases.push_back(SpecConstantTwoIntCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                     62,             -20,    addScToInput,           outputInts1));
2746         cases.push_back(SpecConstantTwoIntCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                     100,    58,             addScToInput,           outputInts1));
2747         cases.push_back(SpecConstantTwoIntCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                     -2,             -21,    addScToInput,           outputInts1));
2748         cases.push_back(SpecConstantTwoIntCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                     -126,   -3,             addScToInput,           outputInts1));
2749         cases.push_back(SpecConstantTwoIntCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                     126,    3,              addScToInput,           outputInts1));
2750         cases.push_back(SpecConstantTwoIntCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
2751         cases.push_back(SpecConstantTwoIntCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
2752         cases.push_back(SpecConstantTwoIntCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                     342,    50,             addScToInput,           outputInts1));
2753         cases.push_back(SpecConstantTwoIntCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                     42,             63,             addScToInput,           outputInts1));
2754         cases.push_back(SpecConstantTwoIntCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                     34,             8,              addScToInput,           outputInts1));
2755         cases.push_back(SpecConstantTwoIntCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                     18,             56,             addScToInput,           outputInts1));
2756         cases.push_back(SpecConstantTwoIntCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
2757         cases.push_back(SpecConstantTwoIntCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
2758         cases.push_back(SpecConstantTwoIntCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                     21,             1,              addScToInput,           outputInts1));
2759         cases.push_back(SpecConstantTwoIntCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                     -20,    -10,    selectTrueUsingSc,      outputInts2));
2760         cases.push_back(SpecConstantTwoIntCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                     10,             20,             selectTrueUsingSc,      outputInts2));
2761         cases.push_back(SpecConstantTwoIntCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
2762         cases.push_back(SpecConstantTwoIntCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                     10,             5,              selectTrueUsingSc,      outputInts2));
2763         cases.push_back(SpecConstantTwoIntCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                     -10,    -10,    selectTrueUsingSc,      outputInts2));
2764         cases.push_back(SpecConstantTwoIntCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                     50,             100,    selectTrueUsingSc,      outputInts2));
2765         cases.push_back(SpecConstantTwoIntCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
2766         cases.push_back(SpecConstantTwoIntCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                     10,             10,             selectTrueUsingSc,      outputInts2));
2767         cases.push_back(SpecConstantTwoIntCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                     42,             24,             selectFalseUsingSc,     outputInts2));
2768         cases.push_back(SpecConstantTwoIntCase("inotequal",                             " %i32 0",              " %i32 0",              "%bool",        "INotEqual            %sc_0 %sc_1",                     42,             24,             selectTrueUsingSc,      outputInts2));
2769         cases.push_back(SpecConstantTwoIntCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
2770         cases.push_back(SpecConstantTwoIntCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
2771         cases.push_back(SpecConstantTwoIntCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
2772         cases.push_back(SpecConstantTwoIntCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
2773         cases.push_back(SpecConstantTwoIntCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                           -42,    0,              addScToInput,           outputInts1));
2774         cases.push_back(SpecConstantTwoIntCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                           -43,    0,              addScToInput,           outputInts1));
2775         cases.push_back(SpecConstantTwoIntCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                           1,              0,              selectFalseUsingSc,     outputInts2));
2776         cases.push_back(SpecConstantTwoIntCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %zero",       1,              42,             addScToInput,           outputInts1));
2777         cases.push_back(SpecConstantTwoIntCase("sconvert",                              " %i32 0",              " %i32 0",              "%i16",         "SConvert             %sc_0",                           -11200, 0,              addSc32ToInput,         outputInts3));
2778         // -969998336 stored as 32-bit two's complement is the binary representation of -11200 as IEEE-754 Float
2779         cases.push_back(SpecConstantTwoIntCase("fconvert",                              " %f32 0",              " %f32 0",              "%f64",         "FConvert             %sc_0",                           -969998336, 0,  addSc32ToInput,         outputInts3));
2780         cases.push_back(SpecConstantTwoIntCase("fconvert16",                    " %f16 0",              " %f16 0",              "%f32",         "FConvert             %sc_0",                           p1AsFloat16, 0, addSc32ToInput,         outputInts4, sizeof(deFloat16)));
2781
2782         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
2783         {
2784                 map<string, string>             specializations;
2785                 ComputeShaderSpec               spec;
2786
2787                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
2788                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
2789                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
2790                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
2791                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
2792
2793                 // Special SPIR-V code for SConvert-case
2794                 if (strcmp(cases[caseNdx].caseName, "sconvert") == 0)
2795                 {
2796                         spec.requestedVulkanFeatures.coreFeatures.shaderInt16   = VK_TRUE;
2797                         specializations["CAPABILITIES"]                                                 = "OpCapability Int16\n";                                                       // Adds 16-bit integer capability
2798                         specializations["OPTYPE_DEFINITIONS"]                                   = "%i16 = OpTypeInt 16 1\n";                                            // Adds 16-bit integer type
2799                         specializations["TYPE_CONVERT"]                                                 = "%sc_final32 = OpSConvert %i32 %sc_final\n";          // Converts 16-bit integer to 32-bit integer
2800                 }
2801
2802                 // Special SPIR-V code for FConvert-case
2803                 if (strcmp(cases[caseNdx].caseName, "fconvert") == 0)
2804                 {
2805                         spec.requestedVulkanFeatures.coreFeatures.shaderFloat64 = VK_TRUE;
2806                         specializations["CAPABILITIES"]                                                 = "OpCapability Float64\n";                                                     // Adds 64-bit float capability
2807                         specializations["OPTYPE_DEFINITIONS"]                                   = "%f64 = OpTypeFloat 64\n";                                            // Adds 64-bit float type
2808                         specializations["TYPE_CONVERT"]                                                 = "%sc_final32 = OpConvertFToS %i32 %sc_final\n";       // Converts 64-bit float to 32-bit integer
2809                 }
2810
2811                 // Special SPIR-V code for FConvert-case for 16-bit floats
2812                 if (strcmp(cases[caseNdx].caseName, "fconvert16") == 0)
2813                 {
2814                         spec.extensions.push_back("VK_KHR_shader_float16_int8");
2815                         spec.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
2816                         specializations["CAPABILITIES"]                 = "OpCapability Float16\n";                                                     // Adds 16-bit float capability
2817                         specializations["OPTYPE_DEFINITIONS"]   = "%f16 = OpTypeFloat 16\n";                                            // Adds 16-bit float type
2818                         specializations["TYPE_CONVERT"]                 = "%sc_final32 = OpConvertFToS %i32 %sc_final\n";       // Converts 16-bit float to 32-bit integer
2819                 }
2820
2821                 spec.assembly = shaderTemplate.specialize(specializations);
2822                 spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
2823                 spec.outputs.push_back(BufferSp(new Int32Buffer(cases[caseNdx].expectedOutput)));
2824                 spec.numWorkGroups = IVec3(numElements, 1, 1);
2825                 spec.specConstants.append(&cases[caseNdx].scActualValue0, cases[caseNdx].scActualValueLength);
2826                 spec.specConstants.append(&cases[caseNdx].scActualValue1, cases[caseNdx].scActualValueLength);
2827
2828                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].caseName, cases[caseNdx].caseName, spec));
2829         }
2830
2831         ComputeShaderSpec                               spec;
2832
2833         spec.assembly =
2834                 string(getComputeAsmShaderPreamble()) +
2835
2836                 "OpName %main           \"main\"\n"
2837                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2838
2839                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2840                 "OpDecorate %sc_0  SpecId 0\n"
2841                 "OpDecorate %sc_1  SpecId 1\n"
2842                 "OpDecorate %sc_2  SpecId 2\n"
2843                 "OpDecorate %i32arr ArrayStride 4\n"
2844
2845                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2846
2847                 "%ivec3       = OpTypeVector %i32 3\n"
2848                 "%buf         = OpTypeStruct %i32arr\n"
2849                 "%bufptr      = OpTypePointer Uniform %buf\n"
2850                 "%indata      = OpVariable %bufptr Uniform\n"
2851                 "%outdata     = OpVariable %bufptr Uniform\n"
2852
2853                 "%id          = OpVariable %uvec3ptr Input\n"
2854                 "%zero        = OpConstant %i32 0\n"
2855                 "%ivec3_0     = OpConstantComposite %ivec3 %zero %zero %zero\n"
2856                 "%vec3_undef  = OpUndef %ivec3\n"
2857
2858                 "%sc_0        = OpSpecConstant %i32 0\n"
2859                 "%sc_1        = OpSpecConstant %i32 0\n"
2860                 "%sc_2        = OpSpecConstant %i32 0\n"
2861                 "%sc_vec3_0   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_0        %ivec3_0     0\n"                                                 // (sc_0, 0, 0)
2862                 "%sc_vec3_1   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_1        %ivec3_0     1\n"                                                 // (0, sc_1, 0)
2863                 "%sc_vec3_2   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_2        %ivec3_0     2\n"                                                 // (0, 0, sc_2)
2864                 "%sc_vec3_0_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0   %vec3_undef  0          0xFFFFFFFF 2\n"   // (sc_0, ???,  0)
2865                 "%sc_vec3_1_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_1   %vec3_undef  0xFFFFFFFF 1          0\n"   // (???,  sc_1, 0)
2866                 "%sc_vec3_2_s = OpSpecConstantOp %ivec3 VectorShuffle    %vec3_undef  %sc_vec3_2   5          0xFFFFFFFF 5\n"   // (sc_2, ???,  sc_2)
2867                 "%sc_vec3_01  = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0_s %sc_vec3_1_s 1 0 4\n"                                             // (0,    sc_0, sc_1)
2868                 "%sc_vec3_012 = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_01  %sc_vec3_2_s 5 1 2\n"                                             // (sc_2, sc_0, sc_1)
2869                 "%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              0\n"                                                 // sc_2
2870                 "%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              1\n"                                                 // sc_0
2871                 "%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              2\n"                                                 // sc_1
2872                 "%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"                                                              // (sc_2 - sc_0)
2873                 "%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n"                                                              // (sc_2 - sc_0) * sc_1
2874
2875                 "%main      = OpFunction %void None %voidf\n"
2876                 "%label     = OpLabel\n"
2877                 "%idval     = OpLoad %uvec3 %id\n"
2878                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2879                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
2880                 "%inval     = OpLoad %i32 %inloc\n"
2881                 "%final     = OpIAdd %i32 %inval %sc_final\n"
2882                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2883                 "             OpStore %outloc %final\n"
2884                 "             OpReturn\n"
2885                 "             OpFunctionEnd\n";
2886         spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
2887         spec.outputs.push_back(BufferSp(new Int32Buffer(outputInts3)));
2888         spec.numWorkGroups = IVec3(numElements, 1, 1);
2889         spec.specConstants.append<deInt32>(123);
2890         spec.specConstants.append<deInt32>(56);
2891         spec.specConstants.append<deInt32>(-77);
2892
2893         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector_related", "VectorShuffle, CompositeExtract, & CompositeInsert", spec));
2894
2895         return group.release();
2896 }
2897
2898 void createOpPhiVartypeTests (de::MovePtr<tcu::TestCaseGroup>& group, tcu::TestContext& testCtx)
2899 {
2900         ComputeShaderSpec       specInt;
2901         ComputeShaderSpec       specFloat;
2902         ComputeShaderSpec       specFloat16;
2903         ComputeShaderSpec       specVec3;
2904         ComputeShaderSpec       specMat4;
2905         ComputeShaderSpec       specArray;
2906         ComputeShaderSpec       specStruct;
2907         de::Random                      rnd                             (deStringHash(group->getName()));
2908         const int                       numElements             = 100;
2909         vector<float>           inputFloats             (numElements, 0);
2910         vector<float>           outputFloats    (numElements, 0);
2911         vector<deFloat16>       inputFloats16   (numElements, 0);
2912         vector<deFloat16>       outputFloats16  (numElements, 0);
2913
2914         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
2915
2916         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2917         floorAll(inputFloats);
2918
2919         for (size_t ndx = 0; ndx < numElements; ++ndx)
2920         {
2921                 // Just check if the value is positive or not
2922                 outputFloats[ndx] = (inputFloats[ndx] > 0) ? 1.0f : -1.0f;
2923         }
2924
2925         for (size_t ndx = 0; ndx < numElements; ++ndx)
2926         {
2927                 inputFloats16[ndx] = tcu::Float16(inputFloats[ndx]).bits();
2928                 outputFloats16[ndx] = tcu::Float16(outputFloats[ndx]).bits();
2929         }
2930
2931         // All of the tests are of the form:
2932         //
2933         // testtype r
2934         //
2935         // if (inputdata > 0)
2936         //   r = 1
2937         // else
2938         //   r = -1
2939         //
2940         // return (float)r
2941
2942         specFloat.assembly =
2943                 string(getComputeAsmShaderPreamble()) +
2944
2945                 "OpSource GLSL 430\n"
2946                 "OpName %main \"main\"\n"
2947                 "OpName %id \"gl_GlobalInvocationID\"\n"
2948
2949                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2950
2951                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2952
2953                 "%id = OpVariable %uvec3ptr Input\n"
2954                 "%zero       = OpConstant %i32 0\n"
2955                 "%float_0    = OpConstant %f32 0.0\n"
2956                 "%float_1    = OpConstant %f32 1.0\n"
2957                 "%float_n1   = OpConstant %f32 -1.0\n"
2958
2959                 "%main     = OpFunction %void None %voidf\n"
2960                 "%entry    = OpLabel\n"
2961                 "%idval    = OpLoad %uvec3 %id\n"
2962                 "%x        = OpCompositeExtract %u32 %idval 0\n"
2963                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
2964                 "%inval    = OpLoad %f32 %inloc\n"
2965
2966                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
2967                 "            OpSelectionMerge %cm None\n"
2968                 "            OpBranchConditional %comp %tb %fb\n"
2969                 "%tb       = OpLabel\n"
2970                 "            OpBranch %cm\n"
2971                 "%fb       = OpLabel\n"
2972                 "            OpBranch %cm\n"
2973                 "%cm       = OpLabel\n"
2974                 "%res      = OpPhi %f32 %float_1 %tb %float_n1 %fb\n"
2975
2976                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
2977                 "            OpStore %outloc %res\n"
2978                 "            OpReturn\n"
2979
2980                 "            OpFunctionEnd\n";
2981         specFloat.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2982         specFloat.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2983         specFloat.numWorkGroups = IVec3(numElements, 1, 1);
2984
2985         specFloat16.assembly =
2986                 "OpCapability Shader\n"
2987                 "OpCapability StorageUniformBufferBlock16\n"
2988                 "OpExtension \"SPV_KHR_16bit_storage\"\n"
2989                 "OpMemoryModel Logical GLSL450\n"
2990                 "OpEntryPoint GLCompute %main \"main\" %id\n"
2991                 "OpExecutionMode %main LocalSize 1 1 1\n"
2992
2993                 "OpSource GLSL 430\n"
2994                 "OpName %main \"main\"\n"
2995                 "OpName %id \"gl_GlobalInvocationID\"\n"
2996
2997                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2998
2999                 "OpDecorate %buf BufferBlock\n"
3000                 "OpDecorate %indata DescriptorSet 0\n"
3001                 "OpDecorate %indata Binding 0\n"
3002                 "OpDecorate %outdata DescriptorSet 0\n"
3003                 "OpDecorate %outdata Binding 1\n"
3004                 "OpDecorate %f16arr ArrayStride 2\n"
3005                 "OpMemberDecorate %buf 0 Offset 0\n"
3006
3007                 "%f16      = OpTypeFloat 16\n"
3008                 "%f16ptr   = OpTypePointer Uniform %f16\n"
3009                 "%f16arr   = OpTypeRuntimeArray %f16\n"
3010
3011                 + string(getComputeAsmCommonTypes()) +
3012
3013                 "%buf      = OpTypeStruct %f16arr\n"
3014                 "%bufptr   = OpTypePointer Uniform %buf\n"
3015                 "%indata   = OpVariable %bufptr Uniform\n"
3016                 "%outdata  = OpVariable %bufptr Uniform\n"
3017
3018                 "%id       = OpVariable %uvec3ptr Input\n"
3019                 "%zero     = OpConstant %i32 0\n"
3020                 "%float_0  = OpConstant %f16 0.0\n"
3021                 "%float_1  = OpConstant %f16 1.0\n"
3022                 "%float_n1 = OpConstant %f16 -1.0\n"
3023
3024                 "%main     = OpFunction %void None %voidf\n"
3025                 "%entry    = OpLabel\n"
3026                 "%idval    = OpLoad %uvec3 %id\n"
3027                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3028                 "%inloc    = OpAccessChain %f16ptr %indata %zero %x\n"
3029                 "%inval    = OpLoad %f16 %inloc\n"
3030
3031                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3032                 "            OpSelectionMerge %cm None\n"
3033                 "            OpBranchConditional %comp %tb %fb\n"
3034                 "%tb       = OpLabel\n"
3035                 "            OpBranch %cm\n"
3036                 "%fb       = OpLabel\n"
3037                 "            OpBranch %cm\n"
3038                 "%cm       = OpLabel\n"
3039                 "%res      = OpPhi %f16 %float_1 %tb %float_n1 %fb\n"
3040
3041                 "%outloc   = OpAccessChain %f16ptr %outdata %zero %x\n"
3042                 "            OpStore %outloc %res\n"
3043                 "            OpReturn\n"
3044
3045                 "            OpFunctionEnd\n";
3046         specFloat16.inputs.push_back(BufferSp(new Float16Buffer(inputFloats16)));
3047         specFloat16.outputs.push_back(BufferSp(new Float16Buffer(outputFloats16)));
3048         specFloat16.numWorkGroups = IVec3(numElements, 1, 1);
3049         specFloat16.requestedVulkanFeatures.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
3050         specFloat16.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
3051
3052         specMat4.assembly =
3053                 string(getComputeAsmShaderPreamble()) +
3054
3055                 "OpSource GLSL 430\n"
3056                 "OpName %main \"main\"\n"
3057                 "OpName %id \"gl_GlobalInvocationID\"\n"
3058
3059                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3060
3061                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3062
3063                 "%id = OpVariable %uvec3ptr Input\n"
3064                 "%v4f32      = OpTypeVector %f32 4\n"
3065                 "%mat4v4f32  = OpTypeMatrix %v4f32 4\n"
3066                 "%zero       = OpConstant %i32 0\n"
3067                 "%float_0    = OpConstant %f32 0.0\n"
3068                 "%float_1    = OpConstant %f32 1.0\n"
3069                 "%float_n1   = OpConstant %f32 -1.0\n"
3070                 "%m11        = OpConstantComposite %v4f32 %float_1 %float_0 %float_0 %float_0\n"
3071                 "%m12        = OpConstantComposite %v4f32 %float_0 %float_1 %float_0 %float_0\n"
3072                 "%m13        = OpConstantComposite %v4f32 %float_0 %float_0 %float_1 %float_0\n"
3073                 "%m14        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_1\n"
3074                 "%m1         = OpConstantComposite %mat4v4f32 %m11 %m12 %m13 %m14\n"
3075                 "%m21        = OpConstantComposite %v4f32 %float_n1 %float_0 %float_0 %float_0\n"
3076                 "%m22        = OpConstantComposite %v4f32 %float_0 %float_n1 %float_0 %float_0\n"
3077                 "%m23        = OpConstantComposite %v4f32 %float_0 %float_0 %float_n1 %float_0\n"
3078                 "%m24        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_n1\n"
3079                 "%m2         = OpConstantComposite %mat4v4f32 %m21 %m22 %m23 %m24\n"
3080
3081                 "%main     = OpFunction %void None %voidf\n"
3082                 "%entry    = OpLabel\n"
3083                 "%idval    = OpLoad %uvec3 %id\n"
3084                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3085                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3086                 "%inval    = OpLoad %f32 %inloc\n"
3087
3088                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3089                 "            OpSelectionMerge %cm None\n"
3090                 "            OpBranchConditional %comp %tb %fb\n"
3091                 "%tb       = OpLabel\n"
3092                 "            OpBranch %cm\n"
3093                 "%fb       = OpLabel\n"
3094                 "            OpBranch %cm\n"
3095                 "%cm       = OpLabel\n"
3096                 "%mres     = OpPhi %mat4v4f32 %m1 %tb %m2 %fb\n"
3097                 "%res      = OpCompositeExtract %f32 %mres 2 2\n"
3098
3099                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3100                 "            OpStore %outloc %res\n"
3101                 "            OpReturn\n"
3102
3103                 "            OpFunctionEnd\n";
3104         specMat4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3105         specMat4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3106         specMat4.numWorkGroups = IVec3(numElements, 1, 1);
3107
3108         specVec3.assembly =
3109                 string(getComputeAsmShaderPreamble()) +
3110
3111                 "OpSource GLSL 430\n"
3112                 "OpName %main \"main\"\n"
3113                 "OpName %id \"gl_GlobalInvocationID\"\n"
3114
3115                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3116
3117                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3118
3119                 "%id = OpVariable %uvec3ptr Input\n"
3120                 "%zero       = OpConstant %i32 0\n"
3121                 "%float_0    = OpConstant %f32 0.0\n"
3122                 "%float_1    = OpConstant %f32 1.0\n"
3123                 "%float_n1   = OpConstant %f32 -1.0\n"
3124                 "%v1         = OpConstantComposite %fvec3 %float_1 %float_1 %float_1\n"
3125                 "%v2         = OpConstantComposite %fvec3 %float_n1 %float_n1 %float_n1\n"
3126
3127                 "%main     = OpFunction %void None %voidf\n"
3128                 "%entry    = OpLabel\n"
3129                 "%idval    = OpLoad %uvec3 %id\n"
3130                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3131                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3132                 "%inval    = OpLoad %f32 %inloc\n"
3133
3134                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3135                 "            OpSelectionMerge %cm None\n"
3136                 "            OpBranchConditional %comp %tb %fb\n"
3137                 "%tb       = OpLabel\n"
3138                 "            OpBranch %cm\n"
3139                 "%fb       = OpLabel\n"
3140                 "            OpBranch %cm\n"
3141                 "%cm       = OpLabel\n"
3142                 "%vres     = OpPhi %fvec3 %v1 %tb %v2 %fb\n"
3143                 "%res      = OpCompositeExtract %f32 %vres 2\n"
3144
3145                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3146                 "            OpStore %outloc %res\n"
3147                 "            OpReturn\n"
3148
3149                 "            OpFunctionEnd\n";
3150         specVec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3151         specVec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3152         specVec3.numWorkGroups = IVec3(numElements, 1, 1);
3153
3154         specInt.assembly =
3155                 string(getComputeAsmShaderPreamble()) +
3156
3157                 "OpSource GLSL 430\n"
3158                 "OpName %main \"main\"\n"
3159                 "OpName %id \"gl_GlobalInvocationID\"\n"
3160
3161                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3162
3163                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3164
3165                 "%id = OpVariable %uvec3ptr Input\n"
3166                 "%zero       = OpConstant %i32 0\n"
3167                 "%float_0    = OpConstant %f32 0.0\n"
3168                 "%i1         = OpConstant %i32 1\n"
3169                 "%i2         = OpConstant %i32 -1\n"
3170
3171                 "%main     = OpFunction %void None %voidf\n"
3172                 "%entry    = OpLabel\n"
3173                 "%idval    = OpLoad %uvec3 %id\n"
3174                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3175                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3176                 "%inval    = OpLoad %f32 %inloc\n"
3177
3178                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3179                 "            OpSelectionMerge %cm None\n"
3180                 "            OpBranchConditional %comp %tb %fb\n"
3181                 "%tb       = OpLabel\n"
3182                 "            OpBranch %cm\n"
3183                 "%fb       = OpLabel\n"
3184                 "            OpBranch %cm\n"
3185                 "%cm       = OpLabel\n"
3186                 "%ires     = OpPhi %i32 %i1 %tb %i2 %fb\n"
3187                 "%res      = OpConvertSToF %f32 %ires\n"
3188
3189                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3190                 "            OpStore %outloc %res\n"
3191                 "            OpReturn\n"
3192
3193                 "            OpFunctionEnd\n";
3194         specInt.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3195         specInt.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3196         specInt.numWorkGroups = IVec3(numElements, 1, 1);
3197
3198         specArray.assembly =
3199                 string(getComputeAsmShaderPreamble()) +
3200
3201                 "OpSource GLSL 430\n"
3202                 "OpName %main \"main\"\n"
3203                 "OpName %id \"gl_GlobalInvocationID\"\n"
3204
3205                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3206
3207                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3208
3209                 "%id = OpVariable %uvec3ptr Input\n"
3210                 "%zero       = OpConstant %i32 0\n"
3211                 "%u7         = OpConstant %u32 7\n"
3212                 "%float_0    = OpConstant %f32 0.0\n"
3213                 "%float_1    = OpConstant %f32 1.0\n"
3214                 "%float_n1   = OpConstant %f32 -1.0\n"
3215                 "%f32a7      = OpTypeArray %f32 %u7\n"
3216                 "%a1         = OpConstantComposite %f32a7 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1\n"
3217                 "%a2         = OpConstantComposite %f32a7 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1\n"
3218                 "%main     = OpFunction %void None %voidf\n"
3219                 "%entry    = OpLabel\n"
3220                 "%idval    = OpLoad %uvec3 %id\n"
3221                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3222                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3223                 "%inval    = OpLoad %f32 %inloc\n"
3224
3225                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3226                 "            OpSelectionMerge %cm None\n"
3227                 "            OpBranchConditional %comp %tb %fb\n"
3228                 "%tb       = OpLabel\n"
3229                 "            OpBranch %cm\n"
3230                 "%fb       = OpLabel\n"
3231                 "            OpBranch %cm\n"
3232                 "%cm       = OpLabel\n"
3233                 "%ares     = OpPhi %f32a7 %a1 %tb %a2 %fb\n"
3234                 "%res      = OpCompositeExtract %f32 %ares 5\n"
3235
3236                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3237                 "            OpStore %outloc %res\n"
3238                 "            OpReturn\n"
3239
3240                 "            OpFunctionEnd\n";
3241         specArray.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3242         specArray.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3243         specArray.numWorkGroups = IVec3(numElements, 1, 1);
3244
3245         specStruct.assembly =
3246                 string(getComputeAsmShaderPreamble()) +
3247
3248                 "OpSource GLSL 430\n"
3249                 "OpName %main \"main\"\n"
3250                 "OpName %id \"gl_GlobalInvocationID\"\n"
3251
3252                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3253
3254                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3255
3256                 "%id = OpVariable %uvec3ptr Input\n"
3257                 "%zero       = OpConstant %i32 0\n"
3258                 "%float_0    = OpConstant %f32 0.0\n"
3259                 "%float_1    = OpConstant %f32 1.0\n"
3260                 "%float_n1   = OpConstant %f32 -1.0\n"
3261
3262                 "%v2f32      = OpTypeVector %f32 2\n"
3263                 "%Data2      = OpTypeStruct %f32 %v2f32\n"
3264                 "%Data       = OpTypeStruct %Data2 %f32\n"
3265
3266                 "%in1a       = OpConstantComposite %v2f32 %float_1 %float_1\n"
3267                 "%in1b       = OpConstantComposite %Data2 %float_1 %in1a\n"
3268                 "%s1         = OpConstantComposite %Data %in1b %float_1\n"
3269                 "%in2a       = OpConstantComposite %v2f32 %float_n1 %float_n1\n"
3270                 "%in2b       = OpConstantComposite %Data2 %float_n1 %in2a\n"
3271                 "%s2         = OpConstantComposite %Data %in2b %float_n1\n"
3272
3273                 "%main     = OpFunction %void None %voidf\n"
3274                 "%entry    = OpLabel\n"
3275                 "%idval    = OpLoad %uvec3 %id\n"
3276                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3277                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3278                 "%inval    = OpLoad %f32 %inloc\n"
3279
3280                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3281                 "            OpSelectionMerge %cm None\n"
3282                 "            OpBranchConditional %comp %tb %fb\n"
3283                 "%tb       = OpLabel\n"
3284                 "            OpBranch %cm\n"
3285                 "%fb       = OpLabel\n"
3286                 "            OpBranch %cm\n"
3287                 "%cm       = OpLabel\n"
3288                 "%sres     = OpPhi %Data %s1 %tb %s2 %fb\n"
3289                 "%res      = OpCompositeExtract %f32 %sres 0 0\n"
3290
3291                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3292                 "            OpStore %outloc %res\n"
3293                 "            OpReturn\n"
3294
3295                 "            OpFunctionEnd\n";
3296         specStruct.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3297         specStruct.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3298         specStruct.numWorkGroups = IVec3(numElements, 1, 1);
3299
3300         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_int", "OpPhi with int variables", specInt));
3301         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_float", "OpPhi with float variables", specFloat));
3302         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_float16", "OpPhi with 16bit float variables", specFloat16));
3303         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_vec3", "OpPhi with vec3 variables", specVec3));
3304         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_mat4", "OpPhi with mat4 variables", specMat4));
3305         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_array", "OpPhi with array variables", specArray));
3306         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_struct", "OpPhi with struct variables", specStruct));
3307 }
3308
3309 string generateConstantDefinitions (int count)
3310 {
3311         std::ostringstream      r;
3312         for (int i = 0; i < count; i++)
3313                 r << "%cf" << (i * 10 + 5) << " = OpConstant %f32 " <<(i * 10 + 5) << ".0\n";
3314         r << "\n";
3315         return r.str();
3316 }
3317
3318 string generateSwitchCases (int count)
3319 {
3320         std::ostringstream      r;
3321         for (int i = 0; i < count; i++)
3322                 r << " " << i << " %case" << i;
3323         r << "\n";
3324         return r.str();
3325 }
3326
3327 string generateSwitchTargets (int count)
3328 {
3329         std::ostringstream      r;
3330         for (int i = 0; i < count; i++)
3331                 r << "%case" << i << " = OpLabel\n            OpBranch %phi\n";
3332         r << "\n";
3333         return r.str();
3334 }
3335
3336 string generateOpPhiParams (int count)
3337 {
3338         std::ostringstream      r;
3339         for (int i = 0; i < count; i++)
3340                 r << " %cf" << (i * 10 + 5) << " %case" << i;
3341         r << "\n";
3342         return r.str();
3343 }
3344
3345 string generateIntWidth (int value)
3346 {
3347         std::ostringstream      r;
3348         r << value;
3349         return r.str();
3350 }
3351
3352 // Expand input string by injecting "ABC" between the input
3353 // string characters. The acc/add/treshold parameters are used
3354 // to skip some of the injections to make the result less
3355 // uniform (and a lot shorter).
3356 string expandOpPhiCase5 (const string& s, int &acc, int add, int treshold)
3357 {
3358         std::ostringstream      res;
3359         const char*                     p = s.c_str();
3360
3361         while (*p)
3362         {
3363                 res << *p;
3364                 acc += add;
3365                 if (acc > treshold)
3366                 {
3367                         acc -= treshold;
3368                         res << "ABC";
3369                 }
3370                 p++;
3371         }
3372         return res.str();
3373 }
3374
3375 // Calculate expected result based on the code string
3376 float calcOpPhiCase5 (float val, const string& s)
3377 {
3378         const char*             p               = s.c_str();
3379         float                   x[8];
3380         bool                    b[8];
3381         const float             tv[8]   = { 0.5f, 1.5f, 3.5f, 7.5f, 15.5f, 31.5f, 63.5f, 127.5f };
3382         const float             v               = deFloatAbs(val);
3383         float                   res             = 0;
3384         int                             depth   = -1;
3385         int                             skip    = 0;
3386
3387         for (int i = 7; i >= 0; --i)
3388                 x[i] = std::fmod((float)v, (float)(2 << i));
3389         for (int i = 7; i >= 0; --i)
3390                 b[i] = x[i] > tv[i];
3391
3392         while (*p)
3393         {
3394                 if (*p == 'A')
3395                 {
3396                         depth++;
3397                         if (skip == 0 && b[depth])
3398                         {
3399                                 res++;
3400                         }
3401                         else
3402                                 skip++;
3403                 }
3404                 if (*p == 'B')
3405                 {
3406                         if (skip)
3407                                 skip--;
3408                         if (b[depth] || skip)
3409                                 skip++;
3410                 }
3411                 if (*p == 'C')
3412                 {
3413                         depth--;
3414                         if (skip)
3415                                 skip--;
3416                 }
3417                 p++;
3418         }
3419         return res;
3420 }
3421
3422 // In the code string, the letters represent the following:
3423 //
3424 // A:
3425 //     if (certain bit is set)
3426 //     {
3427 //       result++;
3428 //
3429 // B:
3430 //     } else {
3431 //
3432 // C:
3433 //     }
3434 //
3435 // examples:
3436 // AABCBC leads to if(){r++;if(){r++;}else{}}else{}
3437 // ABABCC leads to if(){r++;}else{if(){r++;}else{}}
3438 // ABCABC leads to if(){r++;}else{}if(){r++;}else{}
3439 //
3440 // Code generation gets a bit complicated due to the else-branches,
3441 // which do not generate new values. Thus, the generator needs to
3442 // keep track of the previous variable change seen by the else
3443 // branch.
3444 string generateOpPhiCase5 (const string& s)
3445 {
3446         std::stack<int>                         idStack;
3447         std::stack<std::string>         value;
3448         std::stack<std::string>         valueLabel;
3449         std::stack<std::string>         mergeLeft;
3450         std::stack<std::string>         mergeRight;
3451         std::ostringstream                      res;
3452         const char*                                     p                       = s.c_str();
3453         int                                                     depth           = -1;
3454         int                                                     currId          = 0;
3455         int                                                     iter            = 0;
3456
3457         idStack.push(-1);
3458         value.push("%f32_0");
3459         valueLabel.push("%f32_0 %entry");
3460
3461         while (*p)
3462         {
3463                 if (*p == 'A')
3464                 {
3465                         depth++;
3466                         currId = iter;
3467                         idStack.push(currId);
3468                         res << "\tOpSelectionMerge %m" << currId << " None\n";
3469                         res << "\tOpBranchConditional %b" << depth << " %t" << currId << " %f" << currId << "\n";
3470                         res << "%t" << currId << " = OpLabel\n";
3471                         res << "%rt" << currId << " = OpFAdd %f32 " << value.top() << " %f32_1\n";
3472                         std::ostringstream tag;
3473                         tag << "%rt" << currId;
3474                         value.push(tag.str());
3475                         tag << " %t" << currId;
3476                         valueLabel.push(tag.str());
3477                 }
3478
3479                 if (*p == 'B')
3480                 {
3481                         mergeLeft.push(valueLabel.top());
3482                         value.pop();
3483                         valueLabel.pop();
3484                         res << "\tOpBranch %m" << currId << "\n";
3485                         res << "%f" << currId << " = OpLabel\n";
3486                         std::ostringstream tag;
3487                         tag << value.top() << " %f" << currId;
3488                         valueLabel.pop();
3489                         valueLabel.push(tag.str());
3490                 }
3491
3492                 if (*p == 'C')
3493                 {
3494                         mergeRight.push(valueLabel.top());
3495                         res << "\tOpBranch %m" << currId << "\n";
3496                         res << "%m" << currId << " = OpLabel\n";
3497                         if (*(p + 1) == 0)
3498                                 res << "%res"; // last result goes to %res
3499                         else
3500                                 res << "%rm" << currId;
3501                         res << " = OpPhi %f32  " << mergeLeft.top() << "  " << mergeRight.top() << "\n";
3502                         std::ostringstream tag;
3503                         tag << "%rm" << currId;
3504                         value.pop();
3505                         value.push(tag.str());
3506                         tag << " %m" << currId;
3507                         valueLabel.pop();
3508                         valueLabel.push(tag.str());
3509                         mergeLeft.pop();
3510                         mergeRight.pop();
3511                         depth--;
3512                         idStack.pop();
3513                         currId = idStack.top();
3514                 }
3515                 p++;
3516                 iter++;
3517         }
3518         return res.str();
3519 }
3520
3521 tcu::TestCaseGroup* createOpPhiGroup (tcu::TestContext& testCtx)
3522 {
3523         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
3524         ComputeShaderSpec                               spec1;
3525         ComputeShaderSpec                               spec2;
3526         ComputeShaderSpec                               spec3;
3527         ComputeShaderSpec                               spec4;
3528         ComputeShaderSpec                               spec5;
3529         de::Random                                              rnd                             (deStringHash(group->getName()));
3530         const int                                               numElements             = 100;
3531         vector<float>                                   inputFloats             (numElements, 0);
3532         vector<float>                                   outputFloats1   (numElements, 0);
3533         vector<float>                                   outputFloats2   (numElements, 0);
3534         vector<float>                                   outputFloats3   (numElements, 0);
3535         vector<float>                                   outputFloats4   (numElements, 0);
3536         vector<float>                                   outputFloats5   (numElements, 0);
3537         std::string                                             codestring              = "ABC";
3538         const int                                               test4Width              = 1024;
3539
3540         // Build case 5 code string. Each iteration makes the hierarchy more complicated.
3541         // 9 iterations with (7, 24) parameters makes the hierarchy 8 deep with about 1500 lines of
3542         // shader code.
3543         for (int i = 0, acc = 0; i < 9; i++)
3544                 codestring = expandOpPhiCase5(codestring, acc, 7, 24);
3545
3546         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
3547
3548         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3549         floorAll(inputFloats);
3550
3551         for (size_t ndx = 0; ndx < numElements; ++ndx)
3552         {
3553                 switch (ndx % 3)
3554                 {
3555                         case 0:         outputFloats1[ndx] = inputFloats[ndx] + 5.5f;   break;
3556                         case 1:         outputFloats1[ndx] = inputFloats[ndx] + 20.5f;  break;
3557                         case 2:         outputFloats1[ndx] = inputFloats[ndx] + 1.75f;  break;
3558                         default:        break;
3559                 }
3560                 outputFloats2[ndx] = inputFloats[ndx] + 6.5f * 3;
3561                 outputFloats3[ndx] = 8.5f - inputFloats[ndx];
3562
3563                 int index4 = (int)deFloor(deAbs((float)ndx * inputFloats[ndx]));
3564                 outputFloats4[ndx] = (float)(index4 % test4Width) * 10.0f + 5.0f;
3565
3566                 outputFloats5[ndx] = calcOpPhiCase5(inputFloats[ndx], codestring);
3567         }
3568
3569         spec1.assembly =
3570                 string(getComputeAsmShaderPreamble()) +
3571
3572                 "OpSource GLSL 430\n"
3573                 "OpName %main \"main\"\n"
3574                 "OpName %id \"gl_GlobalInvocationID\"\n"
3575
3576                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3577
3578                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3579
3580                 "%id = OpVariable %uvec3ptr Input\n"
3581                 "%zero       = OpConstant %i32 0\n"
3582                 "%three      = OpConstant %u32 3\n"
3583                 "%constf5p5  = OpConstant %f32 5.5\n"
3584                 "%constf20p5 = OpConstant %f32 20.5\n"
3585                 "%constf1p75 = OpConstant %f32 1.75\n"
3586                 "%constf8p5  = OpConstant %f32 8.5\n"
3587                 "%constf6p5  = OpConstant %f32 6.5\n"
3588
3589                 "%main     = OpFunction %void None %voidf\n"
3590                 "%entry    = OpLabel\n"
3591                 "%idval    = OpLoad %uvec3 %id\n"
3592                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3593                 "%selector = OpUMod %u32 %x %three\n"
3594                 "            OpSelectionMerge %phi None\n"
3595                 "            OpSwitch %selector %default 0 %case0 1 %case1 2 %case2\n"
3596
3597                 // Case 1 before OpPhi.
3598                 "%case1    = OpLabel\n"
3599                 "            OpBranch %phi\n"
3600
3601                 "%default  = OpLabel\n"
3602                 "            OpUnreachable\n"
3603
3604                 "%phi      = OpLabel\n"
3605                 "%operand  = OpPhi %f32   %constf1p75 %case2   %constf20p5 %case1   %constf5p5 %case0\n" // not in the order of blocks
3606                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3607                 "%inval    = OpLoad %f32 %inloc\n"
3608                 "%add      = OpFAdd %f32 %inval %operand\n"
3609                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3610                 "            OpStore %outloc %add\n"
3611                 "            OpReturn\n"
3612
3613                 // Case 0 after OpPhi.
3614                 "%case0    = OpLabel\n"
3615                 "            OpBranch %phi\n"
3616
3617
3618                 // Case 2 after OpPhi.
3619                 "%case2    = OpLabel\n"
3620                 "            OpBranch %phi\n"
3621
3622                 "            OpFunctionEnd\n";
3623         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3624         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
3625         spec1.numWorkGroups = IVec3(numElements, 1, 1);
3626
3627         group->addChild(new SpvAsmComputeShaderCase(testCtx, "block", "out-of-order and unreachable blocks for OpPhi", spec1));
3628
3629         spec2.assembly =
3630                 string(getComputeAsmShaderPreamble()) +
3631
3632                 "OpName %main \"main\"\n"
3633                 "OpName %id \"gl_GlobalInvocationID\"\n"
3634
3635                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3636
3637                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3638
3639                 "%id         = OpVariable %uvec3ptr Input\n"
3640                 "%zero       = OpConstant %i32 0\n"
3641                 "%one        = OpConstant %i32 1\n"
3642                 "%three      = OpConstant %i32 3\n"
3643                 "%constf6p5  = OpConstant %f32 6.5\n"
3644
3645                 "%main       = OpFunction %void None %voidf\n"
3646                 "%entry      = OpLabel\n"
3647                 "%idval      = OpLoad %uvec3 %id\n"
3648                 "%x          = OpCompositeExtract %u32 %idval 0\n"
3649                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3650                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3651                 "%inval      = OpLoad %f32 %inloc\n"
3652                 "              OpBranch %phi\n"
3653
3654                 "%phi        = OpLabel\n"
3655                 "%step       = OpPhi %i32 %zero  %entry %step_next  %phi\n"
3656                 "%accum      = OpPhi %f32 %inval %entry %accum_next %phi\n"
3657                 "%step_next  = OpIAdd %i32 %step %one\n"
3658                 "%accum_next = OpFAdd %f32 %accum %constf6p5\n"
3659                 "%still_loop = OpSLessThan %bool %step %three\n"
3660                 "              OpLoopMerge %exit %phi None\n"
3661                 "              OpBranchConditional %still_loop %phi %exit\n"
3662
3663                 "%exit       = OpLabel\n"
3664                 "              OpStore %outloc %accum\n"
3665                 "              OpReturn\n"
3666                 "              OpFunctionEnd\n";
3667         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3668         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
3669         spec2.numWorkGroups = IVec3(numElements, 1, 1);
3670
3671         group->addChild(new SpvAsmComputeShaderCase(testCtx, "induction", "The usual way induction variables are handled in LLVM IR", spec2));
3672
3673         spec3.assembly =
3674                 string(getComputeAsmShaderPreamble()) +
3675
3676                 "OpName %main \"main\"\n"
3677                 "OpName %id \"gl_GlobalInvocationID\"\n"
3678
3679                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3680
3681                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3682
3683                 "%f32ptr_f   = OpTypePointer Function %f32\n"
3684                 "%id         = OpVariable %uvec3ptr Input\n"
3685                 "%true       = OpConstantTrue %bool\n"
3686                 "%false      = OpConstantFalse %bool\n"
3687                 "%zero       = OpConstant %i32 0\n"
3688                 "%constf8p5  = OpConstant %f32 8.5\n"
3689
3690                 "%main       = OpFunction %void None %voidf\n"
3691                 "%entry      = OpLabel\n"
3692                 "%b          = OpVariable %f32ptr_f Function %constf8p5\n"
3693                 "%idval      = OpLoad %uvec3 %id\n"
3694                 "%x          = OpCompositeExtract %u32 %idval 0\n"
3695                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3696                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3697                 "%a_init     = OpLoad %f32 %inloc\n"
3698                 "%b_init     = OpLoad %f32 %b\n"
3699                 "              OpBranch %phi\n"
3700
3701                 "%phi        = OpLabel\n"
3702                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
3703                 "%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
3704                 "%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
3705                 "              OpLoopMerge %exit %phi None\n"
3706                 "              OpBranchConditional %still_loop %phi %exit\n"
3707
3708                 "%exit       = OpLabel\n"
3709                 "%sub        = OpFSub %f32 %a_next %b_next\n"
3710                 "              OpStore %outloc %sub\n"
3711                 "              OpReturn\n"
3712                 "              OpFunctionEnd\n";
3713         spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3714         spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
3715         spec3.numWorkGroups = IVec3(numElements, 1, 1);
3716
3717         group->addChild(new SpvAsmComputeShaderCase(testCtx, "swap", "Swap the values of two variables using OpPhi", spec3));
3718
3719         spec4.assembly =
3720                 "OpCapability Shader\n"
3721                 "%ext = OpExtInstImport \"GLSL.std.450\"\n"
3722                 "OpMemoryModel Logical GLSL450\n"
3723                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3724                 "OpExecutionMode %main LocalSize 1 1 1\n"
3725
3726                 "OpSource GLSL 430\n"
3727                 "OpName %main \"main\"\n"
3728                 "OpName %id \"gl_GlobalInvocationID\"\n"
3729
3730                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3731
3732                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3733
3734                 "%id       = OpVariable %uvec3ptr Input\n"
3735                 "%zero     = OpConstant %i32 0\n"
3736                 "%cimod    = OpConstant %u32 " + generateIntWidth(test4Width) + "\n"
3737
3738                 + generateConstantDefinitions(test4Width) +
3739
3740                 "%main     = OpFunction %void None %voidf\n"
3741                 "%entry    = OpLabel\n"
3742                 "%idval    = OpLoad %uvec3 %id\n"
3743                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3744                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3745                 "%inval    = OpLoad %f32 %inloc\n"
3746                 "%xf       = OpConvertUToF %f32 %x\n"
3747                 "%xm       = OpFMul %f32 %xf %inval\n"
3748                 "%xa       = OpExtInst %f32 %ext FAbs %xm\n"
3749                 "%xi       = OpConvertFToU %u32 %xa\n"
3750                 "%selector = OpUMod %u32 %xi %cimod\n"
3751                 "            OpSelectionMerge %phi None\n"
3752                 "            OpSwitch %selector %default "
3753
3754                 + generateSwitchCases(test4Width) +
3755
3756                 "%default  = OpLabel\n"
3757                 "            OpUnreachable\n"
3758
3759                 + generateSwitchTargets(test4Width) +
3760
3761                 "%phi      = OpLabel\n"
3762                 "%result   = OpPhi %f32"
3763
3764                 + generateOpPhiParams(test4Width) +
3765
3766                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3767                 "            OpStore %outloc %result\n"
3768                 "            OpReturn\n"
3769
3770                 "            OpFunctionEnd\n";
3771         spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3772         spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
3773         spec4.numWorkGroups = IVec3(numElements, 1, 1);
3774
3775         group->addChild(new SpvAsmComputeShaderCase(testCtx, "wide", "OpPhi with a lot of parameters", spec4));
3776
3777         spec5.assembly =
3778                 "OpCapability Shader\n"
3779                 "%ext      = OpExtInstImport \"GLSL.std.450\"\n"
3780                 "OpMemoryModel Logical GLSL450\n"
3781                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3782                 "OpExecutionMode %main LocalSize 1 1 1\n"
3783                 "%code     = OpString \"" + codestring + "\"\n"
3784
3785                 "OpSource GLSL 430\n"
3786                 "OpName %main \"main\"\n"
3787                 "OpName %id \"gl_GlobalInvocationID\"\n"
3788
3789                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3790
3791                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3792
3793                 "%id       = OpVariable %uvec3ptr Input\n"
3794                 "%zero     = OpConstant %i32 0\n"
3795                 "%f32_0    = OpConstant %f32 0.0\n"
3796                 "%f32_0_5  = OpConstant %f32 0.5\n"
3797                 "%f32_1    = OpConstant %f32 1.0\n"
3798                 "%f32_1_5  = OpConstant %f32 1.5\n"
3799                 "%f32_2    = OpConstant %f32 2.0\n"
3800                 "%f32_3_5  = OpConstant %f32 3.5\n"
3801                 "%f32_4    = OpConstant %f32 4.0\n"
3802                 "%f32_7_5  = OpConstant %f32 7.5\n"
3803                 "%f32_8    = OpConstant %f32 8.0\n"
3804                 "%f32_15_5 = OpConstant %f32 15.5\n"
3805                 "%f32_16   = OpConstant %f32 16.0\n"
3806                 "%f32_31_5 = OpConstant %f32 31.5\n"
3807                 "%f32_32   = OpConstant %f32 32.0\n"
3808                 "%f32_63_5 = OpConstant %f32 63.5\n"
3809                 "%f32_64   = OpConstant %f32 64.0\n"
3810                 "%f32_127_5 = OpConstant %f32 127.5\n"
3811                 "%f32_128  = OpConstant %f32 128.0\n"
3812                 "%f32_256  = OpConstant %f32 256.0\n"
3813
3814                 "%main     = OpFunction %void None %voidf\n"
3815                 "%entry    = OpLabel\n"
3816                 "%idval    = OpLoad %uvec3 %id\n"
3817                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3818                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3819                 "%inval    = OpLoad %f32 %inloc\n"
3820
3821                 "%xabs     = OpExtInst %f32 %ext FAbs %inval\n"
3822                 "%x8       = OpFMod %f32 %xabs %f32_256\n"
3823                 "%x7       = OpFMod %f32 %xabs %f32_128\n"
3824                 "%x6       = OpFMod %f32 %xabs %f32_64\n"
3825                 "%x5       = OpFMod %f32 %xabs %f32_32\n"
3826                 "%x4       = OpFMod %f32 %xabs %f32_16\n"
3827                 "%x3       = OpFMod %f32 %xabs %f32_8\n"
3828                 "%x2       = OpFMod %f32 %xabs %f32_4\n"
3829                 "%x1       = OpFMod %f32 %xabs %f32_2\n"
3830
3831                 "%b7       = OpFOrdGreaterThanEqual %bool %x8 %f32_127_5\n"
3832                 "%b6       = OpFOrdGreaterThanEqual %bool %x7 %f32_63_5\n"
3833                 "%b5       = OpFOrdGreaterThanEqual %bool %x6 %f32_31_5\n"
3834                 "%b4       = OpFOrdGreaterThanEqual %bool %x5 %f32_15_5\n"
3835                 "%b3       = OpFOrdGreaterThanEqual %bool %x4 %f32_7_5\n"
3836                 "%b2       = OpFOrdGreaterThanEqual %bool %x3 %f32_3_5\n"
3837                 "%b1       = OpFOrdGreaterThanEqual %bool %x2 %f32_1_5\n"
3838                 "%b0       = OpFOrdGreaterThanEqual %bool %x1 %f32_0_5\n"
3839
3840                 + generateOpPhiCase5(codestring) +
3841
3842                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3843                 "            OpStore %outloc %res\n"
3844                 "            OpReturn\n"
3845
3846                 "            OpFunctionEnd\n";
3847         spec5.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3848         spec5.outputs.push_back(BufferSp(new Float32Buffer(outputFloats5)));
3849         spec5.numWorkGroups = IVec3(numElements, 1, 1);
3850
3851         group->addChild(new SpvAsmComputeShaderCase(testCtx, "nested", "Stress OpPhi with a lot of nesting", spec5));
3852
3853         createOpPhiVartypeTests(group, testCtx);
3854
3855         return group.release();
3856 }
3857
3858 // Assembly code used for testing block order is based on GLSL source code:
3859 //
3860 // #version 430
3861 //
3862 // layout(std140, set = 0, binding = 0) readonly buffer Input {
3863 //   float elements[];
3864 // } input_data;
3865 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
3866 //   float elements[];
3867 // } output_data;
3868 //
3869 // void main() {
3870 //   uint x = gl_GlobalInvocationID.x;
3871 //   output_data.elements[x] = input_data.elements[x];
3872 //   if (x > uint(50)) {
3873 //     switch (x % uint(3)) {
3874 //       case 0: output_data.elements[x] += 1.5f; break;
3875 //       case 1: output_data.elements[x] += 42.f; break;
3876 //       case 2: output_data.elements[x] -= 27.f; break;
3877 //       default: break;
3878 //     }
3879 //   } else {
3880 //     output_data.elements[x] = -input_data.elements[x];
3881 //   }
3882 // }
3883 tcu::TestCaseGroup* createBlockOrderGroup (tcu::TestContext& testCtx)
3884 {
3885         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "block_order", "Test block orders"));
3886         ComputeShaderSpec                               spec;
3887         de::Random                                              rnd                             (deStringHash(group->getName()));
3888         const int                                               numElements             = 100;
3889         vector<float>                                   inputFloats             (numElements, 0);
3890         vector<float>                                   outputFloats    (numElements, 0);
3891
3892         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
3893
3894         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3895         floorAll(inputFloats);
3896
3897         for (size_t ndx = 0; ndx <= 50; ++ndx)
3898                 outputFloats[ndx] = -inputFloats[ndx];
3899
3900         for (size_t ndx = 51; ndx < numElements; ++ndx)
3901         {
3902                 switch (ndx % 3)
3903                 {
3904                         case 0:         outputFloats[ndx] = inputFloats[ndx] + 1.5f; break;
3905                         case 1:         outputFloats[ndx] = inputFloats[ndx] + 42.f; break;
3906                         case 2:         outputFloats[ndx] = inputFloats[ndx] - 27.f; break;
3907                         default:        break;
3908                 }
3909         }
3910
3911         spec.assembly =
3912                 string(getComputeAsmShaderPreamble()) +
3913
3914                 "OpSource GLSL 430\n"
3915                 "OpName %main \"main\"\n"
3916                 "OpName %id \"gl_GlobalInvocationID\"\n"
3917
3918                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3919
3920                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
3921
3922                 "%u32ptr       = OpTypePointer Function %u32\n"
3923                 "%u32ptr_input = OpTypePointer Input %u32\n"
3924
3925                 + string(getComputeAsmInputOutputBuffer()) +
3926
3927                 "%id        = OpVariable %uvec3ptr Input\n"
3928                 "%zero      = OpConstant %i32 0\n"
3929                 "%const3    = OpConstant %u32 3\n"
3930                 "%const50   = OpConstant %u32 50\n"
3931                 "%constf1p5 = OpConstant %f32 1.5\n"
3932                 "%constf27  = OpConstant %f32 27.0\n"
3933                 "%constf42  = OpConstant %f32 42.0\n"
3934
3935                 "%main = OpFunction %void None %voidf\n"
3936
3937                 // entry block.
3938                 "%entry    = OpLabel\n"
3939
3940                 // Create a temporary variable to hold the value of gl_GlobalInvocationID.x.
3941                 "%xvar     = OpVariable %u32ptr Function\n"
3942                 "%xptr     = OpAccessChain %u32ptr_input %id %zero\n"
3943                 "%x        = OpLoad %u32 %xptr\n"
3944                 "            OpStore %xvar %x\n"
3945
3946                 "%cmp      = OpUGreaterThan %bool %x %const50\n"
3947                 "            OpSelectionMerge %if_merge None\n"
3948                 "            OpBranchConditional %cmp %if_true %if_false\n"
3949
3950                 // False branch for if-statement: placed in the middle of switch cases and before true branch.
3951                 "%if_false = OpLabel\n"
3952                 "%x_f      = OpLoad %u32 %xvar\n"
3953                 "%inloc_f  = OpAccessChain %f32ptr %indata %zero %x_f\n"
3954                 "%inval_f  = OpLoad %f32 %inloc_f\n"
3955                 "%negate   = OpFNegate %f32 %inval_f\n"
3956                 "%outloc_f = OpAccessChain %f32ptr %outdata %zero %x_f\n"
3957                 "            OpStore %outloc_f %negate\n"
3958                 "            OpBranch %if_merge\n"
3959
3960                 // Merge block for if-statement: placed in the middle of true and false branch.
3961                 "%if_merge = OpLabel\n"
3962                 "            OpReturn\n"
3963
3964                 // True branch for if-statement: placed in the middle of swtich cases and after the false branch.
3965                 "%if_true  = OpLabel\n"
3966                 "%xval_t   = OpLoad %u32 %xvar\n"
3967                 "%mod      = OpUMod %u32 %xval_t %const3\n"
3968                 "            OpSelectionMerge %switch_merge None\n"
3969                 "            OpSwitch %mod %default 0 %case0 1 %case1 2 %case2\n"
3970
3971                 // Merge block for switch-statement: placed before the case
3972                 // bodies.  But it must follow OpSwitch which dominates it.
3973                 "%switch_merge = OpLabel\n"
3974                 "                OpBranch %if_merge\n"
3975
3976                 // Case 1 for switch-statement: placed before case 0.
3977                 // It must follow the OpSwitch that dominates it.
3978                 "%case1    = OpLabel\n"
3979                 "%x_1      = OpLoad %u32 %xvar\n"
3980                 "%inloc_1  = OpAccessChain %f32ptr %indata %zero %x_1\n"
3981                 "%inval_1  = OpLoad %f32 %inloc_1\n"
3982                 "%addf42   = OpFAdd %f32 %inval_1 %constf42\n"
3983                 "%outloc_1 = OpAccessChain %f32ptr %outdata %zero %x_1\n"
3984                 "            OpStore %outloc_1 %addf42\n"
3985                 "            OpBranch %switch_merge\n"
3986
3987                 // Case 2 for switch-statement.
3988                 "%case2    = OpLabel\n"
3989                 "%x_2      = OpLoad %u32 %xvar\n"
3990                 "%inloc_2  = OpAccessChain %f32ptr %indata %zero %x_2\n"
3991                 "%inval_2  = OpLoad %f32 %inloc_2\n"
3992                 "%subf27   = OpFSub %f32 %inval_2 %constf27\n"
3993                 "%outloc_2 = OpAccessChain %f32ptr %outdata %zero %x_2\n"
3994                 "            OpStore %outloc_2 %subf27\n"
3995                 "            OpBranch %switch_merge\n"
3996
3997                 // Default case for switch-statement: placed in the middle of normal cases.
3998                 "%default = OpLabel\n"
3999                 "           OpBranch %switch_merge\n"
4000
4001                 // Case 0 for switch-statement: out of order.
4002                 "%case0    = OpLabel\n"
4003                 "%x_0      = OpLoad %u32 %xvar\n"
4004                 "%inloc_0  = OpAccessChain %f32ptr %indata %zero %x_0\n"
4005                 "%inval_0  = OpLoad %f32 %inloc_0\n"
4006                 "%addf1p5  = OpFAdd %f32 %inval_0 %constf1p5\n"
4007                 "%outloc_0 = OpAccessChain %f32ptr %outdata %zero %x_0\n"
4008                 "            OpStore %outloc_0 %addf1p5\n"
4009                 "            OpBranch %switch_merge\n"
4010
4011                 "            OpFunctionEnd\n";
4012         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4013         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
4014         spec.numWorkGroups = IVec3(numElements, 1, 1);
4015
4016         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "various out-of-order blocks", spec));
4017
4018         return group.release();
4019 }
4020
4021 tcu::TestCaseGroup* createMultipleShaderGroup (tcu::TestContext& testCtx)
4022 {
4023         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "multiple_shaders", "Test multiple shaders in the same module"));
4024         ComputeShaderSpec                               spec1;
4025         ComputeShaderSpec                               spec2;
4026         de::Random                                              rnd                             (deStringHash(group->getName()));
4027         const int                                               numElements             = 100;
4028         vector<float>                                   inputFloats             (numElements, 0);
4029         vector<float>                                   outputFloats1   (numElements, 0);
4030         vector<float>                                   outputFloats2   (numElements, 0);
4031         fillRandomScalars(rnd, -500.f, 500.f, &inputFloats[0], numElements);
4032
4033         for (size_t ndx = 0; ndx < numElements; ++ndx)
4034         {
4035                 outputFloats1[ndx] = inputFloats[ndx] + inputFloats[ndx];
4036                 outputFloats2[ndx] = -inputFloats[ndx];
4037         }
4038
4039         const string assembly(
4040                 "OpCapability Shader\n"
4041                 "OpMemoryModel Logical GLSL450\n"
4042                 "OpEntryPoint GLCompute %comp_main1 \"entrypoint1\" %id\n"
4043                 "OpEntryPoint GLCompute %comp_main2 \"entrypoint2\" %id\n"
4044                 // A module cannot have two OpEntryPoint instructions with the same Execution Model and the same Name string.
4045                 "OpEntryPoint Vertex    %vert_main  \"entrypoint2\" %vert_builtins %vertexIndex %instanceIndex\n"
4046                 "OpExecutionMode %comp_main1 LocalSize 1 1 1\n"
4047                 "OpExecutionMode %comp_main2 LocalSize 1 1 1\n"
4048
4049                 "OpName %comp_main1              \"entrypoint1\"\n"
4050                 "OpName %comp_main2              \"entrypoint2\"\n"
4051                 "OpName %vert_main               \"entrypoint2\"\n"
4052                 "OpName %id                      \"gl_GlobalInvocationID\"\n"
4053                 "OpName %vert_builtin_st         \"gl_PerVertex\"\n"
4054                 "OpName %vertexIndex             \"gl_VertexIndex\"\n"
4055                 "OpName %instanceIndex           \"gl_InstanceIndex\"\n"
4056                 "OpMemberName %vert_builtin_st 0 \"gl_Position\"\n"
4057                 "OpMemberName %vert_builtin_st 1 \"gl_PointSize\"\n"
4058                 "OpMemberName %vert_builtin_st 2 \"gl_ClipDistance\"\n"
4059
4060                 "OpDecorate %id                      BuiltIn GlobalInvocationId\n"
4061                 "OpDecorate %vertexIndex             BuiltIn VertexIndex\n"
4062                 "OpDecorate %instanceIndex           BuiltIn InstanceIndex\n"
4063                 "OpDecorate %vert_builtin_st         Block\n"
4064                 "OpMemberDecorate %vert_builtin_st 0 BuiltIn Position\n"
4065                 "OpMemberDecorate %vert_builtin_st 1 BuiltIn PointSize\n"
4066                 "OpMemberDecorate %vert_builtin_st 2 BuiltIn ClipDistance\n"
4067
4068                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4069
4070                 "%zero       = OpConstant %i32 0\n"
4071                 "%one        = OpConstant %u32 1\n"
4072                 "%c_f32_1    = OpConstant %f32 1\n"
4073
4074                 "%i32inputptr         = OpTypePointer Input %i32\n"
4075                 "%vec4                = OpTypeVector %f32 4\n"
4076                 "%vec4ptr             = OpTypePointer Output %vec4\n"
4077                 "%f32arr1             = OpTypeArray %f32 %one\n"
4078                 "%vert_builtin_st     = OpTypeStruct %vec4 %f32 %f32arr1\n"
4079                 "%vert_builtin_st_ptr = OpTypePointer Output %vert_builtin_st\n"
4080                 "%vert_builtins       = OpVariable %vert_builtin_st_ptr Output\n"
4081
4082                 "%id         = OpVariable %uvec3ptr Input\n"
4083                 "%vertexIndex = OpVariable %i32inputptr Input\n"
4084                 "%instanceIndex = OpVariable %i32inputptr Input\n"
4085                 "%c_vec4_1   = OpConstantComposite %vec4 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
4086
4087                 // gl_Position = vec4(1.);
4088                 "%vert_main  = OpFunction %void None %voidf\n"
4089                 "%vert_entry = OpLabel\n"
4090                 "%position   = OpAccessChain %vec4ptr %vert_builtins %zero\n"
4091                 "              OpStore %position %c_vec4_1\n"
4092                 "              OpReturn\n"
4093                 "              OpFunctionEnd\n"
4094
4095                 // Double inputs.
4096                 "%comp_main1  = OpFunction %void None %voidf\n"
4097                 "%comp1_entry = OpLabel\n"
4098                 "%idval1      = OpLoad %uvec3 %id\n"
4099                 "%x1          = OpCompositeExtract %u32 %idval1 0\n"
4100                 "%inloc1      = OpAccessChain %f32ptr %indata %zero %x1\n"
4101                 "%inval1      = OpLoad %f32 %inloc1\n"
4102                 "%add         = OpFAdd %f32 %inval1 %inval1\n"
4103                 "%outloc1     = OpAccessChain %f32ptr %outdata %zero %x1\n"
4104                 "               OpStore %outloc1 %add\n"
4105                 "               OpReturn\n"
4106                 "               OpFunctionEnd\n"
4107
4108                 // Negate inputs.
4109                 "%comp_main2  = OpFunction %void None %voidf\n"
4110                 "%comp2_entry = OpLabel\n"
4111                 "%idval2      = OpLoad %uvec3 %id\n"
4112                 "%x2          = OpCompositeExtract %u32 %idval2 0\n"
4113                 "%inloc2      = OpAccessChain %f32ptr %indata %zero %x2\n"
4114                 "%inval2      = OpLoad %f32 %inloc2\n"
4115                 "%neg         = OpFNegate %f32 %inval2\n"
4116                 "%outloc2     = OpAccessChain %f32ptr %outdata %zero %x2\n"
4117                 "               OpStore %outloc2 %neg\n"
4118                 "               OpReturn\n"
4119                 "               OpFunctionEnd\n");
4120
4121         spec1.assembly = assembly;
4122         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4123         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
4124         spec1.numWorkGroups = IVec3(numElements, 1, 1);
4125         spec1.entryPoint = "entrypoint1";
4126
4127         spec2.assembly = assembly;
4128         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4129         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
4130         spec2.numWorkGroups = IVec3(numElements, 1, 1);
4131         spec2.entryPoint = "entrypoint2";
4132
4133         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader1", "multiple shaders in the same module", spec1));
4134         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader2", "multiple shaders in the same module", spec2));
4135
4136         return group.release();
4137 }
4138
4139 inline std::string makeLongUTF8String (size_t num4ByteChars)
4140 {
4141         // An example of a longest valid UTF-8 character.  Be explicit about the
4142         // character type because Microsoft compilers can otherwise interpret the
4143         // character string as being over wide (16-bit) characters. Ideally, we
4144         // would just use a C++11 UTF-8 string literal, but we want to support older
4145         // Microsoft compilers.
4146         const std::basic_string<char> earthAfrica("\xF0\x9F\x8C\x8D");
4147         std::string longString;
4148         longString.reserve(num4ByteChars * 4);
4149         for (size_t count = 0; count < num4ByteChars; count++)
4150         {
4151                 longString += earthAfrica;
4152         }
4153         return longString;
4154 }
4155
4156 tcu::TestCaseGroup* createOpSourceGroup (tcu::TestContext& testCtx)
4157 {
4158         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsource", "Tests the OpSource & OpSourceContinued instruction"));
4159         vector<CaseParameter>                   cases;
4160         de::Random                                              rnd                             (deStringHash(group->getName()));
4161         const int                                               numElements             = 100;
4162         vector<float>                                   positiveFloats  (numElements, 0);
4163         vector<float>                                   negativeFloats  (numElements, 0);
4164         const StringTemplate                    shaderTemplate  (
4165                 "OpCapability Shader\n"
4166                 "OpMemoryModel Logical GLSL450\n"
4167
4168                 "OpEntryPoint GLCompute %main \"main\" %id\n"
4169                 "OpExecutionMode %main LocalSize 1 1 1\n"
4170
4171                 "${SOURCE}\n"
4172
4173                 "OpName %main           \"main\"\n"
4174                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4175
4176                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4177
4178                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4179
4180                 "%id        = OpVariable %uvec3ptr Input\n"
4181                 "%zero      = OpConstant %i32 0\n"
4182
4183                 "%main      = OpFunction %void None %voidf\n"
4184                 "%label     = OpLabel\n"
4185                 "%idval     = OpLoad %uvec3 %id\n"
4186                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4187                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4188                 "%inval     = OpLoad %f32 %inloc\n"
4189                 "%neg       = OpFNegate %f32 %inval\n"
4190                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4191                 "             OpStore %outloc %neg\n"
4192                 "             OpReturn\n"
4193                 "             OpFunctionEnd\n");
4194
4195         cases.push_back(CaseParameter("unknown_source",                                                 "OpSource Unknown 0"));
4196         cases.push_back(CaseParameter("wrong_source",                                                   "OpSource OpenCL_C 210"));
4197         cases.push_back(CaseParameter("normal_filename",                                                "%fname = OpString \"filename\"\n"
4198                                                                                                                                                         "OpSource GLSL 430 %fname"));
4199         cases.push_back(CaseParameter("empty_filename",                                                 "%fname = OpString \"\"\n"
4200                                                                                                                                                         "OpSource GLSL 430 %fname"));
4201         cases.push_back(CaseParameter("normal_source_code",                                             "%fname = OpString \"filename\"\n"
4202                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\""));
4203         cases.push_back(CaseParameter("empty_source_code",                                              "%fname = OpString \"filename\"\n"
4204                                                                                                                                                         "OpSource GLSL 430 %fname \"\""));
4205         cases.push_back(CaseParameter("long_source_code",                                               "%fname = OpString \"filename\"\n"
4206                                                                                                                                                         "OpSource GLSL 430 %fname \"" + makeLongUTF8String(65530) + "ccc\"")); // word count: 65535
4207         cases.push_back(CaseParameter("utf8_source_code",                                               "%fname = OpString \"filename\"\n"
4208                                                                                                                                                         "OpSource GLSL 430 %fname \"\xE2\x98\x82\xE2\x98\x85\"")); // umbrella & black star symbol
4209         cases.push_back(CaseParameter("normal_sourcecontinued",                                 "%fname = OpString \"filename\"\n"
4210                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvo\"\n"
4211                                                                                                                                                         "OpSourceContinued \"id main() {}\""));
4212         cases.push_back(CaseParameter("empty_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
4213                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4214                                                                                                                                                         "OpSourceContinued \"\""));
4215         cases.push_back(CaseParameter("long_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
4216                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4217                                                                                                                                                         "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\"")); // word count: 65535
4218         cases.push_back(CaseParameter("utf8_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
4219                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4220                                                                                                                                                         "OpSourceContinued \"\xE2\x98\x8E\xE2\x9A\x91\"")); // white telephone & black flag symbol
4221         cases.push_back(CaseParameter("multi_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
4222                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\n\"\n"
4223                                                                                                                                                         "OpSourceContinued \"void\"\n"
4224                                                                                                                                                         "OpSourceContinued \"main()\"\n"
4225                                                                                                                                                         "OpSourceContinued \"{}\""));
4226         cases.push_back(CaseParameter("empty_source_before_sourcecontinued",    "%fname = OpString \"filename\"\n"
4227                                                                                                                                                         "OpSource GLSL 430 %fname \"\"\n"
4228                                                                                                                                                         "OpSourceContinued \"#version 430\nvoid main() {}\""));
4229
4230         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4231
4232         for (size_t ndx = 0; ndx < numElements; ++ndx)
4233                 negativeFloats[ndx] = -positiveFloats[ndx];
4234
4235         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4236         {
4237                 map<string, string>             specializations;
4238                 ComputeShaderSpec               spec;
4239
4240                 specializations["SOURCE"] = cases[caseNdx].param;
4241                 spec.assembly = shaderTemplate.specialize(specializations);
4242                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4243                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4244                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4245
4246                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4247         }
4248
4249         return group.release();
4250 }
4251
4252 tcu::TestCaseGroup* createOpSourceExtensionGroup (tcu::TestContext& testCtx)
4253 {
4254         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsourceextension", "Tests the OpSource instruction"));
4255         vector<CaseParameter>                   cases;
4256         de::Random                                              rnd                             (deStringHash(group->getName()));
4257         const int                                               numElements             = 100;
4258         vector<float>                                   inputFloats             (numElements, 0);
4259         vector<float>                                   outputFloats    (numElements, 0);
4260         const StringTemplate                    shaderTemplate  (
4261                 string(getComputeAsmShaderPreamble()) +
4262
4263                 "OpSourceExtension \"${EXTENSION}\"\n"
4264
4265                 "OpName %main           \"main\"\n"
4266                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4267
4268                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4269
4270                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4271
4272                 "%id        = OpVariable %uvec3ptr Input\n"
4273                 "%zero      = OpConstant %i32 0\n"
4274
4275                 "%main      = OpFunction %void None %voidf\n"
4276                 "%label     = OpLabel\n"
4277                 "%idval     = OpLoad %uvec3 %id\n"
4278                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4279                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4280                 "%inval     = OpLoad %f32 %inloc\n"
4281                 "%neg       = OpFNegate %f32 %inval\n"
4282                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4283                 "             OpStore %outloc %neg\n"
4284                 "             OpReturn\n"
4285                 "             OpFunctionEnd\n");
4286
4287         cases.push_back(CaseParameter("empty_extension",        ""));
4288         cases.push_back(CaseParameter("real_extension",         "GL_ARB_texture_rectangle"));
4289         cases.push_back(CaseParameter("fake_extension",         "GL_ARB_im_the_ultimate_extension"));
4290         cases.push_back(CaseParameter("utf8_extension",         "GL_ARB_\xE2\x98\x82\xE2\x98\x85"));
4291         cases.push_back(CaseParameter("long_extension",         makeLongUTF8String(65533) + "ccc")); // word count: 65535
4292
4293         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
4294
4295         for (size_t ndx = 0; ndx < numElements; ++ndx)
4296                 outputFloats[ndx] = -inputFloats[ndx];
4297
4298         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4299         {
4300                 map<string, string>             specializations;
4301                 ComputeShaderSpec               spec;
4302
4303                 specializations["EXTENSION"] = cases[caseNdx].param;
4304                 spec.assembly = shaderTemplate.specialize(specializations);
4305                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4306                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
4307                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4308
4309                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4310         }
4311
4312         return group.release();
4313 }
4314
4315 // Checks that a compute shader can generate a constant null value of various types, without exercising a computation on it.
4316 tcu::TestCaseGroup* createOpConstantNullGroup (tcu::TestContext& testCtx)
4317 {
4318         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnull", "Tests the OpConstantNull instruction"));
4319         vector<CaseParameter>                   cases;
4320         de::Random                                              rnd                             (deStringHash(group->getName()));
4321         const int                                               numElements             = 100;
4322         vector<float>                                   positiveFloats  (numElements, 0);
4323         vector<float>                                   negativeFloats  (numElements, 0);
4324         const StringTemplate                    shaderTemplate  (
4325                 string(getComputeAsmShaderPreamble()) +
4326
4327                 "OpSource GLSL 430\n"
4328                 "OpName %main           \"main\"\n"
4329                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4330
4331                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4332
4333                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4334                 "%uvec2     = OpTypeVector %u32 2\n"
4335                 "%bvec3     = OpTypeVector %bool 3\n"
4336                 "%fvec4     = OpTypeVector %f32 4\n"
4337                 "%fmat33    = OpTypeMatrix %fvec3 3\n"
4338                 "%const100  = OpConstant %u32 100\n"
4339                 "%uarr100   = OpTypeArray %i32 %const100\n"
4340                 "%struct    = OpTypeStruct %f32 %i32 %u32\n"
4341                 "%pointer   = OpTypePointer Function %i32\n"
4342                 + string(getComputeAsmInputOutputBuffer()) +
4343
4344                 "%null      = OpConstantNull ${TYPE}\n"
4345
4346                 "%id        = OpVariable %uvec3ptr Input\n"
4347                 "%zero      = OpConstant %i32 0\n"
4348
4349                 "%main      = OpFunction %void None %voidf\n"
4350                 "%label     = OpLabel\n"
4351                 "%idval     = OpLoad %uvec3 %id\n"
4352                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4353                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4354                 "%inval     = OpLoad %f32 %inloc\n"
4355                 "%neg       = OpFNegate %f32 %inval\n"
4356                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4357                 "             OpStore %outloc %neg\n"
4358                 "             OpReturn\n"
4359                 "             OpFunctionEnd\n");
4360
4361         cases.push_back(CaseParameter("bool",                   "%bool"));
4362         cases.push_back(CaseParameter("sint32",                 "%i32"));
4363         cases.push_back(CaseParameter("uint32",                 "%u32"));
4364         cases.push_back(CaseParameter("float32",                "%f32"));
4365         cases.push_back(CaseParameter("vec4float32",    "%fvec4"));
4366         cases.push_back(CaseParameter("vec3bool",               "%bvec3"));
4367         cases.push_back(CaseParameter("vec2uint32",             "%uvec2"));
4368         cases.push_back(CaseParameter("matrix",                 "%fmat33"));
4369         cases.push_back(CaseParameter("array",                  "%uarr100"));
4370         cases.push_back(CaseParameter("struct",                 "%struct"));
4371         cases.push_back(CaseParameter("pointer",                "%pointer"));
4372
4373         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4374
4375         for (size_t ndx = 0; ndx < numElements; ++ndx)
4376                 negativeFloats[ndx] = -positiveFloats[ndx];
4377
4378         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4379         {
4380                 map<string, string>             specializations;
4381                 ComputeShaderSpec               spec;
4382
4383                 specializations["TYPE"] = cases[caseNdx].param;
4384                 spec.assembly = shaderTemplate.specialize(specializations);
4385                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4386                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4387                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4388
4389                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4390         }
4391
4392         return group.release();
4393 }
4394
4395 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
4396 tcu::TestCaseGroup* createOpConstantCompositeGroup (tcu::TestContext& testCtx)
4397 {
4398         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "Tests the OpConstantComposite instruction"));
4399         vector<CaseParameter>                   cases;
4400         de::Random                                              rnd                             (deStringHash(group->getName()));
4401         const int                                               numElements             = 100;
4402         vector<float>                                   positiveFloats  (numElements, 0);
4403         vector<float>                                   negativeFloats  (numElements, 0);
4404         const StringTemplate                    shaderTemplate  (
4405                 string(getComputeAsmShaderPreamble()) +
4406
4407                 "OpSource GLSL 430\n"
4408                 "OpName %main           \"main\"\n"
4409                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4410
4411                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4412
4413                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4414
4415                 "%id        = OpVariable %uvec3ptr Input\n"
4416                 "%zero      = OpConstant %i32 0\n"
4417
4418                 "${CONSTANT}\n"
4419
4420                 "%main      = OpFunction %void None %voidf\n"
4421                 "%label     = OpLabel\n"
4422                 "%idval     = OpLoad %uvec3 %id\n"
4423                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4424                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4425                 "%inval     = OpLoad %f32 %inloc\n"
4426                 "%neg       = OpFNegate %f32 %inval\n"
4427                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4428                 "             OpStore %outloc %neg\n"
4429                 "             OpReturn\n"
4430                 "             OpFunctionEnd\n");
4431
4432         cases.push_back(CaseParameter("vector",                 "%five = OpConstant %u32 5\n"
4433                                                                                                         "%const = OpConstantComposite %uvec3 %five %zero %five"));
4434         cases.push_back(CaseParameter("matrix",                 "%m3fvec3 = OpTypeMatrix %fvec3 3\n"
4435                                                                                                         "%ten = OpConstant %f32 10.\n"
4436                                                                                                         "%fzero = OpConstant %f32 0.\n"
4437                                                                                                         "%vec = OpConstantComposite %fvec3 %ten %fzero %ten\n"
4438                                                                                                         "%mat = OpConstantComposite %m3fvec3 %vec %vec %vec"));
4439         cases.push_back(CaseParameter("struct",                 "%m2vec3 = OpTypeMatrix %fvec3 2\n"
4440                                                                                                         "%struct = OpTypeStruct %i32 %f32 %fvec3 %m2vec3\n"
4441                                                                                                         "%fzero = OpConstant %f32 0.\n"
4442                                                                                                         "%one = OpConstant %f32 1.\n"
4443                                                                                                         "%point5 = OpConstant %f32 0.5\n"
4444                                                                                                         "%vec = OpConstantComposite %fvec3 %one %one %fzero\n"
4445                                                                                                         "%mat = OpConstantComposite %m2vec3 %vec %vec\n"
4446                                                                                                         "%const = OpConstantComposite %struct %zero %point5 %vec %mat"));
4447         cases.push_back(CaseParameter("nested_struct",  "%st1 = OpTypeStruct %u32 %f32\n"
4448                                                                                                         "%st2 = OpTypeStruct %i32 %i32\n"
4449                                                                                                         "%struct = OpTypeStruct %st1 %st2\n"
4450                                                                                                         "%point5 = OpConstant %f32 0.5\n"
4451                                                                                                         "%one = OpConstant %u32 1\n"
4452                                                                                                         "%ten = OpConstant %i32 10\n"
4453                                                                                                         "%st1val = OpConstantComposite %st1 %one %point5\n"
4454                                                                                                         "%st2val = OpConstantComposite %st2 %ten %ten\n"
4455                                                                                                         "%const = OpConstantComposite %struct %st1val %st2val"));
4456
4457         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4458
4459         for (size_t ndx = 0; ndx < numElements; ++ndx)
4460                 negativeFloats[ndx] = -positiveFloats[ndx];
4461
4462         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4463         {
4464                 map<string, string>             specializations;
4465                 ComputeShaderSpec               spec;
4466
4467                 specializations["CONSTANT"] = cases[caseNdx].param;
4468                 spec.assembly = shaderTemplate.specialize(specializations);
4469                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4470                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4471                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4472
4473                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4474         }
4475
4476         return group.release();
4477 }
4478
4479 // Creates a floating point number with the given exponent, and significand
4480 // bits set. It can only create normalized numbers. Only the least significant
4481 // 24 bits of the significand will be examined. The final bit of the
4482 // significand will also be ignored. This allows alignment to be written
4483 // similarly to C99 hex-floats.
4484 // For example if you wanted to write 0x1.7f34p-12 you would call
4485 // constructNormalizedFloat(-12, 0x7f3400)
4486 float constructNormalizedFloat (deInt32 exponent, deUint32 significand)
4487 {
4488         float f = 1.0f;
4489
4490         for (deInt32 idx = 0; idx < 23; ++idx)
4491         {
4492                 f += ((significand & 0x800000) == 0) ? 0.f : std::ldexp(1.0f, -(idx + 1));
4493                 significand <<= 1;
4494         }
4495
4496         return std::ldexp(f, exponent);
4497 }
4498
4499 // Compare instruction for the OpQuantizeF16 compute exact case.
4500 // Returns true if the output is what is expected from the test case.
4501 bool compareOpQuantizeF16ComputeExactCase (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
4502 {
4503         if (outputAllocs.size() != 1)
4504                 return false;
4505
4506         // Only size is needed because we cannot compare Nans.
4507         size_t byteSize = expectedOutputs[0].getByteSize();
4508
4509         const float*    outputAsFloat   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
4510
4511         if (byteSize != 4*sizeof(float)) {
4512                 return false;
4513         }
4514
4515         if (*outputAsFloat != constructNormalizedFloat(8, 0x304000) &&
4516                 *outputAsFloat != constructNormalizedFloat(8, 0x300000)) {
4517                 return false;
4518         }
4519         outputAsFloat++;
4520
4521         if (*outputAsFloat != -constructNormalizedFloat(-7, 0x600000) &&
4522                 *outputAsFloat != -constructNormalizedFloat(-7, 0x604000)) {
4523                 return false;
4524         }
4525         outputAsFloat++;
4526
4527         if (*outputAsFloat != constructNormalizedFloat(2, 0x01C000) &&
4528                 *outputAsFloat != constructNormalizedFloat(2, 0x020000)) {
4529                 return false;
4530         }
4531         outputAsFloat++;
4532
4533         if (*outputAsFloat != constructNormalizedFloat(1, 0xFFC000) &&
4534                 *outputAsFloat != constructNormalizedFloat(2, 0x000000)) {
4535                 return false;
4536         }
4537
4538         return true;
4539 }
4540
4541 // Checks that every output from a test-case is a float NaN.
4542 bool compareNan (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
4543 {
4544         if (outputAllocs.size() != 1)
4545                 return false;
4546
4547         // Only size is needed because we cannot compare Nans.
4548         size_t byteSize = expectedOutputs[0].getByteSize();
4549
4550         const float* const      output_as_float = static_cast<const float*>(outputAllocs[0]->getHostPtr());
4551
4552         for (size_t idx = 0; idx < byteSize / sizeof(float); ++idx)
4553         {
4554                 if (!deFloatIsNaN(output_as_float[idx]))
4555                 {
4556                         return false;
4557                 }
4558         }
4559
4560         return true;
4561 }
4562
4563 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
4564 tcu::TestCaseGroup* createOpQuantizeToF16Group (tcu::TestContext& testCtx)
4565 {
4566         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opquantize", "Tests the OpQuantizeToF16 instruction"));
4567
4568         const std::string shader (
4569                 string(getComputeAsmShaderPreamble()) +
4570
4571                 "OpSource GLSL 430\n"
4572                 "OpName %main           \"main\"\n"
4573                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4574
4575                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4576
4577                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4578
4579                 "%id        = OpVariable %uvec3ptr Input\n"
4580                 "%zero      = OpConstant %i32 0\n"
4581
4582                 "%main      = OpFunction %void None %voidf\n"
4583                 "%label     = OpLabel\n"
4584                 "%idval     = OpLoad %uvec3 %id\n"
4585                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4586                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4587                 "%inval     = OpLoad %f32 %inloc\n"
4588                 "%quant     = OpQuantizeToF16 %f32 %inval\n"
4589                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4590                 "             OpStore %outloc %quant\n"
4591                 "             OpReturn\n"
4592                 "             OpFunctionEnd\n");
4593
4594         {
4595                 ComputeShaderSpec       spec;
4596                 const deUint32          numElements             = 100;
4597                 vector<float>           infinities;
4598                 vector<float>           results;
4599
4600                 infinities.reserve(numElements);
4601                 results.reserve(numElements);
4602
4603                 for (size_t idx = 0; idx < numElements; ++idx)
4604                 {
4605                         switch(idx % 4)
4606                         {
4607                                 case 0:
4608                                         infinities.push_back(std::numeric_limits<float>::infinity());
4609                                         results.push_back(std::numeric_limits<float>::infinity());
4610                                         break;
4611                                 case 1:
4612                                         infinities.push_back(-std::numeric_limits<float>::infinity());
4613                                         results.push_back(-std::numeric_limits<float>::infinity());
4614                                         break;
4615                                 case 2:
4616                                         infinities.push_back(std::ldexp(1.0f, 16));
4617                                         results.push_back(std::numeric_limits<float>::infinity());
4618                                         break;
4619                                 case 3:
4620                                         infinities.push_back(std::ldexp(-1.0f, 32));
4621                                         results.push_back(-std::numeric_limits<float>::infinity());
4622                                         break;
4623                         }
4624                 }
4625
4626                 spec.assembly = shader;
4627                 spec.inputs.push_back(BufferSp(new Float32Buffer(infinities)));
4628                 spec.outputs.push_back(BufferSp(new Float32Buffer(results)));
4629                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4630
4631                 group->addChild(new SpvAsmComputeShaderCase(
4632                         testCtx, "infinities", "Check that infinities propagated and created", spec));
4633         }
4634
4635         {
4636                 ComputeShaderSpec       spec;
4637                 vector<float>           nans;
4638                 const deUint32          numElements             = 100;
4639
4640                 nans.reserve(numElements);
4641
4642                 for (size_t idx = 0; idx < numElements; ++idx)
4643                 {
4644                         if (idx % 2 == 0)
4645                         {
4646                                 nans.push_back(std::numeric_limits<float>::quiet_NaN());
4647                         }
4648                         else
4649                         {
4650                                 nans.push_back(-std::numeric_limits<float>::quiet_NaN());
4651                         }
4652                 }
4653
4654                 spec.assembly = shader;
4655                 spec.inputs.push_back(BufferSp(new Float32Buffer(nans)));
4656                 spec.outputs.push_back(BufferSp(new Float32Buffer(nans)));
4657                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4658                 spec.verifyIO = &compareNan;
4659
4660                 group->addChild(new SpvAsmComputeShaderCase(
4661                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
4662         }
4663
4664         {
4665                 ComputeShaderSpec       spec;
4666                 vector<float>           small;
4667                 vector<float>           zeros;
4668                 const deUint32          numElements             = 100;
4669
4670                 small.reserve(numElements);
4671                 zeros.reserve(numElements);
4672
4673                 for (size_t idx = 0; idx < numElements; ++idx)
4674                 {
4675                         switch(idx % 6)
4676                         {
4677                                 case 0:
4678                                         small.push_back(0.f);
4679                                         zeros.push_back(0.f);
4680                                         break;
4681                                 case 1:
4682                                         small.push_back(-0.f);
4683                                         zeros.push_back(-0.f);
4684                                         break;
4685                                 case 2:
4686                                         small.push_back(std::ldexp(1.0f, -16));
4687                                         zeros.push_back(0.f);
4688                                         break;
4689                                 case 3:
4690                                         small.push_back(std::ldexp(-1.0f, -32));
4691                                         zeros.push_back(-0.f);
4692                                         break;
4693                                 case 4:
4694                                         small.push_back(std::ldexp(1.0f, -127));
4695                                         zeros.push_back(0.f);
4696                                         break;
4697                                 case 5:
4698                                         small.push_back(-std::ldexp(1.0f, -128));
4699                                         zeros.push_back(-0.f);
4700                                         break;
4701                         }
4702                 }
4703
4704                 spec.assembly = shader;
4705                 spec.inputs.push_back(BufferSp(new Float32Buffer(small)));
4706                 spec.outputs.push_back(BufferSp(new Float32Buffer(zeros)));
4707                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4708
4709                 group->addChild(new SpvAsmComputeShaderCase(
4710                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
4711         }
4712
4713         {
4714                 ComputeShaderSpec       spec;
4715                 vector<float>           exact;
4716                 const deUint32          numElements             = 200;
4717
4718                 exact.reserve(numElements);
4719
4720                 for (size_t idx = 0; idx < numElements; ++idx)
4721                         exact.push_back(static_cast<float>(static_cast<int>(idx) - 100));
4722
4723                 spec.assembly = shader;
4724                 spec.inputs.push_back(BufferSp(new Float32Buffer(exact)));
4725                 spec.outputs.push_back(BufferSp(new Float32Buffer(exact)));
4726                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4727
4728                 group->addChild(new SpvAsmComputeShaderCase(
4729                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
4730         }
4731
4732         {
4733                 ComputeShaderSpec       spec;
4734                 vector<float>           inputs;
4735                 const deUint32          numElements             = 4;
4736
4737                 inputs.push_back(constructNormalizedFloat(8,    0x300300));
4738                 inputs.push_back(-constructNormalizedFloat(-7,  0x600800));
4739                 inputs.push_back(constructNormalizedFloat(2,    0x01E000));
4740                 inputs.push_back(constructNormalizedFloat(1,    0xFFE000));
4741
4742                 spec.assembly = shader;
4743                 spec.verifyIO = &compareOpQuantizeF16ComputeExactCase;
4744                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4745                 spec.outputs.push_back(BufferSp(new Float32Buffer(inputs)));
4746                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4747
4748                 group->addChild(new SpvAsmComputeShaderCase(
4749                         testCtx, "rounded", "Check that are rounded when needed", spec));
4750         }
4751
4752         return group.release();
4753 }
4754
4755 tcu::TestCaseGroup* createSpecConstantOpQuantizeToF16Group (tcu::TestContext& testCtx)
4756 {
4757         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opspecconstantop_opquantize", "Tests the OpQuantizeToF16 opcode for the OpSpecConstantOp instruction"));
4758
4759         const std::string shader (
4760                 string(getComputeAsmShaderPreamble()) +
4761
4762                 "OpName %main           \"main\"\n"
4763                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4764
4765                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4766
4767                 "OpDecorate %sc_0  SpecId 0\n"
4768                 "OpDecorate %sc_1  SpecId 1\n"
4769                 "OpDecorate %sc_2  SpecId 2\n"
4770                 "OpDecorate %sc_3  SpecId 3\n"
4771                 "OpDecorate %sc_4  SpecId 4\n"
4772                 "OpDecorate %sc_5  SpecId 5\n"
4773
4774                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4775
4776                 "%id        = OpVariable %uvec3ptr Input\n"
4777                 "%zero      = OpConstant %i32 0\n"
4778                 "%c_u32_6   = OpConstant %u32 6\n"
4779
4780                 "%sc_0      = OpSpecConstant %f32 0.\n"
4781                 "%sc_1      = OpSpecConstant %f32 0.\n"
4782                 "%sc_2      = OpSpecConstant %f32 0.\n"
4783                 "%sc_3      = OpSpecConstant %f32 0.\n"
4784                 "%sc_4      = OpSpecConstant %f32 0.\n"
4785                 "%sc_5      = OpSpecConstant %f32 0.\n"
4786
4787                 "%sc_0_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_0\n"
4788                 "%sc_1_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_1\n"
4789                 "%sc_2_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_2\n"
4790                 "%sc_3_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_3\n"
4791                 "%sc_4_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_4\n"
4792                 "%sc_5_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_5\n"
4793
4794                 "%main      = OpFunction %void None %voidf\n"
4795                 "%label     = OpLabel\n"
4796                 "%idval     = OpLoad %uvec3 %id\n"
4797                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4798                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4799                 "%selector  = OpUMod %u32 %x %c_u32_6\n"
4800                 "            OpSelectionMerge %exit None\n"
4801                 "            OpSwitch %selector %exit 0 %case0 1 %case1 2 %case2 3 %case3 4 %case4 5 %case5\n"
4802
4803                 "%case0     = OpLabel\n"
4804                 "             OpStore %outloc %sc_0_quant\n"
4805                 "             OpBranch %exit\n"
4806
4807                 "%case1     = OpLabel\n"
4808                 "             OpStore %outloc %sc_1_quant\n"
4809                 "             OpBranch %exit\n"
4810
4811                 "%case2     = OpLabel\n"
4812                 "             OpStore %outloc %sc_2_quant\n"
4813                 "             OpBranch %exit\n"
4814
4815                 "%case3     = OpLabel\n"
4816                 "             OpStore %outloc %sc_3_quant\n"
4817                 "             OpBranch %exit\n"
4818
4819                 "%case4     = OpLabel\n"
4820                 "             OpStore %outloc %sc_4_quant\n"
4821                 "             OpBranch %exit\n"
4822
4823                 "%case5     = OpLabel\n"
4824                 "             OpStore %outloc %sc_5_quant\n"
4825                 "             OpBranch %exit\n"
4826
4827                 "%exit      = OpLabel\n"
4828                 "             OpReturn\n"
4829
4830                 "             OpFunctionEnd\n");
4831
4832         {
4833                 ComputeShaderSpec       spec;
4834                 const deUint8           numCases        = 4;
4835                 vector<float>           inputs          (numCases, 0.f);
4836                 vector<float>           outputs;
4837
4838                 spec.assembly           = shader;
4839                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4840
4841                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::numeric_limits<float>::infinity()));
4842                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-std::numeric_limits<float>::infinity()));
4843                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, 16)));
4844                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(-1.0f, 32)));
4845
4846                 outputs.push_back(std::numeric_limits<float>::infinity());
4847                 outputs.push_back(-std::numeric_limits<float>::infinity());
4848                 outputs.push_back(std::numeric_limits<float>::infinity());
4849                 outputs.push_back(-std::numeric_limits<float>::infinity());
4850
4851                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4852                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4853
4854                 group->addChild(new SpvAsmComputeShaderCase(
4855                         testCtx, "infinities", "Check that infinities propagated and created", spec));
4856         }
4857
4858         {
4859                 ComputeShaderSpec       spec;
4860                 const deUint8           numCases        = 2;
4861                 vector<float>           inputs          (numCases, 0.f);
4862                 vector<float>           outputs;
4863
4864                 spec.assembly           = shader;
4865                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4866                 spec.verifyIO           = &compareNan;
4867
4868                 outputs.push_back(std::numeric_limits<float>::quiet_NaN());
4869                 outputs.push_back(-std::numeric_limits<float>::quiet_NaN());
4870
4871                 for (deUint8 idx = 0; idx < numCases; ++idx)
4872                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(outputs[idx]));
4873
4874                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4875                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4876
4877                 group->addChild(new SpvAsmComputeShaderCase(
4878                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
4879         }
4880
4881         {
4882                 ComputeShaderSpec       spec;
4883                 const deUint8           numCases        = 6;
4884                 vector<float>           inputs          (numCases, 0.f);
4885                 vector<float>           outputs;
4886
4887                 spec.assembly           = shader;
4888                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4889
4890                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(0.f));
4891                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-0.f));
4892                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, -16)));
4893                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(-1.0f, -32)));
4894                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, -127)));
4895                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-std::ldexp(1.0f, -128)));
4896
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                 outputs.push_back(0.f);
4902                 outputs.push_back(-0.f);
4903
4904                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4905                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4906
4907                 group->addChild(new SpvAsmComputeShaderCase(
4908                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
4909         }
4910
4911         {
4912                 ComputeShaderSpec       spec;
4913                 const deUint8           numCases        = 6;
4914                 vector<float>           inputs          (numCases, 0.f);
4915                 vector<float>           outputs;
4916
4917                 spec.assembly           = shader;
4918                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4919
4920                 for (deUint8 idx = 0; idx < 6; ++idx)
4921                 {
4922                         const float f = static_cast<float>(idx * 10 - 30) / 4.f;
4923                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(f));
4924                         outputs.push_back(f);
4925                 }
4926
4927                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4928                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4929
4930                 group->addChild(new SpvAsmComputeShaderCase(
4931                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
4932         }
4933
4934         {
4935                 ComputeShaderSpec       spec;
4936                 const deUint8           numCases        = 4;
4937                 vector<float>           inputs          (numCases, 0.f);
4938                 vector<float>           outputs;
4939
4940                 spec.assembly           = shader;
4941                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4942                 spec.verifyIO           = &compareOpQuantizeF16ComputeExactCase;
4943
4944                 outputs.push_back(constructNormalizedFloat(8, 0x300300));
4945                 outputs.push_back(-constructNormalizedFloat(-7, 0x600800));
4946                 outputs.push_back(constructNormalizedFloat(2, 0x01E000));
4947                 outputs.push_back(constructNormalizedFloat(1, 0xFFE000));
4948
4949                 for (deUint8 idx = 0; idx < numCases; ++idx)
4950                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(outputs[idx]));
4951
4952                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4953                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4954
4955                 group->addChild(new SpvAsmComputeShaderCase(
4956                         testCtx, "rounded", "Check that are rounded when needed", spec));
4957         }
4958
4959         return group.release();
4960 }
4961
4962 // Checks that constant null/composite values can be used in computation.
4963 tcu::TestCaseGroup* createOpConstantUsageGroup (tcu::TestContext& testCtx)
4964 {
4965         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnullcomposite", "Spotcheck the OpConstantNull & OpConstantComposite instruction"));
4966         ComputeShaderSpec                               spec;
4967         de::Random                                              rnd                             (deStringHash(group->getName()));
4968         const int                                               numElements             = 100;
4969         vector<float>                                   positiveFloats  (numElements, 0);
4970         vector<float>                                   negativeFloats  (numElements, 0);
4971
4972         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4973
4974         for (size_t ndx = 0; ndx < numElements; ++ndx)
4975                 negativeFloats[ndx] = -positiveFloats[ndx];
4976
4977         spec.assembly =
4978                 "OpCapability Shader\n"
4979                 "%std450 = OpExtInstImport \"GLSL.std.450\"\n"
4980                 "OpMemoryModel Logical GLSL450\n"
4981                 "OpEntryPoint GLCompute %main \"main\" %id\n"
4982                 "OpExecutionMode %main LocalSize 1 1 1\n"
4983
4984                 "OpSource GLSL 430\n"
4985                 "OpName %main           \"main\"\n"
4986                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4987
4988                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4989
4990                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4991
4992                 "%fmat      = OpTypeMatrix %fvec3 3\n"
4993                 "%ten       = OpConstant %u32 10\n"
4994                 "%f32arr10  = OpTypeArray %f32 %ten\n"
4995                 "%fst       = OpTypeStruct %f32 %f32\n"
4996
4997                 + string(getComputeAsmInputOutputBuffer()) +
4998
4999                 "%id        = OpVariable %uvec3ptr Input\n"
5000                 "%zero      = OpConstant %i32 0\n"
5001
5002                 // Create a bunch of null values
5003                 "%unull     = OpConstantNull %u32\n"
5004                 "%fnull     = OpConstantNull %f32\n"
5005                 "%vnull     = OpConstantNull %fvec3\n"
5006                 "%mnull     = OpConstantNull %fmat\n"
5007                 "%anull     = OpConstantNull %f32arr10\n"
5008                 "%snull     = OpConstantComposite %fst %fnull %fnull\n"
5009
5010                 "%main      = OpFunction %void None %voidf\n"
5011                 "%label     = OpLabel\n"
5012                 "%idval     = OpLoad %uvec3 %id\n"
5013                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5014                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5015                 "%inval     = OpLoad %f32 %inloc\n"
5016                 "%neg       = OpFNegate %f32 %inval\n"
5017
5018                 // Get the abs() of (a certain element of) those null values
5019                 "%unull_cov = OpConvertUToF %f32 %unull\n"
5020                 "%unull_abs = OpExtInst %f32 %std450 FAbs %unull_cov\n"
5021                 "%fnull_abs = OpExtInst %f32 %std450 FAbs %fnull\n"
5022                 "%vnull_0   = OpCompositeExtract %f32 %vnull 0\n"
5023                 "%vnull_abs = OpExtInst %f32 %std450 FAbs %vnull_0\n"
5024                 "%mnull_12  = OpCompositeExtract %f32 %mnull 1 2\n"
5025                 "%mnull_abs = OpExtInst %f32 %std450 FAbs %mnull_12\n"
5026                 "%anull_3   = OpCompositeExtract %f32 %anull 3\n"
5027                 "%anull_abs = OpExtInst %f32 %std450 FAbs %anull_3\n"
5028                 "%snull_1   = OpCompositeExtract %f32 %snull 1\n"
5029                 "%snull_abs = OpExtInst %f32 %std450 FAbs %snull_1\n"
5030
5031                 // Add them all
5032                 "%add1      = OpFAdd %f32 %neg  %unull_abs\n"
5033                 "%add2      = OpFAdd %f32 %add1 %fnull_abs\n"
5034                 "%add3      = OpFAdd %f32 %add2 %vnull_abs\n"
5035                 "%add4      = OpFAdd %f32 %add3 %mnull_abs\n"
5036                 "%add5      = OpFAdd %f32 %add4 %anull_abs\n"
5037                 "%final     = OpFAdd %f32 %add5 %snull_abs\n"
5038
5039                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5040                 "             OpStore %outloc %final\n" // write to output
5041                 "             OpReturn\n"
5042                 "             OpFunctionEnd\n";
5043         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
5044         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
5045         spec.numWorkGroups = IVec3(numElements, 1, 1);
5046
5047         group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "Check that values constructed via OpConstantNull & OpConstantComposite can be used", spec));
5048
5049         return group.release();
5050 }
5051
5052 // Assembly code used for testing loop control is based on GLSL source code:
5053 // #version 430
5054 //
5055 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5056 //   float elements[];
5057 // } input_data;
5058 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5059 //   float elements[];
5060 // } output_data;
5061 //
5062 // void main() {
5063 //   uint x = gl_GlobalInvocationID.x;
5064 //   output_data.elements[x] = input_data.elements[x];
5065 //   for (uint i = 0; i < 4; ++i)
5066 //     output_data.elements[x] += 1.f;
5067 // }
5068 tcu::TestCaseGroup* createLoopControlGroup (tcu::TestContext& testCtx)
5069 {
5070         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "loop_control", "Tests loop control cases"));
5071         vector<CaseParameter>                   cases;
5072         de::Random                                              rnd                             (deStringHash(group->getName()));
5073         const int                                               numElements             = 100;
5074         vector<float>                                   inputFloats             (numElements, 0);
5075         vector<float>                                   outputFloats    (numElements, 0);
5076         const StringTemplate                    shaderTemplate  (
5077                 string(getComputeAsmShaderPreamble()) +
5078
5079                 "OpSource GLSL 430\n"
5080                 "OpName %main \"main\"\n"
5081                 "OpName %id \"gl_GlobalInvocationID\"\n"
5082
5083                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5084
5085                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5086
5087                 "%u32ptr      = OpTypePointer Function %u32\n"
5088
5089                 "%id          = OpVariable %uvec3ptr Input\n"
5090                 "%zero        = OpConstant %i32 0\n"
5091                 "%uzero       = OpConstant %u32 0\n"
5092                 "%one         = OpConstant %i32 1\n"
5093                 "%constf1     = OpConstant %f32 1.0\n"
5094                 "%four        = OpConstant %u32 4\n"
5095
5096                 "%main        = OpFunction %void None %voidf\n"
5097                 "%entry       = OpLabel\n"
5098                 "%i           = OpVariable %u32ptr Function\n"
5099                 "               OpStore %i %uzero\n"
5100
5101                 "%idval       = OpLoad %uvec3 %id\n"
5102                 "%x           = OpCompositeExtract %u32 %idval 0\n"
5103                 "%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
5104                 "%inval       = OpLoad %f32 %inloc\n"
5105                 "%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
5106                 "               OpStore %outloc %inval\n"
5107                 "               OpBranch %loop_entry\n"
5108
5109                 "%loop_entry  = OpLabel\n"
5110                 "%i_val       = OpLoad %u32 %i\n"
5111                 "%cmp_lt      = OpULessThan %bool %i_val %four\n"
5112                 "               OpLoopMerge %loop_merge %loop_body ${CONTROL}\n"
5113                 "               OpBranchConditional %cmp_lt %loop_body %loop_merge\n"
5114                 "%loop_body   = OpLabel\n"
5115                 "%outval      = OpLoad %f32 %outloc\n"
5116                 "%addf1       = OpFAdd %f32 %outval %constf1\n"
5117                 "               OpStore %outloc %addf1\n"
5118                 "%new_i       = OpIAdd %u32 %i_val %one\n"
5119                 "               OpStore %i %new_i\n"
5120                 "               OpBranch %loop_entry\n"
5121                 "%loop_merge  = OpLabel\n"
5122                 "               OpReturn\n"
5123                 "               OpFunctionEnd\n");
5124
5125         cases.push_back(CaseParameter("none",                           "None"));
5126         cases.push_back(CaseParameter("unroll",                         "Unroll"));
5127         cases.push_back(CaseParameter("dont_unroll",            "DontUnroll"));
5128         cases.push_back(CaseParameter("unroll_dont_unroll",     "Unroll|DontUnroll"));
5129
5130         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5131
5132         for (size_t ndx = 0; ndx < numElements; ++ndx)
5133                 outputFloats[ndx] = inputFloats[ndx] + 4.f;
5134
5135         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5136         {
5137                 map<string, string>             specializations;
5138                 ComputeShaderSpec               spec;
5139
5140                 specializations["CONTROL"] = cases[caseNdx].param;
5141                 spec.assembly = shaderTemplate.specialize(specializations);
5142                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5143                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5144                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5145
5146                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5147         }
5148
5149         group->addChild(new SpvAsmLoopControlDependencyLengthCase(testCtx, "dependency_length", "dependency_length"));
5150         group->addChild(new SpvAsmLoopControlDependencyInfiniteCase(testCtx, "dependency_infinite", "dependency_infinite"));
5151
5152         return group.release();
5153 }
5154
5155 // Assembly code used for testing selection control is based on GLSL source code:
5156 // #version 430
5157 //
5158 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5159 //   float elements[];
5160 // } input_data;
5161 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5162 //   float elements[];
5163 // } output_data;
5164 //
5165 // void main() {
5166 //   uint x = gl_GlobalInvocationID.x;
5167 //   float val = input_data.elements[x];
5168 //   if (val > 10.f)
5169 //     output_data.elements[x] = val + 1.f;
5170 //   else
5171 //     output_data.elements[x] = val - 1.f;
5172 // }
5173 tcu::TestCaseGroup* createSelectionControlGroup (tcu::TestContext& testCtx)
5174 {
5175         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "selection_control", "Tests selection control cases"));
5176         vector<CaseParameter>                   cases;
5177         de::Random                                              rnd                             (deStringHash(group->getName()));
5178         const int                                               numElements             = 100;
5179         vector<float>                                   inputFloats             (numElements, 0);
5180         vector<float>                                   outputFloats    (numElements, 0);
5181         const StringTemplate                    shaderTemplate  (
5182                 string(getComputeAsmShaderPreamble()) +
5183
5184                 "OpSource GLSL 430\n"
5185                 "OpName %main \"main\"\n"
5186                 "OpName %id \"gl_GlobalInvocationID\"\n"
5187
5188                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5189
5190                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5191
5192                 "%id       = OpVariable %uvec3ptr Input\n"
5193                 "%zero     = OpConstant %i32 0\n"
5194                 "%constf1  = OpConstant %f32 1.0\n"
5195                 "%constf10 = OpConstant %f32 10.0\n"
5196
5197                 "%main     = OpFunction %void None %voidf\n"
5198                 "%entry    = OpLabel\n"
5199                 "%idval    = OpLoad %uvec3 %id\n"
5200                 "%x        = OpCompositeExtract %u32 %idval 0\n"
5201                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
5202                 "%inval    = OpLoad %f32 %inloc\n"
5203                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
5204                 "%cmp_gt   = OpFOrdGreaterThan %bool %inval %constf10\n"
5205
5206                 "            OpSelectionMerge %if_end ${CONTROL}\n"
5207                 "            OpBranchConditional %cmp_gt %if_true %if_false\n"
5208                 "%if_true  = OpLabel\n"
5209                 "%addf1    = OpFAdd %f32 %inval %constf1\n"
5210                 "            OpStore %outloc %addf1\n"
5211                 "            OpBranch %if_end\n"
5212                 "%if_false = OpLabel\n"
5213                 "%subf1    = OpFSub %f32 %inval %constf1\n"
5214                 "            OpStore %outloc %subf1\n"
5215                 "            OpBranch %if_end\n"
5216                 "%if_end   = OpLabel\n"
5217                 "            OpReturn\n"
5218                 "            OpFunctionEnd\n");
5219
5220         cases.push_back(CaseParameter("none",                                   "None"));
5221         cases.push_back(CaseParameter("flatten",                                "Flatten"));
5222         cases.push_back(CaseParameter("dont_flatten",                   "DontFlatten"));
5223         cases.push_back(CaseParameter("flatten_dont_flatten",   "DontFlatten|Flatten"));
5224
5225         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5226
5227         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
5228         floorAll(inputFloats);
5229
5230         for (size_t ndx = 0; ndx < numElements; ++ndx)
5231                 outputFloats[ndx] = inputFloats[ndx] + (inputFloats[ndx] > 10.f ? 1.f : -1.f);
5232
5233         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5234         {
5235                 map<string, string>             specializations;
5236                 ComputeShaderSpec               spec;
5237
5238                 specializations["CONTROL"] = cases[caseNdx].param;
5239                 spec.assembly = shaderTemplate.specialize(specializations);
5240                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5241                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5242                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5243
5244                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5245         }
5246
5247         return group.release();
5248 }
5249
5250 void getOpNameAbuseCases (vector<CaseParameter> &abuseCases)
5251 {
5252         // Generate a long name.
5253         std::string longname;
5254         longname.resize(65535, 'k'); // max string literal, spir-v 2.17
5255
5256         // Some bad names, abusing utf-8 encoding. This may also cause problems
5257         // with the logs.
5258         // 1. Various illegal code points in utf-8
5259         std::string utf8illegal =
5260                 "Illegal bytes in UTF-8: "
5261                 "\xc0 \xc1 \xf5 \xf6 \xf7 \xf8 \xf9 \xfa \xfb \xfc \xfd \xfe \xff"
5262                 "illegal surrogates: \xed\xad\xbf \xed\xbe\x80";
5263
5264         // 2. Zero encoded as overlong, not exactly legal but often supported to differentiate from terminating zero
5265         std::string utf8nul = "UTF-8 encoded nul \xC0\x80 (should not end name)";
5266
5267         // 3. Some overlong encodings
5268         std::string utf8overlong =
5269                 "UTF-8 overlong \xF0\x82\x82\xAC \xfc\x83\xbf\xbf\xbf\xbf \xf8\x87\xbf\xbf\xbf "
5270                 "\xf0\x8f\xbf\xbf";
5271
5272         // 4. Internet "zalgo" meme "bleeding text"
5273         std::string utf8zalgo =
5274                 "\x56\xcc\xb5\xcc\x85\xcc\x94\xcc\x88\xcd\x8a\xcc\x91\xcc\x88\xcd\x91\xcc\x83\xcd\x82"
5275                 "\xcc\x83\xcd\x90\xcc\x8a\xcc\x92\xcc\x92\xcd\x8b\xcc\x94\xcd\x9d\xcc\x98\xcc\xab\xcc"
5276                 "\xae\xcc\xa9\xcc\xad\xcc\x97\xcc\xb0\x75\xcc\xb6\xcc\xbe\xcc\x80\xcc\x82\xcc\x84\xcd"
5277                 "\x84\xcc\x90\xcd\x86\xcc\x9a\xcd\x84\xcc\x9b\xcd\x86\xcd\x92\xcc\x9a\xcd\x99\xcd\x99"
5278                 "\xcc\xbb\xcc\x98\xcd\x8e\xcd\x88\xcd\x9a\xcc\xa6\xcc\x9c\xcc\xab\xcc\x99\xcd\x94\xcd"
5279                 "\x99\xcd\x95\xcc\xa5\xcc\xab\xcd\x89\x6c\xcc\xb8\xcc\x8e\xcc\x8b\xcc\x8b\xcc\x9a\xcc"
5280                 "\x8e\xcd\x9d\xcc\x80\xcc\xa1\xcc\xad\xcd\x9c\xcc\xba\xcc\x96\xcc\xb3\xcc\xa2\xcd\x8e"
5281                 "\xcc\xa2\xcd\x96\x6b\xcc\xb8\xcc\x84\xcd\x81\xcc\xbf\xcc\x8d\xcc\x89\xcc\x85\xcc\x92"
5282                 "\xcc\x84\xcc\x90\xcd\x81\xcc\x93\xcd\x90\xcd\x92\xcd\x9d\xcc\x84\xcd\x98\xcd\x9d\xcd"
5283                 "\xa0\xcd\x91\xcc\x94\xcc\xb9\xcd\x93\xcc\xa5\xcd\x87\xcc\xad\xcc\xa7\xcd\x96\xcd\x99"
5284                 "\xcc\x9d\xcc\xbc\xcd\x96\xcd\x93\xcc\x9d\xcc\x99\xcc\xa8\xcc\xb1\xcd\x85\xcc\xba\xcc"
5285                 "\xa7\x61\xcc\xb8\xcc\x8e\xcc\x81\xcd\x90\xcd\x84\xcd\x8c\xcc\x8c\xcc\x85\xcd\x86\xcc"
5286                 "\x84\xcd\x84\xcc\x90\xcc\x84\xcc\x8d\xcd\x99\xcd\x8d\xcc\xb0\xcc\xa3\xcc\xa6\xcd\x89"
5287                 "\xcd\x8d\xcd\x87\xcc\x98\xcd\x8d\xcc\xa4\xcd\x9a\xcd\x8e\xcc\xab\xcc\xb9\xcc\xac\xcc"
5288                 "\xa2\xcd\x87\xcc\xa0\xcc\xb3\xcd\x89\xcc\xb9\xcc\xa7\xcc\xa6\xcd\x89\xcd\x95\x6e\xcc"
5289                 "\xb8\xcd\x8a\xcc\x8a\xcd\x82\xcc\x9b\xcd\x81\xcd\x90\xcc\x85\xcc\x9b\xcd\x80\xcd\x91"
5290                 "\xcd\x9b\xcc\x81\xcd\x81\xcc\x9a\xcc\xb3\xcd\x9c\xcc\x9e\xcc\x9d\xcd\x99\xcc\xa2\xcd"
5291                 "\x93\xcd\x96\xcc\x97\xff";
5292
5293         // General name abuses
5294         abuseCases.push_back(CaseParameter("_has_very_long_name", longname));
5295         abuseCases.push_back(CaseParameter("_utf8_illegal", utf8illegal));
5296         abuseCases.push_back(CaseParameter("_utf8_nul", utf8nul));
5297         abuseCases.push_back(CaseParameter("_utf8_overlong", utf8overlong));
5298         abuseCases.push_back(CaseParameter("_utf8_zalgo", utf8zalgo));
5299
5300         // GL keywords
5301         abuseCases.push_back(CaseParameter("_is_gl_Position", "gl_Position"));
5302         abuseCases.push_back(CaseParameter("_is_gl_InstanceID", "gl_InstanceID"));
5303         abuseCases.push_back(CaseParameter("_is_gl_PrimitiveID", "gl_PrimitiveID"));
5304         abuseCases.push_back(CaseParameter("_is_gl_TessCoord", "gl_TessCoord"));
5305         abuseCases.push_back(CaseParameter("_is_gl_PerVertex", "gl_PerVertex"));
5306         abuseCases.push_back(CaseParameter("_is_gl_InvocationID", "gl_InvocationID"));
5307         abuseCases.push_back(CaseParameter("_is_gl_PointSize", "gl_PointSize"));
5308         abuseCases.push_back(CaseParameter("_is_gl_PointCoord", "gl_PointCoord"));
5309         abuseCases.push_back(CaseParameter("_is_gl_Layer", "gl_Layer"));
5310         abuseCases.push_back(CaseParameter("_is_gl_FragDepth", "gl_FragDepth"));
5311         abuseCases.push_back(CaseParameter("_is_gl_NumWorkGroups", "gl_NumWorkGroups"));
5312         abuseCases.push_back(CaseParameter("_is_gl_WorkGroupID", "gl_WorkGroupID"));
5313         abuseCases.push_back(CaseParameter("_is_gl_LocalInvocationID", "gl_LocalInvocationID"));
5314         abuseCases.push_back(CaseParameter("_is_gl_GlobalInvocationID", "gl_GlobalInvocationID"));
5315         abuseCases.push_back(CaseParameter("_is_gl_MaxVertexAttribs", "gl_MaxVertexAttribs"));
5316         abuseCases.push_back(CaseParameter("_is_gl_MaxViewports", "gl_MaxViewports"));
5317         abuseCases.push_back(CaseParameter("_is_gl_MaxComputeWorkGroupCount", "gl_MaxComputeWorkGroupCount"));
5318         abuseCases.push_back(CaseParameter("_is_mat3", "mat3"));
5319         abuseCases.push_back(CaseParameter("_is_volatile", "volatile"));
5320         abuseCases.push_back(CaseParameter("_is_inout", "inout"));
5321         abuseCases.push_back(CaseParameter("_is_isampler3d", "isampler3d"));
5322 }
5323
5324 tcu::TestCaseGroup* createOpNameGroup (tcu::TestContext& testCtx)
5325 {
5326         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opname", "Tests OpName cases"));
5327         de::MovePtr<tcu::TestCaseGroup> entryMainGroup  (new tcu::TestCaseGroup(testCtx, "entry_main", "OpName tests with entry main"));
5328         de::MovePtr<tcu::TestCaseGroup> entryNotGroup   (new tcu::TestCaseGroup(testCtx, "entry_rdc", "OpName tests with entry rdc"));
5329         de::MovePtr<tcu::TestCaseGroup> abuseGroup              (new tcu::TestCaseGroup(testCtx, "abuse", "OpName abuse tests"));
5330         vector<CaseParameter>                   cases;
5331         vector<CaseParameter>                   abuseCases;
5332         vector<string>                                  testFunc;
5333         de::Random                                              rnd                             (deStringHash(group->getName()));
5334         const int                                               numElements             = 128;
5335         vector<float>                                   inputFloats             (numElements, 0);
5336         vector<float>                                   outputFloats    (numElements, 0);
5337
5338         getOpNameAbuseCases(abuseCases);
5339
5340         fillRandomScalars(rnd, -100.0f, 100.0f, &inputFloats[0], numElements);
5341
5342         for(size_t ndx = 0; ndx < numElements; ++ndx)
5343                 outputFloats[ndx] = -inputFloats[ndx];
5344
5345         const string commonShaderHeader =
5346                 "OpCapability Shader\n"
5347                 "OpMemoryModel Logical GLSL450\n"
5348                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5349                 "OpExecutionMode %main LocalSize 1 1 1\n";
5350
5351         const string commonShaderFooter =
5352                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5353
5354                 + string(getComputeAsmInputOutputBufferTraits())
5355                 + string(getComputeAsmCommonTypes())
5356                 + string(getComputeAsmInputOutputBuffer()) +
5357
5358                 "%id        = OpVariable %uvec3ptr Input\n"
5359                 "%zero      = OpConstant %i32 0\n"
5360
5361                 "%func      = OpFunction %void None %voidf\n"
5362                 "%5         = OpLabel\n"
5363                 "             OpReturn\n"
5364                 "             OpFunctionEnd\n"
5365
5366                 "%main      = OpFunction %void None %voidf\n"
5367                 "%entry     = OpLabel\n"
5368                 "%7         = OpFunctionCall %void %func\n"
5369
5370                 "%idval     = OpLoad %uvec3 %id\n"
5371                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5372
5373                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5374                 "%inval     = OpLoad %f32 %inloc\n"
5375                 "%neg       = OpFNegate %f32 %inval\n"
5376                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5377                 "             OpStore %outloc %neg\n"
5378
5379                 "             OpReturn\n"
5380                 "             OpFunctionEnd\n";
5381
5382         const StringTemplate shaderTemplate (
5383                 "OpCapability Shader\n"
5384                 "OpMemoryModel Logical GLSL450\n"
5385                 "OpEntryPoint GLCompute %main \"${ENTRY}\" %id\n"
5386                 "OpExecutionMode %main LocalSize 1 1 1\n"
5387                 "OpName %${ID} \"${NAME}\"\n" +
5388                 commonShaderFooter);
5389
5390         const std::string multipleNames =
5391                 commonShaderHeader +
5392                 "OpName %main \"to_be\"\n"
5393                 "OpName %id   \"or_not\"\n"
5394                 "OpName %main \"to_be\"\n"
5395                 "OpName %main \"makes_no\"\n"
5396                 "OpName %func \"difference\"\n"
5397                 "OpName %5    \"to_me\"\n" +
5398                 commonShaderFooter;
5399
5400         {
5401                 ComputeShaderSpec       spec;
5402
5403                 spec.assembly           = multipleNames;
5404                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5405                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5406                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5407
5408                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "main_has_multiple_names", "multiple_names", spec));
5409         }
5410
5411         const std::string everythingNamed =
5412                 commonShaderHeader +
5413                 "OpName %main   \"name1\"\n"
5414                 "OpName %id     \"name2\"\n"
5415                 "OpName %zero   \"name3\"\n"
5416                 "OpName %entry  \"name4\"\n"
5417                 "OpName %func   \"name5\"\n"
5418                 "OpName %5      \"name6\"\n"
5419                 "OpName %7      \"name7\"\n"
5420                 "OpName %idval  \"name8\"\n"
5421                 "OpName %inloc  \"name9\"\n"
5422                 "OpName %inval  \"name10\"\n"
5423                 "OpName %neg    \"name11\"\n"
5424                 "OpName %outloc \"name12\"\n"+
5425                 commonShaderFooter;
5426         {
5427                 ComputeShaderSpec       spec;
5428
5429                 spec.assembly           = everythingNamed;
5430                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5431                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5432                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5433
5434                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named", "everything_named", spec));
5435         }
5436
5437         const std::string everythingNamedTheSame =
5438                 commonShaderHeader +
5439                 "OpName %main   \"the_same\"\n"
5440                 "OpName %id     \"the_same\"\n"
5441                 "OpName %zero   \"the_same\"\n"
5442                 "OpName %entry  \"the_same\"\n"
5443                 "OpName %func   \"the_same\"\n"
5444                 "OpName %5      \"the_same\"\n"
5445                 "OpName %7      \"the_same\"\n"
5446                 "OpName %idval  \"the_same\"\n"
5447                 "OpName %inloc  \"the_same\"\n"
5448                 "OpName %inval  \"the_same\"\n"
5449                 "OpName %neg    \"the_same\"\n"
5450                 "OpName %outloc \"the_same\"\n"+
5451                 commonShaderFooter;
5452         {
5453                 ComputeShaderSpec       spec;
5454
5455                 spec.assembly           = everythingNamedTheSame;
5456                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5457                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5458                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5459
5460                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named_the_same", "everything_named_the_same", spec));
5461         }
5462
5463         // main_is_...
5464         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5465         {
5466                 map<string, string>     specializations;
5467                 ComputeShaderSpec       spec;
5468
5469                 specializations["ENTRY"]        = "main";
5470                 specializations["ID"]           = "main";
5471                 specializations["NAME"]         = abuseCases[ndx].param;
5472                 spec.assembly                           = shaderTemplate.specialize(specializations);
5473                 spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5474                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5475                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5476
5477                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("main") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5478         }
5479
5480         // x_is_....
5481         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5482         {
5483                 map<string, string>     specializations;
5484                 ComputeShaderSpec       spec;
5485
5486                 specializations["ENTRY"]        = "main";
5487                 specializations["ID"]           = "x";
5488                 specializations["NAME"]         = abuseCases[ndx].param;
5489                 spec.assembly                           = shaderTemplate.specialize(specializations);
5490                 spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5491                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5492                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5493
5494                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("x") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5495         }
5496
5497         cases.push_back(CaseParameter("_is_main", "main"));
5498         cases.push_back(CaseParameter("_is_not_main", "not_main"));
5499         testFunc.push_back("main");
5500         testFunc.push_back("func");
5501
5502         for(size_t fNdx = 0; fNdx < testFunc.size(); ++fNdx)
5503         {
5504                 for(size_t ndx = 0; ndx < cases.size(); ++ndx)
5505                 {
5506                         map<string, string>     specializations;
5507                         ComputeShaderSpec       spec;
5508
5509                         specializations["ENTRY"]        = "main";
5510                         specializations["ID"]           = testFunc[fNdx];
5511                         specializations["NAME"]         = cases[ndx].param;
5512                         spec.assembly                           = shaderTemplate.specialize(specializations);
5513                         spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5514                         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5515                         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5516
5517                         entryMainGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (testFunc[fNdx] + cases[ndx].name).c_str(), cases[ndx].name, spec));
5518                 }
5519         }
5520
5521         cases.push_back(CaseParameter("_is_entry", "rdc"));
5522
5523         for(size_t fNdx = 0; fNdx < testFunc.size(); ++fNdx)
5524         {
5525                 for(size_t ndx = 0; ndx < cases.size(); ++ndx)
5526                 {
5527                         map<string, string>     specializations;
5528                         ComputeShaderSpec       spec;
5529
5530                         specializations["ENTRY"]        = "rdc";
5531                         specializations["ID"]           = testFunc[fNdx];
5532                         specializations["NAME"]         = cases[ndx].param;
5533                         spec.assembly                           = shaderTemplate.specialize(specializations);
5534                         spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5535                         spec.entryPoint                         = "rdc";
5536                         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5537                         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5538
5539                         entryNotGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (testFunc[fNdx] + cases[ndx].name).c_str(), cases[ndx].name, spec));
5540                 }
5541         }
5542
5543         group->addChild(entryMainGroup.release());
5544         group->addChild(entryNotGroup.release());
5545         group->addChild(abuseGroup.release());
5546
5547         return group.release();
5548 }
5549
5550 tcu::TestCaseGroup* createOpMemberNameGroup (tcu::TestContext& testCtx)
5551 {
5552         de::MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "opmembername", "Tests OpMemberName cases"));
5553         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "abuse", "OpMemberName abuse tests"));
5554         vector<CaseParameter>                   abuseCases;
5555         vector<string>                                  testFunc;
5556         de::Random                                              rnd(deStringHash(group->getName()));
5557         const int                                               numElements = 128;
5558         vector<float>                                   inputFloats(numElements, 0);
5559         vector<float>                                   outputFloats(numElements, 0);
5560
5561         getOpNameAbuseCases(abuseCases);
5562
5563         fillRandomScalars(rnd, -100.0f, 100.0f, &inputFloats[0], numElements);
5564
5565         for (size_t ndx = 0; ndx < numElements; ++ndx)
5566                 outputFloats[ndx] = -inputFloats[ndx];
5567
5568         const string commonShaderHeader =
5569                 "OpCapability Shader\n"
5570                 "OpMemoryModel Logical GLSL450\n"
5571                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5572                 "OpExecutionMode %main LocalSize 1 1 1\n";
5573
5574         const string commonShaderFooter =
5575                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5576
5577                 + string(getComputeAsmInputOutputBufferTraits())
5578                 + string(getComputeAsmCommonTypes())
5579                 + string(getComputeAsmInputOutputBuffer()) +
5580
5581                 "%u3str     = OpTypeStruct %u32 %u32 %u32\n"
5582
5583                 "%id        = OpVariable %uvec3ptr Input\n"
5584                 "%zero      = OpConstant %i32 0\n"
5585
5586                 "%main      = OpFunction %void None %voidf\n"
5587                 "%entry     = OpLabel\n"
5588
5589                 "%idval     = OpLoad %uvec3 %id\n"
5590                 "%x0        = OpCompositeExtract %u32 %idval 0\n"
5591
5592                 "%idstr     = OpCompositeConstruct %u3str %x0 %x0 %x0\n"
5593                 "%x         = OpCompositeExtract %u32 %idstr 0\n"
5594
5595                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5596                 "%inval     = OpLoad %f32 %inloc\n"
5597                 "%neg       = OpFNegate %f32 %inval\n"
5598                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5599                 "             OpStore %outloc %neg\n"
5600
5601                 "             OpReturn\n"
5602                 "             OpFunctionEnd\n";
5603
5604         const StringTemplate shaderTemplate(
5605                 commonShaderHeader +
5606                 "OpMemberName %u3str 0 \"${NAME}\"\n" +
5607                 commonShaderFooter);
5608
5609         const std::string multipleNames =
5610                 commonShaderHeader +
5611                 "OpMemberName %u3str 0 \"to_be\"\n"
5612                 "OpMemberName %u3str 1 \"or_not\"\n"
5613                 "OpMemberName %u3str 0 \"to_be\"\n"
5614                 "OpMemberName %u3str 2 \"makes_no\"\n"
5615                 "OpMemberName %u3str 0 \"difference\"\n"
5616                 "OpMemberName %u3str 0 \"to_me\"\n" +
5617                 commonShaderFooter;
5618         {
5619                 ComputeShaderSpec       spec;
5620
5621                 spec.assembly = multipleNames;
5622                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5623                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5624                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5625
5626                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "u3str_x_has_multiple_names", "multiple_names", spec));
5627         }
5628
5629         const std::string everythingNamedTheSame =
5630                 commonShaderHeader +
5631                 "OpMemberName %u3str 0 \"the_same\"\n"
5632                 "OpMemberName %u3str 1 \"the_same\"\n"
5633                 "OpMemberName %u3str 2 \"the_same\"\n" +
5634                 commonShaderFooter;
5635
5636         {
5637                 ComputeShaderSpec       spec;
5638
5639                 spec.assembly = everythingNamedTheSame;
5640                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5641                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5642                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5643
5644                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named_the_same", "everything_named_the_same", spec));
5645         }
5646
5647         // u3str_x_is_....
5648         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5649         {
5650                 map<string, string>     specializations;
5651                 ComputeShaderSpec       spec;
5652
5653                 specializations["NAME"] = abuseCases[ndx].param;
5654                 spec.assembly = shaderTemplate.specialize(specializations);
5655                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5656                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5657                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5658
5659                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("u3str_x") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5660         }
5661
5662         group->addChild(abuseGroup.release());
5663
5664         return group.release();
5665 }
5666
5667 // Assembly code used for testing function control is based on GLSL source code:
5668 //
5669 // #version 430
5670 //
5671 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5672 //   float elements[];
5673 // } input_data;
5674 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5675 //   float elements[];
5676 // } output_data;
5677 //
5678 // float const10() { return 10.f; }
5679 //
5680 // void main() {
5681 //   uint x = gl_GlobalInvocationID.x;
5682 //   output_data.elements[x] = input_data.elements[x] + const10();
5683 // }
5684 tcu::TestCaseGroup* createFunctionControlGroup (tcu::TestContext& testCtx)
5685 {
5686         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "function_control", "Tests function control cases"));
5687         vector<CaseParameter>                   cases;
5688         de::Random                                              rnd                             (deStringHash(group->getName()));
5689         const int                                               numElements             = 100;
5690         vector<float>                                   inputFloats             (numElements, 0);
5691         vector<float>                                   outputFloats    (numElements, 0);
5692         const StringTemplate                    shaderTemplate  (
5693                 string(getComputeAsmShaderPreamble()) +
5694
5695                 "OpSource GLSL 430\n"
5696                 "OpName %main \"main\"\n"
5697                 "OpName %func_const10 \"const10(\"\n"
5698                 "OpName %id \"gl_GlobalInvocationID\"\n"
5699
5700                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5701
5702                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5703
5704                 "%f32f = OpTypeFunction %f32\n"
5705                 "%id = OpVariable %uvec3ptr Input\n"
5706                 "%zero = OpConstant %i32 0\n"
5707                 "%constf10 = OpConstant %f32 10.0\n"
5708
5709                 "%main         = OpFunction %void None %voidf\n"
5710                 "%entry        = OpLabel\n"
5711                 "%idval        = OpLoad %uvec3 %id\n"
5712                 "%x            = OpCompositeExtract %u32 %idval 0\n"
5713                 "%inloc        = OpAccessChain %f32ptr %indata %zero %x\n"
5714                 "%inval        = OpLoad %f32 %inloc\n"
5715                 "%ret_10       = OpFunctionCall %f32 %func_const10\n"
5716                 "%fadd         = OpFAdd %f32 %inval %ret_10\n"
5717                 "%outloc       = OpAccessChain %f32ptr %outdata %zero %x\n"
5718                 "                OpStore %outloc %fadd\n"
5719                 "                OpReturn\n"
5720                 "                OpFunctionEnd\n"
5721
5722                 "%func_const10 = OpFunction %f32 ${CONTROL} %f32f\n"
5723                 "%label        = OpLabel\n"
5724                 "                OpReturnValue %constf10\n"
5725                 "                OpFunctionEnd\n");
5726
5727         cases.push_back(CaseParameter("none",                                           "None"));
5728         cases.push_back(CaseParameter("inline",                                         "Inline"));
5729         cases.push_back(CaseParameter("dont_inline",                            "DontInline"));
5730         cases.push_back(CaseParameter("pure",                                           "Pure"));
5731         cases.push_back(CaseParameter("const",                                          "Const"));
5732         cases.push_back(CaseParameter("inline_pure",                            "Inline|Pure"));
5733         cases.push_back(CaseParameter("const_dont_inline",                      "Const|DontInline"));
5734         cases.push_back(CaseParameter("inline_dont_inline",                     "Inline|DontInline"));
5735         cases.push_back(CaseParameter("pure_inline_dont_inline",        "Pure|Inline|DontInline"));
5736
5737         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5738
5739         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
5740         floorAll(inputFloats);
5741
5742         for (size_t ndx = 0; ndx < numElements; ++ndx)
5743                 outputFloats[ndx] = inputFloats[ndx] + 10.f;
5744
5745         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5746         {
5747                 map<string, string>             specializations;
5748                 ComputeShaderSpec               spec;
5749
5750                 specializations["CONTROL"] = cases[caseNdx].param;
5751                 spec.assembly = shaderTemplate.specialize(specializations);
5752                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5753                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5754                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5755
5756                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5757         }
5758
5759         return group.release();
5760 }
5761
5762 tcu::TestCaseGroup* createMemoryAccessGroup (tcu::TestContext& testCtx)
5763 {
5764         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "memory_access", "Tests memory access cases"));
5765         vector<CaseParameter>                   cases;
5766         de::Random                                              rnd                             (deStringHash(group->getName()));
5767         const int                                               numElements             = 100;
5768         vector<float>                                   inputFloats             (numElements, 0);
5769         vector<float>                                   outputFloats    (numElements, 0);
5770         const StringTemplate                    shaderTemplate  (
5771                 string(getComputeAsmShaderPreamble()) +
5772
5773                 "OpSource GLSL 430\n"
5774                 "OpName %main           \"main\"\n"
5775                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5776
5777                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5778
5779                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5780
5781                 "%f32ptr_f  = OpTypePointer Function %f32\n"
5782
5783                 "%id        = OpVariable %uvec3ptr Input\n"
5784                 "%zero      = OpConstant %i32 0\n"
5785                 "%four      = OpConstant %i32 4\n"
5786
5787                 "%main      = OpFunction %void None %voidf\n"
5788                 "%label     = OpLabel\n"
5789                 "%copy      = OpVariable %f32ptr_f Function\n"
5790                 "%idval     = OpLoad %uvec3 %id ${ACCESS}\n"
5791                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5792                 "%inloc     = OpAccessChain %f32ptr %indata  %zero %x\n"
5793                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5794                 "             OpCopyMemory %copy %inloc ${ACCESS}\n"
5795                 "%val1      = OpLoad %f32 %copy\n"
5796                 "%val2      = OpLoad %f32 %inloc\n"
5797                 "%add       = OpFAdd %f32 %val1 %val2\n"
5798                 "             OpStore %outloc %add ${ACCESS}\n"
5799                 "             OpReturn\n"
5800                 "             OpFunctionEnd\n");
5801
5802         cases.push_back(CaseParameter("null",                                   ""));
5803         cases.push_back(CaseParameter("none",                                   "None"));
5804         cases.push_back(CaseParameter("volatile",                               "Volatile"));
5805         cases.push_back(CaseParameter("aligned",                                "Aligned 4"));
5806         cases.push_back(CaseParameter("nontemporal",                    "Nontemporal"));
5807         cases.push_back(CaseParameter("aligned_nontemporal",    "Aligned|Nontemporal 4"));
5808         cases.push_back(CaseParameter("aligned_volatile",               "Volatile|Aligned 4"));
5809
5810         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5811
5812         for (size_t ndx = 0; ndx < numElements; ++ndx)
5813                 outputFloats[ndx] = inputFloats[ndx] + inputFloats[ndx];
5814
5815         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5816         {
5817                 map<string, string>             specializations;
5818                 ComputeShaderSpec               spec;
5819
5820                 specializations["ACCESS"] = cases[caseNdx].param;
5821                 spec.assembly = shaderTemplate.specialize(specializations);
5822                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5823                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5824                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5825
5826                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5827         }
5828
5829         return group.release();
5830 }
5831
5832 // Checks that we can get undefined values for various types, without exercising a computation with it.
5833 tcu::TestCaseGroup* createOpUndefGroup (tcu::TestContext& testCtx)
5834 {
5835         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opundef", "Tests the OpUndef instruction"));
5836         vector<CaseParameter>                   cases;
5837         de::Random                                              rnd                             (deStringHash(group->getName()));
5838         const int                                               numElements             = 100;
5839         vector<float>                                   positiveFloats  (numElements, 0);
5840         vector<float>                                   negativeFloats  (numElements, 0);
5841         const StringTemplate                    shaderTemplate  (
5842                 string(getComputeAsmShaderPreamble()) +
5843
5844                 "OpSource GLSL 430\n"
5845                 "OpName %main           \"main\"\n"
5846                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5847
5848                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5849
5850                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
5851                 "%uvec2     = OpTypeVector %u32 2\n"
5852                 "%fvec4     = OpTypeVector %f32 4\n"
5853                 "%fmat33    = OpTypeMatrix %fvec3 3\n"
5854                 "%image     = OpTypeImage %f32 2D 0 0 0 1 Unknown\n"
5855                 "%sampler   = OpTypeSampler\n"
5856                 "%simage    = OpTypeSampledImage %image\n"
5857                 "%const100  = OpConstant %u32 100\n"
5858                 "%uarr100   = OpTypeArray %i32 %const100\n"
5859                 "%struct    = OpTypeStruct %f32 %i32 %u32\n"
5860                 "%pointer   = OpTypePointer Function %i32\n"
5861                 + string(getComputeAsmInputOutputBuffer()) +
5862
5863                 "%id        = OpVariable %uvec3ptr Input\n"
5864                 "%zero      = OpConstant %i32 0\n"
5865
5866                 "%main      = OpFunction %void None %voidf\n"
5867                 "%label     = OpLabel\n"
5868
5869                 "%undef     = OpUndef ${TYPE}\n"
5870
5871                 "%idval     = OpLoad %uvec3 %id\n"
5872                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5873
5874                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5875                 "%inval     = OpLoad %f32 %inloc\n"
5876                 "%neg       = OpFNegate %f32 %inval\n"
5877                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5878                 "             OpStore %outloc %neg\n"
5879                 "             OpReturn\n"
5880                 "             OpFunctionEnd\n");
5881
5882         cases.push_back(CaseParameter("bool",                   "%bool"));
5883         cases.push_back(CaseParameter("sint32",                 "%i32"));
5884         cases.push_back(CaseParameter("uint32",                 "%u32"));
5885         cases.push_back(CaseParameter("float32",                "%f32"));
5886         cases.push_back(CaseParameter("vec4float32",    "%fvec4"));
5887         cases.push_back(CaseParameter("vec2uint32",             "%uvec2"));
5888         cases.push_back(CaseParameter("matrix",                 "%fmat33"));
5889         cases.push_back(CaseParameter("image",                  "%image"));
5890         cases.push_back(CaseParameter("sampler",                "%sampler"));
5891         cases.push_back(CaseParameter("sampledimage",   "%simage"));
5892         cases.push_back(CaseParameter("array",                  "%uarr100"));
5893         cases.push_back(CaseParameter("runtimearray",   "%f32arr"));
5894         cases.push_back(CaseParameter("struct",                 "%struct"));
5895         cases.push_back(CaseParameter("pointer",                "%pointer"));
5896
5897         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
5898
5899         for (size_t ndx = 0; ndx < numElements; ++ndx)
5900                 negativeFloats[ndx] = -positiveFloats[ndx];
5901
5902         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5903         {
5904                 map<string, string>             specializations;
5905                 ComputeShaderSpec               spec;
5906
5907                 specializations["TYPE"] = cases[caseNdx].param;
5908                 spec.assembly = shaderTemplate.specialize(specializations);
5909                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
5910                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
5911                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5912
5913                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5914         }
5915
5916                 return group.release();
5917 }
5918
5919 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
5920 tcu::TestCaseGroup* createFloat16OpConstantCompositeGroup (tcu::TestContext& testCtx)
5921 {
5922         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "Tests the OpConstantComposite instruction"));
5923         vector<CaseParameter>                   cases;
5924         de::Random                                              rnd                             (deStringHash(group->getName()));
5925         const int                                               numElements             = 100;
5926         vector<float>                                   positiveFloats  (numElements, 0);
5927         vector<float>                                   negativeFloats  (numElements, 0);
5928         const StringTemplate                    shaderTemplate  (
5929                 "OpCapability Shader\n"
5930                 "OpCapability Float16\n"
5931                 "OpMemoryModel Logical GLSL450\n"
5932                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5933                 "OpExecutionMode %main LocalSize 1 1 1\n"
5934                 "OpSource GLSL 430\n"
5935                 "OpName %main           \"main\"\n"
5936                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5937
5938                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5939
5940                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5941
5942                 "%id        = OpVariable %uvec3ptr Input\n"
5943                 "%zero      = OpConstant %i32 0\n"
5944                 "%f16       = OpTypeFloat 16\n"
5945                 "%c_f16_0   = OpConstant %f16 0.0\n"
5946                 "%c_f16_0_5 = OpConstant %f16 0.5\n"
5947                 "%c_f16_1   = OpConstant %f16 1.0\n"
5948                 "%v2f16     = OpTypeVector %f16 2\n"
5949                 "%v3f16     = OpTypeVector %f16 3\n"
5950                 "%v4f16     = OpTypeVector %f16 4\n"
5951
5952                 "${CONSTANT}\n"
5953
5954                 "%main      = OpFunction %void None %voidf\n"
5955                 "%label     = OpLabel\n"
5956                 "%idval     = OpLoad %uvec3 %id\n"
5957                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5958                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5959                 "%inval     = OpLoad %f32 %inloc\n"
5960                 "%neg       = OpFNegate %f32 %inval\n"
5961                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5962                 "             OpStore %outloc %neg\n"
5963                 "             OpReturn\n"
5964                 "             OpFunctionEnd\n");
5965
5966
5967         cases.push_back(CaseParameter("vector",                 "%const = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"));
5968         cases.push_back(CaseParameter("matrix",                 "%m3v3f16 = OpTypeMatrix %v3f16 3\n"
5969                                                                                                         "%vec = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"
5970                                                                                                         "%mat = OpConstantComposite %m3v3f16 %vec %vec %vec"));
5971         cases.push_back(CaseParameter("struct",                 "%m2v3f16 = OpTypeMatrix %v3f16 2\n"
5972                                                                                                         "%struct = OpTypeStruct %i32 %f16 %v3f16 %m2v3f16\n"
5973                                                                                                         "%vec = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"
5974                                                                                                         "%mat = OpConstantComposite %m2v3f16 %vec %vec\n"
5975                                                                                                         "%const = OpConstantComposite %struct %zero %c_f16_0_5 %vec %mat\n"));
5976         cases.push_back(CaseParameter("nested_struct",  "%st1 = OpTypeStruct %i32 %f16\n"
5977                                                                                                         "%st2 = OpTypeStruct %i32 %i32\n"
5978                                                                                                         "%struct = OpTypeStruct %st1 %st2\n"
5979                                                                                                         "%st1val = OpConstantComposite %st1 %zero %c_f16_0_5\n"
5980                                                                                                         "%st2val = OpConstantComposite %st2 %zero %zero\n"
5981                                                                                                         "%const = OpConstantComposite %struct %st1val %st2val"));
5982
5983         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
5984
5985         for (size_t ndx = 0; ndx < numElements; ++ndx)
5986                 negativeFloats[ndx] = -positiveFloats[ndx];
5987
5988         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5989         {
5990                 map<string, string>             specializations;
5991                 ComputeShaderSpec               spec;
5992
5993                 specializations["CONSTANT"] = cases[caseNdx].param;
5994                 spec.assembly = shaderTemplate.specialize(specializations);
5995                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
5996                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
5997                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5998
5999                 spec.extensions.push_back("VK_KHR_16bit_storage");
6000                 spec.extensions.push_back("VK_KHR_shader_float16_int8");
6001
6002                 spec.requestedVulkanFeatures.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
6003                 spec.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
6004
6005                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
6006         }
6007
6008         return group.release();
6009 }
6010
6011 const vector<deFloat16> squarize(const vector<deFloat16>& inData, const deUint32 argNo)
6012 {
6013         const size_t            inDataLength    = inData.size();
6014         vector<deFloat16>       result;
6015
6016         result.reserve(inDataLength * inDataLength);
6017
6018         if (argNo == 0)
6019         {
6020                 for (size_t numIdx = 0; numIdx < inDataLength; ++numIdx)
6021                         result.insert(result.end(), inData.begin(), inData.end());
6022         }
6023
6024         if (argNo == 1)
6025         {
6026                 for (size_t numIdx = 0; numIdx < inDataLength; ++numIdx)
6027                 {
6028                         const vector<deFloat16> tmp(inDataLength, inData[numIdx]);
6029
6030                         result.insert(result.end(), tmp.begin(), tmp.end());
6031                 }
6032         }
6033
6034         return result;
6035 }
6036
6037 const vector<deFloat16> squarizeVector(const vector<deFloat16>& inData, const deUint32 argNo)
6038 {
6039         vector<deFloat16>       vec;
6040         vector<deFloat16>       result;
6041
6042         // Create vectors. vec will contain each possible pair from inData
6043         {
6044                 const size_t    inDataLength    = inData.size();
6045
6046                 DE_ASSERT(inDataLength <= 64);
6047
6048                 vec.reserve(2 * inDataLength * inDataLength);
6049
6050                 for (size_t numIdxX = 0; numIdxX < inDataLength; ++numIdxX)
6051                 for (size_t numIdxY = 0; numIdxY < inDataLength; ++numIdxY)
6052                 {
6053                         vec.push_back(inData[numIdxX]);
6054                         vec.push_back(inData[numIdxY]);
6055                 }
6056         }
6057
6058         // Create vector pairs. result will contain each possible pair from vec
6059         {
6060                 const size_t    coordsPerVector = 2;
6061                 const size_t    vectorsCount    = vec.size() / coordsPerVector;
6062
6063                 result.reserve(coordsPerVector * vectorsCount * vectorsCount);
6064
6065                 if (argNo == 0)
6066                 {
6067                         for (size_t numIdxX = 0; numIdxX < vectorsCount; ++numIdxX)
6068                         for (size_t numIdxY = 0; numIdxY < vectorsCount; ++numIdxY)
6069                         {
6070                                 for (size_t coordNdx = 0; coordNdx < coordsPerVector; ++coordNdx)
6071                                         result.push_back(vec[coordsPerVector * numIdxY + coordNdx]);
6072                         }
6073                 }
6074
6075                 if (argNo == 1)
6076                 {
6077                         for (size_t numIdxX = 0; numIdxX < vectorsCount; ++numIdxX)
6078                         for (size_t numIdxY = 0; numIdxY < vectorsCount; ++numIdxY)
6079                         {
6080                                 for (size_t coordNdx = 0; coordNdx < coordsPerVector; ++coordNdx)
6081                                         result.push_back(vec[coordsPerVector * numIdxX + coordNdx]);
6082                         }
6083                 }
6084         }
6085
6086         return result;
6087 }
6088
6089 struct fp16isNan                        { bool operator()(const tcu::Float16 in1, const tcu::Float16)           { return in1.isNaN(); } };
6090 struct fp16isInf                        { bool operator()(const tcu::Float16 in1, const tcu::Float16)           { return in1.isInf(); } };
6091 struct fp16isEqual                      { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() == in2.asFloat(); } };
6092 struct fp16isUnequal            { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() != in2.asFloat(); } };
6093 struct fp16isLess                       { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() <  in2.asFloat(); } };
6094 struct fp16isGreater            { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() >  in2.asFloat(); } };
6095 struct fp16isLessOrEqual        { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() <= in2.asFloat(); } };
6096 struct fp16isGreaterOrEqual     { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() >= in2.asFloat(); } };
6097
6098 template <class TestedLogicalFunction, bool onlyTestFunc, bool unationModeAnd, bool nanSupported>
6099 bool compareFP16Logical (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
6100 {
6101         if (inputs.size() != 2 || outputAllocs.size() != 1)
6102                 return false;
6103
6104         vector<deUint8> input1Bytes;
6105         vector<deUint8> input2Bytes;
6106
6107         inputs[0].getBytes(input1Bytes);
6108         inputs[1].getBytes(input2Bytes);
6109
6110         const deUint32                  denormModesCount                        = 2;
6111         const deFloat16                 float16one                                      = tcu::Float16(1.0f).bits();
6112         const deFloat16                 float16zero                                     = tcu::Float16(0.0f).bits();
6113         const tcu::Float16              zero                                            = tcu::Float16::zero(1);
6114         const deFloat16* const  outputAsFP16                            = static_cast<deFloat16*>(outputAllocs[0]->getHostPtr());
6115         const deFloat16* const  input1AsFP16                            = reinterpret_cast<deFloat16* const>(&input1Bytes.front());
6116         const deFloat16* const  input2AsFP16                            = reinterpret_cast<deFloat16* const>(&input2Bytes.front());
6117         deUint32                                successfulRuns                          = denormModesCount;
6118         std::string                             results[denormModesCount];
6119         TestedLogicalFunction   testedLogicalFunction;
6120
6121         for (deUint32 denormMode = 0; denormMode < denormModesCount; denormMode++)
6122         {
6123                 const bool flushToZero = (denormMode == 1);
6124
6125                 for (size_t idx = 0; idx < input1Bytes.size() / sizeof(deFloat16); ++idx)
6126                 {
6127                         const tcu::Float16      f1pre                   = tcu::Float16(input1AsFP16[idx]);
6128                         const tcu::Float16      f2pre                   = tcu::Float16(input2AsFP16[idx]);
6129                         const tcu::Float16      f1                              = (flushToZero && f1pre.isDenorm()) ? zero : f1pre;
6130                         const tcu::Float16      f2                              = (flushToZero && f2pre.isDenorm()) ? zero : f2pre;
6131                         deFloat16                       expectedOutput  = float16zero;
6132
6133                         if (onlyTestFunc)
6134                         {
6135                                 if (testedLogicalFunction(f1, f2))
6136                                         expectedOutput = float16one;
6137                         }
6138                         else
6139                         {
6140                                 const bool      f1nan   = f1.isNaN();
6141                                 const bool      f2nan   = f2.isNaN();
6142
6143                                 // Skip NaN floats if not supported by implementation
6144                                 if (!nanSupported && (f1nan || f2nan))
6145                                         continue;
6146
6147                                 if (unationModeAnd)
6148                                 {
6149                                         const bool      ordered         = !f1nan && !f2nan;
6150
6151                                         if (ordered && testedLogicalFunction(f1, f2))
6152                                                 expectedOutput = float16one;
6153                                 }
6154                                 else
6155                                 {
6156                                         const bool      unordered       = f1nan || f2nan;
6157
6158                                         if (unordered || testedLogicalFunction(f1, f2))
6159                                                 expectedOutput = float16one;
6160                                 }
6161                         }
6162
6163                         if (outputAsFP16[idx] != expectedOutput)
6164                         {
6165                                 std::ostringstream str;
6166
6167                                 str << "ERROR: Sub-case #" << idx
6168                                         << " flushToZero:" << flushToZero
6169                                         << std::hex
6170                                         << " failed, inputs: 0x" << f1.bits()
6171                                         << ";0x" << f2.bits()
6172                                         << " output: 0x" << outputAsFP16[idx]
6173                                         << " expected output: 0x" << expectedOutput;
6174
6175                                 results[denormMode] = str.str();
6176
6177                                 successfulRuns--;
6178
6179                                 break;
6180                         }
6181                 }
6182         }
6183
6184         if (successfulRuns == 0)
6185                 for (deUint32 denormMode = 0; denormMode < denormModesCount; denormMode++)
6186                         log << TestLog::Message << results[denormMode] << TestLog::EndMessage;
6187
6188         return successfulRuns > 0;
6189 }
6190
6191 } // anonymous
6192
6193 tcu::TestCaseGroup* createOpSourceTests (tcu::TestContext& testCtx)
6194 {
6195         struct NameCodePair { string name, code; };
6196         RGBA                                                    defaultColors[4];
6197         de::MovePtr<tcu::TestCaseGroup> opSourceTests                   (new tcu::TestCaseGroup(testCtx, "opsource", "OpSource instruction"));
6198         const std::string                               opsourceGLSLWithFile    = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile ";
6199         map<string, string>                             fragments                               = passthruFragments();
6200         const NameCodePair                              tests[]                                 =
6201         {
6202                 {"unknown", "OpSource Unknown 321"},
6203                 {"essl", "OpSource ESSL 310"},
6204                 {"glsl", "OpSource GLSL 450"},
6205                 {"opencl_cpp", "OpSource OpenCL_CPP 120"},
6206                 {"opencl_c", "OpSource OpenCL_C 120"},
6207                 {"multiple", "OpSource GLSL 450\nOpSource GLSL 450"},
6208                 {"file", opsourceGLSLWithFile},
6209                 {"source", opsourceGLSLWithFile + "\"void main(){}\""},
6210                 // Longest possible source string: SPIR-V limits instructions to 65535
6211                 // words, of which the first 4 are opsourceGLSLWithFile; the rest will
6212                 // contain 65530 UTF8 characters (one word each) plus one last word
6213                 // containing 3 ASCII characters and \0.
6214                 {"longsource", opsourceGLSLWithFile + '"' + makeLongUTF8String(65530) + "ccc" + '"'}
6215         };
6216
6217         getDefaultColors(defaultColors);
6218         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
6219         {
6220                 fragments["debug"] = tests[testNdx].code;
6221                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
6222         }
6223
6224         return opSourceTests.release();
6225 }
6226
6227 tcu::TestCaseGroup* createOpSourceContinuedTests (tcu::TestContext& testCtx)
6228 {
6229         struct NameCodePair { string name, code; };
6230         RGBA                                                            defaultColors[4];
6231         de::MovePtr<tcu::TestCaseGroup>         opSourceTests           (new tcu::TestCaseGroup(testCtx, "opsourcecontinued", "OpSourceContinued instruction"));
6232         map<string, string>                                     fragments                       = passthruFragments();
6233         const std::string                                       opsource                        = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile \"void main(){}\"\n";
6234         const NameCodePair                                      tests[]                         =
6235         {
6236                 {"empty", opsource + "OpSourceContinued \"\""},
6237                 {"short", opsource + "OpSourceContinued \"abcde\""},
6238                 {"multiple", opsource + "OpSourceContinued \"abcde\"\nOpSourceContinued \"fghij\""},
6239                 // Longest possible source string: SPIR-V limits instructions to 65535
6240                 // words, of which the first one is OpSourceContinued/length; the rest
6241                 // will contain 65533 UTF8 characters (one word each) plus one last word
6242                 // containing 3 ASCII characters and \0.
6243                 {"long", opsource + "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\""}
6244         };
6245
6246         getDefaultColors(defaultColors);
6247         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
6248         {
6249                 fragments["debug"] = tests[testNdx].code;
6250                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
6251         }
6252
6253         return opSourceTests.release();
6254 }
6255 tcu::TestCaseGroup* createOpNoLineTests(tcu::TestContext& testCtx)
6256 {
6257         RGBA                                                             defaultColors[4];
6258         de::MovePtr<tcu::TestCaseGroup>          opLineTests             (new tcu::TestCaseGroup(testCtx, "opnoline", "OpNoLine instruction"));
6259         map<string, string>                                      fragments;
6260         getDefaultColors(defaultColors);
6261         fragments["debug"]                      =
6262                 "%name = OpString \"name\"\n";
6263
6264         fragments["pre_main"]   =
6265                 "OpNoLine\n"
6266                 "OpNoLine\n"
6267                 "OpLine %name 1 1\n"
6268                 "OpNoLine\n"
6269                 "OpLine %name 1 1\n"
6270                 "OpLine %name 1 1\n"
6271                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6272                 "OpNoLine\n"
6273                 "OpLine %name 1 1\n"
6274                 "OpNoLine\n"
6275                 "OpLine %name 1 1\n"
6276                 "OpLine %name 1 1\n"
6277                 "%second_param1 = OpFunctionParameter %v4f32\n"
6278                 "OpNoLine\n"
6279                 "OpNoLine\n"
6280                 "%label_secondfunction = OpLabel\n"
6281                 "OpNoLine\n"
6282                 "OpReturnValue %second_param1\n"
6283                 "OpFunctionEnd\n"
6284                 "OpNoLine\n"
6285                 "OpNoLine\n";
6286
6287         fragments["testfun"]            =
6288                 // A %test_code function that returns its argument unchanged.
6289                 "OpNoLine\n"
6290                 "OpNoLine\n"
6291                 "OpLine %name 1 1\n"
6292                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6293                 "OpNoLine\n"
6294                 "%param1 = OpFunctionParameter %v4f32\n"
6295                 "OpNoLine\n"
6296                 "OpNoLine\n"
6297                 "%label_testfun = OpLabel\n"
6298                 "OpNoLine\n"
6299                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6300                 "OpReturnValue %val1\n"
6301                 "OpFunctionEnd\n"
6302                 "OpLine %name 1 1\n"
6303                 "OpNoLine\n";
6304
6305         createTestsForAllStages("opnoline", defaultColors, defaultColors, fragments, opLineTests.get());
6306
6307         return opLineTests.release();
6308 }
6309
6310 tcu::TestCaseGroup* createOpModuleProcessedTests(tcu::TestContext& testCtx)
6311 {
6312         RGBA                                                            defaultColors[4];
6313         de::MovePtr<tcu::TestCaseGroup>         opModuleProcessedTests                  (new tcu::TestCaseGroup(testCtx, "opmoduleprocessed", "OpModuleProcessed instruction"));
6314         map<string, string>                                     fragments;
6315         std::vector<std::string>                        noExtensions;
6316         GraphicsResources                                       resources;
6317
6318         getDefaultColors(defaultColors);
6319         resources.verifyBinary = veryfiBinaryShader;
6320         resources.spirvVersion = SPIRV_VERSION_1_3;
6321
6322         fragments["moduleprocessed"]                                                    =
6323                 "OpModuleProcessed \"VULKAN CTS\"\n"
6324                 "OpModuleProcessed \"Negative values\"\n"
6325                 "OpModuleProcessed \"Date: 2017/09/21\"\n";
6326
6327         fragments["pre_main"]   =
6328                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6329                 "%second_param1 = OpFunctionParameter %v4f32\n"
6330                 "%label_secondfunction = OpLabel\n"
6331                 "OpReturnValue %second_param1\n"
6332                 "OpFunctionEnd\n";
6333
6334         fragments["testfun"]            =
6335                 // A %test_code function that returns its argument unchanged.
6336                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6337                 "%param1 = OpFunctionParameter %v4f32\n"
6338                 "%label_testfun = OpLabel\n"
6339                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6340                 "OpReturnValue %val1\n"
6341                 "OpFunctionEnd\n";
6342
6343         createTestsForAllStages ("opmoduleprocessed", defaultColors, defaultColors, fragments, resources, noExtensions, opModuleProcessedTests.get());
6344
6345         return opModuleProcessedTests.release();
6346 }
6347
6348
6349 tcu::TestCaseGroup* createOpLineTests(tcu::TestContext& testCtx)
6350 {
6351         RGBA                                                                                                    defaultColors[4];
6352         de::MovePtr<tcu::TestCaseGroup>                                                 opLineTests                     (new tcu::TestCaseGroup(testCtx, "opline", "OpLine instruction"));
6353         map<string, string>                                                                             fragments;
6354         std::vector<std::pair<std::string, std::string> >               problemStrings;
6355
6356         problemStrings.push_back(std::make_pair<std::string, std::string>("empty_name", ""));
6357         problemStrings.push_back(std::make_pair<std::string, std::string>("short_name", "short_name"));
6358         problemStrings.push_back(std::make_pair<std::string, std::string>("long_name", makeLongUTF8String(65530) + "ccc"));
6359         getDefaultColors(defaultColors);
6360
6361         fragments["debug"]                      =
6362                 "%other_name = OpString \"other_name\"\n";
6363
6364         fragments["pre_main"]   =
6365                 "OpLine %file_name 32 0\n"
6366                 "OpLine %file_name 32 32\n"
6367                 "OpLine %file_name 32 40\n"
6368                 "OpLine %other_name 32 40\n"
6369                 "OpLine %other_name 0 100\n"
6370                 "OpLine %other_name 0 4294967295\n"
6371                 "OpLine %other_name 4294967295 0\n"
6372                 "OpLine %other_name 32 40\n"
6373                 "OpLine %file_name 0 0\n"
6374                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6375                 "OpLine %file_name 1 0\n"
6376                 "%second_param1 = OpFunctionParameter %v4f32\n"
6377                 "OpLine %file_name 1 3\n"
6378                 "OpLine %file_name 1 2\n"
6379                 "%label_secondfunction = OpLabel\n"
6380                 "OpLine %file_name 0 2\n"
6381                 "OpReturnValue %second_param1\n"
6382                 "OpFunctionEnd\n"
6383                 "OpLine %file_name 0 2\n"
6384                 "OpLine %file_name 0 2\n";
6385
6386         fragments["testfun"]            =
6387                 // A %test_code function that returns its argument unchanged.
6388                 "OpLine %file_name 1 0\n"
6389                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6390                 "OpLine %file_name 16 330\n"
6391                 "%param1 = OpFunctionParameter %v4f32\n"
6392                 "OpLine %file_name 14 442\n"
6393                 "%label_testfun = OpLabel\n"
6394                 "OpLine %file_name 11 1024\n"
6395                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6396                 "OpLine %file_name 2 97\n"
6397                 "OpReturnValue %val1\n"
6398                 "OpFunctionEnd\n"
6399                 "OpLine %file_name 5 32\n";
6400
6401         for (size_t i = 0; i < problemStrings.size(); ++i)
6402         {
6403                 map<string, string> testFragments = fragments;
6404                 testFragments["debug"] += "%file_name = OpString \"" + problemStrings[i].second + "\"\n";
6405                 createTestsForAllStages(string("opline") + "_" + problemStrings[i].first, defaultColors, defaultColors, testFragments, opLineTests.get());
6406         }
6407
6408         return opLineTests.release();
6409 }
6410
6411 tcu::TestCaseGroup* createOpConstantNullTests(tcu::TestContext& testCtx)
6412 {
6413         de::MovePtr<tcu::TestCaseGroup> opConstantNullTests             (new tcu::TestCaseGroup(testCtx, "opconstantnull", "OpConstantNull instruction"));
6414         RGBA                                                    colors[4];
6415
6416
6417         const char                                              functionStart[] =
6418                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6419                 "%param1 = OpFunctionParameter %v4f32\n"
6420                 "%lbl    = OpLabel\n";
6421
6422         const char                                              functionEnd[]   =
6423                 "OpReturnValue %transformed_param\n"
6424                 "OpFunctionEnd\n";
6425
6426         struct NameConstantsCode
6427         {
6428                 string name;
6429                 string constants;
6430                 string code;
6431         };
6432
6433         NameConstantsCode tests[] =
6434         {
6435                 {
6436                         "vec4",
6437                         "%cnull = OpConstantNull %v4f32\n",
6438                         "%transformed_param = OpFAdd %v4f32 %param1 %cnull\n"
6439                 },
6440                 {
6441                         "float",
6442                         "%cnull = OpConstantNull %f32\n",
6443                         "%vp = OpVariable %fp_v4f32 Function\n"
6444                         "%v  = OpLoad %v4f32 %vp\n"
6445                         "%v0 = OpVectorInsertDynamic %v4f32 %v %cnull %c_i32_0\n"
6446                         "%v1 = OpVectorInsertDynamic %v4f32 %v0 %cnull %c_i32_1\n"
6447                         "%v2 = OpVectorInsertDynamic %v4f32 %v1 %cnull %c_i32_2\n"
6448                         "%v3 = OpVectorInsertDynamic %v4f32 %v2 %cnull %c_i32_3\n"
6449                         "%transformed_param = OpFAdd %v4f32 %param1 %v3\n"
6450                 },
6451                 {
6452                         "bool",
6453                         "%cnull             = OpConstantNull %bool\n",
6454                         "%v                 = OpVariable %fp_v4f32 Function\n"
6455                         "                     OpStore %v %param1\n"
6456                         "                     OpSelectionMerge %false_label None\n"
6457                         "                     OpBranchConditional %cnull %true_label %false_label\n"
6458                         "%true_label        = OpLabel\n"
6459                         "                     OpStore %v %c_v4f32_0_5_0_5_0_5_0_5\n"
6460                         "                     OpBranch %false_label\n"
6461                         "%false_label       = OpLabel\n"
6462                         "%transformed_param = OpLoad %v4f32 %v\n"
6463                 },
6464                 {
6465                         "i32",
6466                         "%cnull             = OpConstantNull %i32\n",
6467                         "%v                 = OpVariable %fp_v4f32 Function %c_v4f32_0_5_0_5_0_5_0_5\n"
6468                         "%b                 = OpIEqual %bool %cnull %c_i32_0\n"
6469                         "                     OpSelectionMerge %false_label None\n"
6470                         "                     OpBranchConditional %b %true_label %false_label\n"
6471                         "%true_label        = OpLabel\n"
6472                         "                     OpStore %v %param1\n"
6473                         "                     OpBranch %false_label\n"
6474                         "%false_label       = OpLabel\n"
6475                         "%transformed_param = OpLoad %v4f32 %v\n"
6476                 },
6477                 {
6478                         "struct",
6479                         "%stype             = OpTypeStruct %f32 %v4f32\n"
6480                         "%fp_stype          = OpTypePointer Function %stype\n"
6481                         "%cnull             = OpConstantNull %stype\n",
6482                         "%v                 = OpVariable %fp_stype Function %cnull\n"
6483                         "%f                 = OpAccessChain %fp_v4f32 %v %c_i32_1\n"
6484                         "%f_val             = OpLoad %v4f32 %f\n"
6485                         "%transformed_param = OpFAdd %v4f32 %param1 %f_val\n"
6486                 },
6487                 {
6488                         "array",
6489                         "%a4_v4f32          = OpTypeArray %v4f32 %c_u32_4\n"
6490                         "%fp_a4_v4f32       = OpTypePointer Function %a4_v4f32\n"
6491                         "%cnull             = OpConstantNull %a4_v4f32\n",
6492                         "%v                 = OpVariable %fp_a4_v4f32 Function %cnull\n"
6493                         "%f                 = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
6494                         "%f1                = OpAccessChain %fp_v4f32 %v %c_u32_1\n"
6495                         "%f2                = OpAccessChain %fp_v4f32 %v %c_u32_2\n"
6496                         "%f3                = OpAccessChain %fp_v4f32 %v %c_u32_3\n"
6497                         "%f_val             = OpLoad %v4f32 %f\n"
6498                         "%f1_val            = OpLoad %v4f32 %f1\n"
6499                         "%f2_val            = OpLoad %v4f32 %f2\n"
6500                         "%f3_val            = OpLoad %v4f32 %f3\n"
6501                         "%t0                = OpFAdd %v4f32 %param1 %f_val\n"
6502                         "%t1                = OpFAdd %v4f32 %t0 %f1_val\n"
6503                         "%t2                = OpFAdd %v4f32 %t1 %f2_val\n"
6504                         "%transformed_param = OpFAdd %v4f32 %t2 %f3_val\n"
6505                 },
6506                 {
6507                         "matrix",
6508                         "%mat4x4_f32        = OpTypeMatrix %v4f32 4\n"
6509                         "%cnull             = OpConstantNull %mat4x4_f32\n",
6510                         // Our null matrix * any vector should result in a zero vector.
6511                         "%v                 = OpVectorTimesMatrix %v4f32 %param1 %cnull\n"
6512                         "%transformed_param = OpFAdd %v4f32 %param1 %v\n"
6513                 }
6514         };
6515
6516         getHalfColorsFullAlpha(colors);
6517
6518         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
6519         {
6520                 map<string, string> fragments;
6521                 fragments["pre_main"] = tests[testNdx].constants;
6522                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
6523                 createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, opConstantNullTests.get());
6524         }
6525         return opConstantNullTests.release();
6526 }
6527 tcu::TestCaseGroup* createOpConstantCompositeTests(tcu::TestContext& testCtx)
6528 {
6529         de::MovePtr<tcu::TestCaseGroup> opConstantCompositeTests                (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "OpConstantComposite instruction"));
6530         RGBA                                                    inputColors[4];
6531         RGBA                                                    outputColors[4];
6532
6533
6534         const char                                              functionStart[]  =
6535                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6536                 "%param1 = OpFunctionParameter %v4f32\n"
6537                 "%lbl    = OpLabel\n";
6538
6539         const char                                              functionEnd[]           =
6540                 "OpReturnValue %transformed_param\n"
6541                 "OpFunctionEnd\n";
6542
6543         struct NameConstantsCode
6544         {
6545                 string name;
6546                 string constants;
6547                 string code;
6548         };
6549
6550         NameConstantsCode tests[] =
6551         {
6552                 {
6553                         "vec4",
6554
6555                         "%cval              = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0\n",
6556                         "%transformed_param = OpFAdd %v4f32 %param1 %cval\n"
6557                 },
6558                 {
6559                         "struct",
6560
6561                         "%stype             = OpTypeStruct %v4f32 %f32\n"
6562                         "%fp_stype          = OpTypePointer Function %stype\n"
6563                         "%f32_n_1           = OpConstant %f32 -1.0\n"
6564                         "%f32_1_5           = OpConstant %f32 !0x3fc00000\n" // +1.5
6565                         "%cvec              = OpConstantComposite %v4f32 %f32_1_5 %f32_1_5 %f32_1_5 %c_f32_1\n"
6566                         "%cval              = OpConstantComposite %stype %cvec %f32_n_1\n",
6567
6568                         "%v                 = OpVariable %fp_stype Function %cval\n"
6569                         "%vec_ptr           = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
6570                         "%f32_ptr           = OpAccessChain %fp_f32 %v %c_u32_1\n"
6571                         "%vec_val           = OpLoad %v4f32 %vec_ptr\n"
6572                         "%f32_val           = OpLoad %f32 %f32_ptr\n"
6573                         "%tmp1              = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_1 %f32_val\n" // vec4(-1)
6574                         "%tmp2              = OpFAdd %v4f32 %tmp1 %param1\n" // param1 + vec4(-1)
6575                         "%transformed_param = OpFAdd %v4f32 %tmp2 %vec_val\n" // param1 + vec4(-1) + vec4(1.5, 1.5, 1.5, 1.0)
6576                 },
6577                 {
6578                         // [1|0|0|0.5] [x] = x + 0.5
6579                         // [0|1|0|0.5] [y] = y + 0.5
6580                         // [0|0|1|0.5] [z] = z + 0.5
6581                         // [0|0|0|1  ] [1] = 1
6582                         "matrix",
6583
6584                         "%mat4x4_f32          = OpTypeMatrix %v4f32 4\n"
6585                         "%v4f32_1_0_0_0       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_0 %c_f32_0 %c_f32_0\n"
6586                         "%v4f32_0_1_0_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_1 %c_f32_0 %c_f32_0\n"
6587                         "%v4f32_0_0_1_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_1 %c_f32_0\n"
6588                         "%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"
6589                         "%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",
6590
6591                         "%transformed_param   = OpMatrixTimesVector %v4f32 %cval %param1\n"
6592                 },
6593                 {
6594                         "array",
6595
6596                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
6597                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
6598                         "%f32_n_1             = OpConstant %f32 -1.0\n"
6599                         "%f32_1_5             = OpConstant %f32 !0x3fc00000\n" // +1.5
6600                         "%carr                = OpConstantComposite %a4f32 %c_f32_0 %f32_n_1 %f32_1_5 %c_f32_0\n",
6601
6602                         "%v                   = OpVariable %fp_a4f32 Function %carr\n"
6603                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_0\n"
6604                         "%f1                  = OpAccessChain %fp_f32 %v %c_u32_1\n"
6605                         "%f2                  = OpAccessChain %fp_f32 %v %c_u32_2\n"
6606                         "%f3                  = OpAccessChain %fp_f32 %v %c_u32_3\n"
6607                         "%f_val               = OpLoad %f32 %f\n"
6608                         "%f1_val              = OpLoad %f32 %f1\n"
6609                         "%f2_val              = OpLoad %f32 %f2\n"
6610                         "%f3_val              = OpLoad %f32 %f3\n"
6611                         "%ftot1               = OpFAdd %f32 %f_val %f1_val\n"
6612                         "%ftot2               = OpFAdd %f32 %ftot1 %f2_val\n"
6613                         "%ftot3               = OpFAdd %f32 %ftot2 %f3_val\n"  // 0 - 1 + 1.5 + 0
6614                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %ftot3\n"
6615                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
6616                 },
6617                 {
6618                         //
6619                         // [
6620                         //   {
6621                         //      0.0,
6622                         //      [ 1.0, 1.0, 1.0, 1.0]
6623                         //   },
6624                         //   {
6625                         //      1.0,
6626                         //      [ 0.0, 0.5, 0.0, 0.0]
6627                         //   }, //     ^^^
6628                         //   {
6629                         //      0.0,
6630                         //      [ 1.0, 1.0, 1.0, 1.0]
6631                         //   }
6632                         // ]
6633                         "array_of_struct_of_array",
6634
6635                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
6636                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
6637                         "%stype               = OpTypeStruct %f32 %a4f32\n"
6638                         "%a3stype             = OpTypeArray %stype %c_u32_3\n"
6639                         "%fp_a3stype          = OpTypePointer Function %a3stype\n"
6640                         "%ca4f32_0            = OpConstantComposite %a4f32 %c_f32_0 %c_f32_0_5 %c_f32_0 %c_f32_0\n"
6641                         "%ca4f32_1            = OpConstantComposite %a4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
6642                         "%cstype1             = OpConstantComposite %stype %c_f32_0 %ca4f32_1\n"
6643                         "%cstype2             = OpConstantComposite %stype %c_f32_1 %ca4f32_0\n"
6644                         "%carr                = OpConstantComposite %a3stype %cstype1 %cstype2 %cstype1",
6645
6646                         "%v                   = OpVariable %fp_a3stype Function %carr\n"
6647                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_1 %c_u32_1 %c_u32_1\n"
6648                         "%f_l                 = OpLoad %f32 %f\n"
6649                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %f_l\n"
6650                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
6651                 }
6652         };
6653
6654         getHalfColorsFullAlpha(inputColors);
6655         outputColors[0] = RGBA(255, 255, 255, 255);
6656         outputColors[1] = RGBA(255, 127, 127, 255);
6657         outputColors[2] = RGBA(127, 255, 127, 255);
6658         outputColors[3] = RGBA(127, 127, 255, 255);
6659
6660         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
6661         {
6662                 map<string, string> fragments;
6663                 fragments["pre_main"] = tests[testNdx].constants;
6664                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
6665                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, opConstantCompositeTests.get());
6666         }
6667         return opConstantCompositeTests.release();
6668 }
6669
6670 tcu::TestCaseGroup* createSelectionBlockOrderTests(tcu::TestContext& testCtx)
6671 {
6672         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "selection_block_order", "Out-of-order blocks for selection"));
6673         RGBA                                                    inputColors[4];
6674         RGBA                                                    outputColors[4];
6675         map<string, string>                             fragments;
6676
6677         // vec4 test_code(vec4 param) {
6678         //   vec4 result = param;
6679         //   for (int i = 0; i < 4; ++i) {
6680         //     if (i == 0) result[i] = 0.;
6681         //     else        result[i] = 1. - result[i];
6682         //   }
6683         //   return result;
6684         // }
6685         const char                                              function[]                      =
6686                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6687                 "%param1    = OpFunctionParameter %v4f32\n"
6688                 "%lbl       = OpLabel\n"
6689                 "%iptr      = OpVariable %fp_i32 Function\n"
6690                 "%result    = OpVariable %fp_v4f32 Function\n"
6691                 "             OpStore %iptr %c_i32_0\n"
6692                 "             OpStore %result %param1\n"
6693                 "             OpBranch %loop\n"
6694
6695                 // Loop entry block.
6696                 "%loop      = OpLabel\n"
6697                 "%ival      = OpLoad %i32 %iptr\n"
6698                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6699                 "             OpLoopMerge %exit %if_entry None\n"
6700                 "             OpBranchConditional %lt_4 %if_entry %exit\n"
6701
6702                 // Merge block for loop.
6703                 "%exit      = OpLabel\n"
6704                 "%ret       = OpLoad %v4f32 %result\n"
6705                 "             OpReturnValue %ret\n"
6706
6707                 // If-statement entry block.
6708                 "%if_entry  = OpLabel\n"
6709                 "%loc       = OpAccessChain %fp_f32 %result %ival\n"
6710                 "%eq_0      = OpIEqual %bool %ival %c_i32_0\n"
6711                 "             OpSelectionMerge %if_exit None\n"
6712                 "             OpBranchConditional %eq_0 %if_true %if_false\n"
6713
6714                 // False branch for if-statement.
6715                 "%if_false  = OpLabel\n"
6716                 "%val       = OpLoad %f32 %loc\n"
6717                 "%sub       = OpFSub %f32 %c_f32_1 %val\n"
6718                 "             OpStore %loc %sub\n"
6719                 "             OpBranch %if_exit\n"
6720
6721                 // Merge block for if-statement.
6722                 "%if_exit   = OpLabel\n"
6723                 "%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
6724                 "             OpStore %iptr %ival_next\n"
6725                 "             OpBranch %loop\n"
6726
6727                 // True branch for if-statement.
6728                 "%if_true   = OpLabel\n"
6729                 "             OpStore %loc %c_f32_0\n"
6730                 "             OpBranch %if_exit\n"
6731
6732                 "             OpFunctionEnd\n";
6733
6734         fragments["testfun"]    = function;
6735
6736         inputColors[0]                  = RGBA(127, 127, 127, 0);
6737         inputColors[1]                  = RGBA(127, 0,   0,   0);
6738         inputColors[2]                  = RGBA(0,   127, 0,   0);
6739         inputColors[3]                  = RGBA(0,   0,   127, 0);
6740
6741         outputColors[0]                 = RGBA(0, 128, 128, 255);
6742         outputColors[1]                 = RGBA(0, 255, 255, 255);
6743         outputColors[2]                 = RGBA(0, 128, 255, 255);
6744         outputColors[3]                 = RGBA(0, 255, 128, 255);
6745
6746         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
6747
6748         return group.release();
6749 }
6750
6751 tcu::TestCaseGroup* createSwitchBlockOrderTests(tcu::TestContext& testCtx)
6752 {
6753         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "switch_block_order", "Out-of-order blocks for switch"));
6754         RGBA                                                    inputColors[4];
6755         RGBA                                                    outputColors[4];
6756         map<string, string>                             fragments;
6757
6758         const char                                              typesAndConstants[]     =
6759                 "%c_f32_p2  = OpConstant %f32 0.2\n"
6760                 "%c_f32_p4  = OpConstant %f32 0.4\n"
6761                 "%c_f32_p6  = OpConstant %f32 0.6\n"
6762                 "%c_f32_p8  = OpConstant %f32 0.8\n";
6763
6764         // vec4 test_code(vec4 param) {
6765         //   vec4 result = param;
6766         //   for (int i = 0; i < 4; ++i) {
6767         //     switch (i) {
6768         //       case 0: result[i] += .2; break;
6769         //       case 1: result[i] += .6; break;
6770         //       case 2: result[i] += .4; break;
6771         //       case 3: result[i] += .8; break;
6772         //       default: break; // unreachable
6773         //     }
6774         //   }
6775         //   return result;
6776         // }
6777         const char                                              function[]                      =
6778                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6779                 "%param1    = OpFunctionParameter %v4f32\n"
6780                 "%lbl       = OpLabel\n"
6781                 "%iptr      = OpVariable %fp_i32 Function\n"
6782                 "%result    = OpVariable %fp_v4f32 Function\n"
6783                 "             OpStore %iptr %c_i32_0\n"
6784                 "             OpStore %result %param1\n"
6785                 "             OpBranch %loop\n"
6786
6787                 // Loop entry block.
6788                 "%loop      = OpLabel\n"
6789                 "%ival      = OpLoad %i32 %iptr\n"
6790                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6791                 "             OpLoopMerge %exit %switch_exit None\n"
6792                 "             OpBranchConditional %lt_4 %switch_entry %exit\n"
6793
6794                 // Merge block for loop.
6795                 "%exit      = OpLabel\n"
6796                 "%ret       = OpLoad %v4f32 %result\n"
6797                 "             OpReturnValue %ret\n"
6798
6799                 // Switch-statement entry block.
6800                 "%switch_entry   = OpLabel\n"
6801                 "%loc            = OpAccessChain %fp_f32 %result %ival\n"
6802                 "%val            = OpLoad %f32 %loc\n"
6803                 "                  OpSelectionMerge %switch_exit None\n"
6804                 "                  OpSwitch %ival %switch_default 0 %case0 1 %case1 2 %case2 3 %case3\n"
6805
6806                 "%case2          = OpLabel\n"
6807                 "%addp4          = OpFAdd %f32 %val %c_f32_p4\n"
6808                 "                  OpStore %loc %addp4\n"
6809                 "                  OpBranch %switch_exit\n"
6810
6811                 "%switch_default = OpLabel\n"
6812                 "                  OpUnreachable\n"
6813
6814                 "%case3          = OpLabel\n"
6815                 "%addp8          = OpFAdd %f32 %val %c_f32_p8\n"
6816                 "                  OpStore %loc %addp8\n"
6817                 "                  OpBranch %switch_exit\n"
6818
6819                 "%case0          = OpLabel\n"
6820                 "%addp2          = OpFAdd %f32 %val %c_f32_p2\n"
6821                 "                  OpStore %loc %addp2\n"
6822                 "                  OpBranch %switch_exit\n"
6823
6824                 // Merge block for switch-statement.
6825                 "%switch_exit    = OpLabel\n"
6826                 "%ival_next      = OpIAdd %i32 %ival %c_i32_1\n"
6827                 "                  OpStore %iptr %ival_next\n"
6828                 "                  OpBranch %loop\n"
6829
6830                 "%case1          = OpLabel\n"
6831                 "%addp6          = OpFAdd %f32 %val %c_f32_p6\n"
6832                 "                  OpStore %loc %addp6\n"
6833                 "                  OpBranch %switch_exit\n"
6834
6835                 "                  OpFunctionEnd\n";
6836
6837         fragments["pre_main"]   = typesAndConstants;
6838         fragments["testfun"]    = function;
6839
6840         inputColors[0]                  = RGBA(127, 27,  127, 51);
6841         inputColors[1]                  = RGBA(127, 0,   0,   51);
6842         inputColors[2]                  = RGBA(0,   27,  0,   51);
6843         inputColors[3]                  = RGBA(0,   0,   127, 51);
6844
6845         outputColors[0]                 = RGBA(178, 180, 229, 255);
6846         outputColors[1]                 = RGBA(178, 153, 102, 255);
6847         outputColors[2]                 = RGBA(51,  180, 102, 255);
6848         outputColors[3]                 = RGBA(51,  153, 229, 255);
6849
6850         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
6851
6852         return group.release();
6853 }
6854
6855 tcu::TestCaseGroup* createDecorationGroupTests(tcu::TestContext& testCtx)
6856 {
6857         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "decoration_group", "Decoration group tests"));
6858         RGBA                                                    inputColors[4];
6859         RGBA                                                    outputColors[4];
6860         map<string, string>                             fragments;
6861
6862         const char                                              decorations[]           =
6863                 "OpDecorate %array_group         ArrayStride 4\n"
6864                 "OpDecorate %struct_member_group Offset 0\n"
6865                 "%array_group         = OpDecorationGroup\n"
6866                 "%struct_member_group = OpDecorationGroup\n"
6867
6868                 "OpDecorate %group1 RelaxedPrecision\n"
6869                 "OpDecorate %group3 RelaxedPrecision\n"
6870                 "OpDecorate %group3 Invariant\n"
6871                 "OpDecorate %group3 Restrict\n"
6872                 "%group0 = OpDecorationGroup\n"
6873                 "%group1 = OpDecorationGroup\n"
6874                 "%group3 = OpDecorationGroup\n";
6875
6876         const char                                              typesAndConstants[]     =
6877                 "%a3f32     = OpTypeArray %f32 %c_u32_3\n"
6878                 "%struct1   = OpTypeStruct %a3f32\n"
6879                 "%struct2   = OpTypeStruct %a3f32\n"
6880                 "%fp_struct1 = OpTypePointer Function %struct1\n"
6881                 "%fp_struct2 = OpTypePointer Function %struct2\n"
6882                 "%c_f32_2    = OpConstant %f32 2.\n"
6883                 "%c_f32_n2   = OpConstant %f32 -2.\n"
6884
6885                 "%c_a3f32_1 = OpConstantComposite %a3f32 %c_f32_1 %c_f32_2 %c_f32_1\n"
6886                 "%c_a3f32_2 = OpConstantComposite %a3f32 %c_f32_n1 %c_f32_n2 %c_f32_n1\n"
6887                 "%c_struct1 = OpConstantComposite %struct1 %c_a3f32_1\n"
6888                 "%c_struct2 = OpConstantComposite %struct2 %c_a3f32_2\n";
6889
6890         const char                                              function[]                      =
6891                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6892                 "%param     = OpFunctionParameter %v4f32\n"
6893                 "%entry     = OpLabel\n"
6894                 "%result    = OpVariable %fp_v4f32 Function\n"
6895                 "%v_struct1 = OpVariable %fp_struct1 Function\n"
6896                 "%v_struct2 = OpVariable %fp_struct2 Function\n"
6897                 "             OpStore %result %param\n"
6898                 "             OpStore %v_struct1 %c_struct1\n"
6899                 "             OpStore %v_struct2 %c_struct2\n"
6900                 "%ptr1      = OpAccessChain %fp_f32 %v_struct1 %c_i32_0 %c_i32_2\n"
6901                 "%val1      = OpLoad %f32 %ptr1\n"
6902                 "%ptr2      = OpAccessChain %fp_f32 %v_struct2 %c_i32_0 %c_i32_2\n"
6903                 "%val2      = OpLoad %f32 %ptr2\n"
6904                 "%addvalues = OpFAdd %f32 %val1 %val2\n"
6905                 "%ptr       = OpAccessChain %fp_f32 %result %c_i32_1\n"
6906                 "%val       = OpLoad %f32 %ptr\n"
6907                 "%addresult = OpFAdd %f32 %addvalues %val\n"
6908                 "             OpStore %ptr %addresult\n"
6909                 "%ret       = OpLoad %v4f32 %result\n"
6910                 "             OpReturnValue %ret\n"
6911                 "             OpFunctionEnd\n";
6912
6913         struct CaseNameDecoration
6914         {
6915                 string name;
6916                 string decoration;
6917         };
6918
6919         CaseNameDecoration tests[] =
6920         {
6921                 {
6922                         "same_decoration_group_on_multiple_types",
6923                         "OpGroupMemberDecorate %struct_member_group %struct1 0 %struct2 0\n"
6924                 },
6925                 {
6926                         "empty_decoration_group",
6927                         "OpGroupDecorate %group0      %a3f32\n"
6928                         "OpGroupDecorate %group0      %result\n"
6929                 },
6930                 {
6931                         "one_element_decoration_group",
6932                         "OpGroupDecorate %array_group %a3f32\n"
6933                 },
6934                 {
6935                         "multiple_elements_decoration_group",
6936                         "OpGroupDecorate %group3      %v_struct1\n"
6937                 },
6938                 {
6939                         "multiple_decoration_groups_on_same_variable",
6940                         "OpGroupDecorate %group0      %v_struct2\n"
6941                         "OpGroupDecorate %group1      %v_struct2\n"
6942                         "OpGroupDecorate %group3      %v_struct2\n"
6943                 },
6944                 {
6945                         "same_decoration_group_multiple_times",
6946                         "OpGroupDecorate %group1      %addvalues\n"
6947                         "OpGroupDecorate %group1      %addvalues\n"
6948                         "OpGroupDecorate %group1      %addvalues\n"
6949                 },
6950
6951         };
6952
6953         getHalfColorsFullAlpha(inputColors);
6954         getHalfColorsFullAlpha(outputColors);
6955
6956         for (size_t idx = 0; idx < (sizeof(tests) / sizeof(tests[0])); ++idx)
6957         {
6958                 fragments["decoration"] = decorations + tests[idx].decoration;
6959                 fragments["pre_main"]   = typesAndConstants;
6960                 fragments["testfun"]    = function;
6961
6962                 createTestsForAllStages(tests[idx].name, inputColors, outputColors, fragments, group.get());
6963         }
6964
6965         return group.release();
6966 }
6967
6968 struct SpecConstantTwoIntGraphicsCase
6969 {
6970         const char*             caseName;
6971         const char*             scDefinition0;
6972         const char*             scDefinition1;
6973         const char*             scResultType;
6974         const char*             scOperation;
6975         deInt32                 scActualValue0;
6976         deInt32                 scActualValue1;
6977         const char*             resultOperation;
6978         RGBA                    expectedColors[4];
6979         deInt32                 scActualValueLength;
6980
6981                                         SpecConstantTwoIntGraphicsCase (const char*             name,
6982                                                                                                         const char*             definition0,
6983                                                                                                         const char*             definition1,
6984                                                                                                         const char*             resultType,
6985                                                                                                         const char*             operation,
6986                                                                                                         const deInt32   value0,
6987                                                                                                         const deInt32   value1,
6988                                                                                                         const char*             resultOp,
6989                                                                                                         const RGBA              (&output)[4],
6990                                                                                                         const deInt32   valueLength = sizeof(deInt32))
6991                                                 : caseName                              (name)
6992                                                 , scDefinition0                 (definition0)
6993                                                 , scDefinition1                 (definition1)
6994                                                 , scResultType                  (resultType)
6995                                                 , scOperation                   (operation)
6996                                                 , scActualValue0                (value0)
6997                                                 , scActualValue1                (value1)
6998                                                 , resultOperation               (resultOp)
6999                                                 , scActualValueLength   (valueLength)
7000         {
7001                 expectedColors[0] = output[0];
7002                 expectedColors[1] = output[1];
7003                 expectedColors[2] = output[2];
7004                 expectedColors[3] = output[3];
7005         }
7006 };
7007
7008 tcu::TestCaseGroup* createSpecConstantTests (tcu::TestContext& testCtx)
7009 {
7010         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
7011         vector<SpecConstantTwoIntGraphicsCase>  cases;
7012         RGBA                                                    inputColors[4];
7013         RGBA                                                    outputColors0[4];
7014         RGBA                                                    outputColors1[4];
7015         RGBA                                                    outputColors2[4];
7016
7017         const deInt32                                   m1AsFloat16                     = 0xbc00; // -1(fp16) == 1 01111 0000000000 == 1011 1100 0000 0000
7018
7019         const char      decorations1[]                  =
7020                 "OpDecorate %sc_0  SpecId 0\n"
7021                 "OpDecorate %sc_1  SpecId 1\n";
7022
7023         const char      typesAndConstants1[]    =
7024                 "${OPTYPE_DEFINITIONS:opt}"
7025                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
7026                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
7027                 "%sc_op     = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n";
7028
7029         const char      function1[]                             =
7030                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7031                 "%param     = OpFunctionParameter %v4f32\n"
7032                 "%label     = OpLabel\n"
7033                 "%result    = OpVariable %fp_v4f32 Function\n"
7034                 "${TYPE_CONVERT:opt}"
7035                 "             OpStore %result %param\n"
7036                 "%gen       = ${GEN_RESULT}\n"
7037                 "%index     = OpIAdd %i32 %gen %c_i32_1\n"
7038                 "%loc       = OpAccessChain %fp_f32 %result %index\n"
7039                 "%val       = OpLoad %f32 %loc\n"
7040                 "%add       = OpFAdd %f32 %val %c_f32_0_5\n"
7041                 "             OpStore %loc %add\n"
7042                 "%ret       = OpLoad %v4f32 %result\n"
7043                 "             OpReturnValue %ret\n"
7044                 "             OpFunctionEnd\n";
7045
7046         inputColors[0] = RGBA(127, 127, 127, 255);
7047         inputColors[1] = RGBA(127, 0,   0,   255);
7048         inputColors[2] = RGBA(0,   127, 0,   255);
7049         inputColors[3] = RGBA(0,   0,   127, 255);
7050
7051         // Derived from inputColors[x] by adding 128 to inputColors[x][0].
7052         outputColors0[0] = RGBA(255, 127, 127, 255);
7053         outputColors0[1] = RGBA(255, 0,   0,   255);
7054         outputColors0[2] = RGBA(128, 127, 0,   255);
7055         outputColors0[3] = RGBA(128, 0,   127, 255);
7056
7057         // Derived from inputColors[x] by adding 128 to inputColors[x][1].
7058         outputColors1[0] = RGBA(127, 255, 127, 255);
7059         outputColors1[1] = RGBA(127, 128, 0,   255);
7060         outputColors1[2] = RGBA(0,   255, 0,   255);
7061         outputColors1[3] = RGBA(0,   128, 127, 255);
7062
7063         // Derived from inputColors[x] by adding 128 to inputColors[x][2].
7064         outputColors2[0] = RGBA(127, 127, 255, 255);
7065         outputColors2[1] = RGBA(127, 0,   128, 255);
7066         outputColors2[2] = RGBA(0,   127, 128, 255);
7067         outputColors2[3] = RGBA(0,   0,   255, 255);
7068
7069         const char addZeroToSc[]                = "OpIAdd %i32 %c_i32_0 %sc_op";
7070         const char addZeroToSc32[]              = "OpIAdd %i32 %c_i32_0 %sc_op32";
7071         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_op %c_i32_1 %c_i32_0";
7072         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_op %c_i32_0 %c_i32_1";
7073
7074         cases.push_back(SpecConstantTwoIntGraphicsCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                             19,             -20,    addZeroToSc,            outputColors0));
7075         cases.push_back(SpecConstantTwoIntGraphicsCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                             19,             20,             addZeroToSc,            outputColors0));
7076         cases.push_back(SpecConstantTwoIntGraphicsCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                             -1,             -1,             addZeroToSc,            outputColors2));
7077         cases.push_back(SpecConstantTwoIntGraphicsCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                             -126,   126,    addZeroToSc,            outputColors0));
7078         cases.push_back(SpecConstantTwoIntGraphicsCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                             126,    126,    addZeroToSc,            outputColors2));
7079         cases.push_back(SpecConstantTwoIntGraphicsCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
7080         cases.push_back(SpecConstantTwoIntGraphicsCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
7081         cases.push_back(SpecConstantTwoIntGraphicsCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                             1001,   500,    addZeroToSc,            outputColors2));
7082         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                             0x33,   0x0d,   addZeroToSc,            outputColors2));
7083         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                             0,              1,              addZeroToSc,            outputColors2));
7084         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                             0x2e,   0x2f,   addZeroToSc,            outputColors2));
7085         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                             2,              1,              addZeroToSc,            outputColors2));
7086         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                             -4,             2,              addZeroToSc,            outputColors0));
7087         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                             1,              0,              addZeroToSc,            outputColors2));
7088         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                             -20,    -10,    selectTrueUsingSc,      outputColors2));
7089         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                             10,             20,             selectTrueUsingSc,      outputColors2));
7090         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
7091         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                             10,             5,              selectTrueUsingSc,      outputColors2));
7092         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                             -10,    -10,    selectTrueUsingSc,      outputColors2));
7093         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                             50,             100,    selectTrueUsingSc,      outputColors2));
7094         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
7095         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                             10,             10,             selectTrueUsingSc,      outputColors2));
7096         cases.push_back(SpecConstantTwoIntGraphicsCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                             42,             24,             selectFalseUsingSc,     outputColors2));
7097         cases.push_back(SpecConstantTwoIntGraphicsCase("inotequal",                             " %i32 0",              " %i32 0",              "%bool",        "INotEqual            %sc_0 %sc_1",                             42,             24,             selectTrueUsingSc,      outputColors2));
7098         cases.push_back(SpecConstantTwoIntGraphicsCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
7099         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
7100         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
7101         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
7102         cases.push_back(SpecConstantTwoIntGraphicsCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                                   -1,             0,              addZeroToSc,            outputColors2));
7103         cases.push_back(SpecConstantTwoIntGraphicsCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                                   -2,             0,              addZeroToSc,            outputColors2));
7104         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                                   1,              0,              selectFalseUsingSc,     outputColors2));
7105         cases.push_back(SpecConstantTwoIntGraphicsCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %c_i32_0",    1,              1,              addZeroToSc,            outputColors2));
7106         cases.push_back(SpecConstantTwoIntGraphicsCase("sconvert",                              " %i32 0",              " %i32 0",              "%i16",         "SConvert             %sc_0",                                   -1,             0,              addZeroToSc32,          outputColors0));
7107         // -1082130432 stored as 32-bit two's complement is the binary representation of -1 as IEEE-754 Float
7108         cases.push_back(SpecConstantTwoIntGraphicsCase("fconvert",                              " %f32 0",              " %f32 0",              "%f64",         "FConvert             %sc_0",                                   -1082130432, 0, addZeroToSc32,          outputColors0));
7109         cases.push_back(SpecConstantTwoIntGraphicsCase("fconvert16",                    " %f16 0",              " %f16 0",              "%f32",         "FConvert             %sc_0",                                   m1AsFloat16, 0, addZeroToSc32,          outputColors0, sizeof(deFloat16)));
7110         // \todo[2015-12-1 antiagainst] OpQuantizeToF16
7111
7112         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
7113         {
7114                 map<string, string>                     specializations;
7115                 map<string, string>                     fragments;
7116                 SpecConstants                           specConstants;
7117                 PushConstants                           noPushConstants;
7118                 GraphicsResources                       noResources;
7119                 GraphicsInterfaces                      noInterfaces;
7120                 vector<string>                          extensions;
7121                 VulkanFeatures                          requiredFeatures;
7122
7123                 // Special SPIR-V code for SConvert-case
7124                 if (strcmp(cases[caseNdx].caseName, "sconvert") == 0)
7125                 {
7126                         requiredFeatures.coreFeatures.shaderInt16 = VK_TRUE;
7127                         fragments["capability"]                                 = "OpCapability Int16\n";                                       // Adds 16-bit integer capability
7128                         specializations["OPTYPE_DEFINITIONS"]   = "%i16 = OpTypeInt 16 1\n";                            // Adds 16-bit integer type
7129                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpSConvert %i32 %sc_op\n";        // Converts 16-bit integer to 32-bit integer
7130                 }
7131
7132                 // Special SPIR-V code for FConvert-case
7133                 if (strcmp(cases[caseNdx].caseName, "fconvert") == 0)
7134                 {
7135                         requiredFeatures.coreFeatures.shaderFloat64 = VK_TRUE;
7136                         fragments["capability"]                                 = "OpCapability Float64\n";                                     // Adds 64-bit float capability
7137                         specializations["OPTYPE_DEFINITIONS"]   = "%f64 = OpTypeFloat 64\n";                            // Adds 64-bit float type
7138                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpConvertFToS %i32 %sc_op\n";     // Converts 64-bit float to 32-bit integer
7139                 }
7140
7141                 // Special SPIR-V code for FConvert-case for 16-bit floats
7142                 if (strcmp(cases[caseNdx].caseName, "fconvert16") == 0)
7143                 {
7144                         extensions.push_back("VK_KHR_shader_float16_int8");
7145                         requiredFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
7146                         fragments["capability"]                                 = "OpCapability Float16\n";                                     // Adds 16-bit float capability
7147                         specializations["OPTYPE_DEFINITIONS"]   = "%f16 = OpTypeFloat 16\n";                            // Adds 16-bit float type
7148                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpConvertFToS %i32 %sc_op\n";     // Converts 16-bit float to 32-bit integer
7149                 }
7150
7151                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
7152                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
7153                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
7154                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
7155                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
7156
7157                 fragments["decoration"]                         = tcu::StringTemplate(decorations1).specialize(specializations);
7158                 fragments["pre_main"]                           = tcu::StringTemplate(typesAndConstants1).specialize(specializations);
7159                 fragments["testfun"]                            = tcu::StringTemplate(function1).specialize(specializations);
7160
7161                 specConstants.append(&cases[caseNdx].scActualValue0, cases[caseNdx].scActualValueLength);
7162                 specConstants.append(&cases[caseNdx].scActualValue1, cases[caseNdx].scActualValueLength);
7163
7164                 createTestsForAllStages(
7165                         cases[caseNdx].caseName, inputColors, cases[caseNdx].expectedColors, fragments, specConstants,
7166                         noPushConstants, noResources, noInterfaces, extensions, requiredFeatures, group.get());
7167         }
7168
7169         const char      decorations2[]                  =
7170                 "OpDecorate %sc_0  SpecId 0\n"
7171                 "OpDecorate %sc_1  SpecId 1\n"
7172                 "OpDecorate %sc_2  SpecId 2\n";
7173
7174         const char      typesAndConstants2[]    =
7175                 "%vec3_0      = OpConstantComposite %v3i32 %c_i32_0 %c_i32_0 %c_i32_0\n"
7176                 "%vec3_undef  = OpUndef %v3i32\n"
7177
7178                 "%sc_0        = OpSpecConstant %i32 0\n"
7179                 "%sc_1        = OpSpecConstant %i32 0\n"
7180                 "%sc_2        = OpSpecConstant %i32 0\n"
7181                 "%sc_vec3_0   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_0        %vec3_0      0\n"                                                 // (sc_0, 0,    0)
7182                 "%sc_vec3_1   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_1        %vec3_0      1\n"                                                 // (0,    sc_1, 0)
7183                 "%sc_vec3_2   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_2        %vec3_0      2\n"                                                 // (0,    0,    sc_2)
7184                 "%sc_vec3_0_s = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_0   %vec3_undef  0          0xFFFFFFFF 2\n"   // (sc_0, ???,  0)
7185                 "%sc_vec3_1_s = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_1   %vec3_undef  0xFFFFFFFF 1          0\n"   // (???,  sc_1, 0)
7186                 "%sc_vec3_2_s = OpSpecConstantOp %v3i32 VectorShuffle    %vec3_undef  %sc_vec3_2   5          0xFFFFFFFF 5\n"   // (sc_2, ???,  sc_2)
7187                 "%sc_vec3_01  = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_0_s %sc_vec3_1_s 1 0 4\n"                                             // (0,    sc_0, sc_1)
7188                 "%sc_vec3_012 = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_01  %sc_vec3_2_s 5 1 2\n"                                             // (sc_2, sc_0, sc_1)
7189                 "%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              0\n"                                                 // sc_2
7190                 "%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              1\n"                                                 // sc_0
7191                 "%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              2\n"                                                 // sc_1
7192                 "%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"                                                              // (sc_2 - sc_0)
7193                 "%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n";                                                             // (sc_2 - sc_0) * sc_1
7194
7195         const char      function2[]                             =
7196                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7197                 "%param     = OpFunctionParameter %v4f32\n"
7198                 "%label     = OpLabel\n"
7199                 "%result    = OpVariable %fp_v4f32 Function\n"
7200                 "             OpStore %result %param\n"
7201                 "%loc       = OpAccessChain %fp_f32 %result %sc_final\n"
7202                 "%val       = OpLoad %f32 %loc\n"
7203                 "%add       = OpFAdd %f32 %val %c_f32_0_5\n"
7204                 "             OpStore %loc %add\n"
7205                 "%ret       = OpLoad %v4f32 %result\n"
7206                 "             OpReturnValue %ret\n"
7207                 "             OpFunctionEnd\n";
7208
7209         map<string, string>     fragments;
7210         SpecConstants           specConstants;
7211
7212         fragments["decoration"] = decorations2;
7213         fragments["pre_main"]   = typesAndConstants2;
7214         fragments["testfun"]    = function2;
7215
7216         specConstants.append<deInt32>(56789);
7217         specConstants.append<deInt32>(-2);
7218         specConstants.append<deInt32>(56788);
7219
7220         createTestsForAllStages("vector_related", inputColors, outputColors2, fragments, specConstants, group.get());
7221
7222         return group.release();
7223 }
7224
7225 tcu::TestCaseGroup* createOpPhiTests(tcu::TestContext& testCtx)
7226 {
7227         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
7228         RGBA                                                    inputColors[4];
7229         RGBA                                                    outputColors1[4];
7230         RGBA                                                    outputColors2[4];
7231         RGBA                                                    outputColors3[4];
7232         RGBA                                                    outputColors4[4];
7233         map<string, string>                             fragments1;
7234         map<string, string>                             fragments2;
7235         map<string, string>                             fragments3;
7236         map<string, string>                             fragments4;
7237         std::vector<std::string>                extensions4;
7238         GraphicsResources                               resources4;
7239         VulkanFeatures                                  vulkanFeatures4;
7240
7241         const char      typesAndConstants1[]    =
7242                 "%c_f32_p2  = OpConstant %f32 0.2\n"
7243                 "%c_f32_p4  = OpConstant %f32 0.4\n"
7244                 "%c_f32_p5  = OpConstant %f32 0.5\n"
7245                 "%c_f32_p8  = OpConstant %f32 0.8\n";
7246
7247         // vec4 test_code(vec4 param) {
7248         //   vec4 result = param;
7249         //   for (int i = 0; i < 4; ++i) {
7250         //     float operand;
7251         //     switch (i) {
7252         //       case 0: operand = .2; break;
7253         //       case 1: operand = .5; break;
7254         //       case 2: operand = .4; break;
7255         //       case 3: operand = .0; break;
7256         //       default: break; // unreachable
7257         //     }
7258         //     result[i] += operand;
7259         //   }
7260         //   return result;
7261         // }
7262         const char      function1[]                             =
7263                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7264                 "%param1    = OpFunctionParameter %v4f32\n"
7265                 "%lbl       = OpLabel\n"
7266                 "%iptr      = OpVariable %fp_i32 Function\n"
7267                 "%result    = OpVariable %fp_v4f32 Function\n"
7268                 "             OpStore %iptr %c_i32_0\n"
7269                 "             OpStore %result %param1\n"
7270                 "             OpBranch %loop\n"
7271
7272                 "%loop      = OpLabel\n"
7273                 "%ival      = OpLoad %i32 %iptr\n"
7274                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
7275                 "             OpLoopMerge %exit %phi None\n"
7276                 "             OpBranchConditional %lt_4 %entry %exit\n"
7277
7278                 "%entry     = OpLabel\n"
7279                 "%loc       = OpAccessChain %fp_f32 %result %ival\n"
7280                 "%val       = OpLoad %f32 %loc\n"
7281                 "             OpSelectionMerge %phi None\n"
7282                 "             OpSwitch %ival %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
7283
7284                 "%case0     = OpLabel\n"
7285                 "             OpBranch %phi\n"
7286                 "%case1     = OpLabel\n"
7287                 "             OpBranch %phi\n"
7288                 "%case2     = OpLabel\n"
7289                 "             OpBranch %phi\n"
7290                 "%case3     = OpLabel\n"
7291                 "             OpBranch %phi\n"
7292
7293                 "%default   = OpLabel\n"
7294                 "             OpUnreachable\n"
7295
7296                 "%phi       = OpLabel\n"
7297                 "%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
7298                 "%add       = OpFAdd %f32 %val %operand\n"
7299                 "             OpStore %loc %add\n"
7300                 "%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
7301                 "             OpStore %iptr %ival_next\n"
7302                 "             OpBranch %loop\n"
7303
7304                 "%exit      = OpLabel\n"
7305                 "%ret       = OpLoad %v4f32 %result\n"
7306                 "             OpReturnValue %ret\n"
7307
7308                 "             OpFunctionEnd\n";
7309
7310         fragments1["pre_main"]  = typesAndConstants1;
7311         fragments1["testfun"]   = function1;
7312
7313         getHalfColorsFullAlpha(inputColors);
7314
7315         outputColors1[0]                = RGBA(178, 255, 229, 255);
7316         outputColors1[1]                = RGBA(178, 127, 102, 255);
7317         outputColors1[2]                = RGBA(51,  255, 102, 255);
7318         outputColors1[3]                = RGBA(51,  127, 229, 255);
7319
7320         createTestsForAllStages("out_of_order", inputColors, outputColors1, fragments1, group.get());
7321
7322         const char      typesAndConstants2[]    =
7323                 "%c_f32_p2  = OpConstant %f32 0.2\n";
7324
7325         // Add .4 to the second element of the given parameter.
7326         const char      function2[]                             =
7327                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7328                 "%param     = OpFunctionParameter %v4f32\n"
7329                 "%entry     = OpLabel\n"
7330                 "%result    = OpVariable %fp_v4f32 Function\n"
7331                 "             OpStore %result %param\n"
7332                 "%loc       = OpAccessChain %fp_f32 %result %c_i32_1\n"
7333                 "%val       = OpLoad %f32 %loc\n"
7334                 "             OpBranch %phi\n"
7335
7336                 "%phi        = OpLabel\n"
7337                 "%step       = OpPhi %i32 %c_i32_0  %entry %step_next  %phi\n"
7338                 "%accum      = OpPhi %f32 %val      %entry %accum_next %phi\n"
7339                 "%step_next  = OpIAdd %i32 %step  %c_i32_1\n"
7340                 "%accum_next = OpFAdd %f32 %accum %c_f32_p2\n"
7341                 "%still_loop = OpSLessThan %bool %step %c_i32_2\n"
7342                 "              OpLoopMerge %exit %phi None\n"
7343                 "              OpBranchConditional %still_loop %phi %exit\n"
7344
7345                 "%exit       = OpLabel\n"
7346                 "              OpStore %loc %accum\n"
7347                 "%ret        = OpLoad %v4f32 %result\n"
7348                 "              OpReturnValue %ret\n"
7349
7350                 "              OpFunctionEnd\n";
7351
7352         fragments2["pre_main"]  = typesAndConstants2;
7353         fragments2["testfun"]   = function2;
7354
7355         outputColors2[0]                        = RGBA(127, 229, 127, 255);
7356         outputColors2[1]                        = RGBA(127, 102, 0,   255);
7357         outputColors2[2]                        = RGBA(0,   229, 0,   255);
7358         outputColors2[3]                        = RGBA(0,   102, 127, 255);
7359
7360         createTestsForAllStages("induction", inputColors, outputColors2, fragments2, group.get());
7361
7362         const char      typesAndConstants3[]    =
7363                 "%true      = OpConstantTrue %bool\n"
7364                 "%false     = OpConstantFalse %bool\n"
7365                 "%c_f32_p2  = OpConstant %f32 0.2\n";
7366
7367         // Swap the second and the third element of the given parameter.
7368         const char      function3[]                             =
7369                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7370                 "%param     = OpFunctionParameter %v4f32\n"
7371                 "%entry     = OpLabel\n"
7372                 "%result    = OpVariable %fp_v4f32 Function\n"
7373                 "             OpStore %result %param\n"
7374                 "%a_loc     = OpAccessChain %fp_f32 %result %c_i32_1\n"
7375                 "%a_init    = OpLoad %f32 %a_loc\n"
7376                 "%b_loc     = OpAccessChain %fp_f32 %result %c_i32_2\n"
7377                 "%b_init    = OpLoad %f32 %b_loc\n"
7378                 "             OpBranch %phi\n"
7379
7380                 "%phi        = OpLabel\n"
7381                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
7382                 "%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
7383                 "%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
7384                 "              OpLoopMerge %exit %phi None\n"
7385                 "              OpBranchConditional %still_loop %phi %exit\n"
7386
7387                 "%exit       = OpLabel\n"
7388                 "              OpStore %a_loc %a_next\n"
7389                 "              OpStore %b_loc %b_next\n"
7390                 "%ret        = OpLoad %v4f32 %result\n"
7391                 "              OpReturnValue %ret\n"
7392
7393                 "              OpFunctionEnd\n";
7394
7395         fragments3["pre_main"]  = typesAndConstants3;
7396         fragments3["testfun"]   = function3;
7397
7398         outputColors3[0]                        = RGBA(127, 127, 127, 255);
7399         outputColors3[1]                        = RGBA(127, 0,   0,   255);
7400         outputColors3[2]                        = RGBA(0,   0,   127, 255);
7401         outputColors3[3]                        = RGBA(0,   127, 0,   255);
7402
7403         createTestsForAllStages("swap", inputColors, outputColors3, fragments3, group.get());
7404
7405         const char      typesAndConstants4[]    =
7406                 "%f16        = OpTypeFloat 16\n"
7407                 "%v4f16      = OpTypeVector %f16 4\n"
7408                 "%fp_f16     = OpTypePointer Function %f16\n"
7409                 "%fp_v4f16   = OpTypePointer Function %v4f16\n"
7410                 "%true       = OpConstantTrue %bool\n"
7411                 "%false      = OpConstantFalse %bool\n"
7412                 "%c_f32_p2   = OpConstant %f32 0.2\n";
7413
7414         // Swap the second and the third element of the given parameter.
7415         const char      function4[]                             =
7416                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7417                 "%param      = OpFunctionParameter %v4f32\n"
7418                 "%entry      = OpLabel\n"
7419                 "%result     = OpVariable %fp_v4f16 Function\n"
7420                 "%param16    = OpFConvert %v4f16 %param\n"
7421                 "              OpStore %result %param16\n"
7422                 "%a_loc      = OpAccessChain %fp_f16 %result %c_i32_1\n"
7423                 "%a_init     = OpLoad %f16 %a_loc\n"
7424                 "%b_loc      = OpAccessChain %fp_f16 %result %c_i32_2\n"
7425                 "%b_init     = OpLoad %f16 %b_loc\n"
7426                 "              OpBranch %phi\n"
7427
7428                 "%phi        = OpLabel\n"
7429                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
7430                 "%a_next     = OpPhi %f16  %a_init %entry %b_next %phi\n"
7431                 "%b_next     = OpPhi %f16  %b_init %entry %a_next %phi\n"
7432                 "              OpLoopMerge %exit %phi None\n"
7433                 "              OpBranchConditional %still_loop %phi %exit\n"
7434
7435                 "%exit       = OpLabel\n"
7436                 "              OpStore %a_loc %a_next\n"
7437                 "              OpStore %b_loc %b_next\n"
7438                 "%ret16      = OpLoad %v4f16 %result\n"
7439                 "%ret        = OpFConvert %v4f32 %ret16\n"
7440                 "              OpReturnValue %ret\n"
7441
7442                 "              OpFunctionEnd\n";
7443
7444         fragments4["pre_main"]          = typesAndConstants4;
7445         fragments4["testfun"]           = function4;
7446         fragments4["capability"]        = "OpCapability StorageUniformBufferBlock16\n";
7447         fragments4["extension"]         = "OpExtension \"SPV_KHR_16bit_storage\"";
7448
7449         extensions4.push_back("VK_KHR_16bit_storage");
7450         extensions4.push_back("VK_KHR_shader_float16_int8");
7451
7452         vulkanFeatures4.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
7453         vulkanFeatures4.extFloat16Int8  = EXTFLOAT16INT8FEATURES_FLOAT16;
7454
7455         outputColors4[0]                        = RGBA(127, 127, 127, 255);
7456         outputColors4[1]                        = RGBA(127, 0,   0,   255);
7457         outputColors4[2]                        = RGBA(0,   0,   127, 255);
7458         outputColors4[3]                        = RGBA(0,   127, 0,   255);
7459
7460         createTestsForAllStages("swap16", inputColors, outputColors4, fragments4, resources4, extensions4, group.get(), vulkanFeatures4);
7461
7462         return group.release();
7463 }
7464
7465 tcu::TestCaseGroup* createNoContractionTests(tcu::TestContext& testCtx)
7466 {
7467         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
7468         RGBA                                                    inputColors[4];
7469         RGBA                                                    outputColors[4];
7470
7471         // With NoContraction, (1 + 2^-23) * (1 - 2^-23) - 1 should be conducted as a multiplication and an addition separately.
7472         // For the multiplication, the result is 1 - 2^-46, which is out of the precision range for 32-bit float. (32-bit float
7473         // only have 23-bit fraction.) So it will be rounded to 1. Or 0x1.fffffc. Then the final result is 0 or -0x1p-24.
7474         // On the contrary, the result will be 2^-46, which is a normalized number perfectly representable as 32-bit float.
7475         const char                                              constantsAndTypes[]      =
7476                 "%c_vec4_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_0 %c_f32_1\n"
7477                 "%c_vec4_1       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
7478                 "%c_f32_1pl2_23  = OpConstant %f32 0x1.000002p+0\n" // 1 + 2^-23
7479                 "%c_f32_1mi2_23  = OpConstant %f32 0x1.fffffcp-1\n" // 1 - 2^-23
7480                 "%c_f32_n1pn24   = OpConstant %f32 -0x1p-24\n";
7481
7482         const char                                              function[]       =
7483                 "%test_code      = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7484                 "%param          = OpFunctionParameter %v4f32\n"
7485                 "%label          = OpLabel\n"
7486                 "%var1           = OpVariable %fp_f32 Function %c_f32_1pl2_23\n"
7487                 "%var2           = OpVariable %fp_f32 Function\n"
7488                 "%red            = OpCompositeExtract %f32 %param 0\n"
7489                 "%plus_red       = OpFAdd %f32 %c_f32_1mi2_23 %red\n"
7490                 "                  OpStore %var2 %plus_red\n"
7491                 "%val1           = OpLoad %f32 %var1\n"
7492                 "%val2           = OpLoad %f32 %var2\n"
7493                 "%mul            = OpFMul %f32 %val1 %val2\n"
7494                 "%add            = OpFAdd %f32 %mul %c_f32_n1\n"
7495                 "%is0            = OpFOrdEqual %bool %add %c_f32_0\n"
7496                 "%isn1n24         = OpFOrdEqual %bool %add %c_f32_n1pn24\n"
7497                 "%success        = OpLogicalOr %bool %is0 %isn1n24\n"
7498                 "%v4success      = OpCompositeConstruct %v4bool %success %success %success %success\n"
7499                 "%ret            = OpSelect %v4f32 %v4success %c_vec4_0 %c_vec4_1\n"
7500                 "                  OpReturnValue %ret\n"
7501                 "                  OpFunctionEnd\n";
7502
7503         struct CaseNameDecoration
7504         {
7505                 string name;
7506                 string decoration;
7507         };
7508
7509
7510         CaseNameDecoration tests[] = {
7511                 {"multiplication",      "OpDecorate %mul NoContraction"},
7512                 {"addition",            "OpDecorate %add NoContraction"},
7513                 {"both",                        "OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"},
7514         };
7515
7516         getHalfColorsFullAlpha(inputColors);
7517
7518         for (deUint8 idx = 0; idx < 4; ++idx)
7519         {
7520                 inputColors[idx].setRed(0);
7521                 outputColors[idx] = RGBA(0, 0, 0, 255);
7522         }
7523
7524         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(CaseNameDecoration); ++testNdx)
7525         {
7526                 map<string, string> fragments;
7527
7528                 fragments["decoration"] = tests[testNdx].decoration;
7529                 fragments["pre_main"] = constantsAndTypes;
7530                 fragments["testfun"] = function;
7531
7532                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, group.get());
7533         }
7534
7535         return group.release();
7536 }
7537
7538 tcu::TestCaseGroup* createMemoryAccessTests(tcu::TestContext& testCtx)
7539 {
7540         de::MovePtr<tcu::TestCaseGroup> memoryAccessTests (new tcu::TestCaseGroup(testCtx, "opmemoryaccess", "Memory Semantics"));
7541         RGBA                                                    colors[4];
7542
7543         const char                                              constantsAndTypes[]      =
7544                 "%c_a2f32_1         = OpConstantComposite %a2f32 %c_f32_1 %c_f32_1\n"
7545                 "%fp_a2f32          = OpTypePointer Function %a2f32\n"
7546                 "%stype             = OpTypeStruct  %v4f32 %a2f32 %f32\n"
7547                 "%fp_stype          = OpTypePointer Function %stype\n";
7548
7549         const char                                              function[]       =
7550                 "%test_code         = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7551                 "%param1            = OpFunctionParameter %v4f32\n"
7552                 "%lbl               = OpLabel\n"
7553                 "%v1                = OpVariable %fp_v4f32 Function\n"
7554                 "%v2                = OpVariable %fp_a2f32 Function\n"
7555                 "%v3                = OpVariable %fp_f32 Function\n"
7556                 "%v                 = OpVariable %fp_stype Function\n"
7557                 "%vv                = OpVariable %fp_stype Function\n"
7558                 "%vvv               = OpVariable %fp_f32 Function\n"
7559
7560                 "                     OpStore %v1 %c_v4f32_1_1_1_1\n"
7561                 "                     OpStore %v2 %c_a2f32_1\n"
7562                 "                     OpStore %v3 %c_f32_1\n"
7563
7564                 "%p_v4f32          = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
7565                 "%p_a2f32          = OpAccessChain %fp_a2f32 %v %c_u32_1\n"
7566                 "%p_f32            = OpAccessChain %fp_f32 %v %c_u32_2\n"
7567                 "%v1_v             = OpLoad %v4f32 %v1 ${access_type}\n"
7568                 "%v2_v             = OpLoad %a2f32 %v2 ${access_type}\n"
7569                 "%v3_v             = OpLoad %f32 %v3 ${access_type}\n"
7570
7571                 "                    OpStore %p_v4f32 %v1_v ${access_type}\n"
7572                 "                    OpStore %p_a2f32 %v2_v ${access_type}\n"
7573                 "                    OpStore %p_f32 %v3_v ${access_type}\n"
7574
7575                 "                    OpCopyMemory %vv %v ${access_type}\n"
7576                 "                    OpCopyMemory %vvv %p_f32 ${access_type}\n"
7577
7578                 "%p_f32_2          = OpAccessChain %fp_f32 %vv %c_u32_2\n"
7579                 "%v_f32_2          = OpLoad %f32 %p_f32_2\n"
7580                 "%v_f32_3          = OpLoad %f32 %vvv\n"
7581
7582                 "%ret1             = OpVectorTimesScalar %v4f32 %param1 %v_f32_2\n"
7583                 "%ret2             = OpVectorTimesScalar %v4f32 %ret1 %v_f32_3\n"
7584                 "                    OpReturnValue %ret2\n"
7585                 "                    OpFunctionEnd\n";
7586
7587         struct NameMemoryAccess
7588         {
7589                 string name;
7590                 string accessType;
7591         };
7592
7593
7594         NameMemoryAccess tests[] =
7595         {
7596                 { "none", "" },
7597                 { "volatile", "Volatile" },
7598                 { "aligned",  "Aligned 1" },
7599                 { "volatile_aligned",  "Volatile|Aligned 1" },
7600                 { "nontemporal_aligned",  "Nontemporal|Aligned 1" },
7601                 { "volatile_nontemporal",  "Volatile|Nontemporal" },
7602                 { "volatile_nontermporal_aligned",  "Volatile|Nontemporal|Aligned 1" },
7603         };
7604
7605         getHalfColorsFullAlpha(colors);
7606
7607         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameMemoryAccess); ++testNdx)
7608         {
7609                 map<string, string> fragments;
7610                 map<string, string> memoryAccess;
7611                 memoryAccess["access_type"] = tests[testNdx].accessType;
7612
7613                 fragments["pre_main"] = constantsAndTypes;
7614                 fragments["testfun"] = tcu::StringTemplate(function).specialize(memoryAccess);
7615                 createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, memoryAccessTests.get());
7616         }
7617         return memoryAccessTests.release();
7618 }
7619 tcu::TestCaseGroup* createOpUndefTests(tcu::TestContext& testCtx)
7620 {
7621         de::MovePtr<tcu::TestCaseGroup>         opUndefTests             (new tcu::TestCaseGroup(testCtx, "opundef", "Test OpUndef"));
7622         RGBA                                                            defaultColors[4];
7623         map<string, string>                                     fragments;
7624         getDefaultColors(defaultColors);
7625
7626         // First, simple cases that don't do anything with the OpUndef result.
7627         struct NameCodePair { string name, decl, type; };
7628         const NameCodePair tests[] =
7629         {
7630                 {"bool", "", "%bool"},
7631                 {"vec2uint32", "", "%v2u32"},
7632                 {"image", "%type = OpTypeImage %f32 2D 0 0 0 1 Unknown", "%type"},
7633                 {"sampler", "%type = OpTypeSampler", "%type"},
7634                 {"sampledimage", "%img = OpTypeImage %f32 2D 0 0 0 1 Unknown\n" "%type = OpTypeSampledImage %img", "%type"},
7635                 {"pointer", "", "%fp_i32"},
7636                 {"runtimearray", "%type = OpTypeRuntimeArray %f32", "%type"},
7637                 {"array", "%c_u32_100 = OpConstant %u32 100\n" "%type = OpTypeArray %i32 %c_u32_100", "%type"},
7638                 {"struct", "%type = OpTypeStruct %f32 %i32 %u32", "%type"}};
7639         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
7640         {
7641                 fragments["undef_type"] = tests[testNdx].type;
7642                 fragments["testfun"] = StringTemplate(
7643                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7644                         "%param1 = OpFunctionParameter %v4f32\n"
7645                         "%label_testfun = OpLabel\n"
7646                         "%undef = OpUndef ${undef_type}\n"
7647                         "OpReturnValue %param1\n"
7648                         "OpFunctionEnd\n").specialize(fragments);
7649                 fragments["pre_main"] = tests[testNdx].decl;
7650                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opUndefTests.get());
7651         }
7652         fragments.clear();
7653
7654         fragments["testfun"] =
7655                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7656                 "%param1 = OpFunctionParameter %v4f32\n"
7657                 "%label_testfun = OpLabel\n"
7658                 "%undef = OpUndef %f32\n"
7659                 "%zero = OpFMul %f32 %undef %c_f32_0\n"
7660                 "%is_nan = OpIsNan %bool %zero\n" //OpUndef may result in NaN which may turn %zero into Nan.
7661                 "%actually_zero = OpSelect %f32 %is_nan %c_f32_0 %zero\n"
7662                 "%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7663                 "%b = OpFAdd %f32 %a %actually_zero\n"
7664                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %b %c_i32_0\n"
7665                 "OpReturnValue %ret\n"
7666                 "OpFunctionEnd\n";
7667
7668         createTestsForAllStages("float32", defaultColors, defaultColors, fragments, opUndefTests.get());
7669
7670         fragments["testfun"] =
7671                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7672                 "%param1 = OpFunctionParameter %v4f32\n"
7673                 "%label_testfun = OpLabel\n"
7674                 "%undef = OpUndef %i32\n"
7675                 "%zero = OpIMul %i32 %undef %c_i32_0\n"
7676                 "%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
7677                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
7678                 "OpReturnValue %ret\n"
7679                 "OpFunctionEnd\n";
7680
7681         createTestsForAllStages("sint32", defaultColors, defaultColors, fragments, opUndefTests.get());
7682
7683         fragments["testfun"] =
7684                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7685                 "%param1 = OpFunctionParameter %v4f32\n"
7686                 "%label_testfun = OpLabel\n"
7687                 "%undef = OpUndef %u32\n"
7688                 "%zero = OpIMul %u32 %undef %c_i32_0\n"
7689                 "%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
7690                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
7691                 "OpReturnValue %ret\n"
7692                 "OpFunctionEnd\n";
7693
7694         createTestsForAllStages("uint32", defaultColors, defaultColors, fragments, opUndefTests.get());
7695
7696         fragments["testfun"] =
7697                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7698                 "%param1 = OpFunctionParameter %v4f32\n"
7699                 "%label_testfun = OpLabel\n"
7700                 "%undef = OpUndef %v4f32\n"
7701                 "%vzero = OpVectorTimesScalar %v4f32 %undef %c_f32_0\n"
7702                 "%zero_0 = OpVectorExtractDynamic %f32 %vzero %c_i32_0\n"
7703                 "%zero_1 = OpVectorExtractDynamic %f32 %vzero %c_i32_1\n"
7704                 "%zero_2 = OpVectorExtractDynamic %f32 %vzero %c_i32_2\n"
7705                 "%zero_3 = OpVectorExtractDynamic %f32 %vzero %c_i32_3\n"
7706                 "%is_nan_0 = OpIsNan %bool %zero_0\n"
7707                 "%is_nan_1 = OpIsNan %bool %zero_1\n"
7708                 "%is_nan_2 = OpIsNan %bool %zero_2\n"
7709                 "%is_nan_3 = OpIsNan %bool %zero_3\n"
7710                 "%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
7711                 "%actually_zero_1 = OpSelect %f32 %is_nan_1 %c_f32_0 %zero_1\n"
7712                 "%actually_zero_2 = OpSelect %f32 %is_nan_2 %c_f32_0 %zero_2\n"
7713                 "%actually_zero_3 = OpSelect %f32 %is_nan_3 %c_f32_0 %zero_3\n"
7714                 "%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7715                 "%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
7716                 "%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
7717                 "%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
7718                 "%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
7719                 "%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
7720                 "%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
7721                 "%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
7722                 "%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
7723                 "%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
7724                 "%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
7725                 "%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
7726                 "OpReturnValue %ret\n"
7727                 "OpFunctionEnd\n";
7728
7729         createTestsForAllStages("vec4float32", defaultColors, defaultColors, fragments, opUndefTests.get());
7730
7731         fragments["pre_main"] =
7732                 "%m2x2f32 = OpTypeMatrix %v2f32 2\n";
7733         fragments["testfun"] =
7734                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7735                 "%param1 = OpFunctionParameter %v4f32\n"
7736                 "%label_testfun = OpLabel\n"
7737                 "%undef = OpUndef %m2x2f32\n"
7738                 "%mzero = OpMatrixTimesScalar %m2x2f32 %undef %c_f32_0\n"
7739                 "%zero_0 = OpCompositeExtract %f32 %mzero 0 0\n"
7740                 "%zero_1 = OpCompositeExtract %f32 %mzero 0 1\n"
7741                 "%zero_2 = OpCompositeExtract %f32 %mzero 1 0\n"
7742                 "%zero_3 = OpCompositeExtract %f32 %mzero 1 1\n"
7743                 "%is_nan_0 = OpIsNan %bool %zero_0\n"
7744                 "%is_nan_1 = OpIsNan %bool %zero_1\n"
7745                 "%is_nan_2 = OpIsNan %bool %zero_2\n"
7746                 "%is_nan_3 = OpIsNan %bool %zero_3\n"
7747                 "%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
7748                 "%actually_zero_1 = OpSelect %f32 %is_nan_1 %c_f32_0 %zero_1\n"
7749                 "%actually_zero_2 = OpSelect %f32 %is_nan_2 %c_f32_0 %zero_2\n"
7750                 "%actually_zero_3 = OpSelect %f32 %is_nan_3 %c_f32_0 %zero_3\n"
7751                 "%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7752                 "%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
7753                 "%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
7754                 "%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
7755                 "%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
7756                 "%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
7757                 "%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
7758                 "%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
7759                 "%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
7760                 "%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
7761                 "%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
7762                 "%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
7763                 "OpReturnValue %ret\n"
7764                 "OpFunctionEnd\n";
7765
7766         createTestsForAllStages("matrix", defaultColors, defaultColors, fragments, opUndefTests.get());
7767
7768         return opUndefTests.release();
7769 }
7770
7771 void createOpQuantizeSingleOptionTests(tcu::TestCaseGroup* testCtx)
7772 {
7773         const RGBA              inputColors[4]          =
7774         {
7775                 RGBA(0,         0,              0,              255),
7776                 RGBA(0,         0,              255,    255),
7777                 RGBA(0,         255,    0,              255),
7778                 RGBA(0,         255,    255,    255)
7779         };
7780
7781         const RGBA              expectedColors[4]       =
7782         {
7783                 RGBA(255,        0,              0,              255),
7784                 RGBA(255,        0,              0,              255),
7785                 RGBA(255,        0,              0,              255),
7786                 RGBA(255,        0,              0,              255)
7787         };
7788
7789         const struct SingleFP16Possibility
7790         {
7791                 const char* name;
7792                 const char* constant;  // Value to assign to %test_constant.
7793                 float           valueAsFloat;
7794                 const char* condition; // Must assign to %cond an expression that evaluates to true after %c = OpQuantizeToF16(%test_constant + 0).
7795         }                               tests[]                         =
7796         {
7797                 {
7798                         "negative",
7799                         "-0x1.3p1\n",
7800                         -constructNormalizedFloat(1, 0x300000),
7801                         "%cond = OpFOrdEqual %bool %c %test_constant\n"
7802                 }, // -19
7803                 {
7804                         "positive",
7805                         "0x1.0p7\n",
7806                         constructNormalizedFloat(7, 0x000000),
7807                         "%cond = OpFOrdEqual %bool %c %test_constant\n"
7808                 },  // +128
7809                 // SPIR-V requires that OpQuantizeToF16 flushes
7810                 // any numbers that would end up denormalized in F16 to zero.
7811                 {
7812                         "denorm",
7813                         "0x0.0006p-126\n",
7814                         std::ldexp(1.5f, -140),
7815                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7816                 },  // denorm
7817                 {
7818                         "negative_denorm",
7819                         "-0x0.0006p-126\n",
7820                         -std::ldexp(1.5f, -140),
7821                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7822                 }, // -denorm
7823                 {
7824                         "too_small",
7825                         "0x1.0p-16\n",
7826                         std::ldexp(1.0f, -16),
7827                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7828                 },     // too small positive
7829                 {
7830                         "negative_too_small",
7831                         "-0x1.0p-32\n",
7832                         -std::ldexp(1.0f, -32),
7833                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7834                 },      // too small negative
7835                 {
7836                         "negative_inf",
7837                         "-0x1.0p128\n",
7838                         -std::ldexp(1.0f, 128),
7839
7840                         "%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
7841                         "%inf = OpIsInf %bool %c\n"
7842                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7843                 },     // -inf to -inf
7844                 {
7845                         "inf",
7846                         "0x1.0p128\n",
7847                         std::ldexp(1.0f, 128),
7848
7849                         "%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
7850                         "%inf = OpIsInf %bool %c\n"
7851                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7852                 },     // +inf to +inf
7853                 {
7854                         "round_to_negative_inf",
7855                         "-0x1.0p32\n",
7856                         -std::ldexp(1.0f, 32),
7857
7858                         "%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
7859                         "%inf = OpIsInf %bool %c\n"
7860                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7861                 },     // round to -inf
7862                 {
7863                         "round_to_inf",
7864                         "0x1.0p16\n",
7865                         std::ldexp(1.0f, 16),
7866
7867                         "%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
7868                         "%inf = OpIsInf %bool %c\n"
7869                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7870                 },     // round to +inf
7871                 {
7872                         "nan",
7873                         "0x1.1p128\n",
7874                         std::numeric_limits<float>::quiet_NaN(),
7875
7876                         // Test for any NaN value, as NaNs are not preserved
7877                         "%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
7878                         "%cond = OpIsNan %bool %direct_quant\n"
7879                 }, // nan
7880                 {
7881                         "negative_nan",
7882                         "-0x1.0001p128\n",
7883                         std::numeric_limits<float>::quiet_NaN(),
7884
7885                         // Test for any NaN value, as NaNs are not preserved
7886                         "%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
7887                         "%cond = OpIsNan %bool %direct_quant\n"
7888                 } // -nan
7889         };
7890         const char*             constants                       =
7891                 "%test_constant = OpConstant %f32 ";  // The value will be test.constant.
7892
7893         StringTemplate  function                        (
7894                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7895                 "%param1        = OpFunctionParameter %v4f32\n"
7896                 "%label_testfun = OpLabel\n"
7897                 "%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7898                 "%b             = OpFAdd %f32 %test_constant %a\n"
7899                 "%c             = OpQuantizeToF16 %f32 %b\n"
7900                 "${condition}\n"
7901                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
7902                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
7903                 "                 OpReturnValue %retval\n"
7904                 "OpFunctionEnd\n"
7905         );
7906
7907         const char*             specDecorations         = "OpDecorate %test_constant SpecId 0\n";
7908         const char*             specConstants           =
7909                         "%test_constant = OpSpecConstant %f32 0.\n"
7910                         "%c             = OpSpecConstantOp %f32 QuantizeToF16 %test_constant\n";
7911
7912         StringTemplate  specConstantFunction(
7913                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7914                 "%param1        = OpFunctionParameter %v4f32\n"
7915                 "%label_testfun = OpLabel\n"
7916                 "${condition}\n"
7917                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
7918                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
7919                 "                 OpReturnValue %retval\n"
7920                 "OpFunctionEnd\n"
7921         );
7922
7923         for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
7924         {
7925                 map<string, string>                                                             codeSpecialization;
7926                 map<string, string>                                                             fragments;
7927                 codeSpecialization["condition"]                                 = tests[idx].condition;
7928                 fragments["testfun"]                                                    = function.specialize(codeSpecialization);
7929                 fragments["pre_main"]                                                   = string(constants) + tests[idx].constant + "\n";
7930                 createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
7931         }
7932
7933         for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
7934         {
7935                 map<string, string>                                                             codeSpecialization;
7936                 map<string, string>                                                             fragments;
7937                 SpecConstants                                                                   passConstants;
7938
7939                 codeSpecialization["condition"]                                 = tests[idx].condition;
7940                 fragments["testfun"]                                                    = specConstantFunction.specialize(codeSpecialization);
7941                 fragments["decoration"]                                                 = specDecorations;
7942                 fragments["pre_main"]                                                   = specConstants;
7943
7944                 passConstants.append<float>(tests[idx].valueAsFloat);
7945
7946                 createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
7947         }
7948 }
7949
7950 void createOpQuantizeTwoPossibilityTests(tcu::TestCaseGroup* testCtx)
7951 {
7952         RGBA inputColors[4] =  {
7953                 RGBA(0,         0,              0,              255),
7954                 RGBA(0,         0,              255,    255),
7955                 RGBA(0,         255,    0,              255),
7956                 RGBA(0,         255,    255,    255)
7957         };
7958
7959         RGBA expectedColors[4] =
7960         {
7961                 RGBA(255,        0,              0,              255),
7962                 RGBA(255,        0,              0,              255),
7963                 RGBA(255,        0,              0,              255),
7964                 RGBA(255,        0,              0,              255)
7965         };
7966
7967         struct DualFP16Possibility
7968         {
7969                 const char* name;
7970                 const char* input;
7971                 float           inputAsFloat;
7972                 const char* possibleOutput1;
7973                 const char* possibleOutput2;
7974         } tests[] = {
7975                 {
7976                         "positive_round_up_or_round_down",
7977                         "0x1.3003p8",
7978                         constructNormalizedFloat(8, 0x300300),
7979                         "0x1.304p8",
7980                         "0x1.3p8"
7981                 },
7982                 {
7983                         "negative_round_up_or_round_down",
7984                         "-0x1.6008p-7",
7985                         -constructNormalizedFloat(-7, 0x600800),
7986                         "-0x1.6p-7",
7987                         "-0x1.604p-7"
7988                 },
7989                 {
7990                         "carry_bit",
7991                         "0x1.01ep2",
7992                         constructNormalizedFloat(2, 0x01e000),
7993                         "0x1.01cp2",
7994                         "0x1.02p2"
7995                 },
7996                 {
7997                         "carry_to_exponent",
7998                         "0x1.ffep1",
7999                         constructNormalizedFloat(1, 0xffe000),
8000                         "0x1.ffcp1",
8001                         "0x1.0p2"
8002                 },
8003         };
8004         StringTemplate constants (
8005                 "%input_const = OpConstant %f32 ${input}\n"
8006                 "%possible_solution1 = OpConstant %f32 ${output1}\n"
8007                 "%possible_solution2 = OpConstant %f32 ${output2}\n"
8008                 );
8009
8010         StringTemplate specConstants (
8011                 "%input_const = OpSpecConstant %f32 0.\n"
8012                 "%possible_solution1 = OpConstant %f32 ${output1}\n"
8013                 "%possible_solution2 = OpConstant %f32 ${output2}\n"
8014         );
8015
8016         const char* specDecorations = "OpDecorate %input_const  SpecId 0\n";
8017
8018         const char* function  =
8019                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8020                 "%param1        = OpFunctionParameter %v4f32\n"
8021                 "%label_testfun = OpLabel\n"
8022                 "%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8023                 // For the purposes of this test we assume that 0.f will always get
8024                 // faithfully passed through the pipeline stages.
8025                 "%b             = OpFAdd %f32 %input_const %a\n"
8026                 "%c             = OpQuantizeToF16 %f32 %b\n"
8027                 "%eq_1          = OpFOrdEqual %bool %c %possible_solution1\n"
8028                 "%eq_2          = OpFOrdEqual %bool %c %possible_solution2\n"
8029                 "%cond          = OpLogicalOr %bool %eq_1 %eq_2\n"
8030                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
8031                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1"
8032                 "                 OpReturnValue %retval\n"
8033                 "OpFunctionEnd\n";
8034
8035         for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
8036                 map<string, string>                                                                     fragments;
8037                 map<string, string>                                                                     constantSpecialization;
8038
8039                 constantSpecialization["input"]                                         = tests[idx].input;
8040                 constantSpecialization["output1"]                                       = tests[idx].possibleOutput1;
8041                 constantSpecialization["output2"]                                       = tests[idx].possibleOutput2;
8042                 fragments["testfun"]                                                            = function;
8043                 fragments["pre_main"]                                                           = constants.specialize(constantSpecialization);
8044                 createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
8045         }
8046
8047         for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
8048                 map<string, string>                                                                     fragments;
8049                 map<string, string>                                                                     constantSpecialization;
8050                 SpecConstants                                                                           passConstants;
8051
8052                 constantSpecialization["output1"]                                       = tests[idx].possibleOutput1;
8053                 constantSpecialization["output2"]                                       = tests[idx].possibleOutput2;
8054                 fragments["testfun"]                                                            = function;
8055                 fragments["decoration"]                                                         = specDecorations;
8056                 fragments["pre_main"]                                                           = specConstants.specialize(constantSpecialization);
8057
8058                 passConstants.append<float>(tests[idx].inputAsFloat);
8059
8060                 createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
8061         }
8062 }
8063
8064 tcu::TestCaseGroup* createOpQuantizeTests(tcu::TestContext& testCtx)
8065 {
8066         de::MovePtr<tcu::TestCaseGroup> opQuantizeTests (new tcu::TestCaseGroup(testCtx, "opquantize", "Test OpQuantizeToF16"));
8067         createOpQuantizeSingleOptionTests(opQuantizeTests.get());
8068         createOpQuantizeTwoPossibilityTests(opQuantizeTests.get());
8069         return opQuantizeTests.release();
8070 }
8071
8072 struct ShaderPermutation
8073 {
8074         deUint8 vertexPermutation;
8075         deUint8 geometryPermutation;
8076         deUint8 tesscPermutation;
8077         deUint8 tessePermutation;
8078         deUint8 fragmentPermutation;
8079 };
8080
8081 ShaderPermutation getShaderPermutation(deUint8 inputValue)
8082 {
8083         ShaderPermutation       permutation =
8084         {
8085                 static_cast<deUint8>(inputValue & 0x10? 1u: 0u),
8086                 static_cast<deUint8>(inputValue & 0x08? 1u: 0u),
8087                 static_cast<deUint8>(inputValue & 0x04? 1u: 0u),
8088                 static_cast<deUint8>(inputValue & 0x02? 1u: 0u),
8089                 static_cast<deUint8>(inputValue & 0x01? 1u: 0u)
8090         };
8091         return permutation;
8092 }
8093
8094 tcu::TestCaseGroup* createModuleTests(tcu::TestContext& testCtx)
8095 {
8096         RGBA                                                            defaultColors[4];
8097         RGBA                                                            invertedColors[4];
8098         de::MovePtr<tcu::TestCaseGroup>         moduleTests                     (new tcu::TestCaseGroup(testCtx, "module", "Multiple entry points into shaders"));
8099
8100         getDefaultColors(defaultColors);
8101         getInvertedDefaultColors(invertedColors);
8102
8103         // Combined module tests
8104         {
8105                 // Shader stages: vertex and fragment
8106                 {
8107                         const ShaderElement combinedPipeline[]  =
8108                         {
8109                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8110                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8111                         };
8112
8113                         addFunctionCaseWithPrograms<InstanceContext>(
8114                                 moduleTests.get(), "same_module", "", createCombinedModule, runAndVerifyDefaultPipeline,
8115                                 createInstanceContext(combinedPipeline, map<string, string>()));
8116                 }
8117
8118                 // Shader stages: vertex, geometry and fragment
8119                 {
8120                         const ShaderElement combinedPipeline[]  =
8121                         {
8122                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8123                                 ShaderElement("module", "main", VK_SHADER_STAGE_GEOMETRY_BIT),
8124                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8125                         };
8126
8127                         addFunctionCaseWithPrograms<InstanceContext>(
8128                                 moduleTests.get(), "same_module_geom", "", createCombinedModule, runAndVerifyDefaultPipeline,
8129                                 createInstanceContext(combinedPipeline, map<string, string>()));
8130                 }
8131
8132                 // Shader stages: vertex, tessellation control, tessellation evaluation and fragment
8133                 {
8134                         const ShaderElement combinedPipeline[]  =
8135                         {
8136                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8137                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8138                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8139                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8140                         };
8141
8142                         addFunctionCaseWithPrograms<InstanceContext>(
8143                                 moduleTests.get(), "same_module_tessc_tesse", "", createCombinedModule, runAndVerifyDefaultPipeline,
8144                                 createInstanceContext(combinedPipeline, map<string, string>()));
8145                 }
8146
8147                 // Shader stages: vertex, tessellation control, tessellation evaluation, geometry and fragment
8148                 {
8149                         const ShaderElement combinedPipeline[]  =
8150                         {
8151                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8152                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8153                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8154                                 ShaderElement("module", "main", VK_SHADER_STAGE_GEOMETRY_BIT),
8155                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8156                         };
8157
8158                         addFunctionCaseWithPrograms<InstanceContext>(
8159                                 moduleTests.get(), "same_module_tessc_tesse_geom", "", createCombinedModule, runAndVerifyDefaultPipeline,
8160                                 createInstanceContext(combinedPipeline, map<string, string>()));
8161                 }
8162         }
8163
8164         const char* numbers[] =
8165         {
8166                 "1", "2"
8167         };
8168
8169         for (deInt8 idx = 0; idx < 32; ++idx)
8170         {
8171                 ShaderPermutation                       permutation             = getShaderPermutation(idx);
8172                 string                                          name                    = string("vert") + numbers[permutation.vertexPermutation] + "_geom" + numbers[permutation.geometryPermutation] + "_tessc" + numbers[permutation.tesscPermutation] + "_tesse" + numbers[permutation.tessePermutation] + "_frag" + numbers[permutation.fragmentPermutation];
8173                 const ShaderElement                     pipeline[]              =
8174                 {
8175                         ShaderElement("vert",   string("vert") +        numbers[permutation.vertexPermutation],         VK_SHADER_STAGE_VERTEX_BIT),
8176                         ShaderElement("geom",   string("geom") +        numbers[permutation.geometryPermutation],       VK_SHADER_STAGE_GEOMETRY_BIT),
8177                         ShaderElement("tessc",  string("tessc") +       numbers[permutation.tesscPermutation],          VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8178                         ShaderElement("tesse",  string("tesse") +       numbers[permutation.tessePermutation],          VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8179                         ShaderElement("frag",   string("frag") +        numbers[permutation.fragmentPermutation],       VK_SHADER_STAGE_FRAGMENT_BIT)
8180                 };
8181
8182                 // If there are an even number of swaps, then it should be no-op.
8183                 // If there are an odd number, the color should be flipped.
8184                 if ((permutation.vertexPermutation + permutation.geometryPermutation + permutation.tesscPermutation + permutation.tessePermutation + permutation.fragmentPermutation) % 2 == 0)
8185                 {
8186                         addFunctionCaseWithPrograms<InstanceContext>(
8187                                         moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline,
8188                                         createInstanceContext(pipeline, defaultColors, defaultColors, map<string, string>()));
8189                 }
8190                 else
8191                 {
8192                         addFunctionCaseWithPrograms<InstanceContext>(
8193                                         moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline,
8194                                         createInstanceContext(pipeline, defaultColors, invertedColors, map<string, string>()));
8195                 }
8196         }
8197         return moduleTests.release();
8198 }
8199
8200 tcu::TestCaseGroup* createLoopTests(tcu::TestContext& testCtx)
8201 {
8202         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "loop", "Looping control flow"));
8203         RGBA defaultColors[4];
8204         getDefaultColors(defaultColors);
8205         map<string, string> fragments;
8206         fragments["pre_main"] =
8207                 "%c_f32_5 = OpConstant %f32 5.\n";
8208
8209         // A loop with a single block. The Continue Target is the loop block
8210         // itself. In SPIR-V terms, the "loop construct" contains no blocks at all
8211         // -- the "continue construct" forms the entire loop.
8212         fragments["testfun"] =
8213                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8214                 "%param1 = OpFunctionParameter %v4f32\n"
8215
8216                 "%entry = OpLabel\n"
8217                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8218                 "OpBranch %loop\n"
8219
8220                 ";adds and subtracts 1.0 to %val in alternate iterations\n"
8221                 "%loop = OpLabel\n"
8222                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
8223                 "%delta = OpPhi %f32 %c_f32_1 %entry %minus_delta %loop\n"
8224                 "%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
8225                 "%val = OpFAdd %f32 %val1 %delta\n"
8226                 "%minus_delta = OpFSub %f32 %c_f32_0 %delta\n"
8227                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8228                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8229                 "OpLoopMerge %exit %loop None\n"
8230                 "OpBranchConditional %again %loop %exit\n"
8231
8232                 "%exit = OpLabel\n"
8233                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8234                 "OpReturnValue %result\n"
8235
8236                 "OpFunctionEnd\n";
8237
8238         createTestsForAllStages("single_block", defaultColors, defaultColors, fragments, testGroup.get());
8239
8240         // Body comprised of multiple basic blocks.
8241         const StringTemplate multiBlock(
8242                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8243                 "%param1 = OpFunctionParameter %v4f32\n"
8244
8245                 "%entry = OpLabel\n"
8246                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8247                 "OpBranch %loop\n"
8248
8249                 ";adds and subtracts 1.0 to %val in alternate iterations\n"
8250                 "%loop = OpLabel\n"
8251                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %gather\n"
8252                 "%delta = OpPhi %f32 %c_f32_1 %entry %delta_next %gather\n"
8253                 "%val1 = OpPhi %f32 %val0 %entry %val %gather\n"
8254                 // There are several possibilities for the Continue Target below.  Each
8255                 // will be specialized into a separate test case.
8256                 "OpLoopMerge %exit ${continue_target} None\n"
8257                 "OpBranch %if\n"
8258
8259                 "%if = OpLabel\n"
8260                 ";delta_next = (delta > 0) ? -1 : 1;\n"
8261                 "%gt0 = OpFOrdGreaterThan %bool %delta %c_f32_0\n"
8262                 "OpSelectionMerge %gather DontFlatten\n"
8263                 "OpBranchConditional %gt0 %even %odd ;tells us if %count is even or odd\n"
8264
8265                 "%odd = OpLabel\n"
8266                 "OpBranch %gather\n"
8267
8268                 "%even = OpLabel\n"
8269                 "OpBranch %gather\n"
8270
8271                 "%gather = OpLabel\n"
8272                 "%delta_next = OpPhi %f32 %c_f32_n1 %even %c_f32_1 %odd\n"
8273                 "%val = OpFAdd %f32 %val1 %delta\n"
8274                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8275                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8276                 "OpBranchConditional %again %loop %exit\n"
8277
8278                 "%exit = OpLabel\n"
8279                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8280                 "OpReturnValue %result\n"
8281
8282                 "OpFunctionEnd\n");
8283
8284         map<string, string> continue_target;
8285
8286         // The Continue Target is the loop block itself.
8287         continue_target["continue_target"] = "%loop";
8288         fragments["testfun"] = multiBlock.specialize(continue_target);
8289         createTestsForAllStages("multi_block_continue_construct", defaultColors, defaultColors, fragments, testGroup.get());
8290
8291         // The Continue Target is at the end of the loop.
8292         continue_target["continue_target"] = "%gather";
8293         fragments["testfun"] = multiBlock.specialize(continue_target);
8294         createTestsForAllStages("multi_block_loop_construct", defaultColors, defaultColors, fragments, testGroup.get());
8295
8296         // A loop with continue statement.
8297         fragments["testfun"] =
8298                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8299                 "%param1 = OpFunctionParameter %v4f32\n"
8300
8301                 "%entry = OpLabel\n"
8302                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8303                 "OpBranch %loop\n"
8304
8305                 ";adds 4, 3, and 1 to %val0 (skips 2)\n"
8306                 "%loop = OpLabel\n"
8307                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8308                 "%val1 = OpPhi %f32 %val0 %entry %val %continue\n"
8309                 "OpLoopMerge %exit %continue None\n"
8310                 "OpBranch %if\n"
8311
8312                 "%if = OpLabel\n"
8313                 ";skip if %count==2\n"
8314                 "%eq2 = OpIEqual %bool %count %c_i32_2\n"
8315                 "OpSelectionMerge %continue DontFlatten\n"
8316                 "OpBranchConditional %eq2 %continue %body\n"
8317
8318                 "%body = OpLabel\n"
8319                 "%fcount = OpConvertSToF %f32 %count\n"
8320                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8321                 "OpBranch %continue\n"
8322
8323                 "%continue = OpLabel\n"
8324                 "%val = OpPhi %f32 %val2 %body %val1 %if\n"
8325                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8326                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8327                 "OpBranchConditional %again %loop %exit\n"
8328
8329                 "%exit = OpLabel\n"
8330                 "%same = OpFSub %f32 %val %c_f32_8\n"
8331                 "%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8332                 "OpReturnValue %result\n"
8333                 "OpFunctionEnd\n";
8334         createTestsForAllStages("continue", defaultColors, defaultColors, fragments, testGroup.get());
8335
8336         // A loop with break.
8337         fragments["testfun"] =
8338                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8339                 "%param1 = OpFunctionParameter %v4f32\n"
8340
8341                 "%entry = OpLabel\n"
8342                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8343                 "%dot = OpDot %f32 %param1 %param1\n"
8344                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8345                 "%zero = OpConvertFToU %u32 %div\n"
8346                 "%two = OpIAdd %i32 %zero %c_i32_2\n"
8347                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8348                 "OpBranch %loop\n"
8349
8350                 ";adds 4 and 3 to %val0 (exits early)\n"
8351                 "%loop = OpLabel\n"
8352                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8353                 "%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
8354                 "OpLoopMerge %exit %continue None\n"
8355                 "OpBranch %if\n"
8356
8357                 "%if = OpLabel\n"
8358                 ";end loop if %count==%two\n"
8359                 "%above2 = OpSGreaterThan %bool %count %two\n"
8360                 "OpSelectionMerge %continue DontFlatten\n"
8361                 "OpBranchConditional %above2 %body %exit\n"
8362
8363                 "%body = OpLabel\n"
8364                 "%fcount = OpConvertSToF %f32 %count\n"
8365                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8366                 "OpBranch %continue\n"
8367
8368                 "%continue = OpLabel\n"
8369                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8370                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8371                 "OpBranchConditional %again %loop %exit\n"
8372
8373                 "%exit = OpLabel\n"
8374                 "%val_post = OpPhi %f32 %val2 %continue %val1 %if\n"
8375                 "%same = OpFSub %f32 %val_post %c_f32_7\n"
8376                 "%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8377                 "OpReturnValue %result\n"
8378                 "OpFunctionEnd\n";
8379         createTestsForAllStages("break", defaultColors, defaultColors, fragments, testGroup.get());
8380
8381         // A loop with return.
8382         fragments["testfun"] =
8383                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8384                 "%param1 = OpFunctionParameter %v4f32\n"
8385
8386                 "%entry = OpLabel\n"
8387                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8388                 "%dot = OpDot %f32 %param1 %param1\n"
8389                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8390                 "%zero = OpConvertFToU %u32 %div\n"
8391                 "%two = OpIAdd %i32 %zero %c_i32_2\n"
8392                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8393                 "OpBranch %loop\n"
8394
8395                 ";returns early without modifying %param1\n"
8396                 "%loop = OpLabel\n"
8397                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8398                 "%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
8399                 "OpLoopMerge %exit %continue None\n"
8400                 "OpBranch %if\n"
8401
8402                 "%if = OpLabel\n"
8403                 ";return if %count==%two\n"
8404                 "%above2 = OpSGreaterThan %bool %count %two\n"
8405                 "OpSelectionMerge %continue DontFlatten\n"
8406                 "OpBranchConditional %above2 %body %early_exit\n"
8407
8408                 "%early_exit = OpLabel\n"
8409                 "OpReturnValue %param1\n"
8410
8411                 "%body = OpLabel\n"
8412                 "%fcount = OpConvertSToF %f32 %count\n"
8413                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8414                 "OpBranch %continue\n"
8415
8416                 "%continue = OpLabel\n"
8417                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8418                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8419                 "OpBranchConditional %again %loop %exit\n"
8420
8421                 "%exit = OpLabel\n"
8422                 ";should never get here, so return an incorrect result\n"
8423                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val2 %c_i32_0\n"
8424                 "OpReturnValue %result\n"
8425                 "OpFunctionEnd\n";
8426         createTestsForAllStages("return", defaultColors, defaultColors, fragments, testGroup.get());
8427
8428         // Continue inside a switch block to break to enclosing loop's merge block.
8429         // Matches roughly the following GLSL code:
8430         // for (; keep_going; keep_going = false)
8431         // {
8432         //     switch (int(param1.x))
8433         //     {
8434         //         case 0: continue;
8435         //         case 1: continue;
8436         //         default: continue;
8437         //     }
8438         //     dead code: modify return value to invalid result.
8439         // }
8440         fragments["pre_main"] =
8441                 "%fp_bool = OpTypePointer Function %bool\n"
8442                 "%true = OpConstantTrue %bool\n"
8443                 "%false = OpConstantFalse %bool\n";
8444
8445         fragments["testfun"] =
8446                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8447                 "%param1 = OpFunctionParameter %v4f32\n"
8448
8449                 "%entry = OpLabel\n"
8450                 "%keep_going = OpVariable %fp_bool Function\n"
8451                 "%val_ptr = OpVariable %fp_f32 Function\n"
8452                 "%param1_x = OpCompositeExtract %f32 %param1 0\n"
8453                 "OpStore %keep_going %true\n"
8454                 "OpBranch %forloop_begin\n"
8455
8456                 "%forloop_begin = OpLabel\n"
8457                 "OpLoopMerge %forloop_merge %forloop_continue None\n"
8458                 "OpBranch %forloop\n"
8459
8460                 "%forloop = OpLabel\n"
8461                 "%for_condition = OpLoad %bool %keep_going\n"
8462                 "OpBranchConditional %for_condition %forloop_body %forloop_merge\n"
8463
8464                 "%forloop_body = OpLabel\n"
8465                 "OpStore %val_ptr %param1_x\n"
8466                 "%param1_x_int = OpConvertFToS %i32 %param1_x\n"
8467
8468                 "OpSelectionMerge %switch_merge None\n"
8469                 "OpSwitch %param1_x_int %default 0 %case_0 1 %case_1\n"
8470                 "%case_0 = OpLabel\n"
8471                 "OpBranch %forloop_continue\n"
8472                 "%case_1 = OpLabel\n"
8473                 "OpBranch %forloop_continue\n"
8474                 "%default = OpLabel\n"
8475                 "OpBranch %forloop_continue\n"
8476                 "%switch_merge = OpLabel\n"
8477                 ";should never get here, so change the return value to invalid result\n"
8478                 "OpStore %val_ptr %c_f32_1\n"
8479                 "OpBranch %forloop_continue\n"
8480
8481                 "%forloop_continue = OpLabel\n"
8482                 "OpStore %keep_going %false\n"
8483                 "OpBranch %forloop_begin\n"
8484                 "%forloop_merge = OpLabel\n"
8485
8486                 "%val = OpLoad %f32 %val_ptr\n"
8487                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8488                 "OpReturnValue %result\n"
8489                 "OpFunctionEnd\n";
8490         createTestsForAllStages("switch_continue", defaultColors, defaultColors, fragments, testGroup.get());
8491
8492         return testGroup.release();
8493 }
8494
8495 // A collection of tests putting OpControlBarrier in places GLSL forbids but SPIR-V allows.
8496 tcu::TestCaseGroup* createBarrierTests(tcu::TestContext& testCtx)
8497 {
8498         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "barrier", "OpControlBarrier"));
8499         map<string, string> fragments;
8500
8501         // A barrier inside a function body.
8502         fragments["pre_main"] =
8503                 "%Workgroup = OpConstant %i32 2\n"
8504                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n";
8505         fragments["testfun"] =
8506                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8507                 "%param1 = OpFunctionParameter %v4f32\n"
8508                 "%label_testfun = OpLabel\n"
8509                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8510                 "OpReturnValue %param1\n"
8511                 "OpFunctionEnd\n";
8512         addTessCtrlTest(testGroup.get(), "in_function", fragments);
8513
8514         // Common setup code for the following tests.
8515         fragments["pre_main"] =
8516                 "%Workgroup = OpConstant %i32 2\n"
8517                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n"
8518                 "%c_f32_5 = OpConstant %f32 5.\n";
8519         const string setupPercentZero =  // Begins %test_code function with code that sets %zero to 0u but cannot be optimized away.
8520                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8521                 "%param1 = OpFunctionParameter %v4f32\n"
8522                 "%entry = OpLabel\n"
8523                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8524                 "%dot = OpDot %f32 %param1 %param1\n"
8525                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8526                 "%zero = OpConvertFToU %u32 %div\n";
8527
8528         // Barriers inside OpSwitch branches.
8529         fragments["testfun"] =
8530                 setupPercentZero +
8531                 "OpSelectionMerge %switch_exit None\n"
8532                 "OpSwitch %zero %switch_default 0 %case0 1 %case1 ;should always go to %case0\n"
8533
8534                 "%case1 = OpLabel\n"
8535                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8536                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8537                 "%wrong_branch_alert1 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8538                 "OpBranch %switch_exit\n"
8539
8540                 "%switch_default = OpLabel\n"
8541                 "%wrong_branch_alert2 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8542                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8543                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8544                 "OpBranch %switch_exit\n"
8545
8546                 "%case0 = OpLabel\n"
8547                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8548                 "OpBranch %switch_exit\n"
8549
8550                 "%switch_exit = OpLabel\n"
8551                 "%ret = OpPhi %v4f32 %param1 %case0 %wrong_branch_alert1 %case1 %wrong_branch_alert2 %switch_default\n"
8552                 "OpReturnValue %ret\n"
8553                 "OpFunctionEnd\n";
8554         addTessCtrlTest(testGroup.get(), "in_switch", fragments);
8555
8556         // Barriers inside if-then-else.
8557         fragments["testfun"] =
8558                 setupPercentZero +
8559                 "%eq0 = OpIEqual %bool %zero %c_u32_0\n"
8560                 "OpSelectionMerge %exit DontFlatten\n"
8561                 "OpBranchConditional %eq0 %then %else\n"
8562
8563                 "%else = OpLabel\n"
8564                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8565                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8566                 "%wrong_branch_alert = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8567                 "OpBranch %exit\n"
8568
8569                 "%then = OpLabel\n"
8570                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8571                 "OpBranch %exit\n"
8572                 "%exit = OpLabel\n"
8573                 "%ret = OpPhi %v4f32 %param1 %then %wrong_branch_alert %else\n"
8574                 "OpReturnValue %ret\n"
8575                 "OpFunctionEnd\n";
8576         addTessCtrlTest(testGroup.get(), "in_if", fragments);
8577
8578         // A barrier after control-flow reconvergence, tempting the compiler to attempt something like this:
8579         // http://lists.llvm.org/pipermail/llvm-dev/2009-October/026317.html.
8580         fragments["testfun"] =
8581                 setupPercentZero +
8582                 "%thread_id = OpLoad %i32 %BP_gl_InvocationID\n"
8583                 "%thread0 = OpIEqual %bool %thread_id %c_i32_0\n"
8584                 "OpSelectionMerge %exit DontFlatten\n"
8585                 "OpBranchConditional %thread0 %then %else\n"
8586
8587                 "%else = OpLabel\n"
8588                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8589                 "OpBranch %exit\n"
8590
8591                 "%then = OpLabel\n"
8592                 "%val1 = OpVectorExtractDynamic %f32 %param1 %zero\n"
8593                 "OpBranch %exit\n"
8594
8595                 "%exit = OpLabel\n"
8596                 "%val = OpPhi %f32 %val0 %else %val1 %then\n"
8597                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8598                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %val %zero\n"
8599                 "OpReturnValue %ret\n"
8600                 "OpFunctionEnd\n";
8601         addTessCtrlTest(testGroup.get(), "after_divergent_if", fragments);
8602
8603         // A barrier inside a loop.
8604         fragments["pre_main"] =
8605                 "%Workgroup = OpConstant %i32 2\n"
8606                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n"
8607                 "%c_f32_10 = OpConstant %f32 10.\n";
8608         fragments["testfun"] =
8609                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8610                 "%param1 = OpFunctionParameter %v4f32\n"
8611                 "%entry = OpLabel\n"
8612                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8613                 "OpBranch %loop\n"
8614
8615                 ";adds 4, 3, 2, and 1 to %val0\n"
8616                 "%loop = OpLabel\n"
8617                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
8618                 "%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
8619                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8620                 "%fcount = OpConvertSToF %f32 %count\n"
8621                 "%val = OpFAdd %f32 %val1 %fcount\n"
8622                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8623                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8624                 "OpLoopMerge %exit %loop None\n"
8625                 "OpBranchConditional %again %loop %exit\n"
8626
8627                 "%exit = OpLabel\n"
8628                 "%same = OpFSub %f32 %val %c_f32_10\n"
8629                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8630                 "OpReturnValue %ret\n"
8631                 "OpFunctionEnd\n";
8632         addTessCtrlTest(testGroup.get(), "in_loop", fragments);
8633
8634         return testGroup.release();
8635 }
8636
8637 // Test for the OpFRem instruction.
8638 tcu::TestCaseGroup* createFRemTests(tcu::TestContext& testCtx)
8639 {
8640         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "frem", "OpFRem"));
8641         map<string, string>                                     fragments;
8642         RGBA                                                            inputColors[4];
8643         RGBA                                                            outputColors[4];
8644
8645         fragments["pre_main"]                            =
8646                 "%c_f32_3 = OpConstant %f32 3.0\n"
8647                 "%c_f32_n3 = OpConstant %f32 -3.0\n"
8648                 "%c_f32_4 = OpConstant %f32 4.0\n"
8649                 "%c_f32_p75 = OpConstant %f32 0.75\n"
8650                 "%c_v4f32_p75_p75_p75_p75 = OpConstantComposite %v4f32 %c_f32_p75 %c_f32_p75 %c_f32_p75 %c_f32_p75 \n"
8651                 "%c_v4f32_4_4_4_4 = OpConstantComposite %v4f32 %c_f32_4 %c_f32_4 %c_f32_4 %c_f32_4\n"
8652                 "%c_v4f32_3_n3_3_n3 = OpConstantComposite %v4f32 %c_f32_3 %c_f32_n3 %c_f32_3 %c_f32_n3\n";
8653
8654         // The test does the following.
8655         // vec4 result = (param1 * 8.0) - 4.0;
8656         // return (frem(result.x,3) + 0.75, frem(result.y, -3) + 0.75, 0, 1)
8657         fragments["testfun"]                             =
8658                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8659                 "%param1 = OpFunctionParameter %v4f32\n"
8660                 "%label_testfun = OpLabel\n"
8661                 "%v_times_8 = OpVectorTimesScalar %v4f32 %param1 %c_f32_8\n"
8662                 "%minus_4 = OpFSub %v4f32 %v_times_8 %c_v4f32_4_4_4_4\n"
8663                 "%frem = OpFRem %v4f32 %minus_4 %c_v4f32_3_n3_3_n3\n"
8664                 "%added = OpFAdd %v4f32 %frem %c_v4f32_p75_p75_p75_p75\n"
8665                 "%xyz_1 = OpVectorInsertDynamic %v4f32 %added %c_f32_1 %c_i32_3\n"
8666                 "%xy_0_1 = OpVectorInsertDynamic %v4f32 %xyz_1 %c_f32_0 %c_i32_2\n"
8667                 "OpReturnValue %xy_0_1\n"
8668                 "OpFunctionEnd\n";
8669
8670
8671         inputColors[0]          = RGBA(16,      16,             0, 255);
8672         inputColors[1]          = RGBA(232, 232,        0, 255);
8673         inputColors[2]          = RGBA(232, 16,         0, 255);
8674         inputColors[3]          = RGBA(16,      232,    0, 255);
8675
8676         outputColors[0]         = RGBA(64,      64,             0, 255);
8677         outputColors[1]         = RGBA(255, 255,        0, 255);
8678         outputColors[2]         = RGBA(255, 64,         0, 255);
8679         outputColors[3]         = RGBA(64,      255,    0, 255);
8680
8681         createTestsForAllStages("frem", inputColors, outputColors, fragments, testGroup.get());
8682         return testGroup.release();
8683 }
8684
8685 // Test for the OpSRem instruction.
8686 tcu::TestCaseGroup* createOpSRemGraphicsTests(tcu::TestContext& testCtx, qpTestResult negFailResult)
8687 {
8688         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "srem", "OpSRem"));
8689         map<string, string>                                     fragments;
8690
8691         fragments["pre_main"]                            =
8692                 "%c_f32_255 = OpConstant %f32 255.0\n"
8693                 "%c_i32_128 = OpConstant %i32 128\n"
8694                 "%c_i32_255 = OpConstant %i32 255\n"
8695                 "%c_v4f32_255 = OpConstantComposite %v4f32 %c_f32_255 %c_f32_255 %c_f32_255 %c_f32_255 \n"
8696                 "%c_v4f32_0_5 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 \n"
8697                 "%c_v4i32_128 = OpConstantComposite %v4i32 %c_i32_128 %c_i32_128 %c_i32_128 %c_i32_128 \n";
8698
8699         // The test does the following.
8700         // ivec4 ints = int(param1 * 255.0 + 0.5) - 128;
8701         // ivec4 result = ivec4(srem(ints.x, ints.y), srem(ints.y, ints.z), srem(ints.z, ints.x), 255);
8702         // return float(result + 128) / 255.0;
8703         fragments["testfun"]                             =
8704                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8705                 "%param1 = OpFunctionParameter %v4f32\n"
8706                 "%label_testfun = OpLabel\n"
8707                 "%div255 = OpFMul %v4f32 %param1 %c_v4f32_255\n"
8708                 "%add0_5 = OpFAdd %v4f32 %div255 %c_v4f32_0_5\n"
8709                 "%uints_in = OpConvertFToS %v4i32 %add0_5\n"
8710                 "%ints_in = OpISub %v4i32 %uints_in %c_v4i32_128\n"
8711                 "%x_in = OpCompositeExtract %i32 %ints_in 0\n"
8712                 "%y_in = OpCompositeExtract %i32 %ints_in 1\n"
8713                 "%z_in = OpCompositeExtract %i32 %ints_in 2\n"
8714                 "%x_out = OpSRem %i32 %x_in %y_in\n"
8715                 "%y_out = OpSRem %i32 %y_in %z_in\n"
8716                 "%z_out = OpSRem %i32 %z_in %x_in\n"
8717                 "%ints_out = OpCompositeConstruct %v4i32 %x_out %y_out %z_out %c_i32_255\n"
8718                 "%ints_offset = OpIAdd %v4i32 %ints_out %c_v4i32_128\n"
8719                 "%f_ints_offset = OpConvertSToF %v4f32 %ints_offset\n"
8720                 "%float_out = OpFDiv %v4f32 %f_ints_offset %c_v4f32_255\n"
8721                 "OpReturnValue %float_out\n"
8722                 "OpFunctionEnd\n";
8723
8724         const struct CaseParams
8725         {
8726                 const char*             name;
8727                 const char*             failMessageTemplate;    // customized status message
8728                 qpTestResult    failResult;                             // override status on failure
8729                 int                             operands[4][3];                 // four (x, y, z) vectors of operands
8730                 int                             results[4][3];                  // four (x, y, z) vectors of results
8731         } cases[] =
8732         {
8733                 {
8734                         "positive",
8735                         "${reason}",
8736                         QP_TEST_RESULT_FAIL,
8737                         { { 5, 12, 17 }, { 5, 5, 7 }, { 75, 8, 81 }, { 25, 60, 100 } },                 // operands
8738                         { { 5, 12,  2 }, { 0, 5, 2 }, {  3, 8,  6 }, { 25, 60,   0 } },                 // results
8739                 },
8740                 {
8741                         "all",
8742                         "Inconsistent results, but within specification: ${reason}",
8743                         negFailResult,                                                                                                                  // negative operands, not required by the spec
8744                         { { 5, 12, -17 }, { -5, -5, 7 }, { 75, 8, -81 }, { 25, -60, 100 } },    // operands
8745                         { { 5, 12,  -2 }, {  0, -5, 2 }, {  3, 8,  -6 }, { 25, -60,   0 } },    // results
8746                 },
8747         };
8748         // If either operand is negative the result is undefined. Some implementations may still return correct values.
8749
8750         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
8751         {
8752                 const CaseParams&       params                  = cases[caseNdx];
8753                 RGBA                            inputColors[4];
8754                 RGBA                            outputColors[4];
8755
8756                 for (int i = 0; i < 4; ++i)
8757                 {
8758                         inputColors [i] = RGBA(params.operands[i][0] + 128, params.operands[i][1] + 128, params.operands[i][2] + 128, 255);
8759                         outputColors[i] = RGBA(params.results [i][0] + 128, params.results [i][1] + 128, params.results [i][2] + 128, 255);
8760                 }
8761
8762                 createTestsForAllStages(params.name, inputColors, outputColors, fragments, testGroup.get(), params.failResult, params.failMessageTemplate);
8763         }
8764
8765         return testGroup.release();
8766 }
8767
8768 // Test for the OpSMod instruction.
8769 tcu::TestCaseGroup* createOpSModGraphicsTests(tcu::TestContext& testCtx, qpTestResult negFailResult)
8770 {
8771         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "smod", "OpSMod"));
8772         map<string, string>                                     fragments;
8773
8774         fragments["pre_main"]                            =
8775                 "%c_f32_255 = OpConstant %f32 255.0\n"
8776                 "%c_i32_128 = OpConstant %i32 128\n"
8777                 "%c_i32_255 = OpConstant %i32 255\n"
8778                 "%c_v4f32_255 = OpConstantComposite %v4f32 %c_f32_255 %c_f32_255 %c_f32_255 %c_f32_255 \n"
8779                 "%c_v4f32_0_5 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 \n"
8780                 "%c_v4i32_128 = OpConstantComposite %v4i32 %c_i32_128 %c_i32_128 %c_i32_128 %c_i32_128 \n";
8781
8782         // The test does the following.
8783         // ivec4 ints = int(param1 * 255.0 + 0.5) - 128;
8784         // ivec4 result = ivec4(smod(ints.x, ints.y), smod(ints.y, ints.z), smod(ints.z, ints.x), 255);
8785         // return float(result + 128) / 255.0;
8786         fragments["testfun"]                             =
8787                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8788                 "%param1 = OpFunctionParameter %v4f32\n"
8789                 "%label_testfun = OpLabel\n"
8790                 "%div255 = OpFMul %v4f32 %param1 %c_v4f32_255\n"
8791                 "%add0_5 = OpFAdd %v4f32 %div255 %c_v4f32_0_5\n"
8792                 "%uints_in = OpConvertFToS %v4i32 %add0_5\n"
8793                 "%ints_in = OpISub %v4i32 %uints_in %c_v4i32_128\n"
8794                 "%x_in = OpCompositeExtract %i32 %ints_in 0\n"
8795                 "%y_in = OpCompositeExtract %i32 %ints_in 1\n"
8796                 "%z_in = OpCompositeExtract %i32 %ints_in 2\n"
8797                 "%x_out = OpSMod %i32 %x_in %y_in\n"
8798                 "%y_out = OpSMod %i32 %y_in %z_in\n"
8799                 "%z_out = OpSMod %i32 %z_in %x_in\n"
8800                 "%ints_out = OpCompositeConstruct %v4i32 %x_out %y_out %z_out %c_i32_255\n"
8801                 "%ints_offset = OpIAdd %v4i32 %ints_out %c_v4i32_128\n"
8802                 "%f_ints_offset = OpConvertSToF %v4f32 %ints_offset\n"
8803                 "%float_out = OpFDiv %v4f32 %f_ints_offset %c_v4f32_255\n"
8804                 "OpReturnValue %float_out\n"
8805                 "OpFunctionEnd\n";
8806
8807         const struct CaseParams
8808         {
8809                 const char*             name;
8810                 const char*             failMessageTemplate;    // customized status message
8811                 qpTestResult    failResult;                             // override status on failure
8812                 int                             operands[4][3];                 // four (x, y, z) vectors of operands
8813                 int                             results[4][3];                  // four (x, y, z) vectors of results
8814         } cases[] =
8815         {
8816                 {
8817                         "positive",
8818                         "${reason}",
8819                         QP_TEST_RESULT_FAIL,
8820                         { { 5, 12, 17 }, { 5, 5, 7 }, { 75, 8, 81 }, { 25, 60, 100 } },                         // operands
8821                         { { 5, 12,  2 }, { 0, 5, 2 }, {  3, 8,  6 }, { 25, 60,   0 } },                         // results
8822                 },
8823                 {
8824                         "all",
8825                         "Inconsistent results, but within specification: ${reason}",
8826                         negFailResult,                                                                                                                          // negative operands, not required by the spec
8827                         { { 5, 12, -17 }, { -5, -5,  7 }, { 75,   8, -81 }, {  25, -60, 100 } },        // operands
8828                         { { 5, -5,   3 }, {  0,  2, -3 }, {  3, -73,  69 }, { -35,  40,   0 } },        // results
8829                 },
8830         };
8831         // If either operand is negative the result is undefined. Some implementations may still return correct values.
8832
8833         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
8834         {
8835                 const CaseParams&       params                  = cases[caseNdx];
8836                 RGBA                            inputColors[4];
8837                 RGBA                            outputColors[4];
8838
8839                 for (int i = 0; i < 4; ++i)
8840                 {
8841                         inputColors [i] = RGBA(params.operands[i][0] + 128, params.operands[i][1] + 128, params.operands[i][2] + 128, 255);
8842                         outputColors[i] = RGBA(params.results [i][0] + 128, params.results [i][1] + 128, params.results [i][2] + 128, 255);
8843                 }
8844
8845                 createTestsForAllStages(params.name, inputColors, outputColors, fragments, testGroup.get(), params.failResult, params.failMessageTemplate);
8846         }
8847         return testGroup.release();
8848 }
8849
8850 enum ConversionDataType
8851 {
8852         DATA_TYPE_SIGNED_8,
8853         DATA_TYPE_SIGNED_16,
8854         DATA_TYPE_SIGNED_32,
8855         DATA_TYPE_SIGNED_64,
8856         DATA_TYPE_UNSIGNED_8,
8857         DATA_TYPE_UNSIGNED_16,
8858         DATA_TYPE_UNSIGNED_32,
8859         DATA_TYPE_UNSIGNED_64,
8860         DATA_TYPE_FLOAT_16,
8861         DATA_TYPE_FLOAT_32,
8862         DATA_TYPE_FLOAT_64,
8863         DATA_TYPE_VEC2_SIGNED_16,
8864         DATA_TYPE_VEC2_SIGNED_32
8865 };
8866
8867 const string getBitWidthStr (ConversionDataType type)
8868 {
8869         switch (type)
8870         {
8871                 case DATA_TYPE_SIGNED_8:
8872                 case DATA_TYPE_UNSIGNED_8:
8873                         return "8";
8874
8875                 case DATA_TYPE_SIGNED_16:
8876                 case DATA_TYPE_UNSIGNED_16:
8877                 case DATA_TYPE_FLOAT_16:
8878                         return "16";
8879
8880                 case DATA_TYPE_SIGNED_32:
8881                 case DATA_TYPE_UNSIGNED_32:
8882                 case DATA_TYPE_FLOAT_32:
8883                 case DATA_TYPE_VEC2_SIGNED_16:
8884                         return "32";
8885
8886                 case DATA_TYPE_SIGNED_64:
8887                 case DATA_TYPE_UNSIGNED_64:
8888                 case DATA_TYPE_FLOAT_64:
8889                 case DATA_TYPE_VEC2_SIGNED_32:
8890                         return "64";
8891
8892                 default:
8893                         DE_ASSERT(false);
8894         }
8895         return "";
8896 }
8897
8898 const string getByteWidthStr (ConversionDataType type)
8899 {
8900         switch (type)
8901         {
8902                 case DATA_TYPE_SIGNED_8:
8903                 case DATA_TYPE_UNSIGNED_8:
8904                         return "1";
8905
8906                 case DATA_TYPE_SIGNED_16:
8907                 case DATA_TYPE_UNSIGNED_16:
8908                 case DATA_TYPE_FLOAT_16:
8909                         return "2";
8910
8911                 case DATA_TYPE_SIGNED_32:
8912                 case DATA_TYPE_UNSIGNED_32:
8913                 case DATA_TYPE_FLOAT_32:
8914                 case DATA_TYPE_VEC2_SIGNED_16:
8915                         return "4";
8916
8917                 case DATA_TYPE_SIGNED_64:
8918                 case DATA_TYPE_UNSIGNED_64:
8919                 case DATA_TYPE_FLOAT_64:
8920                 case DATA_TYPE_VEC2_SIGNED_32:
8921                         return "8";
8922
8923                 default:
8924                         DE_ASSERT(false);
8925         }
8926         return "";
8927 }
8928
8929 bool isSigned (ConversionDataType type)
8930 {
8931         switch (type)
8932         {
8933                 case DATA_TYPE_SIGNED_8:
8934                 case DATA_TYPE_SIGNED_16:
8935                 case DATA_TYPE_SIGNED_32:
8936                 case DATA_TYPE_SIGNED_64:
8937                 case DATA_TYPE_FLOAT_16:
8938                 case DATA_TYPE_FLOAT_32:
8939                 case DATA_TYPE_FLOAT_64:
8940                 case DATA_TYPE_VEC2_SIGNED_16:
8941                 case DATA_TYPE_VEC2_SIGNED_32:
8942                         return true;
8943
8944                 case DATA_TYPE_UNSIGNED_8:
8945                 case DATA_TYPE_UNSIGNED_16:
8946                 case DATA_TYPE_UNSIGNED_32:
8947                 case DATA_TYPE_UNSIGNED_64:
8948                         return false;
8949
8950                 default:
8951                         DE_ASSERT(false);
8952         }
8953         return false;
8954 }
8955
8956 bool isInt (ConversionDataType type)
8957 {
8958         switch (type)
8959         {
8960                 case DATA_TYPE_SIGNED_8:
8961                 case DATA_TYPE_SIGNED_16:
8962                 case DATA_TYPE_SIGNED_32:
8963                 case DATA_TYPE_SIGNED_64:
8964                 case DATA_TYPE_UNSIGNED_8:
8965                 case DATA_TYPE_UNSIGNED_16:
8966                 case DATA_TYPE_UNSIGNED_32:
8967                 case DATA_TYPE_UNSIGNED_64:
8968                         return true;
8969
8970                 case DATA_TYPE_FLOAT_16:
8971                 case DATA_TYPE_FLOAT_32:
8972                 case DATA_TYPE_FLOAT_64:
8973                 case DATA_TYPE_VEC2_SIGNED_16:
8974                 case DATA_TYPE_VEC2_SIGNED_32:
8975                         return false;
8976
8977                 default:
8978                         DE_ASSERT(false);
8979         }
8980         return false;
8981 }
8982
8983 bool isFloat (ConversionDataType type)
8984 {
8985         switch (type)
8986         {
8987                 case DATA_TYPE_SIGNED_8:
8988                 case DATA_TYPE_SIGNED_16:
8989                 case DATA_TYPE_SIGNED_32:
8990                 case DATA_TYPE_SIGNED_64:
8991                 case DATA_TYPE_UNSIGNED_8:
8992                 case DATA_TYPE_UNSIGNED_16:
8993                 case DATA_TYPE_UNSIGNED_32:
8994                 case DATA_TYPE_UNSIGNED_64:
8995                 case DATA_TYPE_VEC2_SIGNED_16:
8996                 case DATA_TYPE_VEC2_SIGNED_32:
8997                         return false;
8998
8999                 case DATA_TYPE_FLOAT_16:
9000                 case DATA_TYPE_FLOAT_32:
9001                 case DATA_TYPE_FLOAT_64:
9002                         return true;
9003
9004                 default:
9005                         DE_ASSERT(false);
9006         }
9007         return false;
9008 }
9009
9010 const string getTypeName (ConversionDataType type)
9011 {
9012         string prefix = isSigned(type) ? "" : "u";
9013
9014         if              (isInt(type))                                           return prefix + "int"   + getBitWidthStr(type);
9015         else if (isFloat(type))                                         return prefix + "float" + getBitWidthStr(type);
9016         else if (type == DATA_TYPE_VEC2_SIGNED_16)      return "i16vec2";
9017         else if (type == DATA_TYPE_VEC2_SIGNED_32)      return "i32vec2";
9018         else                                                                            DE_ASSERT(false);
9019
9020         return "";
9021 }
9022
9023 const string getTestName (ConversionDataType from, ConversionDataType to, const char* suffix)
9024 {
9025         const string fullSuffix(suffix == DE_NULL ? "" : string("_") + string(suffix));
9026
9027         return getTypeName(from) + "_to_" + getTypeName(to) + fullSuffix;
9028 }
9029
9030 const string getAsmTypeName (ConversionDataType type)
9031 {
9032         string prefix;
9033
9034         if              (isInt(type))                                           prefix = isSigned(type) ? "i" : "u";
9035         else if (isFloat(type))                                         prefix = "f";
9036         else if (type == DATA_TYPE_VEC2_SIGNED_16)      return "i16vec2";
9037         else if (type == DATA_TYPE_VEC2_SIGNED_32)      return "v2i32";
9038         else                                                                            DE_ASSERT(false);
9039
9040         return prefix + getBitWidthStr(type);
9041 }
9042
9043 template<typename T>
9044 BufferSp getSpecializedBuffer (deInt64 number)
9045 {
9046         return BufferSp(new Buffer<T>(vector<T>(1, (T)number)));
9047 }
9048
9049 BufferSp getBuffer (ConversionDataType type, deInt64 number)
9050 {
9051         switch (type)
9052         {
9053                 case DATA_TYPE_SIGNED_8:                return getSpecializedBuffer<deInt8>(number);
9054                 case DATA_TYPE_SIGNED_16:               return getSpecializedBuffer<deInt16>(number);
9055                 case DATA_TYPE_SIGNED_32:               return getSpecializedBuffer<deInt32>(number);
9056                 case DATA_TYPE_SIGNED_64:               return getSpecializedBuffer<deInt64>(number);
9057                 case DATA_TYPE_UNSIGNED_8:              return getSpecializedBuffer<deUint8>(number);
9058                 case DATA_TYPE_UNSIGNED_16:             return getSpecializedBuffer<deUint16>(number);
9059                 case DATA_TYPE_UNSIGNED_32:             return getSpecializedBuffer<deUint32>(number);
9060                 case DATA_TYPE_UNSIGNED_64:             return getSpecializedBuffer<deUint64>(number);
9061                 case DATA_TYPE_FLOAT_16:                return getSpecializedBuffer<deUint16>(number);
9062                 case DATA_TYPE_FLOAT_32:                return getSpecializedBuffer<deUint32>(number);
9063                 case DATA_TYPE_FLOAT_64:                return getSpecializedBuffer<deUint64>(number);
9064                 case DATA_TYPE_VEC2_SIGNED_16:  return getSpecializedBuffer<deUint32>(number);
9065                 case DATA_TYPE_VEC2_SIGNED_32:  return getSpecializedBuffer<deUint64>(number);
9066
9067                 default:                                                TCU_THROW(InternalError, "Unimplemented type passed");
9068         }
9069 }
9070
9071 bool usesInt8 (ConversionDataType from, ConversionDataType to)
9072 {
9073         return (from == DATA_TYPE_SIGNED_8 || to == DATA_TYPE_SIGNED_8 ||
9074                         from == DATA_TYPE_UNSIGNED_8 || to == DATA_TYPE_UNSIGNED_8);
9075 }
9076
9077 bool usesInt16 (ConversionDataType from, ConversionDataType to)
9078 {
9079         return (from == DATA_TYPE_SIGNED_16 || to == DATA_TYPE_SIGNED_16 ||
9080                         from == DATA_TYPE_UNSIGNED_16 || to == DATA_TYPE_UNSIGNED_16 ||
9081                         from == DATA_TYPE_VEC2_SIGNED_16 || to == DATA_TYPE_VEC2_SIGNED_16);
9082 }
9083
9084 bool usesInt32 (ConversionDataType from, ConversionDataType to)
9085 {
9086         return (from == DATA_TYPE_SIGNED_32 || to == DATA_TYPE_SIGNED_32 ||
9087                         from == DATA_TYPE_UNSIGNED_32 || to == DATA_TYPE_UNSIGNED_32 ||
9088                         from == DATA_TYPE_VEC2_SIGNED_32|| to == DATA_TYPE_VEC2_SIGNED_32);
9089 }
9090
9091 bool usesInt64 (ConversionDataType from, ConversionDataType to)
9092 {
9093         return (from == DATA_TYPE_SIGNED_64 || to == DATA_TYPE_SIGNED_64 ||
9094                         from == DATA_TYPE_UNSIGNED_64 || to == DATA_TYPE_UNSIGNED_64);
9095 }
9096
9097 bool usesFloat16 (ConversionDataType from, ConversionDataType to)
9098 {
9099         return (from == DATA_TYPE_FLOAT_16 || to == DATA_TYPE_FLOAT_16);
9100 }
9101
9102 bool usesFloat32 (ConversionDataType from, ConversionDataType to)
9103 {
9104         return (from == DATA_TYPE_FLOAT_32 || to == DATA_TYPE_FLOAT_32);
9105 }
9106
9107 bool usesFloat64 (ConversionDataType from, ConversionDataType to)
9108 {
9109         return (from == DATA_TYPE_FLOAT_64 || to == DATA_TYPE_FLOAT_64);
9110 }
9111
9112 void getVulkanFeaturesAndExtensions (ConversionDataType from, ConversionDataType to, VulkanFeatures& vulkanFeatures, vector<string>& extensions)
9113 {
9114         if (usesInt16(from, to) && !usesInt32(from, to))
9115                 vulkanFeatures.coreFeatures.shaderInt16 = DE_TRUE;
9116
9117         if (usesInt64(from, to))
9118                 vulkanFeatures.coreFeatures.shaderInt64 = DE_TRUE;
9119
9120         if (usesFloat64(from, to))
9121                 vulkanFeatures.coreFeatures.shaderFloat64 = DE_TRUE;
9122
9123         if (usesInt16(from, to) || usesFloat16(from, to))
9124         {
9125                 extensions.push_back("VK_KHR_16bit_storage");
9126                 vulkanFeatures.ext16BitStorage |= EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
9127         }
9128
9129         if (usesFloat16(from, to) || usesInt8(from, to))
9130         {
9131                 extensions.push_back("VK_KHR_shader_float16_int8");
9132
9133                 if (usesFloat16(from, to))
9134                 {
9135                         vulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_FLOAT16;
9136                 }
9137
9138                 if (usesInt8(from, to))
9139                 {
9140                         vulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_INT8;
9141
9142                         extensions.push_back("VK_KHR_8bit_storage");
9143                         vulkanFeatures.ext8BitStorage |= EXT8BITSTORAGEFEATURES_STORAGE_BUFFER;
9144                 }
9145         }
9146 }
9147
9148 struct ConvertCase
9149 {
9150         ConvertCase (const string& instruction, ConversionDataType from, ConversionDataType to, deInt64 number, bool separateOutput = false, deInt64 outputNumber = 0, const char* suffix = DE_NULL)
9151         : m_fromType            (from)
9152         , m_toType                      (to)
9153         , m_name                        (getTestName(from, to, suffix))
9154         , m_inputBuffer         (getBuffer(from, number))
9155         {
9156                 string caps;
9157                 string decl;
9158                 string exts;
9159
9160                 m_asmTypes["inputType"]         = getAsmTypeName(from);
9161                 m_asmTypes["outputType"]        = getAsmTypeName(to);
9162
9163                 if (separateOutput)
9164                         m_outputBuffer = getBuffer(to, outputNumber);
9165                 else
9166                         m_outputBuffer = getBuffer(to, number);
9167
9168                 if (usesInt8(from, to))
9169                 {
9170                         bool requiresInt8Capability = true;
9171                         if (instruction == "OpUConvert" || instruction == "OpSConvert")
9172                         {
9173                                 // Conversions between 8 and 32 bit are provided by SPV_KHR_8bit_storage. The rest requires explicit Int8
9174                                 if (usesInt32(from, to))
9175                                         requiresInt8Capability = false;
9176                         }
9177
9178                         caps += "OpCapability StorageBuffer8BitAccess\n";
9179                         if (requiresInt8Capability)
9180                                 caps += "OpCapability Int8\n";
9181
9182                         decl += "%i8         = OpTypeInt 8 1\n"
9183                                         "%u8         = OpTypeInt 8 0\n";
9184                         exts += "OpExtension \"SPV_KHR_8bit_storage\"\n";
9185                 }
9186
9187                 if (usesInt16(from, to))
9188                 {
9189                         bool requiresInt16Capability = true;
9190
9191                         if (instruction == "OpUConvert" || instruction == "OpSConvert" || instruction == "OpFConvert")
9192                         {
9193                                 // Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Int16
9194                                 if (usesInt32(from, to) || usesFloat32(from, to))
9195                                         requiresInt16Capability = false;
9196                         }
9197
9198                         decl += "%i16        = OpTypeInt 16 1\n"
9199                                         "%u16        = OpTypeInt 16 0\n"
9200                                         "%i16vec2    = OpTypeVector %i16 2\n";
9201
9202                         // Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Int16
9203                         if (requiresInt16Capability)
9204                                 caps += "OpCapability Int16\n";
9205                 }
9206
9207                 if (usesFloat16(from, to))
9208                 {
9209                         decl += "%f16        = OpTypeFloat 16\n";
9210
9211                         // Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Float16
9212                         if (!(usesInt32(from, to) || usesFloat32(from, to)))
9213                                 caps += "OpCapability Float16\n";
9214                 }
9215
9216                 if (usesInt16(from, to) || usesFloat16(from, to))
9217                 {
9218                         caps += "OpCapability StorageUniformBufferBlock16\n";
9219                         exts += "OpExtension \"SPV_KHR_16bit_storage\"\n";
9220                 }
9221
9222                 if (usesInt64(from, to))
9223                 {
9224                         caps += "OpCapability Int64\n";
9225                         decl += "%i64        = OpTypeInt 64 1\n"
9226                                         "%u64        = OpTypeInt 64 0\n";
9227                 }
9228
9229                 if (usesFloat64(from, to))
9230                 {
9231                         caps += "OpCapability Float64\n";
9232                         decl += "%f64        = OpTypeFloat 64\n";
9233                 }
9234
9235                 m_asmTypes["datatype_capabilities"]             = caps;
9236                 m_asmTypes["datatype_additional_decl"]  = decl;
9237                 m_asmTypes["datatype_extensions"]               = exts;
9238         }
9239
9240         ConversionDataType              m_fromType;
9241         ConversionDataType              m_toType;
9242         string                                  m_name;
9243         map<string, string>             m_asmTypes;
9244         BufferSp                                m_inputBuffer;
9245         BufferSp                                m_outputBuffer;
9246 };
9247
9248 const string getConvertCaseShaderStr (const string& instruction, const ConvertCase& convertCase)
9249 {
9250         map<string, string> params = convertCase.m_asmTypes;
9251
9252         params["instruction"]   = instruction;
9253         params["inDecorator"]   = getByteWidthStr(convertCase.m_fromType);
9254         params["outDecorator"]  = getByteWidthStr(convertCase.m_toType);
9255
9256         const StringTemplate shader (
9257                 "OpCapability Shader\n"
9258                 "${datatype_capabilities}"
9259                 "${datatype_extensions:opt}"
9260                 "OpMemoryModel Logical GLSL450\n"
9261                 "OpEntryPoint GLCompute %main \"main\"\n"
9262                 "OpExecutionMode %main LocalSize 1 1 1\n"
9263                 "OpSource GLSL 430\n"
9264                 "OpName %main           \"main\"\n"
9265                 // Decorators
9266                 "OpDecorate %indata DescriptorSet 0\n"
9267                 "OpDecorate %indata Binding 0\n"
9268                 "OpDecorate %outdata DescriptorSet 0\n"
9269                 "OpDecorate %outdata Binding 1\n"
9270                 "OpDecorate %in_buf BufferBlock\n"
9271                 "OpDecorate %out_buf BufferBlock\n"
9272                 "OpMemberDecorate %in_buf 0 Offset 0\n"
9273                 "OpMemberDecorate %out_buf 0 Offset 0\n"
9274                 // Base types
9275                 "%void       = OpTypeVoid\n"
9276                 "%voidf      = OpTypeFunction %void\n"
9277                 "%u32        = OpTypeInt 32 0\n"
9278                 "%i32        = OpTypeInt 32 1\n"
9279                 "%f32        = OpTypeFloat 32\n"
9280                 "%v2i32      = OpTypeVector %i32 2\n"
9281                 "${datatype_additional_decl}"
9282                 "%uvec3      = OpTypeVector %u32 3\n"
9283                 // Derived types
9284                 "%in_ptr     = OpTypePointer Uniform %${inputType}\n"
9285                 "%out_ptr    = OpTypePointer Uniform %${outputType}\n"
9286                 "%in_buf     = OpTypeStruct %${inputType}\n"
9287                 "%out_buf    = OpTypeStruct %${outputType}\n"
9288                 "%in_bufptr  = OpTypePointer Uniform %in_buf\n"
9289                 "%out_bufptr = OpTypePointer Uniform %out_buf\n"
9290                 "%indata     = OpVariable %in_bufptr Uniform\n"
9291                 "%outdata    = OpVariable %out_bufptr Uniform\n"
9292                 // Constants
9293                 "%zero       = OpConstant %i32 0\n"
9294                 // Main function
9295                 "%main       = OpFunction %void None %voidf\n"
9296                 "%label      = OpLabel\n"
9297                 "%inloc      = OpAccessChain %in_ptr %indata %zero\n"
9298                 "%outloc     = OpAccessChain %out_ptr %outdata %zero\n"
9299                 "%inval      = OpLoad %${inputType} %inloc\n"
9300                 "%conv       = ${instruction} %${outputType} %inval\n"
9301                 "              OpStore %outloc %conv\n"
9302                 "              OpReturn\n"
9303                 "              OpFunctionEnd\n"
9304         );
9305
9306         return shader.specialize(params);
9307 }
9308
9309 void createConvertCases (vector<ConvertCase>& testCases, const string& instruction)
9310 {
9311         if (instruction == "OpUConvert")
9312         {
9313                 // Convert unsigned int to unsigned int
9314                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_16,          42));
9315                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_32,          73));
9316                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_64,          121));
9317
9318                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_8,           33));
9319                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_32,          60653));
9320                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_64,          17991));
9321
9322                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_64,          904256275));
9323                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_16,          6275));
9324                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_8,           17));
9325
9326                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_32,          701256243));
9327                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_16,          4741));
9328                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_8,           65));
9329         }
9330         else if (instruction == "OpSConvert")
9331         {
9332                 // Sign extension int->int
9333                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_16,            -30));
9334                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_32,            55));
9335                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_64,            -3));
9336                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_32,            14669));
9337                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_64,            -3341));
9338                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_64,            973610259));
9339
9340                 // Truncate for int->int
9341                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_8,                     81));
9342                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_8,                     -93));
9343                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_8,                     3182748172687672ll,                                     true,   56));
9344                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_16,            12382));
9345                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_32,            -972812359));
9346                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_16,            -1067742499291926803ll,                         true,   -4371));
9347
9348                 // Sign extension for int->uint
9349                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_16,          56));
9350                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_32,          -47,                                                            true,   4294967249u));
9351                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_64,          -5,                                                                     true,   18446744073709551611ull));
9352                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_32,          14669));
9353                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_64,          -3341,                                                          true,   18446744073709548275ull));
9354                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_64,          973610259));
9355
9356                 // Truncate for int->uint
9357                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_8,           -25711,                                                         true,   145));
9358                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_8,           103));
9359                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_8,           -1067742499291926803ll,                         true,   61165));
9360                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_16,          12382));
9361                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_32,          -972812359,                                                     true,   3322154937u));
9362                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_16,          -1067742499291926803ll,                         true,   61165));
9363
9364                 // Sign extension for uint->int
9365                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_16,            71));
9366                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_32,            201,                                                            true,   -55));
9367                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_64,            188,                                                            true,   -68));
9368                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_32,            14669));
9369                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_64,            62195,                                                          true,   -3341));
9370                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_64,            973610259));
9371
9372                 // Truncate for uint->int
9373                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_8,                     67));
9374                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_8,                     133,                                                            true,   -123));
9375                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_8,                     836927654193256494ull,                          true,   46));
9376                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_16,            12382));
9377                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_32,            18446744072736739257ull,                        true,   -972812359));
9378                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_16,            17379001574417624813ull,                        true,   -4371));
9379
9380                 // Convert i16vec2 to i32vec2 and vice versa
9381                 // Unsigned values are used here to represent negative signed values and to allow defined shifting behaviour.
9382                 // The actual signed value -32123 is used here as uint16 value 33413 and uint32 value 4294935173
9383                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_VEC2_SIGNED_16,       DATA_TYPE_VEC2_SIGNED_32,       (33413u << 16)                  | 27593,        true,   (4294935173ull << 32)   | 27593));
9384                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_VEC2_SIGNED_32,       DATA_TYPE_VEC2_SIGNED_16,       (4294935173ull << 32)   | 27593,        true,   (33413u << 16)                  | 27593));
9385         }
9386         else if (instruction == "OpFConvert")
9387         {
9388                 // All hexadecimal values below represent 1234.0 as 16/32/64-bit IEEE 754 float
9389                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_FLOAT_64,                     0x449a4000,                                                     true,   0x4093480000000000));
9390                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_FLOAT_32,                     0x4093480000000000,                                     true,   0x449a4000));
9391
9392                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_FLOAT_16,                     0x449a4000,                                                     true,   0x64D2));
9393                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_FLOAT_32,                     0x64D2,                                                         true,   0x449a4000));
9394
9395                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_FLOAT_64,                     0x64D2,                                                         true,   0x4093480000000000));
9396                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_FLOAT_16,                     0x4093480000000000,                                     true,   0x64D2));
9397         }
9398         else if (instruction == "OpConvertFToU")
9399         {
9400                 // Normal numbers from uint8 range
9401                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x5020,                                                         true,   33,                                                                     "33"));
9402                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x42280000,                                                     true,   42,                                                                     "42"));
9403                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x4067800000000000ull,                          true,   188,                                                            "188"));
9404
9405                 // Maximum uint8 value
9406                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x5BF8,                                                         true,   255,                                                            "max"));
9407                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x437F0000,                                                     true,   255,                                                            "max"));
9408                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x406FE00000000000ull,                          true,   255,                                                            "max"));
9409
9410                 // +0
9411                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x0000,                                                         true,   0,                                                                      "p0"));
9412                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x00000000,                                                     true,   0,                                                                      "p0"));
9413                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x0000000000000000ull,                          true,   0,                                                                      "p0"));
9414
9415                 // -0
9416                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x8000,                                                         true,   0,                                                                      "m0"));
9417                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x80000000,                                                     true,   0,                                                                      "m0"));
9418                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x8000000000000000ull,                          true,   0,                                                                      "m0"));
9419
9420                 // All hexadecimal values below represent 1234.0 as 16/32/64-bit IEEE 754 float
9421                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x64D2,                                                         true,   1234,                                                           "1234"));
9422                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x64D2,                                                         true,   1234,                                                           "1234"));
9423                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x64D2,                                                         true,   1234,                                                           "1234"));
9424
9425                 // 0x7BFF = 0111 1011 1111 1111 = 0 11110 1111111111 = 65504
9426                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x7BFF,                                                         true,   65504,                                                          "max"));
9427                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x7BFF,                                                         true,   65504,                                                          "max"));
9428                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x7BFF,                                                         true,   65504,                                                          "max"));
9429
9430                 // +0
9431                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x0000,                                                         true,   0,                                                                      "p0"));
9432                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x0000,                                                         true,   0,                                                                      "p0"));
9433                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x0000,                                                         true,   0,                                                                      "p0"));
9434
9435                 // -0
9436                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x8000,                                                         true,   0,                                                                      "m0"));
9437                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x8000,                                                         true,   0,                                                                      "m0"));
9438                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x8000,                                                         true,   0,                                                                      "m0"));
9439
9440                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_16,          0x449a4000,                                                     true,   1234));
9441                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_32,          0x449a4000,                                                     true,   1234));
9442                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_64,          0x449a4000,                                                     true,   1234));
9443                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_16,          0x4093480000000000,                                     true,   1234));
9444                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_32,          0x4093480000000000,                                     true,   1234));
9445                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_64,          0x4093480000000000,                                     true,   1234));
9446         }
9447         else if (instruction == "OpConvertUToF")
9448         {
9449                 // Normal numbers from uint8 range
9450                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_16,                     116,                                                            true,   0x5740,                                                         "116"));
9451                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_32,                     232,                                                            true,   0x43680000,                                                     "232"));
9452                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_64,                     164,                                                            true,   0x4064800000000000ull,                          "164"));
9453
9454                 // Maximum uint8 value
9455                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_16,                     255,                                                            true,   0x5BF8,                                                         "max"));
9456                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_32,                     255,                                                            true,   0x437F0000,                                                     "max"));
9457                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_64,                     255,                                                            true,   0x406FE00000000000ull,                          "max"));
9458
9459                 // All hexadecimal values below represent 1234.0 as 32/64-bit IEEE 754 float
9460                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9461                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9462                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9463
9464                 // 0x7BFF = 0111 1011 1111 1111 = 0 11110 1111111111 = 65504
9465                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9466                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9467                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9468
9469                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9470                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9471                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9472                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9473                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9474                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9475         }
9476         else if (instruction == "OpConvertFToS")
9477         {
9478                 // Normal numbers from int8 range
9479                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0xC980,                                                         true,   -11,                                                            "m11"));
9480                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0xC2140000,                                                     true,   -37,                                                            "m37"));
9481                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0xC050800000000000ull,                          true,   -66,                                                            "m66"));
9482
9483                 // Minimum int8 value
9484                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0xD800,                                                         true,   -128,                                                           "min"));
9485                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0xC3000000,                                                     true,   -128,                                                           "min"));
9486                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0xC060000000000000ull,                          true,   -128,                                                           "min"));
9487
9488                 // Maximum int8 value
9489                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x57F0,                                                         true,   127,                                                            "max"));
9490                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x42FE0000,                                                     true,   127,                                                            "max"));
9491                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x405FC00000000000ull,                          true,   127,                                                            "max"));
9492
9493                 // +0
9494                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x0000,                                                         true,   0,                                                                      "p0"));
9495                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x00000000,                                                     true,   0,                                                                      "p0"));
9496                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x0000000000000000ull,                          true,   0,                                                                      "p0"));
9497
9498                 // -0
9499                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x8000,                                                         true,   0,                                                                      "m0"));
9500                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x80000000,                                                     true,   0,                                                                      "m0"));
9501                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x8000000000000000ull,                          true,   0,                                                                      "m0"));
9502
9503                 // All hexadecimal values below represent -1234.0 as 32/64-bit IEEE 754 float
9504                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9505                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9506                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9507
9508                 // 0xF800 = 1111 1000 0000 0000 = 1 11110 0000000000 = -32768
9509                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0xF800,                                                         true,   -32768,                                                         "min"));
9510                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0xF800,                                                         true,   -32768,                                                         "min"));
9511                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0xF800,                                                         true,   -32768,                                                         "min"));
9512
9513                 // 0x77FF = 0111 0111 1111 1111 = 0 11101 1111111111 = 32752
9514                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x77FF,                                                         true,   32752,                                                          "max"));
9515                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x77FF,                                                         true,   32752,                                                          "max"));
9516                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x77FF,                                                         true,   32752,                                                          "max"));
9517
9518                 // +0
9519                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x0000,                                                         true,   0,                                                                      "p0"));
9520                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x0000,                                                         true,   0,                                                                      "p0"));
9521                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x0000,                                                         true,   0,                                                                      "p0"));
9522
9523                 // -0
9524                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x8000,                                                         true,   0,                                                                      "m0"));
9525                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x8000,                                                         true,   0,                                                                      "m0"));
9526                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x8000,                                                         true,   0,                                                                      "m0"));
9527
9528                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0xc49a4000,                                                     true,   -1234));
9529                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_32,            0xc49a4000,                                                     true,   -1234));
9530                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_64,            0xc49a4000,                                                     true,   -1234));
9531                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_16,            0xc093480000000000,                                     true,   -1234));
9532                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_32,            0xc093480000000000,                                     true,   -1234));
9533                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_64,            0xc093480000000000,                                     true,   -1234));
9534                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0x453b9000,                                                     true,    3001,                                                          "p3001"));
9535                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0xc53b9000,                                                     true,   -3001,                                                          "m3001"));
9536         }
9537         else if (instruction == "OpConvertSToF")
9538         {
9539                 // Normal numbers from int8 range
9540                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     -12,                                                            true,   0xCA00,                                                         "m21"));
9541                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     -21,                                                            true,   0xC1A80000,                                                     "m21"));
9542                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     -99,                                                            true,   0xC058C00000000000ull,                          "m99"));
9543
9544                 // Minimum int8 value
9545                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     -128,                                                           true,   0xD800,                                                         "min"));
9546                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     -128,                                                           true,   0xC3000000,                                                     "min"));
9547                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     -128,                                                           true,   0xC060000000000000ull,                          "min"));
9548
9549                 // Maximum int8 value
9550                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     127,                                                            true,   0x57F0,                                                         "max"));
9551                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     127,                                                            true,   0x42FE0000,                                                     "max"));
9552                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     127,                                                            true,   0x405FC00000000000ull,                          "max"));
9553
9554                 // All hexadecimal values below represent 1234.0 as 32/64-bit IEEE 754 float
9555                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9556                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9557                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9558
9559                 // 0xF800 = 1111 1000 0000 0000 = 1 11110 0000000000 = -32768
9560                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9561                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9562                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9563
9564                 // 0x77FF = 0111 0111 1111 1111 = 0 11101 1111111111 = 32752
9565                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9566                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9567                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9568
9569                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9570                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9571                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9572                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9573                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9574                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9575         }
9576         else
9577                 DE_FATAL("Unknown instruction");
9578 }
9579
9580 const map<string, string> getConvertCaseFragments (string instruction, const ConvertCase& convertCase)
9581 {
9582         map<string, string> params = convertCase.m_asmTypes;
9583         map<string, string> fragments;
9584
9585         params["instruction"] = instruction;
9586         params["inDecorator"] = getByteWidthStr(convertCase.m_fromType);
9587
9588         const StringTemplate decoration (
9589                 "      OpDecorate %SSBOi DescriptorSet 0\n"
9590                 "      OpDecorate %SSBOo DescriptorSet 0\n"
9591                 "      OpDecorate %SSBOi Binding 0\n"
9592                 "      OpDecorate %SSBOo Binding 1\n"
9593                 "      OpDecorate %s_SSBOi Block\n"
9594                 "      OpDecorate %s_SSBOo Block\n"
9595                 "OpMemberDecorate %s_SSBOi 0 Offset 0\n"
9596                 "OpMemberDecorate %s_SSBOo 0 Offset 0\n");
9597
9598         const StringTemplate pre_main (
9599                 "${datatype_additional_decl:opt}"
9600                 "    %ptr_in = OpTypePointer StorageBuffer %${inputType}\n"
9601                 "   %ptr_out = OpTypePointer StorageBuffer %${outputType}\n"
9602                 "   %s_SSBOi = OpTypeStruct %${inputType}\n"
9603                 "   %s_SSBOo = OpTypeStruct %${outputType}\n"
9604                 " %ptr_SSBOi = OpTypePointer StorageBuffer %s_SSBOi\n"
9605                 " %ptr_SSBOo = OpTypePointer StorageBuffer %s_SSBOo\n"
9606                 "     %SSBOi = OpVariable %ptr_SSBOi StorageBuffer\n"
9607                 "     %SSBOo = OpVariable %ptr_SSBOo StorageBuffer\n");
9608
9609         const StringTemplate testfun (
9610                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9611                 "%param     = OpFunctionParameter %v4f32\n"
9612                 "%label     = OpLabel\n"
9613                 "%iLoc      = OpAccessChain %ptr_in %SSBOi %c_u32_0\n"
9614                 "%oLoc      = OpAccessChain %ptr_out %SSBOo %c_u32_0\n"
9615                 "%valIn     = OpLoad %${inputType} %iLoc\n"
9616                 "%valOut    = ${instruction} %${outputType} %valIn\n"
9617                 "             OpStore %oLoc %valOut\n"
9618                 "             OpReturnValue %param\n"
9619                 "             OpFunctionEnd\n");
9620
9621         params["datatype_extensions"] =
9622                 params["datatype_extensions"] +
9623                 "OpExtension \"SPV_KHR_storage_buffer_storage_class\"\n";
9624
9625         fragments["capability"] = params["datatype_capabilities"];
9626         fragments["extension"]  = params["datatype_extensions"];
9627         fragments["decoration"] = decoration.specialize(params);
9628         fragments["pre_main"]   = pre_main.specialize(params);
9629         fragments["testfun"]    = testfun.specialize(params);
9630
9631         return fragments;
9632 }
9633
9634 // Test for OpSConvert, OpUConvert, OpFConvert and OpConvert* in compute shaders
9635 tcu::TestCaseGroup* createConvertComputeTests (tcu::TestContext& testCtx, const string& instruction, const string& name)
9636 {
9637         de::MovePtr<tcu::TestCaseGroup>         group(new tcu::TestCaseGroup(testCtx, name.c_str(), instruction.c_str()));
9638         vector<ConvertCase>                                     testCases;
9639         createConvertCases(testCases, instruction);
9640
9641         for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
9642         {
9643                 ComputeShaderSpec spec;
9644                 spec.assembly                   = getConvertCaseShaderStr(instruction, *test);
9645                 spec.numWorkGroups              = IVec3(1, 1, 1);
9646                 spec.inputs.push_back   (test->m_inputBuffer);
9647                 spec.outputs.push_back  (test->m_outputBuffer);
9648
9649                 getVulkanFeaturesAndExtensions(test->m_fromType, test->m_toType, spec.requestedVulkanFeatures, spec.extensions);
9650
9651                 group->addChild(new SpvAsmComputeShaderCase(testCtx, test->m_name.c_str(), "", spec));
9652         }
9653         return group.release();
9654 }
9655
9656 // Test for OpSConvert, OpUConvert, OpFConvert and OpConvert* in graphics shaders
9657 tcu::TestCaseGroup* createConvertGraphicsTests (tcu::TestContext& testCtx, const string& instruction, const string& name)
9658 {
9659         de::MovePtr<tcu::TestCaseGroup>         group(new tcu::TestCaseGroup(testCtx, name.c_str(), instruction.c_str()));
9660         vector<ConvertCase>                                     testCases;
9661         createConvertCases(testCases, instruction);
9662
9663         for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
9664         {
9665                 map<string, string>     fragments               = getConvertCaseFragments(instruction, *test);
9666                 VulkanFeatures          vulkanFeatures;
9667                 GraphicsResources       resources;
9668                 vector<string>          extensions;
9669                 SpecConstants           noSpecConstants;
9670                 PushConstants           noPushConstants;
9671                 GraphicsInterfaces      noInterfaces;
9672                 tcu::RGBA                       defaultColors[4];
9673
9674                 getDefaultColors                        (defaultColors);
9675                 resources.inputs.push_back      (Resource(test->m_inputBuffer, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9676                 resources.outputs.push_back     (Resource(test->m_outputBuffer, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9677                 extensions.push_back            ("VK_KHR_storage_buffer_storage_class");
9678
9679                 getVulkanFeaturesAndExtensions(test->m_fromType, test->m_toType, vulkanFeatures, extensions);
9680
9681                 createTestsForAllStages(
9682                         test->m_name, defaultColors, defaultColors, fragments, noSpecConstants,
9683                         noPushConstants, resources, noInterfaces, extensions, vulkanFeatures, group.get());
9684         }
9685         return group.release();
9686 }
9687
9688 // Constant-Creation Instructions: OpConstant, OpConstantComposite
9689 tcu::TestCaseGroup* createOpConstantFloat16Tests(tcu::TestContext& testCtx)
9690 {
9691         de::MovePtr<tcu::TestCaseGroup> opConstantCompositeTests                (new tcu::TestCaseGroup(testCtx, "opconstant", "OpConstant and OpConstantComposite instruction"));
9692         RGBA                                                    inputColors[4];
9693         RGBA                                                    outputColors[4];
9694         vector<string>                                  extensions;
9695         GraphicsResources                               resources;
9696         VulkanFeatures                                  features;
9697
9698         const char                                              functionStart[]  =
9699                 "%test_code             = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9700                 "%param1                = OpFunctionParameter %v4f32\n"
9701                 "%lbl                   = OpLabel\n";
9702
9703         const char                                              functionEnd[]           =
9704                 "%transformed_param_32  = OpFConvert %v4f32 %transformed_param\n"
9705                 "                         OpReturnValue %transformed_param_32\n"
9706                 "                         OpFunctionEnd\n";
9707
9708         struct NameConstantsCode
9709         {
9710                 string name;
9711                 string constants;
9712                 string code;
9713         };
9714
9715 #define FLOAT_16_COMMON_TYPES_AND_CONSTS \
9716                         "%f16                  = OpTypeFloat 16\n"                                                 \
9717                         "%c_f16_0              = OpConstant %f16 0.0\n"                                            \
9718                         "%c_f16_0_5            = OpConstant %f16 0.5\n"                                            \
9719                         "%c_f16_1              = OpConstant %f16 1.0\n"                                            \
9720                         "%v4f16                = OpTypeVector %f16 4\n"                                            \
9721                         "%fp_f16               = OpTypePointer Function %f16\n"                                    \
9722                         "%fp_v4f16             = OpTypePointer Function %v4f16\n"                                  \
9723                         "%c_v4f16_1_1_1_1      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_1\n" \
9724                         "%a4f16                = OpTypeArray %f16 %c_u32_4\n"                                      \
9725
9726         NameConstantsCode                               tests[] =
9727         {
9728                 {
9729                         "vec4",
9730
9731                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9732                         "%cval                 = OpConstantComposite %v4f16 %c_f16_0_5 %c_f16_0_5 %c_f16_0_5 %c_f16_0\n",
9733                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9734                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %cval\n"
9735                 },
9736                 {
9737                         "struct",
9738
9739                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9740                         "%stype                = OpTypeStruct %v4f16 %f16\n"
9741                         "%fp_stype             = OpTypePointer Function %stype\n"
9742                         "%f16_n_1              = OpConstant %f16 -1.0\n"
9743                         "%f16_1_5              = OpConstant %f16 !0x3e00\n" // +1.5
9744                         "%cvec                 = OpConstantComposite %v4f16 %f16_1_5 %f16_1_5 %f16_1_5 %c_f16_1\n"
9745                         "%cval                 = OpConstantComposite %stype %cvec %f16_n_1\n",
9746
9747                         "%v                    = OpVariable %fp_stype Function %cval\n"
9748                         "%vec_ptr              = OpAccessChain %fp_v4f16 %v %c_u32_0\n"
9749                         "%f16_ptr              = OpAccessChain %fp_f16 %v %c_u32_1\n"
9750                         "%vec_val              = OpLoad %v4f16 %vec_ptr\n"
9751                         "%f16_val              = OpLoad %f16 %f16_ptr\n"
9752                         "%tmp1                 = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_1 %f16_val\n" // vec4(-1)
9753                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9754                         "%tmp2                 = OpFAdd %v4f16 %tmp1 %param1_16\n" // param1 + vec4(-1)
9755                         "%transformed_param    = OpFAdd %v4f16 %tmp2 %vec_val\n" // param1 + vec4(-1) + vec4(1.5, 1.5, 1.5, 1.0)
9756                 },
9757                 {
9758                         // [1|0|0|0.5] [x] = x + 0.5
9759                         // [0|1|0|0.5] [y] = y + 0.5
9760                         // [0|0|1|0.5] [z] = z + 0.5
9761                         // [0|0|0|1  ] [1] = 1
9762                         "matrix",
9763
9764                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9765                         "%mat4x4_f16           = OpTypeMatrix %v4f16 4\n"
9766                         "%v4f16_1_0_0_0        = OpConstantComposite %v4f16 %c_f16_1 %c_f16_0 %c_f16_0 %c_f16_0\n"
9767                         "%v4f16_0_1_0_0        = OpConstantComposite %v4f16 %c_f16_0 %c_f16_1 %c_f16_0 %c_f16_0\n"
9768                         "%v4f16_0_0_1_0        = OpConstantComposite %v4f16 %c_f16_0 %c_f16_0 %c_f16_1 %c_f16_0\n"
9769                         "%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"
9770                         "%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",
9771
9772                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9773                         "%transformed_param    = OpMatrixTimesVector %v4f16 %cval %param1_16\n"
9774                 },
9775                 {
9776                         "array",
9777
9778                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9779                         "%c_v4f16_1_1_1_0      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_0\n"
9780                         "%fp_a4f16             = OpTypePointer Function %a4f16\n"
9781                         "%f16_n_1              = OpConstant %f16 -1.0\n"
9782                         "%f16_1_5              = OpConstant %f16 !0x3e00\n" // +1.5
9783                         "%carr                 = OpConstantComposite %a4f16 %c_f16_0 %f16_n_1 %f16_1_5 %c_f16_0\n",
9784
9785                         "%v                    = OpVariable %fp_a4f16 Function %carr\n"
9786                         "%f                    = OpAccessChain %fp_f16 %v %c_u32_0\n"
9787                         "%f1                   = OpAccessChain %fp_f16 %v %c_u32_1\n"
9788                         "%f2                   = OpAccessChain %fp_f16 %v %c_u32_2\n"
9789                         "%f3                   = OpAccessChain %fp_f16 %v %c_u32_3\n"
9790                         "%f_val                = OpLoad %f16 %f\n"
9791                         "%f1_val               = OpLoad %f16 %f1\n"
9792                         "%f2_val               = OpLoad %f16 %f2\n"
9793                         "%f3_val               = OpLoad %f16 %f3\n"
9794                         "%ftot1                = OpFAdd %f16 %f_val %f1_val\n"
9795                         "%ftot2                = OpFAdd %f16 %ftot1 %f2_val\n"
9796                         "%ftot3                = OpFAdd %f16 %ftot2 %f3_val\n"  // 0 - 1 + 1.5 + 0
9797                         "%add_vec              = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_0 %ftot3\n"
9798                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9799                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %add_vec\n"
9800                 },
9801                 {
9802                         //
9803                         // [
9804                         //   {
9805                         //      0.0,
9806                         //      [ 1.0, 1.0, 1.0, 1.0]
9807                         //   },
9808                         //   {
9809                         //      1.0,
9810                         //      [ 0.0, 0.5, 0.0, 0.0]
9811                         //   }, //     ^^^
9812                         //   {
9813                         //      0.0,
9814                         //      [ 1.0, 1.0, 1.0, 1.0]
9815                         //   }
9816                         // ]
9817                         "array_of_struct_of_array",
9818
9819                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9820                         "%c_v4f16_1_1_1_0      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_0\n"
9821                         "%fp_a4f16             = OpTypePointer Function %a4f16\n"
9822                         "%stype                = OpTypeStruct %f16 %a4f16\n"
9823                         "%a3stype              = OpTypeArray %stype %c_u32_3\n"
9824                         "%fp_a3stype           = OpTypePointer Function %a3stype\n"
9825                         "%ca4f16_0             = OpConstantComposite %a4f16 %c_f16_0 %c_f16_0_5 %c_f16_0 %c_f16_0\n"
9826                         "%ca4f16_1             = OpConstantComposite %a4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_1\n"
9827                         "%cstype1              = OpConstantComposite %stype %c_f16_0 %ca4f16_1\n"
9828                         "%cstype2              = OpConstantComposite %stype %c_f16_1 %ca4f16_0\n"
9829                         "%carr                 = OpConstantComposite %a3stype %cstype1 %cstype2 %cstype1",
9830
9831                         "%v                    = OpVariable %fp_a3stype Function %carr\n"
9832                         "%f                    = OpAccessChain %fp_f16 %v %c_u32_1 %c_u32_1 %c_u32_1\n"
9833                         "%f_l                  = OpLoad %f16 %f\n"
9834                         "%add_vec              = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_0 %f_l\n"
9835                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9836                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %add_vec\n"
9837                 }
9838         };
9839
9840         getHalfColorsFullAlpha(inputColors);
9841         outputColors[0] = RGBA(255, 255, 255, 255);
9842         outputColors[1] = RGBA(255, 127, 127, 255);
9843         outputColors[2] = RGBA(127, 255, 127, 255);
9844         outputColors[3] = RGBA(127, 127, 255, 255);
9845
9846         extensions.push_back("VK_KHR_16bit_storage");
9847         extensions.push_back("VK_KHR_shader_float16_int8");
9848         features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
9849
9850         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
9851         {
9852                 map<string, string> fragments;
9853
9854                 fragments["extension"]  = "OpExtension \"SPV_KHR_16bit_storage\"";
9855                 fragments["capability"] = "OpCapability Float16\n";
9856                 fragments["pre_main"]   = tests[testNdx].constants;
9857                 fragments["testfun"]    = string(functionStart) + tests[testNdx].code + functionEnd;
9858
9859                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, resources, extensions, opConstantCompositeTests.get(), features);
9860         }
9861         return opConstantCompositeTests.release();
9862 }
9863
9864 template<typename T>
9865 void finalizeTestsCreation (T&                                                  specResource,
9866                                                         const map<string, string>&      fragments,
9867                                                         tcu::TestContext&                       testCtx,
9868                                                         tcu::TestCaseGroup&                     testGroup,
9869                                                         const std::string&                      testName,
9870                                                         const VulkanFeatures&           vulkanFeatures,
9871                                                         const vector<string>&           extensions,
9872                                                         const IVec3&                            numWorkGroups);
9873
9874 template<>
9875 void finalizeTestsCreation (GraphicsResources&                  specResource,
9876                                                         const map<string, string>&      fragments,
9877                                                         tcu::TestContext&                       ,
9878                                                         tcu::TestCaseGroup&                     testGroup,
9879                                                         const std::string&                      testName,
9880                                                         const VulkanFeatures&           vulkanFeatures,
9881                                                         const vector<string>&           extensions,
9882                                                         const IVec3&                            )
9883 {
9884         RGBA defaultColors[4];
9885         getDefaultColors(defaultColors);
9886
9887         createTestsForAllStages(testName, defaultColors, defaultColors, fragments, specResource, extensions, &testGroup, vulkanFeatures);
9888 }
9889
9890 template<>
9891 void finalizeTestsCreation (ComputeShaderSpec&                  specResource,
9892                                                         const map<string, string>&      fragments,
9893                                                         tcu::TestContext&                       testCtx,
9894                                                         tcu::TestCaseGroup&                     testGroup,
9895                                                         const std::string&                      testName,
9896                                                         const VulkanFeatures&           vulkanFeatures,
9897                                                         const vector<string>&           extensions,
9898                                                         const IVec3&                            numWorkGroups)
9899 {
9900         specResource.numWorkGroups = numWorkGroups;
9901         specResource.requestedVulkanFeatures = vulkanFeatures;
9902         specResource.extensions = extensions;
9903
9904         specResource.assembly = makeComputeShaderAssembly(fragments);
9905
9906         testGroup.addChild(new SpvAsmComputeShaderCase(testCtx, testName.c_str(), "", specResource));
9907 }
9908
9909 template<class SpecResource>
9910 tcu::TestCaseGroup* createFloat16LogicalSet (tcu::TestContext& testCtx, const bool nanSupported)
9911 {
9912         const string                                            nan                                     = nanSupported ? "_nan" : "";
9913         const string                                            groupName                       = "logical" + nan;
9914         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Float 16 logical tests"));
9915
9916         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
9917         const string                                            spvCapabilities         = string("OpCapability StorageUniformBufferBlock16\n") + (nanSupported ? "OpCapability SignedZeroInfNanPreserve\n" : "");
9918         const string                                            spvExtensions           = string("OpExtension \"SPV_KHR_16bit_storage\"\n") + (nanSupported ? "OpExtension \"SPV_KHR_float_controls\"\n" : "");
9919         const string                                            spvExecutionMode        = nanSupported ? "OpExecutionMode %BP_main SignedZeroInfNanPreserve 16\n" : "";
9920         const deUint32                                          numDataPoints           = 16;
9921         const vector<deFloat16>                         float16Data                     = getFloat16s(rnd, numDataPoints);
9922         const vector<deFloat16>                         float16Data1            = squarize(float16Data, 0);
9923         const vector<deFloat16>                         float16Data2            = squarize(float16Data, 1);
9924         const vector<deFloat16>                         float16DataVec1         = squarizeVector(float16Data, 0);
9925         const vector<deFloat16>                         float16DataVec2         = squarizeVector(float16Data, 1);
9926         const vector<deFloat16>                         float16OutDummy         (float16Data1.size(), 0);
9927         const vector<deFloat16>                         float16OutVecDummy      (float16DataVec1.size(), 0);
9928
9929         struct TestOp
9930         {
9931                 const char*             opCode;
9932                 VerifyIOFunc    verifyFuncNan;
9933                 VerifyIOFunc    verifyFuncNonNan;
9934                 const deUint32  argCount;
9935         };
9936
9937         const TestOp    testOps[]       =
9938         {
9939                 { "OpIsNan"                                             ,       compareFP16Logical<fp16isNan,                           true,  false, true>,    compareFP16Logical<fp16isNan,                           true,  false, false>,   1       },
9940                 { "OpIsInf"                                             ,       compareFP16Logical<fp16isInf,                           true,  false, true>,    compareFP16Logical<fp16isInf,                           true,  false, false>,   1       },
9941                 { "OpFOrdEqual"                                 ,       compareFP16Logical<fp16isEqual,                         false, true,  true>,    compareFP16Logical<fp16isEqual,                         false, true,  false>,   2       },
9942                 { "OpFUnordEqual"                               ,       compareFP16Logical<fp16isEqual,                         false, false, true>,    compareFP16Logical<fp16isEqual,                         false, false, false>,   2       },
9943                 { "OpFOrdNotEqual"                              ,       compareFP16Logical<fp16isUnequal,                       false, true,  true>,    compareFP16Logical<fp16isUnequal,                       false, true,  false>,   2       },
9944                 { "OpFUnordNotEqual"                    ,       compareFP16Logical<fp16isUnequal,                       false, false, true>,    compareFP16Logical<fp16isUnequal,                       false, false, false>,   2       },
9945                 { "OpFOrdLessThan"                              ,       compareFP16Logical<fp16isLess,                          false, true,  true>,    compareFP16Logical<fp16isLess,                          false, true,  false>,   2       },
9946                 { "OpFUnordLessThan"                    ,       compareFP16Logical<fp16isLess,                          false, false, true>,    compareFP16Logical<fp16isLess,                          false, false, false>,   2       },
9947                 { "OpFOrdGreaterThan"                   ,       compareFP16Logical<fp16isGreater,                       false, true,  true>,    compareFP16Logical<fp16isGreater,                       false, true,  false>,   2       },
9948                 { "OpFUnordGreaterThan"                 ,       compareFP16Logical<fp16isGreater,                       false, false, true>,    compareFP16Logical<fp16isGreater,                       false, false, false>,   2       },
9949                 { "OpFOrdLessThanEqual"                 ,       compareFP16Logical<fp16isLessOrEqual,           false, true,  true>,    compareFP16Logical<fp16isLessOrEqual,           false, true,  false>,   2       },
9950                 { "OpFUnordLessThanEqual"               ,       compareFP16Logical<fp16isLessOrEqual,           false, false, true>,    compareFP16Logical<fp16isLessOrEqual,           false, false, false>,   2       },
9951                 { "OpFOrdGreaterThanEqual"              ,       compareFP16Logical<fp16isGreaterOrEqual,        false, true,  true>,    compareFP16Logical<fp16isGreaterOrEqual,        false, true,  false>,   2       },
9952                 { "OpFUnordGreaterThanEqual"    ,       compareFP16Logical<fp16isGreaterOrEqual,        false, false, true>,    compareFP16Logical<fp16isGreaterOrEqual,        false, false, false>,   2       },
9953         };
9954
9955         { // scalar cases
9956                 const StringTemplate preMain
9957                 (
9958                         "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
9959                         "      %f16 = OpTypeFloat 16\n"
9960                         "  %c_f16_0 = OpConstant %f16 0.0\n"
9961                         "  %c_f16_1 = OpConstant %f16 1.0\n"
9962                         "   %up_f16 = OpTypePointer Uniform %f16\n"
9963                         "   %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
9964                         "   %SSBO16 = OpTypeStruct %ra_f16\n"
9965                         "%up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
9966                         "%ssbo_src0 = OpVariable %up_SSBO16 Uniform\n"
9967                         "%ssbo_src1 = OpVariable %up_SSBO16 Uniform\n"
9968                         " %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
9969                 );
9970
9971                 const StringTemplate decoration
9972                 (
9973                         "OpDecorate %ra_f16 ArrayStride 2\n"
9974                         "OpMemberDecorate %SSBO16 0 Offset 0\n"
9975                         "OpDecorate %SSBO16 BufferBlock\n"
9976                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
9977                         "OpDecorate %ssbo_src0 Binding 0\n"
9978                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
9979                         "OpDecorate %ssbo_src1 Binding 1\n"
9980                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
9981                         "OpDecorate %ssbo_dst Binding 2\n"
9982                 );
9983
9984                 const StringTemplate testFun
9985                 (
9986                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9987                         "    %param = OpFunctionParameter %v4f32\n"
9988
9989                         "    %entry = OpLabel\n"
9990                         "        %i = OpVariable %fp_i32 Function\n"
9991                         "             OpStore %i %c_i32_0\n"
9992                         "             OpBranch %loop\n"
9993
9994                         "     %loop = OpLabel\n"
9995                         "    %i_cmp = OpLoad %i32 %i\n"
9996                         "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
9997                         "             OpLoopMerge %merge %next None\n"
9998                         "             OpBranchConditional %lt %write %merge\n"
9999
10000                         "    %write = OpLabel\n"
10001                         "      %ndx = OpLoad %i32 %i\n"
10002
10003                         "     %src0 = OpAccessChain %up_f16 %ssbo_src0 %c_i32_0 %ndx\n"
10004                         " %val_src0 = OpLoad %f16 %src0\n"
10005
10006                         "${op_arg1_calc}"
10007
10008                         " %val_bdst = ${op_code} %bool %val_src0 ${op_arg1}\n"
10009                         "  %val_dst = OpSelect %f16 %val_bdst %c_f16_1 %c_f16_0\n"
10010                         "      %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
10011                         "             OpStore %dst %val_dst\n"
10012                         "             OpBranch %next\n"
10013
10014                         "     %next = OpLabel\n"
10015                         "    %i_cur = OpLoad %i32 %i\n"
10016                         "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10017                         "             OpStore %i %i_new\n"
10018                         "             OpBranch %loop\n"
10019
10020                         "    %merge = OpLabel\n"
10021                         "             OpReturnValue %param\n"
10022
10023                         "             OpFunctionEnd\n"
10024                 );
10025
10026                 const StringTemplate arg1Calc
10027                 (
10028                         "     %src1 = OpAccessChain %up_f16 %ssbo_src1 %c_i32_0 %ndx\n"
10029                         " %val_src1 = OpLoad %f16 %src1\n"
10030                 );
10031
10032                 for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10033                 {
10034                         const size_t            iterations              = float16Data1.size();
10035                         const TestOp&           testOp                  = testOps[testOpsIdx];
10036                         const string            testName                = de::toLower(string(testOp.opCode)) + "_scalar";
10037                         SpecResource            specResource;
10038                         map<string, string>     specs;
10039                         VulkanFeatures          features;
10040                         map<string, string>     fragments;
10041                         vector<string>          extensions;
10042
10043                         specs["num_data_points"]        = de::toString(iterations);
10044                         specs["op_code"]                        = testOp.opCode;
10045                         specs["op_arg1"]                        = (testOp.argCount == 1) ? "" : "%val_src1";
10046                         specs["op_arg1_calc"]           = (testOp.argCount == 1) ? "" : arg1Calc.specialize(specs);
10047
10048                         fragments["extension"]          = spvExtensions;
10049                         fragments["capability"]         = spvCapabilities;
10050                         fragments["execution_mode"]     = spvExecutionMode;
10051                         fragments["decoration"]         = decoration.specialize(specs);
10052                         fragments["pre_main"]           = preMain.specialize(specs);
10053                         fragments["testfun"]            = testFun.specialize(specs);
10054
10055                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Data1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10056                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Data2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10057                         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10058                         specResource.verifyIO = nanSupported ? testOp.verifyFuncNan : testOp.verifyFuncNonNan;
10059
10060                         extensions.push_back("VK_KHR_16bit_storage");
10061                         extensions.push_back("VK_KHR_shader_float16_int8");
10062
10063                         if (nanSupported)
10064                         {
10065                                 extensions.push_back("VK_KHR_shader_float_controls");
10066
10067                                 features.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat16 = DE_TRUE;
10068                         }
10069
10070                         features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10071                         features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10072
10073                         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10074                 }
10075         }
10076         { // vector cases
10077                 const StringTemplate preMain
10078                 (
10079                         "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10080                         "     %v2bool = OpTypeVector %bool 2\n"
10081                         "        %f16 = OpTypeFloat 16\n"
10082                         "    %c_f16_0 = OpConstant %f16 0.0\n"
10083                         "    %c_f16_1 = OpConstant %f16 1.0\n"
10084                         "      %v2f16 = OpTypeVector %f16 2\n"
10085                         "%c_v2f16_0_0 = OpConstantComposite %v2f16 %c_f16_0 %c_f16_0\n"
10086                         "%c_v2f16_1_1 = OpConstantComposite %v2f16 %c_f16_1 %c_f16_1\n"
10087                         "   %up_v2f16 = OpTypePointer Uniform %v2f16\n"
10088                         "   %ra_v2f16 = OpTypeArray %v2f16 %c_i32_ndp\n"
10089                         "     %SSBO16 = OpTypeStruct %ra_v2f16\n"
10090                         "  %up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10091                         "  %ssbo_src0 = OpVariable %up_SSBO16 Uniform\n"
10092                         "  %ssbo_src1 = OpVariable %up_SSBO16 Uniform\n"
10093                         "   %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10094                 );
10095
10096                 const StringTemplate decoration
10097                 (
10098                         "OpDecorate %ra_v2f16 ArrayStride 4\n"
10099                         "OpMemberDecorate %SSBO16 0 Offset 0\n"
10100                         "OpDecorate %SSBO16 BufferBlock\n"
10101                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
10102                         "OpDecorate %ssbo_src0 Binding 0\n"
10103                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
10104                         "OpDecorate %ssbo_src1 Binding 1\n"
10105                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
10106                         "OpDecorate %ssbo_dst Binding 2\n"
10107                 );
10108
10109                 const StringTemplate testFun
10110                 (
10111                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10112                         "    %param = OpFunctionParameter %v4f32\n"
10113
10114                         "    %entry = OpLabel\n"
10115                         "        %i = OpVariable %fp_i32 Function\n"
10116                         "             OpStore %i %c_i32_0\n"
10117                         "             OpBranch %loop\n"
10118
10119                         "     %loop = OpLabel\n"
10120                         "    %i_cmp = OpLoad %i32 %i\n"
10121                         "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10122                         "             OpLoopMerge %merge %next None\n"
10123                         "             OpBranchConditional %lt %write %merge\n"
10124
10125                         "    %write = OpLabel\n"
10126                         "      %ndx = OpLoad %i32 %i\n"
10127
10128                         "     %src0 = OpAccessChain %up_v2f16 %ssbo_src0 %c_i32_0 %ndx\n"
10129                         " %val_src0 = OpLoad %v2f16 %src0\n"
10130
10131                         "${op_arg1_calc}"
10132
10133                         " %val_bdst = ${op_code} %v2bool %val_src0 ${op_arg1}\n"
10134                         "  %val_dst = OpSelect %v2f16 %val_bdst %c_v2f16_1_1 %c_v2f16_0_0\n"
10135                         "      %dst = OpAccessChain %up_v2f16 %ssbo_dst %c_i32_0 %ndx\n"
10136                         "             OpStore %dst %val_dst\n"
10137                         "             OpBranch %next\n"
10138
10139                         "     %next = OpLabel\n"
10140                         "    %i_cur = OpLoad %i32 %i\n"
10141                         "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10142                         "             OpStore %i %i_new\n"
10143                         "             OpBranch %loop\n"
10144
10145                         "    %merge = OpLabel\n"
10146                         "             OpReturnValue %param\n"
10147
10148                         "             OpFunctionEnd\n"
10149                 );
10150
10151                 const StringTemplate arg1Calc
10152                 (
10153                         "     %src1 = OpAccessChain %up_v2f16 %ssbo_src1 %c_i32_0 %ndx\n"
10154                         " %val_src1 = OpLoad %v2f16 %src1\n"
10155                 );
10156
10157                 for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10158                 {
10159                         const deUint32          itemsPerVec     = 2;
10160                         const size_t            iterations      = float16DataVec1.size() / itemsPerVec;
10161                         const TestOp&           testOp          = testOps[testOpsIdx];
10162                         const string            testName        = de::toLower(string(testOp.opCode)) + "_vector";
10163                         SpecResource            specResource;
10164                         map<string, string>     specs;
10165                         vector<string>          extensions;
10166                         VulkanFeatures          features;
10167                         map<string, string>     fragments;
10168
10169                         specs["num_data_points"]        = de::toString(iterations);
10170                         specs["op_code"]                        = testOp.opCode;
10171                         specs["op_arg1"]                        = (testOp.argCount == 1) ? "" : "%val_src1";
10172                         specs["op_arg1_calc"]           = (testOp.argCount == 1) ? "" : arg1Calc.specialize(specs);
10173
10174                         fragments["extension"]          = spvExtensions;
10175                         fragments["capability"]         = spvCapabilities;
10176                         fragments["execution_mode"]     = spvExecutionMode;
10177                         fragments["decoration"]         = decoration.specialize(specs);
10178                         fragments["pre_main"]           = preMain.specialize(specs);
10179                         fragments["testfun"]            = testFun.specialize(specs);
10180
10181                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16DataVec1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10182                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16DataVec2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10183                         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutVecDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10184                         specResource.verifyIO = nanSupported ? testOp.verifyFuncNan : testOp.verifyFuncNonNan;
10185
10186                         extensions.push_back("VK_KHR_16bit_storage");
10187                         extensions.push_back("VK_KHR_shader_float16_int8");
10188
10189                         if (nanSupported)
10190                         {
10191                                 extensions.push_back("VK_KHR_shader_float_controls");
10192
10193                                 features.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat16 = DE_TRUE;
10194                         }
10195
10196                         features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10197                         features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10198
10199                         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10200                 }
10201         }
10202
10203         return testGroup.release();
10204 }
10205
10206 bool compareFP16FunctionSetFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10207 {
10208         if (inputs.size() != 1 || outputAllocs.size() != 1)
10209                 return false;
10210
10211         vector<deUint8> input1Bytes;
10212
10213         inputs[0].getBytes(input1Bytes);
10214
10215         const deUint16* const   input1AsFP16    = (const deUint16*)&input1Bytes[0];
10216         const deUint16* const   outputAsFP16    = (const deUint16*)outputAllocs[0]->getHostPtr();
10217         std::string                             error;
10218
10219         for (size_t idx = 0; idx < input1Bytes.size() / sizeof(deUint16); ++idx)
10220         {
10221                 if (!compare16BitFloat(input1AsFP16[idx], outputAsFP16[idx], error))
10222                 {
10223                         log << TestLog::Message << error << TestLog::EndMessage;
10224
10225                         return false;
10226                 }
10227         }
10228
10229         return true;
10230 }
10231
10232 template<class SpecResource>
10233 tcu::TestCaseGroup* createFloat16FuncSet (tcu::TestContext& testCtx)
10234 {
10235         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "function", "Float 16 function call related tests"));
10236
10237         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10238         const StringTemplate                            capabilities            ("OpCapability ${cap}\n");
10239         const deUint32                                          numDataPoints           = 256;
10240         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
10241         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
10242         map<string, string>                                     fragments;
10243
10244         struct TestType
10245         {
10246                 const deUint32  typeComponents;
10247                 const char*             typeName;
10248                 const char*             typeDecls;
10249         };
10250
10251         const TestType  testTypes[]     =
10252         {
10253                 {
10254                         1,
10255                         "f16",
10256                         ""
10257                 },
10258                 {
10259                         2,
10260                         "v2f16",
10261                         "      %v2f16 = OpTypeVector %f16 2\n"
10262                         "  %c_v2f16_0 = OpConstantComposite %v2f16 %c_f16_0 %c_f16_0\n"
10263                 },
10264                 {
10265                         4,
10266                         "v4f16",
10267                         "      %v4f16 = OpTypeVector %f16 4\n"
10268                         "  %c_v4f16_0 = OpConstantComposite %v4f16 %c_f16_0 %c_f16_0 %c_f16_0 %c_f16_0\n"
10269                 },
10270         };
10271
10272         const StringTemplate preMain
10273         (
10274                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10275                 "     %v2bool = OpTypeVector %bool 2\n"
10276                 "        %f16 = OpTypeFloat 16\n"
10277                 "    %c_f16_0 = OpConstant %f16 0.0\n"
10278
10279                 "${type_decls}"
10280
10281                 "  %${tt}_fun = OpTypeFunction %${tt} %${tt}\n"
10282                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
10283                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10284                 "     %SSBO16 = OpTypeStruct %ra_${tt}\n"
10285                 "  %up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10286                 "   %ssbo_src = OpVariable %up_SSBO16 Uniform\n"
10287                 "   %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10288         );
10289
10290         const StringTemplate decoration
10291         (
10292                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10293                 "OpMemberDecorate %SSBO16 0 Offset 0\n"
10294                 "OpDecorate %SSBO16 BufferBlock\n"
10295                 "OpDecorate %ssbo_src DescriptorSet 0\n"
10296                 "OpDecorate %ssbo_src Binding 0\n"
10297                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
10298                 "OpDecorate %ssbo_dst Binding 1\n"
10299         );
10300
10301         const StringTemplate testFun
10302         (
10303                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10304                 "    %param = OpFunctionParameter %v4f32\n"
10305                 "    %entry = OpLabel\n"
10306
10307                 "        %i = OpVariable %fp_i32 Function\n"
10308                 "             OpStore %i %c_i32_0\n"
10309                 "             OpBranch %loop\n"
10310
10311                 "     %loop = OpLabel\n"
10312                 "    %i_cmp = OpLoad %i32 %i\n"
10313                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10314                 "             OpLoopMerge %merge %next None\n"
10315                 "             OpBranchConditional %lt %write %merge\n"
10316
10317                 "    %write = OpLabel\n"
10318                 "      %ndx = OpLoad %i32 %i\n"
10319
10320                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10321                 "  %val_src = OpLoad %${tt} %src\n"
10322
10323                 "  %val_dst = OpFunctionCall %${tt} %pass_fun %val_src\n"
10324                 "      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
10325                 "             OpStore %dst %val_dst\n"
10326                 "             OpBranch %next\n"
10327
10328                 "     %next = OpLabel\n"
10329                 "    %i_cur = OpLoad %i32 %i\n"
10330                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10331                 "             OpStore %i %i_new\n"
10332                 "             OpBranch %loop\n"
10333
10334                 "    %merge = OpLabel\n"
10335                 "             OpReturnValue %param\n"
10336
10337                 "             OpFunctionEnd\n"
10338
10339                 " %pass_fun = OpFunction %${tt} None %${tt}_fun\n"
10340                 "   %param0 = OpFunctionParameter %${tt}\n"
10341                 " %entry_pf = OpLabel\n"
10342                 "     %res0 = OpFAdd %${tt} %param0 %c_${tt}_0\n"
10343                 "             OpReturnValue %res0\n"
10344                 "             OpFunctionEnd\n"
10345         );
10346
10347         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
10348         {
10349                 const TestType&         testType                = testTypes[testTypeIdx];
10350                 const string            testName                = testType.typeName;
10351                 const deUint32          itemsPerType    = testType.typeComponents;
10352                 const size_t            iterations              = float16InputData.size() / itemsPerType;
10353                 const size_t            typeStride              = itemsPerType * sizeof(deFloat16);
10354                 SpecResource            specResource;
10355                 map<string, string>     specs;
10356                 VulkanFeatures          features;
10357                 vector<string>          extensions;
10358
10359                 specs["cap"]                            = "StorageUniformBufferBlock16";
10360                 specs["num_data_points"]        = de::toString(iterations);
10361                 specs["tt"]                                     = testType.typeName;
10362                 specs["tt_stride"]                      = de::toString(typeStride);
10363                 specs["type_decls"]                     = testType.typeDecls;
10364
10365                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
10366                 fragments["capability"]         = capabilities.specialize(specs);
10367                 fragments["decoration"]         = decoration.specialize(specs);
10368                 fragments["pre_main"]           = preMain.specialize(specs);
10369                 fragments["testfun"]            = testFun.specialize(specs);
10370
10371                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10372                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10373                 specResource.verifyIO = compareFP16FunctionSetFunc;
10374
10375                 extensions.push_back("VK_KHR_16bit_storage");
10376                 extensions.push_back("VK_KHR_shader_float16_int8");
10377
10378                 features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10379                 features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10380
10381                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10382         }
10383
10384         return testGroup.release();
10385 }
10386
10387 struct getV_    { deUint32 inline operator()(deUint32 v) const  { return v;        } getV_(){} };
10388 struct getV0    { deUint32 inline operator()(deUint32 v) const  { return v & (~1); } getV0(){} };
10389 struct getV1    { deUint32 inline operator()(deUint32 v) const  { return v | ( 1); } getV1(){} };
10390
10391 template<deUint32 R, deUint32 N>
10392 inline static deUint32 getOffset(deUint32 x, deUint32 y, deUint32 n)
10393 {
10394         return N * ((R * y) + x) + n;
10395 }
10396
10397 template<deUint32 R, deUint32 N, class X0, class X1, class Y0, class Y1>
10398 struct getFDelta
10399 {
10400         float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10401         {
10402                 DE_STATIC_ASSERT(R%2 == 0);
10403                 DE_ASSERT(flavor == 0);
10404                 DE_UNREF(flavor);
10405
10406                 const X0                        x0;
10407                 const X1                        x1;
10408                 const Y0                        y0;
10409                 const Y1                        y1;
10410                 const deFloat16         v0      = data[getOffset<R, N>(x0(x), y0(y), n)];
10411                 const deFloat16         v1      = data[getOffset<R, N>(x1(x), y1(y), n)];
10412                 const tcu::Float16      f0      = tcu::Float16(v0);
10413                 const tcu::Float16      f1      = tcu::Float16(v1);
10414                 const float                     d0      = f0.asFloat();
10415                 const float                     d1      = f1.asFloat();
10416                 const float                     d       = d1 - d0;
10417
10418                 return d;
10419         }
10420
10421         getFDelta(){}
10422 };
10423
10424 template<deUint32 F, class Class0, class Class1>
10425 struct getFOneOf
10426 {
10427         float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10428         {
10429                 DE_ASSERT(flavor < F);
10430
10431                 if (flavor == 0)
10432                 {
10433                         Class0 c;
10434
10435                         return c(data, x, y, n, flavor);
10436                 }
10437                 else
10438                 {
10439                         Class1 c;
10440
10441                         return c(data, x, y, n, flavor - 1);
10442                 }
10443         }
10444
10445         getFOneOf(){}
10446 };
10447
10448 template<class FineX0, class FineX1, class FineY0, class FineY1>
10449 struct calcWidthOf4
10450 {
10451         float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10452         {
10453                 DE_ASSERT(flavor < 4);
10454
10455                 const deUint32                                          flavorX = (flavor & 1) == 0 ? 0 : 1;
10456                 const deUint32                                          flavorY = (flavor & 2) == 0 ? 0 : 1;
10457                 const getFOneOf<2, FineX0, FineX1>      cx;
10458                 const getFOneOf<2, FineY0, FineY1>      cy;
10459                 float                                                           v               = 0;
10460
10461                 v += fabsf(cx(data, x, y, n, flavorX));
10462                 v += fabsf(cy(data, x, y, n, flavorY));
10463
10464                 return v;
10465         }
10466
10467         calcWidthOf4(){}
10468 };
10469
10470 template<deUint32 R, deUint32 N, class Derivative>
10471 bool compareDerivativeWithFlavor (const deFloat16* inputAsFP16, const deFloat16* outputAsFP16, deUint32 flavor, std::string& error)
10472 {
10473         const deUint32          numDataPointsByAxis     = R;
10474         const Derivative        derivativeFunc;
10475
10476         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10477         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10478         for (deUint32 n = 0; n < N; ++n)
10479         {
10480                 const float             expectedFloat   = derivativeFunc(inputAsFP16, x, y, n, flavor);
10481                 deFloat16               expected                = deFloat32To16Round(expectedFloat, DE_ROUNDINGMODE_TO_NEAREST_EVEN);
10482                 const deFloat16 output                  = outputAsFP16[getOffset<R, N>(x, y, n)];
10483
10484                 bool                    reportError             = !compare16BitFloat(expected, output, error);
10485
10486                 if (reportError)
10487                 {
10488                         expected        = deFloat32To16Round(expectedFloat, DE_ROUNDINGMODE_TO_ZERO);
10489                         reportError     = !compare16BitFloat(expected, output, error);
10490                 }
10491
10492                 if (reportError)
10493                 {
10494                         error = "subcase at " + de::toString(x) + "," + de::toString(y) + "," + de::toString(n) + ": " + error;
10495
10496                         return false;
10497                 }
10498         }
10499
10500         return true;
10501 }
10502
10503 template<deUint32 R, deUint32 N, deUint32 FLAVOUR_COUNT, class Derivative>
10504 bool compareDerivative (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10505 {
10506         if (inputs.size() != 1 || outputAllocs.size() != 1)
10507                 return false;
10508
10509         deUint32                        successfulRuns                  = FLAVOUR_COUNT;
10510         std::string                     results[FLAVOUR_COUNT];
10511         vector<deUint8>         inputBytes;
10512
10513         inputs[0].getBytes(inputBytes);
10514
10515         const deFloat16*        inputAsFP16             = reinterpret_cast<deFloat16* const>(&inputBytes.front());
10516         const deFloat16*        outputAsFP16    = static_cast<deFloat16*>(outputAllocs[0]->getHostPtr());
10517
10518         DE_ASSERT(inputBytes.size() ==  R * R * N * sizeof(deFloat16));
10519
10520         for (deUint32 flavor = 0; flavor < FLAVOUR_COUNT; ++flavor)
10521                 if (compareDerivativeWithFlavor<R, N, Derivative> (inputAsFP16, outputAsFP16, flavor, results[flavor]))
10522                 {
10523                         break;
10524                 }
10525                 else
10526                 {
10527                         successfulRuns--;
10528                 }
10529
10530         if (successfulRuns == 0)
10531                 for (deUint32 flavor = 0; flavor < FLAVOUR_COUNT; flavor++)
10532                         log << TestLog::Message << "At flavor #" << flavor << " " << results[flavor] << TestLog::EndMessage;
10533
10534         return successfulRuns > 0;
10535 }
10536
10537 template<deUint32 R, deUint32 N>
10538 tcu::TestCaseGroup* createDerivativeTests (tcu::TestContext& testCtx)
10539 {
10540         typedef getFDelta<R, N, getV0, getV1, getV_, getV_> getFDxFine;
10541         typedef getFDelta<R, N, getV_, getV_, getV0, getV1> getFDyFine;
10542
10543         typedef getFDelta<R, N, getV0, getV1, getV0, getV0> getFdxCoarse0;
10544         typedef getFDelta<R, N, getV0, getV1, getV1, getV1> getFdxCoarse1;
10545         typedef getFDelta<R, N, getV0, getV0, getV0, getV1> getFdyCoarse0;
10546         typedef getFDelta<R, N, getV1, getV1, getV0, getV1> getFdyCoarse1;
10547         typedef getFOneOf<2, getFdxCoarse0, getFdxCoarse1> getFDxCoarse;
10548         typedef getFOneOf<2, getFdyCoarse0, getFdyCoarse1> getFDyCoarse;
10549
10550         typedef calcWidthOf4<getFDxFine, getFDxFine, getFDyFine, getFDyFine> getFWidthFine;
10551         typedef calcWidthOf4<getFdxCoarse0, getFdxCoarse1, getFdyCoarse0, getFdyCoarse1> getFWidthCoarse;
10552
10553         typedef getFOneOf<3, getFDxFine, getFDxCoarse> getFDx;
10554         typedef getFOneOf<3, getFDyFine, getFDyCoarse> getFDy;
10555         typedef getFOneOf<5, getFWidthFine, getFWidthCoarse> getFWidth;
10556
10557         const std::string                                       testGroupName           (std::string("derivative_") + de::toString(N));
10558         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Derivative instruction tests"));
10559
10560         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10561         const deUint32                                          numDataPointsByAxis     = R;
10562         const deUint32                                          numDataPoints           = N * numDataPointsByAxis * numDataPointsByAxis;
10563         vector<deFloat16>                                       float16InputX;
10564         vector<deFloat16>                                       float16InputY;
10565         vector<deFloat16>                                       float16InputW;
10566         vector<deFloat16>                                       float16OutputDummy      (numDataPoints, 0);
10567         RGBA                                                            defaultColors[4];
10568
10569         getDefaultColors(defaultColors);
10570
10571         float16InputX.reserve(numDataPoints);
10572         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10573         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10574         for (deUint32 n = 0; n < N; ++n)
10575         {
10576                 const float arg = static_cast<float>(2 * DE_PI) * static_cast<float>(x * (n + 1)) / static_cast<float>(1 * numDataPointsByAxis);
10577
10578                 if (y%2 == 0)
10579                         float16InputX.push_back(tcu::Float16(sin(arg)).bits());
10580                 else
10581                         float16InputX.push_back(tcu::Float16(cos(arg)).bits());
10582         }
10583
10584         float16InputY.reserve(numDataPoints);
10585         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10586         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10587         for (deUint32 n = 0; n < N; ++n)
10588         {
10589                 const float arg = static_cast<float>(2 * DE_PI) * static_cast<float>(y * (n + 1)) / static_cast<float>(1 * numDataPointsByAxis);
10590
10591                 if (x%2 == 0)
10592                         float16InputY.push_back(tcu::Float16(sin(arg)).bits());
10593                 else
10594                         float16InputY.push_back(tcu::Float16(cos(arg)).bits());
10595         }
10596
10597         const deFloat16 testNumbers[]   =
10598         {
10599                 tcu::Float16( 2.0  ).bits(),
10600                 tcu::Float16( 4.0  ).bits(),
10601                 tcu::Float16( 8.0  ).bits(),
10602                 tcu::Float16( 16.0 ).bits(),
10603                 tcu::Float16( 32.0 ).bits(),
10604                 tcu::Float16( 64.0 ).bits(),
10605                 tcu::Float16( 128.0).bits(),
10606                 tcu::Float16( 256.0).bits(),
10607                 tcu::Float16( 512.0).bits(),
10608                 tcu::Float16(-2.0  ).bits(),
10609                 tcu::Float16(-4.0  ).bits(),
10610                 tcu::Float16(-8.0  ).bits(),
10611                 tcu::Float16(-16.0 ).bits(),
10612                 tcu::Float16(-32.0 ).bits(),
10613                 tcu::Float16(-64.0 ).bits(),
10614                 tcu::Float16(-128.0).bits(),
10615                 tcu::Float16(-256.0).bits(),
10616                 tcu::Float16(-512.0).bits(),
10617         };
10618
10619         float16InputW.reserve(numDataPoints);
10620         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10621         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10622         for (deUint32 n = 0; n < N; ++n)
10623                 float16InputW.push_back(testNumbers[rnd.getInt(0, DE_LENGTH_OF_ARRAY(testNumbers) - 1)]);
10624
10625         struct TestOp
10626         {
10627                 const char*                     opCode;
10628                 vector<deFloat16>&      inputData;
10629                 VerifyIOFunc            verifyFunc;
10630         };
10631
10632         const TestOp    testOps[]       =
10633         {
10634                 { "OpDPdxFine"          ,       float16InputX   ,       compareDerivative<R, N, 1, getFDxFine           >       },
10635                 { "OpDPdyFine"          ,       float16InputY   ,       compareDerivative<R, N, 1, getFDyFine           >       },
10636                 { "OpFwidthFine"        ,       float16InputW   ,       compareDerivative<R, N, 1, getFWidthFine        >       },
10637                 { "OpDPdxCoarse"        ,       float16InputX   ,       compareDerivative<R, N, 3, getFDx                       >       },
10638                 { "OpDPdyCoarse"        ,       float16InputY   ,       compareDerivative<R, N, 3, getFDy                       >       },
10639                 { "OpFwidthCoarse"      ,       float16InputW   ,       compareDerivative<R, N, 5, getFWidth            >       },
10640                 { "OpDPdx"                      ,       float16InputX   ,       compareDerivative<R, N, 3, getFDx                       >       },
10641                 { "OpDPdy"                      ,       float16InputY   ,       compareDerivative<R, N, 3, getFDy                       >       },
10642                 { "OpFwidth"            ,       float16InputW   ,       compareDerivative<R, N, 5, getFWidth            >       },
10643         };
10644
10645         struct TestType
10646         {
10647                 const deUint32  typeComponents;
10648                 const char*             typeName;
10649                 const char*             typeDecls;
10650         };
10651
10652         const TestType  testTypes[]     =
10653         {
10654                 {
10655                         1,
10656                         "f16",
10657                         ""
10658                 },
10659                 {
10660                         2,
10661                         "v2f16",
10662                         "      %v2f16 = OpTypeVector %f16 2\n"
10663                 },
10664                 {
10665                         4,
10666                         "v4f16",
10667                         "      %v4f16 = OpTypeVector %f16 4\n"
10668                 },
10669         };
10670
10671         const deUint32  testTypeNdx     = (N == 1) ? 0
10672                                                                 : (N == 2) ? 1
10673                                                                 : (N == 4) ? 2
10674                                                                 : DE_LENGTH_OF_ARRAY(testTypes);
10675         const TestType& testType        =       testTypes[testTypeNdx];
10676
10677         DE_ASSERT(testTypeNdx < DE_LENGTH_OF_ARRAY(testTypes));
10678         DE_ASSERT(testType.typeComponents == N);
10679
10680         const StringTemplate preMain
10681         (
10682                 "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10683                 " %c_u32_xw = OpConstant %u32 ${items_by_x}\n"
10684                 "      %f16 = OpTypeFloat 16\n"
10685                 "${type_decls}"
10686                 " %up_${tt} = OpTypePointer Uniform %${tt}\n"
10687                 " %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10688                 "   %SSBO16 = OpTypeStruct %ra_${tt}\n"
10689                 "%up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10690                 " %ssbo_src = OpVariable %up_SSBO16 Uniform\n"
10691                 " %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10692         );
10693
10694         const StringTemplate decoration
10695         (
10696                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10697                 "OpMemberDecorate %SSBO16 0 Offset 0\n"
10698                 "OpDecorate %SSBO16 BufferBlock\n"
10699                 "OpDecorate %ssbo_src DescriptorSet 0\n"
10700                 "OpDecorate %ssbo_src Binding 0\n"
10701                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
10702                 "OpDecorate %ssbo_dst Binding 1\n"
10703         );
10704
10705         const StringTemplate testFun
10706         (
10707                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10708                 "    %param = OpFunctionParameter %v4f32\n"
10709                 "    %entry = OpLabel\n"
10710
10711                 "  %loc_x_c = OpAccessChain %ip_f32 %BP_gl_FragCoord %c_i32_0\n"
10712                 "  %loc_y_c = OpAccessChain %ip_f32 %BP_gl_FragCoord %c_i32_1\n"
10713                 "      %x_c = OpLoad %f32 %loc_x_c\n"
10714                 "      %y_c = OpLoad %f32 %loc_y_c\n"
10715                 "    %x_idx = OpConvertFToU %u32 %x_c\n"
10716                 "    %y_idx = OpConvertFToU %u32 %y_c\n"
10717                 "    %ndx_y = OpIMul %u32 %y_idx %c_u32_xw\n"
10718                 "      %ndx = OpIAdd %u32 %ndx_y %x_idx\n"
10719
10720                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10721                 "  %val_src = OpLoad %${tt} %src\n"
10722                 "  %val_dst = ${op_code} %${tt} %val_src\n"
10723                 "      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
10724                 "             OpStore %dst %val_dst\n"
10725                 "             OpBranch %merge\n"
10726
10727                 "    %merge = OpLabel\n"
10728                 "             OpReturnValue %param\n"
10729
10730                 "             OpFunctionEnd\n"
10731         );
10732
10733         for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10734         {
10735                 const TestOp&           testOp                  = testOps[testOpsIdx];
10736                 const string            testName                = de::toLower(string(testOp.opCode));
10737                 const size_t            typeStride              = N * sizeof(deFloat16);
10738                 GraphicsResources       specResource;
10739                 map<string, string>     specs;
10740                 VulkanFeatures          features;
10741                 vector<string>          extensions;
10742                 map<string, string>     fragments;
10743                 SpecConstants           noSpecConstants;
10744                 PushConstants           noPushConstants;
10745                 GraphicsInterfaces      noInterfaces;
10746
10747                 specs["op_code"]                        = testOp.opCode;
10748                 specs["num_data_points"]        = de::toString(testOp.inputData.size() / N);
10749                 specs["items_by_x"]                     = de::toString(numDataPointsByAxis);
10750                 specs["tt"]                                     = testType.typeName;
10751                 specs["tt_stride"]                      = de::toString(typeStride);
10752                 specs["type_decls"]                     = testType.typeDecls;
10753
10754                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
10755                 fragments["capability"]         = "OpCapability DerivativeControl\nOpCapability StorageUniformBufferBlock16\n";
10756                 fragments["decoration"]         = decoration.specialize(specs);
10757                 fragments["pre_main"]           = preMain.specialize(specs);
10758                 fragments["testfun"]            = testFun.specialize(specs);
10759
10760                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(testOp.inputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10761                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10762                 specResource.verifyIO = testOp.verifyFunc;
10763
10764                 extensions.push_back("VK_KHR_16bit_storage");
10765                 extensions.push_back("VK_KHR_shader_float16_int8");
10766
10767                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
10768                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10769
10770                 createTestForStage(VK_SHADER_STAGE_FRAGMENT_BIT, testName.c_str(), defaultColors, defaultColors, fragments, noSpecConstants,
10771                                                         noPushConstants, specResource, noInterfaces, extensions, features, testGroup.get(), QP_TEST_RESULT_FAIL, string(), true);
10772         }
10773
10774         return testGroup.release();
10775 }
10776
10777 bool compareFP16VectorExtractFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10778 {
10779         if (inputs.size() != 2 || outputAllocs.size() != 1)
10780                 return false;
10781
10782         vector<deUint8> input1Bytes;
10783         vector<deUint8> input2Bytes;
10784
10785         inputs[0].getBytes(input1Bytes);
10786         inputs[1].getBytes(input2Bytes);
10787
10788         DE_ASSERT(input1Bytes.size() > 0);
10789         DE_ASSERT(input2Bytes.size() > 0);
10790         DE_ASSERT(input2Bytes.size() % sizeof(deUint32) == 0);
10791
10792         const size_t                    iterations              = input2Bytes.size() / sizeof(deUint32);
10793         const size_t                    components              = input1Bytes.size() / (sizeof(deFloat16) * iterations);
10794         const deFloat16* const  input1AsFP16    = (const deFloat16*)&input1Bytes[0];
10795         const deUint32* const   inputIndices    = (const deUint32*)&input2Bytes[0];
10796         const deFloat16* const  outputAsFP16    = (const deFloat16*)outputAllocs[0]->getHostPtr();
10797         std::string                             error;
10798
10799         DE_ASSERT(components == 2 || components == 4);
10800         DE_ASSERT(input1Bytes.size() == iterations * components * sizeof(deFloat16));
10801
10802         for (size_t idx = 0; idx < iterations; ++idx)
10803         {
10804                 const deUint32  componentNdx    = inputIndices[idx];
10805
10806                 DE_ASSERT(componentNdx < components);
10807
10808                 const deFloat16 expected                = input1AsFP16[components * idx + componentNdx];
10809
10810                 if (!compare16BitFloat(expected, outputAsFP16[idx], error))
10811                 {
10812                         log << TestLog::Message << "At " << idx << error << TestLog::EndMessage;
10813
10814                         return false;
10815                 }
10816         }
10817
10818         return true;
10819 }
10820
10821 template<class SpecResource>
10822 tcu::TestCaseGroup* createFloat16VectorExtractSet (tcu::TestContext& testCtx)
10823 {
10824         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorextractdynamic", "OpVectorExtractDynamic tests"));
10825
10826         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10827         const deUint32                                          numDataPoints           = 256;
10828         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
10829         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
10830
10831         struct TestType
10832         {
10833                 const deUint32  typeComponents;
10834                 const size_t    typeStride;
10835                 const char*             typeName;
10836                 const char*             typeDecls;
10837         };
10838
10839         const TestType  testTypes[]     =
10840         {
10841                 {
10842                         2,
10843                         2 * sizeof(deFloat16),
10844                         "v2f16",
10845                         "      %v2f16 = OpTypeVector %f16 2\n"
10846                 },
10847                 {
10848                         3,
10849                         4 * sizeof(deFloat16),
10850                         "v3f16",
10851                         "      %v3f16 = OpTypeVector %f16 3\n"
10852                 },
10853                 {
10854                         4,
10855                         4 * sizeof(deFloat16),
10856                         "v4f16",
10857                         "      %v4f16 = OpTypeVector %f16 4\n"
10858                 },
10859         };
10860
10861         const StringTemplate preMain
10862         (
10863                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10864                 "        %f16 = OpTypeFloat 16\n"
10865
10866                 "${type_decl}"
10867
10868                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
10869                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10870                 "   %SSBO_SRC = OpTypeStruct %ra_${tt}\n"
10871                 "%up_SSBO_SRC = OpTypePointer Uniform %SSBO_SRC\n"
10872
10873                 "     %up_u32 = OpTypePointer Uniform %u32\n"
10874                 "     %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
10875                 "   %SSBO_IDX = OpTypeStruct %ra_u32\n"
10876                 "%up_SSBO_IDX = OpTypePointer Uniform %SSBO_IDX\n"
10877
10878                 "     %up_f16 = OpTypePointer Uniform %f16\n"
10879                 "     %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
10880                 "   %SSBO_DST = OpTypeStruct %ra_f16\n"
10881                 "%up_SSBO_DST = OpTypePointer Uniform %SSBO_DST\n"
10882
10883                 "   %ssbo_src = OpVariable %up_SSBO_SRC Uniform\n"
10884                 "   %ssbo_idx = OpVariable %up_SSBO_IDX Uniform\n"
10885                 "   %ssbo_dst = OpVariable %up_SSBO_DST Uniform\n"
10886         );
10887
10888         const StringTemplate decoration
10889         (
10890                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10891                 "OpMemberDecorate %SSBO_SRC 0 Offset 0\n"
10892                 "OpDecorate %SSBO_SRC BufferBlock\n"
10893                 "OpDecorate %ssbo_src DescriptorSet 0\n"
10894                 "OpDecorate %ssbo_src Binding 0\n"
10895
10896                 "OpDecorate %ra_u32 ArrayStride 4\n"
10897                 "OpMemberDecorate %SSBO_IDX 0 Offset 0\n"
10898                 "OpDecorate %SSBO_IDX BufferBlock\n"
10899                 "OpDecorate %ssbo_idx DescriptorSet 0\n"
10900                 "OpDecorate %ssbo_idx Binding 1\n"
10901
10902                 "OpDecorate %ra_f16 ArrayStride 2\n"
10903                 "OpMemberDecorate %SSBO_DST 0 Offset 0\n"
10904                 "OpDecorate %SSBO_DST BufferBlock\n"
10905                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
10906                 "OpDecorate %ssbo_dst Binding 2\n"
10907         );
10908
10909         const StringTemplate testFun
10910         (
10911                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10912                 "    %param = OpFunctionParameter %v4f32\n"
10913                 "    %entry = OpLabel\n"
10914
10915                 "        %i = OpVariable %fp_i32 Function\n"
10916                 "             OpStore %i %c_i32_0\n"
10917
10918                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
10919                 "             OpSelectionMerge %end_if None\n"
10920                 "             OpBranchConditional %will_run %run_test %end_if\n"
10921
10922                 " %run_test = OpLabel\n"
10923                 "             OpBranch %loop\n"
10924
10925                 "     %loop = OpLabel\n"
10926                 "    %i_cmp = OpLoad %i32 %i\n"
10927                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10928                 "             OpLoopMerge %merge %next None\n"
10929                 "             OpBranchConditional %lt %write %merge\n"
10930
10931                 "    %write = OpLabel\n"
10932                 "      %ndx = OpLoad %i32 %i\n"
10933
10934                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10935                 "  %val_src = OpLoad %${tt} %src\n"
10936
10937                 "  %src_idx = OpAccessChain %up_u32 %ssbo_idx %c_i32_0 %ndx\n"
10938                 "  %val_idx = OpLoad %u32 %src_idx\n"
10939
10940                 "  %val_dst = OpVectorExtractDynamic %f16 %val_src %val_idx\n"
10941                 "      %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
10942
10943                 "             OpStore %dst %val_dst\n"
10944                 "             OpBranch %next\n"
10945
10946                 "     %next = OpLabel\n"
10947                 "    %i_cur = OpLoad %i32 %i\n"
10948                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10949                 "             OpStore %i %i_new\n"
10950                 "             OpBranch %loop\n"
10951
10952                 "    %merge = OpLabel\n"
10953                 "             OpBranch %end_if\n"
10954                 "   %end_if = OpLabel\n"
10955                 "             OpReturnValue %param\n"
10956
10957                 "             OpFunctionEnd\n"
10958         );
10959
10960         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
10961         {
10962                 const TestType&         testType                = testTypes[testTypeIdx];
10963                 const string            testName                = testType.typeName;
10964                 const size_t            itemsPerType    = testType.typeStride / sizeof(deFloat16);
10965                 const size_t            iterations              = float16InputData.size() / itemsPerType;
10966                 SpecResource            specResource;
10967                 map<string, string>     specs;
10968                 VulkanFeatures          features;
10969                 vector<deUint32>        inputDataNdx;
10970                 map<string, string>     fragments;
10971                 vector<string>          extensions;
10972
10973                 for (deUint32 ndx = 0; ndx < iterations; ++ndx)
10974                         inputDataNdx.push_back(rnd.getUint32() % testType.typeComponents);
10975
10976                 specs["num_data_points"]        = de::toString(iterations);
10977                 specs["tt"]                                     = testType.typeName;
10978                 specs["tt_stride"]                      = de::toString(testType.typeStride);
10979                 specs["type_decl"]                      = testType.typeDecls;
10980
10981                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
10982                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
10983                 fragments["decoration"]         = decoration.specialize(specs);
10984                 fragments["pre_main"]           = preMain.specialize(specs);
10985                 fragments["testfun"]            = testFun.specialize(specs);
10986
10987                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10988                 specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inputDataNdx)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10989                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10990                 specResource.verifyIO = compareFP16VectorExtractFunc;
10991
10992                 extensions.push_back("VK_KHR_16bit_storage");
10993                 extensions.push_back("VK_KHR_shader_float16_int8");
10994
10995                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
10996                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10997
10998                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10999         }
11000
11001         return testGroup.release();
11002 }
11003
11004 template<deUint32 COMPONENTS_COUNT, deUint32 REPLACEMENT>
11005 bool compareFP16VectorInsertFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11006 {
11007         if (inputs.size() != 2 || outputAllocs.size() != 1)
11008                 return false;
11009
11010         vector<deUint8> input1Bytes;
11011         vector<deUint8> input2Bytes;
11012
11013         inputs[0].getBytes(input1Bytes);
11014         inputs[1].getBytes(input2Bytes);
11015
11016         DE_ASSERT(input1Bytes.size() > 0);
11017         DE_ASSERT(input2Bytes.size() > 0);
11018         DE_ASSERT(input2Bytes.size() % sizeof(deUint32) == 0);
11019
11020         const size_t                    iterations                      = input2Bytes.size() / sizeof(deUint32);
11021         const size_t                    componentsStride        = input1Bytes.size() / (sizeof(deFloat16) * iterations);
11022         const deFloat16* const  input1AsFP16            = (const deFloat16*)&input1Bytes[0];
11023         const deUint32* const   inputIndices            = (const deUint32*)&input2Bytes[0];
11024         const deFloat16* const  outputAsFP16            = (const deFloat16*)outputAllocs[0]->getHostPtr();
11025         const deFloat16                 magic                           = tcu::Float16(float(REPLACEMENT)).bits();
11026         std::string                             error;
11027
11028         DE_ASSERT(componentsStride == 2 || componentsStride == 4);
11029         DE_ASSERT(input1Bytes.size() == iterations * componentsStride * sizeof(deFloat16));
11030
11031         for (size_t idx = 0; idx < iterations; ++idx)
11032         {
11033                 const deFloat16*        inputVec                = &input1AsFP16[componentsStride * idx];
11034                 const deFloat16*        outputVec               = &outputAsFP16[componentsStride * idx];
11035                 const deUint32          replacedCompNdx = inputIndices[idx];
11036
11037                 DE_ASSERT(replacedCompNdx < COMPONENTS_COUNT);
11038
11039                 for (size_t compNdx = 0; compNdx < COMPONENTS_COUNT; ++compNdx)
11040                 {
11041                         const deFloat16 expected        = (compNdx == replacedCompNdx) ? magic : inputVec[compNdx];
11042
11043                         if (!compare16BitFloat(expected, outputVec[compNdx], error))
11044                         {
11045                                 log << TestLog::Message << "At " << idx << "[" << compNdx << "]: " << error << TestLog::EndMessage;
11046
11047                                 return false;
11048                         }
11049                 }
11050         }
11051
11052         return true;
11053 }
11054
11055 template<class SpecResource>
11056 tcu::TestCaseGroup* createFloat16VectorInsertSet (tcu::TestContext& testCtx)
11057 {
11058         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorinsertdynamic", "OpVectorInsertDynamic tests"));
11059
11060         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
11061         const deUint32                                          replacement                     = 42;
11062         const deUint32                                          numDataPoints           = 256;
11063         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
11064         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
11065
11066         struct TestType
11067         {
11068                 const deUint32  typeComponents;
11069                 const size_t    typeStride;
11070                 const char*             typeName;
11071                 const char*             typeDecls;
11072                 VerifyIOFunc    verifyIOFunc;
11073         };
11074
11075         const TestType  testTypes[]     =
11076         {
11077                 {
11078                         2,
11079                         2 * sizeof(deFloat16),
11080                         "v2f16",
11081                         "      %v2f16 = OpTypeVector %f16 2\n",
11082                         compareFP16VectorInsertFunc<2, replacement>
11083                 },
11084                 {
11085                         3,
11086                         4 * sizeof(deFloat16),
11087                         "v3f16",
11088                         "      %v3f16 = OpTypeVector %f16 3\n",
11089                         compareFP16VectorInsertFunc<3, replacement>
11090                 },
11091                 {
11092                         4,
11093                         4 * sizeof(deFloat16),
11094                         "v4f16",
11095                         "      %v4f16 = OpTypeVector %f16 4\n",
11096                         compareFP16VectorInsertFunc<4, replacement>
11097                 },
11098         };
11099
11100         const StringTemplate preMain
11101         (
11102                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
11103                 "        %f16 = OpTypeFloat 16\n"
11104                 "  %c_f16_ins = OpConstant %f16 ${replacement}\n"
11105
11106                 "${type_decl}"
11107
11108                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
11109                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
11110                 "   %SSBO_SRC = OpTypeStruct %ra_${tt}\n"
11111                 "%up_SSBO_SRC = OpTypePointer Uniform %SSBO_SRC\n"
11112
11113                 "     %up_u32 = OpTypePointer Uniform %u32\n"
11114                 "     %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
11115                 "   %SSBO_IDX = OpTypeStruct %ra_u32\n"
11116                 "%up_SSBO_IDX = OpTypePointer Uniform %SSBO_IDX\n"
11117
11118                 "   %SSBO_DST = OpTypeStruct %ra_${tt}\n"
11119                 "%up_SSBO_DST = OpTypePointer Uniform %SSBO_DST\n"
11120
11121                 "   %ssbo_src = OpVariable %up_SSBO_SRC Uniform\n"
11122                 "   %ssbo_idx = OpVariable %up_SSBO_IDX Uniform\n"
11123                 "   %ssbo_dst = OpVariable %up_SSBO_DST Uniform\n"
11124         );
11125
11126         const StringTemplate decoration
11127         (
11128                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
11129                 "OpMemberDecorate %SSBO_SRC 0 Offset 0\n"
11130                 "OpDecorate %SSBO_SRC BufferBlock\n"
11131                 "OpDecorate %ssbo_src DescriptorSet 0\n"
11132                 "OpDecorate %ssbo_src Binding 0\n"
11133
11134                 "OpDecorate %ra_u32 ArrayStride 4\n"
11135                 "OpMemberDecorate %SSBO_IDX 0 Offset 0\n"
11136                 "OpDecorate %SSBO_IDX BufferBlock\n"
11137                 "OpDecorate %ssbo_idx DescriptorSet 0\n"
11138                 "OpDecorate %ssbo_idx Binding 1\n"
11139
11140                 "OpMemberDecorate %SSBO_DST 0 Offset 0\n"
11141                 "OpDecorate %SSBO_DST BufferBlock\n"
11142                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11143                 "OpDecorate %ssbo_dst Binding 2\n"
11144         );
11145
11146         const StringTemplate testFun
11147         (
11148                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11149                 "    %param = OpFunctionParameter %v4f32\n"
11150                 "    %entry = OpLabel\n"
11151
11152                 "        %i = OpVariable %fp_i32 Function\n"
11153                 "             OpStore %i %c_i32_0\n"
11154
11155                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11156                 "             OpSelectionMerge %end_if None\n"
11157                 "             OpBranchConditional %will_run %run_test %end_if\n"
11158
11159                 " %run_test = OpLabel\n"
11160                 "             OpBranch %loop\n"
11161
11162                 "     %loop = OpLabel\n"
11163                 "    %i_cmp = OpLoad %i32 %i\n"
11164                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11165                 "             OpLoopMerge %merge %next None\n"
11166                 "             OpBranchConditional %lt %write %merge\n"
11167
11168                 "    %write = OpLabel\n"
11169                 "      %ndx = OpLoad %i32 %i\n"
11170
11171                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
11172                 "  %val_src = OpLoad %${tt} %src\n"
11173
11174                 "  %src_idx = OpAccessChain %up_u32 %ssbo_idx %c_i32_0 %ndx\n"
11175                 "  %val_idx = OpLoad %u32 %src_idx\n"
11176
11177                 "  %val_dst = OpVectorInsertDynamic %${tt} %val_src %c_f16_ins %val_idx\n"
11178                 "      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
11179
11180                 "             OpStore %dst %val_dst\n"
11181                 "             OpBranch %next\n"
11182
11183                 "     %next = OpLabel\n"
11184                 "    %i_cur = OpLoad %i32 %i\n"
11185                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11186                 "             OpStore %i %i_new\n"
11187                 "             OpBranch %loop\n"
11188
11189                 "    %merge = OpLabel\n"
11190                 "             OpBranch %end_if\n"
11191                 "   %end_if = OpLabel\n"
11192                 "             OpReturnValue %param\n"
11193
11194                 "             OpFunctionEnd\n"
11195         );
11196
11197         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
11198         {
11199                 const TestType&         testType                = testTypes[testTypeIdx];
11200                 const string            testName                = testType.typeName;
11201                 const size_t            itemsPerType    = testType.typeStride / sizeof(deFloat16);
11202                 const size_t            iterations              = float16InputData.size() / itemsPerType;
11203                 SpecResource            specResource;
11204                 map<string, string>     specs;
11205                 VulkanFeatures          features;
11206                 vector<deUint32>        inputDataNdx;
11207                 map<string, string>     fragments;
11208                 vector<string>          extensions;
11209
11210                 for (deUint32 ndx = 0; ndx < iterations; ++ndx)
11211                         inputDataNdx.push_back(rnd.getUint32() % testType.typeComponents);
11212
11213                 specs["num_data_points"]        = de::toString(iterations);
11214                 specs["tt"]                                     = testType.typeName;
11215                 specs["tt_stride"]                      = de::toString(testType.typeStride);
11216                 specs["type_decl"]                      = testType.typeDecls;
11217                 specs["replacement"]            = de::toString(replacement);
11218
11219                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11220                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
11221                 fragments["decoration"]         = decoration.specialize(specs);
11222                 fragments["pre_main"]           = preMain.specialize(specs);
11223                 fragments["testfun"]            = testFun.specialize(specs);
11224
11225                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11226                 specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inputDataNdx)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11227                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11228                 specResource.verifyIO = testType.verifyIOFunc;
11229
11230                 extensions.push_back("VK_KHR_16bit_storage");
11231                 extensions.push_back("VK_KHR_shader_float16_int8");
11232
11233                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11234                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11235
11236                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11237         }
11238
11239         return testGroup.release();
11240 }
11241
11242 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)
11243 {
11244         const size_t    compNdxCount    = (vec1Len + vec2Len + 1);
11245         const size_t    compNdxLimited  = iteration % (compNdxCount * compNdxCount);
11246         size_t                  comp;
11247
11248         switch (componentNdx)
11249         {
11250                 case 0: comp = compNdxLimited / compNdxCount; break;
11251                 case 1: comp = compNdxLimited % compNdxCount; break;
11252                 case 2: comp = 0; break;
11253                 case 3: comp = 1; break;
11254                 default: TCU_THROW(InternalError, "Impossible");
11255         }
11256
11257         if (comp >= vec1Len + vec2Len)
11258         {
11259                 validate = false;
11260                 return 0;
11261         }
11262         else
11263         {
11264                 validate = true;
11265                 return (comp < vec1Len) ? input1Vec[comp] : input2Vec[comp - vec1Len];
11266         }
11267 }
11268
11269 template<deUint32 DST_COMPONENTS_COUNT, deUint32 SRC0_COMPONENTS_COUNT, deUint32 SRC1_COMPONENTS_COUNT>
11270 bool compareFP16VectorShuffleFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11271 {
11272         DE_STATIC_ASSERT(DST_COMPONENTS_COUNT == 2 || DST_COMPONENTS_COUNT == 3 || DST_COMPONENTS_COUNT == 4);
11273         DE_STATIC_ASSERT(SRC0_COMPONENTS_COUNT == 2 || SRC0_COMPONENTS_COUNT == 3 || SRC0_COMPONENTS_COUNT == 4);
11274         DE_STATIC_ASSERT(SRC1_COMPONENTS_COUNT == 2 || SRC1_COMPONENTS_COUNT == 3 || SRC1_COMPONENTS_COUNT == 4);
11275
11276         if (inputs.size() != 2 || outputAllocs.size() != 1)
11277                 return false;
11278
11279         vector<deUint8> input1Bytes;
11280         vector<deUint8> input2Bytes;
11281
11282         inputs[0].getBytes(input1Bytes);
11283         inputs[1].getBytes(input2Bytes);
11284
11285         DE_ASSERT(input1Bytes.size() > 0);
11286         DE_ASSERT(input2Bytes.size() > 0);
11287         DE_ASSERT(input2Bytes.size() % sizeof(deFloat16) == 0);
11288
11289         const size_t                    componentsStrideDst             = (DST_COMPONENTS_COUNT == 3) ? 4 : DST_COMPONENTS_COUNT;
11290         const size_t                    componentsStrideSrc0    = (SRC0_COMPONENTS_COUNT == 3) ? 4 : SRC0_COMPONENTS_COUNT;
11291         const size_t                    componentsStrideSrc1    = (SRC1_COMPONENTS_COUNT == 3) ? 4 : SRC1_COMPONENTS_COUNT;
11292         const size_t                    iterations                              = input1Bytes.size() / (componentsStrideSrc0 * sizeof(deFloat16));
11293         const deFloat16* const  input1AsFP16                    = (const deFloat16*)&input1Bytes[0];
11294         const deFloat16* const  input2AsFP16                    = (const deFloat16*)&input2Bytes[0];
11295         const deFloat16* const  outputAsFP16                    = (const deFloat16*)outputAllocs[0]->getHostPtr();
11296         std::string                             error;
11297
11298         DE_ASSERT(input1Bytes.size() == iterations * componentsStrideSrc0 * sizeof(deFloat16));
11299         DE_ASSERT(input2Bytes.size() == iterations * componentsStrideSrc1 * sizeof(deFloat16));
11300
11301         for (size_t idx = 0; idx < iterations; ++idx)
11302         {
11303                 const deFloat16*        input1Vec       = &input1AsFP16[componentsStrideSrc0 * idx];
11304                 const deFloat16*        input2Vec       = &input2AsFP16[componentsStrideSrc1 * idx];
11305                 const deFloat16*        outputVec       = &outputAsFP16[componentsStrideDst * idx];
11306
11307                 for (size_t compNdx = 0; compNdx < DST_COMPONENTS_COUNT; ++compNdx)
11308                 {
11309                         bool            validate        = true;
11310                         deFloat16       expected        = getShuffledComponent(idx, compNdx, input1Vec, input2Vec, SRC0_COMPONENTS_COUNT, SRC1_COMPONENTS_COUNT, validate);
11311
11312                         if (validate && !compare16BitFloat(expected, outputVec[compNdx], error))
11313                         {
11314                                 log << TestLog::Message << "At " << idx << "[" << compNdx << "]: " << error << TestLog::EndMessage;
11315
11316                                 return false;
11317                         }
11318                 }
11319         }
11320
11321         return true;
11322 }
11323
11324 VerifyIOFunc getFloat16VectorShuffleVerifyIOFunc (deUint32 dstComponentsCount, deUint32 src0ComponentsCount, deUint32 src1ComponentsCount)
11325 {
11326         DE_ASSERT(dstComponentsCount <= 4);
11327         DE_ASSERT(src0ComponentsCount <= 4);
11328         DE_ASSERT(src1ComponentsCount <= 4);
11329         deUint32 funcCode = 100 * dstComponentsCount + 10 * src0ComponentsCount + src1ComponentsCount;
11330
11331         switch (funcCode)
11332         {
11333                 case 222:return compareFP16VectorShuffleFunc<2, 2, 2>;
11334                 case 223:return compareFP16VectorShuffleFunc<2, 2, 3>;
11335                 case 224:return compareFP16VectorShuffleFunc<2, 2, 4>;
11336                 case 232:return compareFP16VectorShuffleFunc<2, 3, 2>;
11337                 case 233:return compareFP16VectorShuffleFunc<2, 3, 3>;
11338                 case 234:return compareFP16VectorShuffleFunc<2, 3, 4>;
11339                 case 242:return compareFP16VectorShuffleFunc<2, 4, 2>;
11340                 case 243:return compareFP16VectorShuffleFunc<2, 4, 3>;
11341                 case 244:return compareFP16VectorShuffleFunc<2, 4, 4>;
11342                 case 322:return compareFP16VectorShuffleFunc<3, 2, 2>;
11343                 case 323:return compareFP16VectorShuffleFunc<3, 2, 3>;
11344                 case 324:return compareFP16VectorShuffleFunc<3, 2, 4>;
11345                 case 332:return compareFP16VectorShuffleFunc<3, 3, 2>;
11346                 case 333:return compareFP16VectorShuffleFunc<3, 3, 3>;
11347                 case 334:return compareFP16VectorShuffleFunc<3, 3, 4>;
11348                 case 342:return compareFP16VectorShuffleFunc<3, 4, 2>;
11349                 case 343:return compareFP16VectorShuffleFunc<3, 4, 3>;
11350                 case 344:return compareFP16VectorShuffleFunc<3, 4, 4>;
11351                 case 422:return compareFP16VectorShuffleFunc<4, 2, 2>;
11352                 case 423:return compareFP16VectorShuffleFunc<4, 2, 3>;
11353                 case 424:return compareFP16VectorShuffleFunc<4, 2, 4>;
11354                 case 432:return compareFP16VectorShuffleFunc<4, 3, 2>;
11355                 case 433:return compareFP16VectorShuffleFunc<4, 3, 3>;
11356                 case 434:return compareFP16VectorShuffleFunc<4, 3, 4>;
11357                 case 442:return compareFP16VectorShuffleFunc<4, 4, 2>;
11358                 case 443:return compareFP16VectorShuffleFunc<4, 4, 3>;
11359                 case 444:return compareFP16VectorShuffleFunc<4, 4, 4>;
11360                 default: TCU_THROW(InternalError, "Invalid number of components specified.");
11361         }
11362 }
11363
11364 template<class SpecResource>
11365 tcu::TestCaseGroup* createFloat16VectorShuffleSet (tcu::TestContext& testCtx)
11366 {
11367         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorshuffle", "OpVectorShuffle tests"));
11368         const int                                                       testSpecificSeed        = deStringHash(testGroup->getName());
11369         const int                                                       seed                            = testCtx.getCommandLine().getBaseSeed() ^ testSpecificSeed;
11370         de::Random                                                      rnd                                     (seed);
11371         const deUint32                                          numDataPoints           = 128;
11372         map<string, string>                                     fragments;
11373
11374         struct TestType
11375         {
11376                 const deUint32  typeComponents;
11377                 const char*             typeName;
11378         };
11379
11380         const TestType  testTypes[]     =
11381         {
11382                 {
11383                         2,
11384                         "v2f16",
11385                 },
11386                 {
11387                         3,
11388                         "v3f16",
11389                 },
11390                 {
11391                         4,
11392                         "v4f16",
11393                 },
11394         };
11395
11396         const StringTemplate preMain
11397         (
11398                 "    %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
11399                 "     %c_i32_cc = OpConstant %i32 ${case_count}\n"
11400                 "          %f16 = OpTypeFloat 16\n"
11401                 "        %v2f16 = OpTypeVector %f16 2\n"
11402                 "        %v3f16 = OpTypeVector %f16 3\n"
11403                 "        %v4f16 = OpTypeVector %f16 4\n"
11404
11405                 "     %up_v2f16 = OpTypePointer Uniform %v2f16\n"
11406                 "     %ra_v2f16 = OpTypeArray %v2f16 %c_i32_ndp\n"
11407                 "   %SSBO_v2f16 = OpTypeStruct %ra_v2f16\n"
11408                 "%up_SSBO_v2f16 = OpTypePointer Uniform %SSBO_v2f16\n"
11409
11410                 "     %up_v3f16 = OpTypePointer Uniform %v3f16\n"
11411                 "     %ra_v3f16 = OpTypeArray %v3f16 %c_i32_ndp\n"
11412                 "   %SSBO_v3f16 = OpTypeStruct %ra_v3f16\n"
11413                 "%up_SSBO_v3f16 = OpTypePointer Uniform %SSBO_v3f16\n"
11414
11415                 "     %up_v4f16 = OpTypePointer Uniform %v4f16\n"
11416                 "     %ra_v4f16 = OpTypeArray %v4f16 %c_i32_ndp\n"
11417                 "   %SSBO_v4f16 = OpTypeStruct %ra_v4f16\n"
11418                 "%up_SSBO_v4f16 = OpTypePointer Uniform %SSBO_v4f16\n"
11419
11420                 "        %fun_t = OpTypeFunction %${tt_dst} %${tt_src0} %${tt_src1} %i32\n"
11421
11422                 "    %ssbo_src0 = OpVariable %up_SSBO_${tt_src0} Uniform\n"
11423                 "    %ssbo_src1 = OpVariable %up_SSBO_${tt_src1} Uniform\n"
11424                 "     %ssbo_dst = OpVariable %up_SSBO_${tt_dst} Uniform\n"
11425         );
11426
11427         const StringTemplate decoration
11428         (
11429                 "OpDecorate %ra_v2f16 ArrayStride 4\n"
11430                 "OpDecorate %ra_v3f16 ArrayStride 8\n"
11431                 "OpDecorate %ra_v4f16 ArrayStride 8\n"
11432
11433                 "OpMemberDecorate %SSBO_v2f16 0 Offset 0\n"
11434                 "OpDecorate %SSBO_v2f16 BufferBlock\n"
11435
11436                 "OpMemberDecorate %SSBO_v3f16 0 Offset 0\n"
11437                 "OpDecorate %SSBO_v3f16 BufferBlock\n"
11438
11439                 "OpMemberDecorate %SSBO_v4f16 0 Offset 0\n"
11440                 "OpDecorate %SSBO_v4f16 BufferBlock\n"
11441
11442                 "OpDecorate %ssbo_src0 DescriptorSet 0\n"
11443                 "OpDecorate %ssbo_src0 Binding 0\n"
11444                 "OpDecorate %ssbo_src1 DescriptorSet 0\n"
11445                 "OpDecorate %ssbo_src1 Binding 1\n"
11446                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11447                 "OpDecorate %ssbo_dst Binding 2\n"
11448         );
11449
11450         const StringTemplate testFun
11451         (
11452                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11453                 "    %param = OpFunctionParameter %v4f32\n"
11454                 "    %entry = OpLabel\n"
11455
11456                 "        %i = OpVariable %fp_i32 Function\n"
11457                 "             OpStore %i %c_i32_0\n"
11458
11459                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11460                 "             OpSelectionMerge %end_if None\n"
11461                 "             OpBranchConditional %will_run %run_test %end_if\n"
11462
11463                 " %run_test = OpLabel\n"
11464                 "             OpBranch %loop\n"
11465
11466                 "     %loop = OpLabel\n"
11467                 "    %i_cmp = OpLoad %i32 %i\n"
11468                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11469                 "             OpLoopMerge %merge %next None\n"
11470                 "             OpBranchConditional %lt %write %merge\n"
11471
11472                 "    %write = OpLabel\n"
11473                 "      %ndx = OpLoad %i32 %i\n"
11474                 "     %src0 = OpAccessChain %up_${tt_src0} %ssbo_src0 %c_i32_0 %ndx\n"
11475                 " %val_src0 = OpLoad %${tt_src0} %src0\n"
11476                 "     %src1 = OpAccessChain %up_${tt_src1} %ssbo_src1 %c_i32_0 %ndx\n"
11477                 " %val_src1 = OpLoad %${tt_src1} %src1\n"
11478                 "  %val_dst = OpFunctionCall %${tt_dst} %sw_fun %val_src0 %val_src1 %ndx\n"
11479                 "      %dst = OpAccessChain %up_${tt_dst} %ssbo_dst %c_i32_0 %ndx\n"
11480                 "             OpStore %dst %val_dst\n"
11481                 "             OpBranch %next\n"
11482
11483                 "     %next = OpLabel\n"
11484                 "    %i_cur = OpLoad %i32 %i\n"
11485                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11486                 "             OpStore %i %i_new\n"
11487                 "             OpBranch %loop\n"
11488
11489                 "    %merge = OpLabel\n"
11490                 "             OpBranch %end_if\n"
11491                 "   %end_if = OpLabel\n"
11492                 "             OpReturnValue %param\n"
11493                 "             OpFunctionEnd\n"
11494                 "\n"
11495
11496                 "   %sw_fun = OpFunction %${tt_dst} None %fun_t\n"
11497                 "%sw_param0 = OpFunctionParameter %${tt_src0}\n"
11498                 "%sw_param1 = OpFunctionParameter %${tt_src1}\n"
11499                 "%sw_paramn = OpFunctionParameter %i32\n"
11500                 " %sw_entry = OpLabel\n"
11501                 "   %modulo = OpSMod %i32 %sw_paramn %c_i32_cc\n"
11502                 "             OpSelectionMerge %switch_e None\n"
11503                 "             OpSwitch %modulo %default ${case_list}\n"
11504                 "${case_bodies}"
11505                 "%default   = OpLabel\n"
11506                 "             OpUnreachable\n" // Unreachable default case for switch statement
11507                 "%switch_e  = OpLabel\n"
11508                 "             OpUnreachable\n" // Unreachable merge block for switch statement
11509                 "             OpFunctionEnd\n"
11510         );
11511
11512         const StringTemplate testCaseBody
11513         (
11514                 "%case_${case_ndx}    = OpLabel\n"
11515                 "%val_dst_${case_ndx} = OpVectorShuffle %${tt_dst} %sw_param0 %sw_param1 ${shuffle}\n"
11516                 "             OpReturnValue %val_dst_${case_ndx}\n"
11517         );
11518
11519         for (deUint32 dstTypeIdx = 0; dstTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++dstTypeIdx)
11520         {
11521                 const TestType& dstType                 = testTypes[dstTypeIdx];
11522
11523                 for (deUint32 comp0Idx = 0; comp0Idx < DE_LENGTH_OF_ARRAY(testTypes); ++comp0Idx)
11524                 {
11525                         const TestType& src0Type        = testTypes[comp0Idx];
11526
11527                         for (deUint32 comp1Idx = 0; comp1Idx < DE_LENGTH_OF_ARRAY(testTypes); ++comp1Idx)
11528                         {
11529                                 const TestType&                 src1Type                        = testTypes[comp1Idx];
11530                                 const deUint32                  input0Stride            = (src0Type.typeComponents == 3) ? 4 : src0Type.typeComponents;
11531                                 const deUint32                  input1Stride            = (src1Type.typeComponents == 3) ? 4 : src1Type.typeComponents;
11532                                 const deUint32                  outputStride            = (dstType.typeComponents == 3) ? 4 : dstType.typeComponents;
11533                                 const vector<deFloat16> float16Input0Data       = getFloat16s(rnd, input0Stride * numDataPoints);
11534                                 const vector<deFloat16> float16Input1Data       = getFloat16s(rnd, input1Stride * numDataPoints);
11535                                 const vector<deFloat16> float16OutputDummy      (outputStride * numDataPoints, 0);
11536                                 const string                    testName                        = de::toString(dstType.typeComponents) + de::toString(src0Type.typeComponents) + de::toString(src1Type.typeComponents);
11537                                 deUint32                                caseCount                       = 0;
11538                                 SpecResource                    specResource;
11539                                 map<string, string>             specs;
11540                                 vector<string>                  extensions;
11541                                 VulkanFeatures                  features;
11542                                 string                                  caseBodies;
11543                                 string                                  caseList;
11544
11545                                 // Generate case
11546                                 {
11547                                         vector<string>  componentList;
11548
11549                                         // Generate component possible indices for OpVectorShuffle for components 0 and 1 in output vector
11550                                         {
11551                                                 deUint32                caseNo          = 0;
11552
11553                                                 for (deUint32 comp0IdxLocal = 0; comp0IdxLocal < src0Type.typeComponents; ++comp0IdxLocal)
11554                                                         componentList.push_back(de::toString(caseNo++));
11555                                                 for (deUint32 comp1IdxLocal = 0; comp1IdxLocal < src1Type.typeComponents; ++comp1IdxLocal)
11556                                                         componentList.push_back(de::toString(caseNo++));
11557                                                 componentList.push_back("0xFFFFFFFF");
11558                                         }
11559
11560                                         for (deUint32 comp0IdxLocal = 0; comp0IdxLocal < componentList.size(); ++comp0IdxLocal)
11561                                         {
11562                                                 for (deUint32 comp1IdxLocal = 0; comp1IdxLocal < componentList.size(); ++comp1IdxLocal)
11563                                                 {
11564                                                         map<string, string>     specCase;
11565                                                         string                          shuffle         = componentList[comp0IdxLocal] + " " + componentList[comp1IdxLocal];
11566
11567                                                         for (deUint32 compIdx = 2; compIdx < dstType.typeComponents; ++compIdx)
11568                                                                 shuffle += " " + de::toString(compIdx - 2);
11569
11570                                                         specCase["case_ndx"]    = de::toString(caseCount);
11571                                                         specCase["shuffle"]             = shuffle;
11572                                                         specCase["tt_dst"]              = dstType.typeName;
11573
11574                                                         caseBodies      += testCaseBody.specialize(specCase);
11575                                                         caseList        += de::toString(caseCount) + " %case_" + de::toString(caseCount) + " ";
11576
11577                                                         caseCount++;
11578                                                 }
11579                                         }
11580                                 }
11581
11582                                 specs["num_data_points"]        = de::toString(numDataPoints);
11583                                 specs["tt_dst"]                         = dstType.typeName;
11584                                 specs["tt_src0"]                        = src0Type.typeName;
11585                                 specs["tt_src1"]                        = src1Type.typeName;
11586                                 specs["case_bodies"]            = caseBodies;
11587                                 specs["case_list"]                      = caseList;
11588                                 specs["case_count"]                     = de::toString(caseCount);
11589
11590                                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11591                                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
11592                                 fragments["decoration"]         = decoration.specialize(specs);
11593                                 fragments["pre_main"]           = preMain.specialize(specs);
11594                                 fragments["testfun"]            = testFun.specialize(specs);
11595
11596                                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Input0Data)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11597                                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Input1Data)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11598                                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11599                                 specResource.verifyIO = getFloat16VectorShuffleVerifyIOFunc(dstType.typeComponents, src0Type.typeComponents, src1Type.typeComponents);
11600
11601                                 extensions.push_back("VK_KHR_16bit_storage");
11602                                 extensions.push_back("VK_KHR_shader_float16_int8");
11603
11604                                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11605                                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11606
11607                                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11608                         }
11609                 }
11610         }
11611
11612         return testGroup.release();
11613 }
11614
11615 bool compareFP16CompositeFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11616 {
11617         if (inputs.size() != 1 || outputAllocs.size() != 1)
11618                 return false;
11619
11620         vector<deUint8> input1Bytes;
11621
11622         inputs[0].getBytes(input1Bytes);
11623
11624         DE_ASSERT(input1Bytes.size() > 0);
11625         DE_ASSERT(input1Bytes.size() % sizeof(deFloat16) == 0);
11626
11627         const size_t                    iterations              = input1Bytes.size() / sizeof(deFloat16);
11628         const deFloat16* const  input1AsFP16    = (const deFloat16*)&input1Bytes[0];
11629         const deFloat16* const  outputAsFP16    = (const deFloat16*)outputAllocs[0]->getHostPtr();
11630         const deFloat16                 exceptionValue  = tcu::Float16(-1.0).bits();
11631         std::string                             error;
11632
11633         for (size_t idx = 0; idx < iterations; ++idx)
11634         {
11635                 if (input1AsFP16[idx] == exceptionValue)
11636                         continue;
11637
11638                 if (!compare16BitFloat(input1AsFP16[idx], outputAsFP16[idx], error))
11639                 {
11640                         log << TestLog::Message << "At " << idx << ":" << error << TestLog::EndMessage;
11641
11642                         return false;
11643                 }
11644         }
11645
11646         return true;
11647 }
11648
11649 template<class SpecResource>
11650 tcu::TestCaseGroup* createFloat16CompositeConstructSet (tcu::TestContext& testCtx)
11651 {
11652         de::MovePtr<tcu::TestCaseGroup>         testGroup                               (new tcu::TestCaseGroup(testCtx, "opcompositeconstruct", "OpCompositeConstruct tests"));
11653         const deUint32                                          numElements                             = 8;
11654         const string                                            testName                                = "struct";
11655         const deUint32                                          structItemsCount                = 88;
11656         const deUint32                                          exceptionIndices[]              = { 1, 7, 15, 17, 25, 33, 51, 55, 59, 63, 67, 71, 84, 85, 86, 87 };
11657         const deFloat16                                         exceptionValue                  = tcu::Float16(-1.0).bits();
11658         const deUint32                                          fieldModifier                   = 2;
11659         const deUint32                                          fieldModifiedMulIndex   = 60;
11660         const deUint32                                          fieldModifiedAddIndex   = 66;
11661
11662         const StringTemplate preMain
11663         (
11664                 "    %c_i32_ndp = OpConstant %i32 ${num_elements}\n"
11665                 "          %f16 = OpTypeFloat 16\n"
11666                 "        %v2f16 = OpTypeVector %f16 2\n"
11667                 "        %v3f16 = OpTypeVector %f16 3\n"
11668                 "        %v4f16 = OpTypeVector %f16 4\n"
11669                 "    %c_f16_mod = OpConstant %f16 ${field_modifier}\n"
11670
11671                 "${consts}"
11672
11673                 "      %c_u32_5 = OpConstant %u32 5\n"
11674
11675                 " %f16arr3      = OpTypeArray %f16 %c_u32_3\n"
11676                 " %v2f16arr3    = OpTypeArray %v2f16 %c_u32_3\n"
11677                 " %v2f16arr5    = OpTypeArray %v2f16 %c_u32_5\n"
11678                 " %v3f16arr5    = OpTypeArray %v3f16 %c_u32_5\n"
11679                 " %v4f16arr3    = OpTypeArray %v4f16 %c_u32_3\n"
11680                 " %struct16     = OpTypeStruct %f16 %v2f16arr3\n"
11681                 " %struct16arr3 = OpTypeArray %struct16 %c_u32_3\n"
11682                 " %st_test      = OpTypeStruct %f16 %v2f16 %v3f16 %v4f16 %f16arr3 %struct16arr3 %v2f16arr5 %f16 %v3f16arr5 %v4f16arr3\n"
11683
11684                 "        %up_st = OpTypePointer Uniform %st_test\n"
11685                 "        %ra_st = OpTypeArray %st_test %c_i32_ndp\n"
11686                 "      %SSBO_st = OpTypeStruct %ra_st\n"
11687                 "   %up_SSBO_st = OpTypePointer Uniform %SSBO_st\n"
11688
11689                 "     %ssbo_dst = OpVariable %up_SSBO_st Uniform\n"
11690         );
11691
11692         const StringTemplate decoration
11693         (
11694                 "OpDecorate %SSBO_st BufferBlock\n"
11695                 "OpDecorate %ra_st ArrayStride ${struct_item_size}\n"
11696                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11697                 "OpDecorate %ssbo_dst Binding 1\n"
11698
11699                 "OpMemberDecorate %SSBO_st 0 Offset 0\n"
11700
11701                 "OpDecorate %v2f16arr3 ArrayStride 4\n"
11702                 "OpMemberDecorate %struct16 0 Offset 0\n"
11703                 "OpMemberDecorate %struct16 1 Offset 4\n"
11704                 "OpDecorate %struct16arr3 ArrayStride 16\n"
11705                 "OpDecorate %f16arr3 ArrayStride 2\n"
11706                 "OpDecorate %v2f16arr5 ArrayStride 4\n"
11707                 "OpDecorate %v3f16arr5 ArrayStride 8\n"
11708                 "OpDecorate %v4f16arr3 ArrayStride 8\n"
11709
11710                 "OpMemberDecorate %st_test 0 Offset 0\n"
11711                 "OpMemberDecorate %st_test 1 Offset 4\n"
11712                 "OpMemberDecorate %st_test 2 Offset 8\n"
11713                 "OpMemberDecorate %st_test 3 Offset 16\n"
11714                 "OpMemberDecorate %st_test 4 Offset 24\n"
11715                 "OpMemberDecorate %st_test 5 Offset 32\n"
11716                 "OpMemberDecorate %st_test 6 Offset 80\n"
11717                 "OpMemberDecorate %st_test 7 Offset 100\n"
11718                 "OpMemberDecorate %st_test 8 Offset 104\n"
11719                 "OpMemberDecorate %st_test 9 Offset 144\n"
11720         );
11721
11722         const StringTemplate testFun
11723         (
11724                 " %test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11725                 "     %param = OpFunctionParameter %v4f32\n"
11726                 "     %entry = OpLabel\n"
11727
11728                 "         %i = OpVariable %fp_i32 Function\n"
11729                 "              OpStore %i %c_i32_0\n"
11730
11731                 "  %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11732                 "              OpSelectionMerge %end_if None\n"
11733                 "              OpBranchConditional %will_run %run_test %end_if\n"
11734
11735                 "  %run_test = OpLabel\n"
11736                 "              OpBranch %loop\n"
11737
11738                 "      %loop = OpLabel\n"
11739                 "     %i_cmp = OpLoad %i32 %i\n"
11740                 "        %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11741                 "              OpLoopMerge %merge %next None\n"
11742                 "              OpBranchConditional %lt %write %merge\n"
11743
11744                 "     %write = OpLabel\n"
11745                 "       %ndx = OpLoad %i32 %i\n"
11746
11747                 "      %fld1 = OpCompositeConstruct %v2f16 %c_f16_2 %c_f16_3\n"
11748                 "      %fld2 = OpCompositeConstruct %v3f16 %c_f16_4 %c_f16_5 %c_f16_6\n"
11749                 "      %fld3 = OpCompositeConstruct %v4f16 %c_f16_8 %c_f16_9 %c_f16_10 %c_f16_11\n"
11750
11751                 "      %fld4 = OpCompositeConstruct %f16arr3 %c_f16_12 %c_f16_13 %c_f16_14\n"
11752
11753                 "%fld5_0_1_0 = OpCompositeConstruct %v2f16 %c_f16_18 %c_f16_19\n"
11754                 "%fld5_0_1_1 = OpCompositeConstruct %v2f16 %c_f16_20 %c_f16_21\n"
11755                 "%fld5_0_1_2 = OpCompositeConstruct %v2f16 %c_f16_22 %c_f16_23\n"
11756                 "  %fld5_0_1 = OpCompositeConstruct %v2f16arr3 %fld5_0_1_0 %fld5_0_1_1 %fld5_0_1_2\n"
11757                 "    %fld5_0 = OpCompositeConstruct %struct16 %c_f16_16 %fld5_0_1\n"
11758
11759                 "%fld5_1_1_0 = OpCompositeConstruct %v2f16 %c_f16_26 %c_f16_27\n"
11760                 "%fld5_1_1_1 = OpCompositeConstruct %v2f16 %c_f16_28 %c_f16_29\n"
11761                 "%fld5_1_1_2 = OpCompositeConstruct %v2f16 %c_f16_30 %c_f16_31\n"
11762                 "  %fld5_1_1 = OpCompositeConstruct %v2f16arr3 %fld5_1_1_0 %fld5_1_1_1 %fld5_1_1_2\n"
11763                 "    %fld5_1 = OpCompositeConstruct %struct16 %c_f16_24 %fld5_1_1\n"
11764
11765                 "%fld5_2_1_0 = OpCompositeConstruct %v2f16 %c_f16_34 %c_f16_35\n"
11766                 "%fld5_2_1_1 = OpCompositeConstruct %v2f16 %c_f16_36 %c_f16_37\n"
11767                 "%fld5_2_1_2 = OpCompositeConstruct %v2f16 %c_f16_38 %c_f16_39\n"
11768                 "  %fld5_2_1 = OpCompositeConstruct %v2f16arr3 %fld5_2_1_0 %fld5_2_1_1 %fld5_2_1_2\n"
11769                 "    %fld5_2 = OpCompositeConstruct %struct16 %c_f16_32 %fld5_2_1\n"
11770
11771                 "      %fld5 = OpCompositeConstruct %struct16arr3 %fld5_0 %fld5_1 %fld5_2\n"
11772
11773                 "    %fld6_0 = OpCompositeConstruct %v2f16 %c_f16_40 %c_f16_41\n"
11774                 "    %fld6_1 = OpCompositeConstruct %v2f16 %c_f16_42 %c_f16_43\n"
11775                 "    %fld6_2 = OpCompositeConstruct %v2f16 %c_f16_44 %c_f16_45\n"
11776                 "    %fld6_3 = OpCompositeConstruct %v2f16 %c_f16_46 %c_f16_47\n"
11777                 "    %fld6_4 = OpCompositeConstruct %v2f16 %c_f16_48 %c_f16_49\n"
11778                 "      %fld6 = OpCompositeConstruct %v2f16arr5 %fld6_0 %fld6_1 %fld6_2 %fld6_3 %fld6_4\n"
11779
11780                 "      %fndx = OpConvertSToF %f16 %ndx\n"
11781                 "  %fld8_2a0 = OpFMul %f16 %fndx %c_f16_mod\n"
11782                 "  %fld8_3b1 = OpFAdd %f16 %fndx %c_f16_mod\n"
11783
11784                 "   %fld8_2a = OpCompositeConstruct %v2f16 %fld8_2a0 %c_f16_61\n"
11785                 "   %fld8_3b = OpCompositeConstruct %v2f16 %c_f16_65 %fld8_3b1\n"
11786                 "    %fld8_0 = OpCompositeConstruct %v3f16 %c_f16_52 %c_f16_53 %c_f16_54\n"
11787                 "    %fld8_1 = OpCompositeConstruct %v3f16 %c_f16_56 %c_f16_57 %c_f16_58\n"
11788                 "    %fld8_2 = OpCompositeConstruct %v3f16 %fld8_2a %c_f16_62\n"
11789                 "    %fld8_3 = OpCompositeConstruct %v3f16 %c_f16_64 %fld8_3b\n"
11790                 "    %fld8_4 = OpCompositeConstruct %v3f16 %c_f16_68 %c_f16_69 %c_f16_70\n"
11791                 "      %fld8 = OpCompositeConstruct %v3f16arr5 %fld8_0 %fld8_1 %fld8_2 %fld8_3 %fld8_4\n"
11792
11793                 "    %fld9_0 = OpCompositeConstruct %v4f16 %c_f16_72 %c_f16_73 %c_f16_74 %c_f16_75\n"
11794                 "    %fld9_1 = OpCompositeConstruct %v4f16 %c_f16_76 %c_f16_77 %c_f16_78 %c_f16_79\n"
11795                 "    %fld9_2 = OpCompositeConstruct %v4f16 %c_f16_80 %c_f16_81 %c_f16_82 %c_f16_83\n"
11796                 "      %fld9 = OpCompositeConstruct %v4f16arr3 %fld9_0 %fld9_1 %fld9_2\n"
11797
11798                 "    %st_val = OpCompositeConstruct %st_test %c_f16_0 %fld1 %fld2 %fld3 %fld4 %fld5 %fld6 %c_f16_50 %fld8 %fld9\n"
11799                 "       %dst = OpAccessChain %up_st %ssbo_dst %c_i32_0 %ndx\n"
11800                 "              OpStore %dst %st_val\n"
11801
11802                 "              OpBranch %next\n"
11803
11804                 "      %next = OpLabel\n"
11805                 "     %i_cur = OpLoad %i32 %i\n"
11806                 "     %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11807                 "              OpStore %i %i_new\n"
11808                 "              OpBranch %loop\n"
11809
11810                 "     %merge = OpLabel\n"
11811                 "              OpBranch %end_if\n"
11812                 "    %end_if = OpLabel\n"
11813                 "              OpReturnValue %param\n"
11814                 "              OpFunctionEnd\n"
11815         );
11816
11817         {
11818                 SpecResource            specResource;
11819                 map<string, string>     specs;
11820                 VulkanFeatures          features;
11821                 map<string, string>     fragments;
11822                 vector<string>          extensions;
11823                 vector<deFloat16>       expectedOutput;
11824                 string                          consts;
11825
11826                 for (deUint32 elementNdx = 0; elementNdx < numElements; ++elementNdx)
11827                 {
11828                         vector<deFloat16>       expectedIterationOutput;
11829
11830                         for (deUint32 structItemNdx = 0; structItemNdx < structItemsCount; ++structItemNdx)
11831                                 expectedIterationOutput.push_back(tcu::Float16(float(structItemNdx)).bits());
11832
11833                         for (deUint32 structItemNdx = 0; structItemNdx < DE_LENGTH_OF_ARRAY(exceptionIndices); ++structItemNdx)
11834                                 expectedIterationOutput[exceptionIndices[structItemNdx]] = exceptionValue;
11835
11836                         expectedIterationOutput[fieldModifiedMulIndex] = tcu::Float16(float(elementNdx * fieldModifier)).bits();
11837                         expectedIterationOutput[fieldModifiedAddIndex] = tcu::Float16(float(elementNdx + fieldModifier)).bits();
11838
11839                         expectedOutput.insert(expectedOutput.end(), expectedIterationOutput.begin(), expectedIterationOutput.end());
11840                 }
11841
11842                 for (deUint32 i = 0; i < structItemsCount; ++i)
11843                         consts += "     %c_f16_" + de::toString(i) + " = OpConstant %f16 "  + de::toString(i) + "\n";
11844
11845                 specs["num_elements"]           = de::toString(numElements);
11846                 specs["struct_item_size"]       = de::toString(structItemsCount * sizeof(deFloat16));
11847                 specs["field_modifier"]         = de::toString(fieldModifier);
11848                 specs["consts"]                         = consts;
11849
11850                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11851                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
11852                 fragments["decoration"]         = decoration.specialize(specs);
11853                 fragments["pre_main"]           = preMain.specialize(specs);
11854                 fragments["testfun"]            = testFun.specialize(specs);
11855
11856                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(expectedOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11857                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(expectedOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11858                 specResource.verifyIO = compareFP16CompositeFunc;
11859
11860                 extensions.push_back("VK_KHR_16bit_storage");
11861                 extensions.push_back("VK_KHR_shader_float16_int8");
11862
11863                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11864                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11865
11866                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11867         }
11868
11869         return testGroup.release();
11870 }
11871
11872 template<class SpecResource>
11873 tcu::TestCaseGroup* createFloat16CompositeInsertExtractSet (tcu::TestContext& testCtx, const char* op)
11874 {
11875         de::MovePtr<tcu::TestCaseGroup>         testGroup               (new tcu::TestCaseGroup(testCtx, de::toLower(op).c_str(), op));
11876         const deFloat16                                         exceptionValue  = tcu::Float16(-1.0).bits();
11877         const string                                            opName                  (op);
11878         const deUint32                                          opIndex                 = (opName == "OpCompositeInsert") ? 0
11879                                                                                                                 : (opName == "OpCompositeExtract") ? 1
11880                                                                                                                 : -1;
11881
11882         const StringTemplate preMain
11883         (
11884                 "   %c_i32_ndp = OpConstant %i32 ${num_elements}\n"
11885                 "         %f16 = OpTypeFloat 16\n"
11886                 "       %v2f16 = OpTypeVector %f16 2\n"
11887                 "       %v3f16 = OpTypeVector %f16 3\n"
11888                 "       %v4f16 = OpTypeVector %f16 4\n"
11889                 "    %c_f16_na = OpConstant %f16 -1.0\n"
11890                 "     %c_u32_5 = OpConstant %u32 5\n"
11891
11892                 "%f16arr3      = OpTypeArray %f16 %c_u32_3\n"
11893                 "%v2f16arr3    = OpTypeArray %v2f16 %c_u32_3\n"
11894                 "%v2f16arr5    = OpTypeArray %v2f16 %c_u32_5\n"
11895                 "%v3f16arr5    = OpTypeArray %v3f16 %c_u32_5\n"
11896                 "%v4f16arr3    = OpTypeArray %v4f16 %c_u32_3\n"
11897                 "%struct16     = OpTypeStruct %f16 %v2f16arr3\n"
11898                 "%struct16arr3 = OpTypeArray %struct16 %c_u32_3\n"
11899                 "%st_test      = OpTypeStruct %${field_type}\n"
11900
11901                 "      %up_f16 = OpTypePointer Uniform %f16\n"
11902                 "       %up_st = OpTypePointer Uniform %st_test\n"
11903                 "      %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
11904                 "       %ra_st = OpTypeArray %st_test %c_i32_1\n"
11905
11906                 "${op_premain_decls}"
11907
11908                 " %up_SSBO_src = OpTypePointer Uniform %SSBO_src\n"
11909                 " %up_SSBO_dst = OpTypePointer Uniform %SSBO_dst\n"
11910
11911                 "    %ssbo_src = OpVariable %up_SSBO_src Uniform\n"
11912                 "    %ssbo_dst = OpVariable %up_SSBO_dst Uniform\n"
11913         );
11914
11915         const StringTemplate decoration
11916         (
11917                 "OpDecorate %SSBO_src BufferBlock\n"
11918                 "OpDecorate %SSBO_dst BufferBlock\n"
11919                 "OpDecorate %ra_f16 ArrayStride 2\n"
11920                 "OpDecorate %ra_st ArrayStride ${struct_item_size}\n"
11921                 "OpDecorate %ssbo_src DescriptorSet 0\n"
11922                 "OpDecorate %ssbo_src Binding 0\n"
11923                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11924                 "OpDecorate %ssbo_dst Binding 1\n"
11925
11926                 "OpMemberDecorate %SSBO_src 0 Offset 0\n"
11927                 "OpMemberDecorate %SSBO_dst 0 Offset 0\n"
11928
11929                 "OpDecorate %v2f16arr3 ArrayStride 4\n"
11930                 "OpMemberDecorate %struct16 0 Offset 0\n"
11931                 "OpMemberDecorate %struct16 1 Offset 4\n"
11932                 "OpDecorate %struct16arr3 ArrayStride 16\n"
11933                 "OpDecorate %f16arr3 ArrayStride 2\n"
11934                 "OpDecorate %v2f16arr5 ArrayStride 4\n"
11935                 "OpDecorate %v3f16arr5 ArrayStride 8\n"
11936                 "OpDecorate %v4f16arr3 ArrayStride 8\n"
11937
11938                 "OpMemberDecorate %st_test 0 Offset 0\n"
11939         );
11940
11941         const StringTemplate testFun
11942         (
11943                 " %test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11944                 "     %param = OpFunctionParameter %v4f32\n"
11945                 "     %entry = OpLabel\n"
11946
11947                 "         %i = OpVariable %fp_i32 Function\n"
11948                 "              OpStore %i %c_i32_0\n"
11949
11950                 "  %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11951                 "              OpSelectionMerge %end_if None\n"
11952                 "              OpBranchConditional %will_run %run_test %end_if\n"
11953
11954                 "  %run_test = OpLabel\n"
11955                 "              OpBranch %loop\n"
11956
11957                 "      %loop = OpLabel\n"
11958                 "     %i_cmp = OpLoad %i32 %i\n"
11959                 "        %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11960                 "              OpLoopMerge %merge %next None\n"
11961                 "              OpBranchConditional %lt %write %merge\n"
11962
11963                 "     %write = OpLabel\n"
11964                 "       %ndx = OpLoad %i32 %i\n"
11965
11966                 "${op_sw_fun_call}"
11967
11968                 "              OpStore %dst %val_dst\n"
11969                 "              OpBranch %next\n"
11970
11971                 "      %next = OpLabel\n"
11972                 "     %i_cur = OpLoad %i32 %i\n"
11973                 "     %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11974                 "              OpStore %i %i_new\n"
11975                 "              OpBranch %loop\n"
11976
11977                 "     %merge = OpLabel\n"
11978                 "              OpBranch %end_if\n"
11979                 "    %end_if = OpLabel\n"
11980                 "              OpReturnValue %param\n"
11981                 "              OpFunctionEnd\n"
11982
11983                 "${op_sw_fun_header}"
11984                 " %sw_param = OpFunctionParameter %st_test\n"
11985                 "%sw_paramn = OpFunctionParameter %i32\n"
11986                 " %sw_entry = OpLabel\n"
11987                 "             OpSelectionMerge %switch_e None\n"
11988                 "             OpSwitch %sw_paramn %default ${case_list}\n"
11989
11990                 "${case_bodies}"
11991
11992                 "%default   = OpLabel\n"
11993                 "             OpReturnValue ${op_case_default_value}\n"
11994                 "%switch_e  = OpLabel\n"
11995                 "             OpUnreachable\n" // Unreachable merge block for switch statement
11996                 "             OpFunctionEnd\n"
11997         );
11998
11999         const StringTemplate testCaseBody
12000         (
12001                 "%case_${case_ndx}    = OpLabel\n"
12002                 "%val_ret_${case_ndx} = ${op_name} ${op_args_part} ${access_path}\n"
12003                 "             OpReturnValue %val_ret_${case_ndx}\n"
12004         );
12005
12006         struct OpParts
12007         {
12008                 const char*     premainDecls;
12009                 const char*     swFunCall;
12010                 const char*     swFunHeader;
12011                 const char*     caseDefaultValue;
12012                 const char*     argsPartial;
12013         };
12014
12015         OpParts                                                         opPartsArray[]                  =
12016         {
12017                 // OpCompositeInsert
12018                 {
12019                         "       %fun_t = OpTypeFunction %st_test %f16 %st_test %i32\n"
12020                         "    %SSBO_src = OpTypeStruct %ra_f16\n"
12021                         "    %SSBO_dst = OpTypeStruct %ra_st\n",
12022
12023                         "       %src = OpAccessChain %up_f16 %ssbo_src %c_i32_0 %ndx\n"
12024                         "       %dst = OpAccessChain %up_st %ssbo_dst %c_i32_0 %c_i32_0\n"
12025                         "   %val_new = OpLoad %f16 %src\n"
12026                         "   %val_old = OpLoad %st_test %dst\n"
12027                         "   %val_dst = OpFunctionCall %st_test %sw_fun %val_new %val_old %ndx\n",
12028
12029                         "   %sw_fun = OpFunction %st_test None %fun_t\n"
12030                         "%sw_paramv = OpFunctionParameter %f16\n",
12031
12032                         "%sw_param",
12033
12034                         "%st_test %sw_paramv %sw_param",
12035                 },
12036                 // OpCompositeExtract
12037                 {
12038                         "       %fun_t = OpTypeFunction %f16 %st_test %i32\n"
12039                         "    %SSBO_src = OpTypeStruct %ra_st\n"
12040                         "    %SSBO_dst = OpTypeStruct %ra_f16\n",
12041
12042                         "       %src = OpAccessChain %up_st %ssbo_src %c_i32_0 %c_i32_0\n"
12043                         "       %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
12044                         "   %val_src = OpLoad %st_test %src\n"
12045                         "   %val_dst = OpFunctionCall %f16 %sw_fun %val_src %ndx\n",
12046
12047                         "   %sw_fun = OpFunction %f16 None %fun_t\n",
12048
12049                         "%c_f16_na",
12050
12051                         "%f16 %sw_param",
12052                 },
12053         };
12054
12055         DE_ASSERT(opIndex >= 0 && opIndex < DE_LENGTH_OF_ARRAY(opPartsArray));
12056
12057         const char*     accessPathF16[] =
12058         {
12059                 "0",                    // %f16
12060                 DE_NULL,
12061         };
12062         const char*     accessPathV2F16[] =
12063         {
12064                 "0 0",                  // %v2f16
12065                 "0 1",
12066         };
12067         const char*     accessPathV3F16[] =
12068         {
12069                 "0 0",                  // %v3f16
12070                 "0 1",
12071                 "0 2",
12072                 DE_NULL,
12073         };
12074         const char*     accessPathV4F16[] =
12075         {
12076                 "0 0",                  // %v4f16"
12077                 "0 1",
12078                 "0 2",
12079                 "0 3",
12080         };
12081         const char*     accessPathF16Arr3[] =
12082         {
12083                 "0 0",                  // %f16arr3
12084                 "0 1",
12085                 "0 2",
12086                 DE_NULL,
12087         };
12088         const char*     accessPathStruct16Arr3[] =
12089         {
12090                 "0 0 0",                // %struct16arr3
12091                 DE_NULL,
12092                 "0 0 1 0 0",
12093                 "0 0 1 0 1",
12094                 "0 0 1 1 0",
12095                 "0 0 1 1 1",
12096                 "0 0 1 2 0",
12097                 "0 0 1 2 1",
12098                 "0 1 0",
12099                 DE_NULL,
12100                 "0 1 1 0 0",
12101                 "0 1 1 0 1",
12102                 "0 1 1 1 0",
12103                 "0 1 1 1 1",
12104                 "0 1 1 2 0",
12105                 "0 1 1 2 1",
12106                 "0 2 0",
12107                 DE_NULL,
12108                 "0 2 1 0 0",
12109                 "0 2 1 0 1",
12110                 "0 2 1 1 0",
12111                 "0 2 1 1 1",
12112                 "0 2 1 2 0",
12113                 "0 2 1 2 1",
12114         };
12115         const char*     accessPathV2F16Arr5[] =
12116         {
12117                 "0 0 0",                // %v2f16arr5
12118                 "0 0 1",
12119                 "0 1 0",
12120                 "0 1 1",
12121                 "0 2 0",
12122                 "0 2 1",
12123                 "0 3 0",
12124                 "0 3 1",
12125                 "0 4 0",
12126                 "0 4 1",
12127         };
12128         const char*     accessPathV3F16Arr5[] =
12129         {
12130                 "0 0 0",                // %v3f16arr5
12131                 "0 0 1",
12132                 "0 0 2",
12133                 DE_NULL,
12134                 "0 1 0",
12135                 "0 1 1",
12136                 "0 1 2",
12137                 DE_NULL,
12138                 "0 2 0",
12139                 "0 2 1",
12140                 "0 2 2",
12141                 DE_NULL,
12142                 "0 3 0",
12143                 "0 3 1",
12144                 "0 3 2",
12145                 DE_NULL,
12146                 "0 4 0",
12147                 "0 4 1",
12148                 "0 4 2",
12149                 DE_NULL,
12150         };
12151         const char*     accessPathV4F16Arr3[] =
12152         {
12153                 "0 0 0",                // %v4f16arr3
12154                 "0 0 1",
12155                 "0 0 2",
12156                 "0 0 3",
12157                 "0 1 0",
12158                 "0 1 1",
12159                 "0 1 2",
12160                 "0 1 3",
12161                 "0 2 0",
12162                 "0 2 1",
12163                 "0 2 2",
12164                 "0 2 3",
12165                 DE_NULL,
12166                 DE_NULL,
12167                 DE_NULL,
12168                 DE_NULL,
12169         };
12170
12171         struct TypeTestParameters
12172         {
12173                 const char*             name;
12174                 size_t                  accessPathLength;
12175                 const char**    accessPath;
12176         };
12177
12178         const TypeTestParameters typeTestParameters[] =
12179         {
12180                 {       "f16",                  DE_LENGTH_OF_ARRAY(accessPathF16),                      accessPathF16                   },
12181                 {       "v2f16",                DE_LENGTH_OF_ARRAY(accessPathV2F16),            accessPathV2F16                 },
12182                 {       "v3f16",                DE_LENGTH_OF_ARRAY(accessPathV3F16),            accessPathV3F16                 },
12183                 {       "v4f16",                DE_LENGTH_OF_ARRAY(accessPathV4F16),            accessPathV4F16                 },
12184                 {       "f16arr3",              DE_LENGTH_OF_ARRAY(accessPathF16Arr3),          accessPathF16Arr3               },
12185                 {       "v2f16arr5",    DE_LENGTH_OF_ARRAY(accessPathV2F16Arr5),        accessPathV2F16Arr5             },
12186                 {       "v3f16arr5",    DE_LENGTH_OF_ARRAY(accessPathV3F16Arr5),        accessPathV3F16Arr5             },
12187                 {       "v4f16arr3",    DE_LENGTH_OF_ARRAY(accessPathV4F16Arr3),        accessPathV4F16Arr3             },
12188                 {       "struct16arr3", DE_LENGTH_OF_ARRAY(accessPathStruct16Arr3),     accessPathStruct16Arr3  },
12189         };
12190
12191         for (size_t typeTestNdx = 0; typeTestNdx < DE_LENGTH_OF_ARRAY(typeTestParameters); ++typeTestNdx)
12192         {
12193                 const OpParts           opParts                         = opPartsArray[opIndex];
12194                 const string            testName                        = typeTestParameters[typeTestNdx].name;
12195                 const size_t            structItemsCount        = typeTestParameters[typeTestNdx].accessPathLength;
12196                 const char**            accessPath                      = typeTestParameters[typeTestNdx].accessPath;
12197                 SpecResource            specResource;
12198                 map<string, string>     specs;
12199                 VulkanFeatures          features;
12200                 map<string, string>     fragments;
12201                 vector<string>          extensions;
12202                 vector<deFloat16>       inputFP16;
12203                 vector<deFloat16>       dummyFP16Output;
12204
12205                 // Generate values for input
12206                 inputFP16.reserve(structItemsCount);
12207                 for (deUint32 structItemNdx = 0; structItemNdx < structItemsCount; ++structItemNdx)
12208                         inputFP16.push_back((accessPath[structItemNdx] == DE_NULL) ? exceptionValue : tcu::Float16(float(structItemNdx)).bits());
12209
12210                 dummyFP16Output.resize(structItemsCount);
12211
12212                 // Generate cases for OpSwitch
12213                 {
12214                         string  caseBodies;
12215                         string  caseList;
12216
12217                         for (deUint32 caseNdx = 0; caseNdx < structItemsCount; ++caseNdx)
12218                                 if (accessPath[caseNdx] != DE_NULL)
12219                                 {
12220                                         map<string, string>     specCase;
12221
12222                                         specCase["case_ndx"]            = de::toString(caseNdx);
12223                                         specCase["access_path"]         = accessPath[caseNdx];
12224                                         specCase["op_args_part"]        = opParts.argsPartial;
12225                                         specCase["op_name"]                     = opName;
12226
12227                                         caseBodies      += testCaseBody.specialize(specCase);
12228                                         caseList        += de::toString(caseNdx) + " %case_" + de::toString(caseNdx) + " ";
12229                                 }
12230
12231                         specs["case_bodies"]    = caseBodies;
12232                         specs["case_list"]              = caseList;
12233                 }
12234
12235                 specs["num_elements"]                   = de::toString(structItemsCount);
12236                 specs["field_type"]                             = typeTestParameters[typeTestNdx].name;
12237                 specs["struct_item_size"]               = de::toString(structItemsCount * sizeof(deFloat16));
12238                 specs["op_premain_decls"]               = opParts.premainDecls;
12239                 specs["op_sw_fun_call"]                 = opParts.swFunCall;
12240                 specs["op_sw_fun_header"]               = opParts.swFunHeader;
12241                 specs["op_case_default_value"]  = opParts.caseDefaultValue;
12242
12243                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
12244                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
12245                 fragments["decoration"]         = decoration.specialize(specs);
12246                 fragments["pre_main"]           = preMain.specialize(specs);
12247                 fragments["testfun"]            = testFun.specialize(specs);
12248
12249                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(inputFP16)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
12250                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(dummyFP16Output)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
12251                 specResource.verifyIO = compareFP16CompositeFunc;
12252
12253                 extensions.push_back("VK_KHR_16bit_storage");
12254                 extensions.push_back("VK_KHR_shader_float16_int8");
12255
12256                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
12257                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
12258
12259                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
12260         }
12261
12262         return testGroup.release();
12263 }
12264
12265 struct fp16PerComponent
12266 {
12267         fp16PerComponent()
12268                 : flavor(0)
12269                 , floatFormat16 (-14, 15, 10, true)
12270                 , outCompCount(0)
12271                 , argCompCount(3, 0)
12272         {
12273         }
12274
12275         bool                    callOncePerComponent    ()                                                                      { return true; }
12276         deUint32                getComponentValidity    ()                                                                      { return static_cast<deUint32>(-1); }
12277
12278         virtual double  getULPs                                 (vector<const deFloat16*>&)                     { return 1.0; }
12279         virtual double  getMin                                  (double value, double ulps)                     { return value - floatFormat16.ulp(deAbs(value), ulps); }
12280         virtual double  getMax                                  (double value, double ulps)                     { return value + floatFormat16.ulp(deAbs(value), ulps); }
12281
12282         virtual size_t  getFlavorCount                  ()                                                                      { return flavorNames.empty() ? 1 : flavorNames.size(); }
12283         virtual void    setFlavor                               (size_t flavorNo)                                       { DE_ASSERT(flavorNo < getFlavorCount()); flavor = flavorNo; }
12284         virtual size_t  getFlavor                               ()                                                                      { return flavor; }
12285         virtual string  getCurrentFlavorName    ()                                                                      { return flavorNames.empty() ? string("") : flavorNames[getFlavor()]; }
12286
12287         virtual void    setOutCompCount                 (size_t compCount)                                      { outCompCount = compCount; }
12288         virtual size_t  getOutCompCount                 ()                                                                      { return outCompCount; }
12289
12290         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)        { argCompCount[argNo] = compCount; }
12291         virtual size_t  getArgCompCount                 (size_t argNo)                                          { return argCompCount[argNo]; }
12292
12293 protected:
12294         size_t                          flavor;
12295         tcu::FloatFormat        floatFormat16;
12296         size_t                          outCompCount;
12297         vector<size_t>          argCompCount;
12298         vector<string>          flavorNames;
12299 };
12300
12301 struct fp16OpFNegate : public fp16PerComponent
12302 {
12303         template <class fp16type>
12304         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12305         {
12306                 const fp16type  x               (*in[0]);
12307                 const double    d               (x.asDouble());
12308                 const double    result  (0.0 - d);
12309
12310                 out[0] = fp16type(result).bits();
12311                 min[0] = getMin(result, getULPs(in));
12312                 max[0] = getMax(result, getULPs(in));
12313
12314                 return true;
12315         }
12316 };
12317
12318 struct fp16Round : public fp16PerComponent
12319 {
12320         fp16Round() : fp16PerComponent()
12321         {
12322                 flavorNames.push_back("Floor(x+0.5)");
12323                 flavorNames.push_back("Floor(x-0.5)");
12324                 flavorNames.push_back("RoundEven");
12325         }
12326
12327         template<class fp16type>
12328         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12329         {
12330                 const fp16type  x               (*in[0]);
12331                 const double    d               (x.asDouble());
12332                 double                  result  (0.0);
12333
12334                 switch (flavor)
12335                 {
12336                         case 0:         result = deRound(d);            break;
12337                         case 1:         result = deFloor(d - 0.5);      break;
12338                         case 2:         result = deRoundEven(d);        break;
12339                         default:        TCU_THROW(InternalError, "Invalid flavor specified");
12340                 }
12341
12342                 out[0] = fp16type(result).bits();
12343                 min[0] = getMin(result, getULPs(in));
12344                 max[0] = getMax(result, getULPs(in));
12345
12346                 return true;
12347         }
12348 };
12349
12350 struct fp16RoundEven : public fp16PerComponent
12351 {
12352         template<class fp16type>
12353         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12354         {
12355                 const fp16type  x               (*in[0]);
12356                 const double    d               (x.asDouble());
12357                 const double    result  (deRoundEven(d));
12358
12359                 out[0] = fp16type(result).bits();
12360                 min[0] = getMin(result, getULPs(in));
12361                 max[0] = getMax(result, getULPs(in));
12362
12363                 return true;
12364         }
12365 };
12366
12367 struct fp16Trunc : public fp16PerComponent
12368 {
12369         template<class fp16type>
12370         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12371         {
12372                 const fp16type  x               (*in[0]);
12373                 const double    d               (x.asDouble());
12374                 const double    result  (deTrunc(d));
12375
12376                 out[0] = fp16type(result).bits();
12377                 min[0] = getMin(result, getULPs(in));
12378                 max[0] = getMax(result, getULPs(in));
12379
12380                 return true;
12381         }
12382 };
12383
12384 struct fp16FAbs : public fp16PerComponent
12385 {
12386         template<class fp16type>
12387         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12388         {
12389                 const fp16type  x               (*in[0]);
12390                 const double    d               (x.asDouble());
12391                 const double    result  (deAbs(d));
12392
12393                 out[0] = fp16type(result).bits();
12394                 min[0] = getMin(result, getULPs(in));
12395                 max[0] = getMax(result, getULPs(in));
12396
12397                 return true;
12398         }
12399 };
12400
12401 struct fp16FSign : public fp16PerComponent
12402 {
12403         template<class fp16type>
12404         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12405         {
12406                 const fp16type  x               (*in[0]);
12407                 const double    d               (x.asDouble());
12408                 const double    result  (deSign(d));
12409
12410                 if (x.isNaN())
12411                         return false;
12412
12413                 out[0] = fp16type(result).bits();
12414                 min[0] = getMin(result, getULPs(in));
12415                 max[0] = getMax(result, getULPs(in));
12416
12417                 return true;
12418         }
12419 };
12420
12421 struct fp16Floor : public fp16PerComponent
12422 {
12423         template<class fp16type>
12424         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12425         {
12426                 const fp16type  x               (*in[0]);
12427                 const double    d               (x.asDouble());
12428                 const double    result  (deFloor(d));
12429
12430                 out[0] = fp16type(result).bits();
12431                 min[0] = getMin(result, getULPs(in));
12432                 max[0] = getMax(result, getULPs(in));
12433
12434                 return true;
12435         }
12436 };
12437
12438 struct fp16Ceil : public fp16PerComponent
12439 {
12440         template<class fp16type>
12441         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12442         {
12443                 const fp16type  x               (*in[0]);
12444                 const double    d               (x.asDouble());
12445                 const double    result  (deCeil(d));
12446
12447                 out[0] = fp16type(result).bits();
12448                 min[0] = getMin(result, getULPs(in));
12449                 max[0] = getMax(result, getULPs(in));
12450
12451                 return true;
12452         }
12453 };
12454
12455 struct fp16Fract : public fp16PerComponent
12456 {
12457         template<class fp16type>
12458         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12459         {
12460                 const fp16type  x               (*in[0]);
12461                 const double    d               (x.asDouble());
12462                 const double    result  (deFrac(d));
12463
12464                 out[0] = fp16type(result).bits();
12465                 min[0] = getMin(result, getULPs(in));
12466                 max[0] = getMax(result, getULPs(in));
12467
12468                 return true;
12469         }
12470 };
12471
12472 struct fp16Radians : public fp16PerComponent
12473 {
12474         virtual double getULPs (vector<const deFloat16*>& in)
12475         {
12476                 DE_UNREF(in);
12477
12478                 return 2.5;
12479         }
12480
12481         template<class fp16type>
12482         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12483         {
12484                 const fp16type  x               (*in[0]);
12485                 const float             d               (x.asFloat());
12486                 const float             result  (deFloatRadians(d));
12487
12488                 out[0] = fp16type(result).bits();
12489                 min[0] = getMin(result, getULPs(in));
12490                 max[0] = getMax(result, getULPs(in));
12491
12492                 return true;
12493         }
12494 };
12495
12496 struct fp16Degrees : public fp16PerComponent
12497 {
12498         virtual double getULPs (vector<const deFloat16*>& in)
12499         {
12500                 DE_UNREF(in);
12501
12502                 return 2.5;
12503         }
12504
12505         template<class fp16type>
12506         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12507         {
12508                 const fp16type  x               (*in[0]);
12509                 const float             d               (x.asFloat());
12510                 const float             result  (deFloatDegrees(d));
12511
12512                 out[0] = fp16type(result).bits();
12513                 min[0] = getMin(result, getULPs(in));
12514                 max[0] = getMax(result, getULPs(in));
12515
12516                 return true;
12517         }
12518 };
12519
12520 struct fp16Sin : public fp16PerComponent
12521 {
12522         template<class fp16type>
12523         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12524         {
12525                 const fp16type  x                       (*in[0]);
12526                 const double    d                       (x.asDouble());
12527                 const double    result          (deSin(d));
12528                 const double    unspecUlp       (16.0);
12529                 const double    err                     (de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE) ? deLdExp(1.0, -7) : floatFormat16.ulp(deAbs(result), unspecUlp));
12530
12531                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12532                         return false;
12533
12534                 out[0] = fp16type(result).bits();
12535                 min[0] = result - err;
12536                 max[0] = result + err;
12537
12538                 return true;
12539         }
12540 };
12541
12542 struct fp16Cos : public fp16PerComponent
12543 {
12544         template<class fp16type>
12545         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12546         {
12547                 const fp16type  x                       (*in[0]);
12548                 const double    d                       (x.asDouble());
12549                 const double    result          (deCos(d));
12550                 const double    unspecUlp       (16.0);
12551                 const double    err                     (de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE) ? deLdExp(1.0, -7) : floatFormat16.ulp(deAbs(result), unspecUlp));
12552
12553                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12554                         return false;
12555
12556                 out[0] = fp16type(result).bits();
12557                 min[0] = result - err;
12558                 max[0] = result + err;
12559
12560                 return true;
12561         }
12562 };
12563
12564 struct fp16Tan : public fp16PerComponent
12565 {
12566         template<class fp16type>
12567         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12568         {
12569                 const fp16type  x               (*in[0]);
12570                 const double    d               (x.asDouble());
12571                 const double    result  (deTan(d));
12572
12573                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12574                         return false;
12575
12576                 out[0] = fp16type(result).bits();
12577                 {
12578                         const double    err                     = deLdExp(1.0, -7);
12579                         const double    s1                      = deSin(d) + err;
12580                         const double    s2                      = deSin(d) - err;
12581                         const double    c1                      = deCos(d) + err;
12582                         const double    c2                      = deCos(d) - err;
12583                         const double    edgeVals[]      = {s1/c1, s1/c2, s2/c1, s2/c2};
12584                         double                  edgeLeft        = out[0];
12585                         double                  edgeRight       = out[0];
12586
12587                         if (deSign(c1 * c2) < 0.0)
12588                         {
12589                                 edgeLeft        = -std::numeric_limits<double>::infinity();
12590                                 edgeRight       = +std::numeric_limits<double>::infinity();
12591                         }
12592                         else
12593                         {
12594                                 edgeLeft        = *std::min_element(&edgeVals[0], &edgeVals[DE_LENGTH_OF_ARRAY(edgeVals)]);
12595                                 edgeRight       = *std::max_element(&edgeVals[0], &edgeVals[DE_LENGTH_OF_ARRAY(edgeVals)]);
12596                         }
12597
12598                         min[0] = edgeLeft;
12599                         max[0] = edgeRight;
12600                 }
12601
12602                 return true;
12603         }
12604 };
12605
12606 struct fp16Asin : public fp16PerComponent
12607 {
12608         template<class fp16type>
12609         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12610         {
12611                 const fp16type  x               (*in[0]);
12612                 const double    d               (x.asDouble());
12613                 const double    result  (deAsin(d));
12614                 const double    error   (deAtan2(d, sqrt(1.0 - d * d)));
12615
12616                 if (!x.isNaN() && deAbs(d) > 1.0)
12617                         return false;
12618
12619                 out[0] = fp16type(result).bits();
12620                 min[0] = result - floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12621                 max[0] = result + floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12622
12623                 return true;
12624         }
12625 };
12626
12627 struct fp16Acos : public fp16PerComponent
12628 {
12629         template<class fp16type>
12630         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12631         {
12632                 const fp16type  x               (*in[0]);
12633                 const double    d               (x.asDouble());
12634                 const double    result  (deAcos(d));
12635                 const double    error   (deAtan2(sqrt(1.0 - d * d), d));
12636
12637                 if (!x.isNaN() && deAbs(d) > 1.0)
12638                         return false;
12639
12640                 out[0] = fp16type(result).bits();
12641                 min[0] = result - floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12642                 max[0] = result + floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12643
12644                 return true;
12645         }
12646 };
12647
12648 struct fp16Atan : public fp16PerComponent
12649 {
12650         virtual double getULPs(vector<const deFloat16*>& in)
12651         {
12652                 DE_UNREF(in);
12653
12654                 return 2 * 5.0; // This is not a precision test. Value is not from spec
12655         }
12656
12657         template<class fp16type>
12658         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12659         {
12660                 const fp16type  x               (*in[0]);
12661                 const double    d               (x.asDouble());
12662                 const double    result  (deAtanOver(d));
12663
12664                 out[0] = fp16type(result).bits();
12665                 min[0] = getMin(result, getULPs(in));
12666                 max[0] = getMax(result, getULPs(in));
12667
12668                 return true;
12669         }
12670 };
12671
12672 struct fp16Sinh : public fp16PerComponent
12673 {
12674         fp16Sinh() : fp16PerComponent()
12675         {
12676                 flavorNames.push_back("Double");
12677                 flavorNames.push_back("ExpFP16");
12678         }
12679
12680         template<class fp16type>
12681         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12682         {
12683                 const fp16type  x               (*in[0]);
12684                 const double    d               (x.asDouble());
12685                 const double    ulps    (64 * (1.0 + 2 * deAbs(d))); // This is not a precision test. Value is not from spec
12686                 double                  result  (0.0);
12687                 double                  error   (0.0);
12688
12689                 if (getFlavor() == 0)
12690                 {
12691                         result  = deSinh(d);
12692                         error   = floatFormat16.ulp(deAbs(result), ulps);
12693                 }
12694                 else if (getFlavor() == 1)
12695                 {
12696                         const fp16type  epx     (deExp(d));
12697                         const fp16type  enx     (deExp(-d));
12698                         const fp16type  esx     (epx.asDouble() - enx.asDouble());
12699                         const fp16type  sx2     (esx.asDouble() / 2.0);
12700
12701                         result  = sx2.asDouble();
12702                         error   = deAbs(floatFormat16.ulp(epx.asDouble(), ulps)) + deAbs(floatFormat16.ulp(enx.asDouble(), ulps));
12703                 }
12704                 else
12705                 {
12706                         TCU_THROW(InternalError, "Unknown flavor");
12707                 }
12708
12709                 out[0] = fp16type(result).bits();
12710                 min[0] = result - error;
12711                 max[0] = result + error;
12712
12713                 return true;
12714         }
12715 };
12716
12717 struct fp16Cosh : public fp16PerComponent
12718 {
12719         fp16Cosh() : fp16PerComponent()
12720         {
12721                 flavorNames.push_back("Double");
12722                 flavorNames.push_back("ExpFP16");
12723         }
12724
12725         template<class fp16type>
12726         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12727         {
12728                 const fp16type  x               (*in[0]);
12729                 const double    d               (x.asDouble());
12730                 const double    ulps    (64 * (1.0 + 2 * deAbs(d))); // This is not a precision test. Value is not from spec
12731                 double                  result  (0.0);
12732
12733                 if (getFlavor() == 0)
12734                 {
12735                         result = deCosh(d);
12736                 }
12737                 else if (getFlavor() == 1)
12738                 {
12739                         const fp16type  epx     (deExp(d));
12740                         const fp16type  enx     (deExp(-d));
12741                         const fp16type  esx     (epx.asDouble() + enx.asDouble());
12742                         const fp16type  sx2     (esx.asDouble() / 2.0);
12743
12744                         result = sx2.asDouble();
12745                 }
12746                 else
12747                 {
12748                         TCU_THROW(InternalError, "Unknown flavor");
12749                 }
12750
12751                 out[0] = fp16type(result).bits();
12752                 min[0] = result - floatFormat16.ulp(deAbs(result), ulps);
12753                 max[0] = result + floatFormat16.ulp(deAbs(result), ulps);
12754
12755                 return true;
12756         }
12757 };
12758
12759 struct fp16Tanh : public fp16PerComponent
12760 {
12761         fp16Tanh() : fp16PerComponent()
12762         {
12763                 flavorNames.push_back("Tanh");
12764                 flavorNames.push_back("SinhCosh");
12765                 flavorNames.push_back("SinhCoshFP16");
12766                 flavorNames.push_back("PolyFP16");
12767         }
12768
12769         virtual double getULPs (vector<const deFloat16*>& in)
12770         {
12771                 const tcu::Float16      x       (*in[0]);
12772                 const double            d       (x.asDouble());
12773
12774                 return 2 * (1.0 + 2 * deAbs(d)); // This is not a precision test. Value is not from spec
12775         }
12776
12777         template<class fp16type>
12778         inline double calcPoly (const fp16type& espx, const fp16type& esnx, const fp16type& ecpx, const fp16type& ecnx)
12779         {
12780                 const fp16type  esx     (espx.asDouble() - esnx.asDouble());
12781                 const fp16type  sx2     (esx.asDouble() / 2.0);
12782                 const fp16type  ecx     (ecpx.asDouble() + ecnx.asDouble());
12783                 const fp16type  cx2     (ecx.asDouble() / 2.0);
12784                 const fp16type  tg      (sx2.asDouble() / cx2.asDouble());
12785                 const double    rez     (tg.asDouble());
12786
12787                 return rez;
12788         }
12789
12790         template<class fp16type>
12791         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12792         {
12793                 const fp16type  x               (*in[0]);
12794                 const double    d               (x.asDouble());
12795                 double                  result  (0.0);
12796
12797                 if (getFlavor() == 0)
12798                 {
12799                         result  = deTanh(d);
12800                         min[0]  = getMin(result, getULPs(in));
12801                         max[0]  = getMax(result, getULPs(in));
12802                 }
12803                 else if (getFlavor() == 1)
12804                 {
12805                         result  = deSinh(d) / deCosh(d);
12806                         min[0]  = getMin(result, getULPs(in));
12807                         max[0]  = getMax(result, getULPs(in));
12808                 }
12809                 else if (getFlavor() == 2)
12810                 {
12811                         const fp16type  s       (deSinh(d));
12812                         const fp16type  c       (deCosh(d));
12813
12814                         result  = s.asDouble() / c.asDouble();
12815                         min[0]  = getMin(result, getULPs(in));
12816                         max[0]  = getMax(result, getULPs(in));
12817                 }
12818                 else if (getFlavor() == 3)
12819                 {
12820                         const double    ulps    (getULPs(in));
12821                         const double    epxm    (deExp( d));
12822                         const double    enxm    (deExp(-d));
12823                         const double    epxmerr = floatFormat16.ulp(epxm, ulps);
12824                         const double    enxmerr = floatFormat16.ulp(enxm, ulps);
12825                         const fp16type  epx[]   = { fp16type(epxm - epxmerr), fp16type(epxm + epxmerr) };
12826                         const fp16type  enx[]   = { fp16type(enxm - enxmerr), fp16type(enxm + enxmerr) };
12827                         const fp16type  epxm16  (epxm);
12828                         const fp16type  enxm16  (enxm);
12829                         vector<double>  tgs;
12830
12831                         for (size_t spNdx = 0; spNdx < DE_LENGTH_OF_ARRAY(epx); ++spNdx)
12832                         for (size_t snNdx = 0; snNdx < DE_LENGTH_OF_ARRAY(enx); ++snNdx)
12833                         for (size_t cpNdx = 0; cpNdx < DE_LENGTH_OF_ARRAY(epx); ++cpNdx)
12834                         for (size_t cnNdx = 0; cnNdx < DE_LENGTH_OF_ARRAY(enx); ++cnNdx)
12835                         {
12836                                 const double tgh = calcPoly(epx[spNdx], enx[snNdx], epx[cpNdx], enx[cnNdx]);
12837
12838                                 tgs.push_back(tgh);
12839                         }
12840
12841                         result = calcPoly(epxm16, enxm16, epxm16, enxm16);
12842                         min[0] = *std::min_element(tgs.begin(), tgs.end());
12843                         max[0] = *std::max_element(tgs.begin(), tgs.end());
12844                 }
12845                 else
12846                 {
12847                         TCU_THROW(InternalError, "Unknown flavor");
12848                 }
12849
12850                 out[0] = fp16type(result).bits();
12851
12852                 return true;
12853         }
12854 };
12855
12856 struct fp16Asinh : public fp16PerComponent
12857 {
12858         fp16Asinh() : fp16PerComponent()
12859         {
12860                 flavorNames.push_back("Double");
12861                 flavorNames.push_back("PolyFP16Wiki");
12862                 flavorNames.push_back("PolyFP16Abs");
12863         }
12864
12865         virtual double getULPs (vector<const deFloat16*>& in)
12866         {
12867                 DE_UNREF(in);
12868
12869                 return 256.0; // This is not a precision test. Value is not from spec
12870         }
12871
12872         template<class fp16type>
12873         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12874         {
12875                 const fp16type  x               (*in[0]);
12876                 const double    d               (x.asDouble());
12877                 double                  result  (0.0);
12878
12879                 if (getFlavor() == 0)
12880                 {
12881                         result = deAsinh(d);
12882                 }
12883                 else if (getFlavor() == 1)
12884                 {
12885                         const fp16type  x2              (d * d);
12886                         const fp16type  x2p1    (x2.asDouble() + 1.0);
12887                         const fp16type  sq              (deSqrt(x2p1.asDouble()));
12888                         const fp16type  sxsq    (d + sq.asDouble());
12889                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
12890
12891                         if (lsxsq.isInf())
12892                                 return false;
12893
12894                         result = lsxsq.asDouble();
12895                 }
12896                 else if (getFlavor() == 2)
12897                 {
12898                         const fp16type  x2              (d * d);
12899                         const fp16type  x2p1    (x2.asDouble() + 1.0);
12900                         const fp16type  sq              (deSqrt(x2p1.asDouble()));
12901                         const fp16type  sxsq    (deAbs(d) + sq.asDouble());
12902                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
12903
12904                         result = deSign(d) * lsxsq.asDouble();
12905                 }
12906                 else
12907                 {
12908                         TCU_THROW(InternalError, "Unknown flavor");
12909                 }
12910
12911                 out[0] = fp16type(result).bits();
12912                 min[0] = getMin(result, getULPs(in));
12913                 max[0] = getMax(result, getULPs(in));
12914
12915                 return true;
12916         }
12917 };
12918
12919 struct fp16Acosh : public fp16PerComponent
12920 {
12921         fp16Acosh() : fp16PerComponent()
12922         {
12923                 flavorNames.push_back("Double");
12924                 flavorNames.push_back("PolyFP16");
12925         }
12926
12927         virtual double getULPs (vector<const deFloat16*>& in)
12928         {
12929                 DE_UNREF(in);
12930
12931                 return 16.0; // This is not a precision test. Value is not from spec
12932         }
12933
12934         template<class fp16type>
12935         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12936         {
12937                 const fp16type  x               (*in[0]);
12938                 const double    d               (x.asDouble());
12939                 double                  result  (0.0);
12940
12941                 if (!x.isNaN() && d < 1.0)
12942                         return false;
12943
12944                 if (getFlavor() == 0)
12945                 {
12946                         result = deAcosh(d);
12947                 }
12948                 else if (getFlavor() == 1)
12949                 {
12950                         const fp16type  x2              (d * d);
12951                         const fp16type  x2m1    (x2.asDouble() - 1.0);
12952                         const fp16type  sq              (deSqrt(x2m1.asDouble()));
12953                         const fp16type  sxsq    (d + sq.asDouble());
12954                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
12955
12956                         result = lsxsq.asDouble();
12957                 }
12958                 else
12959                 {
12960                         TCU_THROW(InternalError, "Unknown flavor");
12961                 }
12962
12963                 out[0] = fp16type(result).bits();
12964                 min[0] = getMin(result, getULPs(in));
12965                 max[0] = getMax(result, getULPs(in));
12966
12967                 return true;
12968         }
12969 };
12970
12971 struct fp16Atanh : public fp16PerComponent
12972 {
12973         fp16Atanh() : fp16PerComponent()
12974         {
12975                 flavorNames.push_back("Double");
12976                 flavorNames.push_back("PolyFP16");
12977         }
12978
12979         template<class fp16type>
12980         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12981         {
12982                 const fp16type  x               (*in[0]);
12983                 const double    d               (x.asDouble());
12984                 double                  result  (0.0);
12985
12986                 if (deAbs(d) >= 1.0)
12987                         return false;
12988
12989                 if (getFlavor() == 0)
12990                 {
12991                         const double    ulps    (16.0); // This is not a precision test. Value is not from spec
12992
12993                         result = deAtanh(d);
12994                         min[0] = getMin(result, ulps);
12995                         max[0] = getMax(result, ulps);
12996                 }
12997                 else if (getFlavor() == 1)
12998                 {
12999                         const fp16type  x1a             (1.0 + d);
13000                         const fp16type  x1b             (1.0 - d);
13001                         const fp16type  x1d             (x1a.asDouble() / x1b.asDouble());
13002                         const fp16type  lx1d    (deLog(x1d.asDouble()));
13003                         const fp16type  lx1d2   (0.5 * lx1d.asDouble());
13004                         const double    error   (2 * (de::inRange(deAbs(x1d.asDouble()), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(x1d.asDouble()), 3.0)));
13005
13006                         result = lx1d2.asDouble();
13007                         min[0] = result - error;
13008                         max[0] = result + error;
13009                 }
13010                 else
13011                 {
13012                         TCU_THROW(InternalError, "Unknown flavor");
13013                 }
13014
13015                 out[0] = fp16type(result).bits();
13016
13017                 return true;
13018         }
13019 };
13020
13021 struct fp16Exp : public fp16PerComponent
13022 {
13023         template<class fp16type>
13024         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13025         {
13026                 const fp16type  x               (*in[0]);
13027                 const double    d               (x.asDouble());
13028                 const double    ulps    (10.0 * (1.0 + 2.0 * deAbs(d)));
13029                 const double    result  (deExp(d));
13030
13031                 out[0] = fp16type(result).bits();
13032                 min[0] = getMin(result, ulps);
13033                 max[0] = getMax(result, ulps);
13034
13035                 return true;
13036         }
13037 };
13038
13039 struct fp16Log : public fp16PerComponent
13040 {
13041         template<class fp16type>
13042         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13043         {
13044                 const fp16type  x               (*in[0]);
13045                 const double    d               (x.asDouble());
13046                 const double    result  (deLog(d));
13047                 const double    error   (de::inRange(deAbs(d), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(result), 3.0));
13048
13049                 if (d <= 0.0)
13050                         return false;
13051
13052                 out[0] = fp16type(result).bits();
13053                 min[0] = result - error;
13054                 max[0] = result + error;
13055
13056                 return true;
13057         }
13058 };
13059
13060 struct fp16Exp2 : public fp16PerComponent
13061 {
13062         template<class fp16type>
13063         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13064         {
13065                 const fp16type  x               (*in[0]);
13066                 const double    d               (x.asDouble());
13067                 const double    result  (deExp2(d));
13068                 const double    ulps    (1.0 + 2.0 * deAbs(fp16type(in[0][0]).asDouble()));
13069
13070                 out[0] = fp16type(result).bits();
13071                 min[0] = getMin(result, ulps);
13072                 max[0] = getMax(result, ulps);
13073
13074                 return true;
13075         }
13076 };
13077
13078 struct fp16Log2 : public fp16PerComponent
13079 {
13080         template<class fp16type>
13081         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13082         {
13083                 const fp16type  x               (*in[0]);
13084                 const double    d               (x.asDouble());
13085                 const double    result  (deLog2(d));
13086                 const double    error   (de::inRange(deAbs(d), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(result), 3.0));
13087
13088                 if (d <= 0.0)
13089                         return false;
13090
13091                 out[0] = fp16type(result).bits();
13092                 min[0] = result - error;
13093                 max[0] = result + error;
13094
13095                 return true;
13096         }
13097 };
13098
13099 struct fp16Sqrt : public fp16PerComponent
13100 {
13101         virtual double getULPs (vector<const deFloat16*>& in)
13102         {
13103                 DE_UNREF(in);
13104
13105                 return 6.0;
13106         }
13107
13108         template<class fp16type>
13109         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13110         {
13111                 const fp16type  x               (*in[0]);
13112                 const double    d               (x.asDouble());
13113                 const double    result  (deSqrt(d));
13114
13115                 if (!x.isNaN() && d < 0.0)
13116                         return false;
13117
13118                 out[0] = fp16type(result).bits();
13119                 min[0] = getMin(result, getULPs(in));
13120                 max[0] = getMax(result, getULPs(in));
13121
13122                 return true;
13123         }
13124 };
13125
13126 struct fp16InverseSqrt : public fp16PerComponent
13127 {
13128         virtual double getULPs (vector<const deFloat16*>& in)
13129         {
13130                 DE_UNREF(in);
13131
13132                 return 2.0;
13133         }
13134
13135         template<class fp16type>
13136         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13137         {
13138                 const fp16type  x               (*in[0]);
13139                 const double    d               (x.asDouble());
13140                 const double    result  (1.0/deSqrt(d));
13141
13142                 if (!x.isNaN() && d <= 0.0)
13143                         return false;
13144
13145                 out[0] = fp16type(result).bits();
13146                 min[0] = getMin(result, getULPs(in));
13147                 max[0] = getMax(result, getULPs(in));
13148
13149                 return true;
13150         }
13151 };
13152
13153 struct fp16ModfFrac : public fp16PerComponent
13154 {
13155         template<class fp16type>
13156         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13157         {
13158                 const fp16type  x               (*in[0]);
13159                 const double    d               (x.asDouble());
13160                 double                  i               (0.0);
13161                 const double    result  (deModf(d, &i));
13162
13163                 if (x.isInf() || x.isNaN())
13164                         return false;
13165
13166                 out[0] = fp16type(result).bits();
13167                 min[0] = getMin(result, getULPs(in));
13168                 max[0] = getMax(result, getULPs(in));
13169
13170                 return true;
13171         }
13172 };
13173
13174 struct fp16ModfInt : public fp16PerComponent
13175 {
13176         template<class fp16type>
13177         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13178         {
13179                 const fp16type  x               (*in[0]);
13180                 const double    d               (x.asDouble());
13181                 double                  i               (0.0);
13182                 const double    dummy   (deModf(d, &i));
13183                 const double    result  (i);
13184
13185                 DE_UNREF(dummy);
13186
13187                 if (x.isInf() || x.isNaN())
13188                         return false;
13189
13190                 out[0] = fp16type(result).bits();
13191                 min[0] = getMin(result, getULPs(in));
13192                 max[0] = getMax(result, getULPs(in));
13193
13194                 return true;
13195         }
13196 };
13197
13198 struct fp16FrexpS : public fp16PerComponent
13199 {
13200         template<class fp16type>
13201         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13202         {
13203                 const fp16type  x               (*in[0]);
13204                 const double    d               (x.asDouble());
13205                 int                             e               (0);
13206                 const double    result  (deFrExp(d, &e));
13207
13208                 if (x.isNaN() || x.isInf())
13209                         return false;
13210
13211                 out[0] = fp16type(result).bits();
13212                 min[0] = getMin(result, getULPs(in));
13213                 max[0] = getMax(result, getULPs(in));
13214
13215                 return true;
13216         }
13217 };
13218
13219 struct fp16FrexpE : public fp16PerComponent
13220 {
13221         template<class fp16type>
13222         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13223         {
13224                 const fp16type  x               (*in[0]);
13225                 const double    d               (x.asDouble());
13226                 int                             e               (0);
13227                 const double    dummy   (deFrExp(d, &e));
13228                 const double    result  (static_cast<double>(e));
13229
13230                 DE_UNREF(dummy);
13231
13232                 if (x.isNaN() || x.isInf())
13233                         return false;
13234
13235                 out[0] = fp16type(result).bits();
13236                 min[0] = getMin(result, getULPs(in));
13237                 max[0] = getMax(result, getULPs(in));
13238
13239                 return true;
13240         }
13241 };
13242
13243 struct fp16OpFAdd : public fp16PerComponent
13244 {
13245         template<class fp16type>
13246         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13247         {
13248                 const fp16type  x               (*in[0]);
13249                 const fp16type  y               (*in[1]);
13250                 const double    xd              (x.asDouble());
13251                 const double    yd              (y.asDouble());
13252                 const double    result  (xd + yd);
13253
13254                 out[0] = fp16type(result).bits();
13255                 min[0] = getMin(result, getULPs(in));
13256                 max[0] = getMax(result, getULPs(in));
13257
13258                 return true;
13259         }
13260 };
13261
13262 struct fp16OpFSub : public fp16PerComponent
13263 {
13264         template<class fp16type>
13265         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13266         {
13267                 const fp16type  x               (*in[0]);
13268                 const fp16type  y               (*in[1]);
13269                 const double    xd              (x.asDouble());
13270                 const double    yd              (y.asDouble());
13271                 const double    result  (xd - yd);
13272
13273                 out[0] = fp16type(result).bits();
13274                 min[0] = getMin(result, getULPs(in));
13275                 max[0] = getMax(result, getULPs(in));
13276
13277                 return true;
13278         }
13279 };
13280
13281 struct fp16OpFMul : public fp16PerComponent
13282 {
13283         template<class fp16type>
13284         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13285         {
13286                 const fp16type  x               (*in[0]);
13287                 const fp16type  y               (*in[1]);
13288                 const double    xd              (x.asDouble());
13289                 const double    yd              (y.asDouble());
13290                 const double    result  (xd * yd);
13291
13292                 out[0] = fp16type(result).bits();
13293                 min[0] = getMin(result, getULPs(in));
13294                 max[0] = getMax(result, getULPs(in));
13295
13296                 return true;
13297         }
13298 };
13299
13300 struct fp16OpFDiv : public fp16PerComponent
13301 {
13302         fp16OpFDiv() : fp16PerComponent()
13303         {
13304                 flavorNames.push_back("DirectDiv");
13305                 flavorNames.push_back("InverseDiv");
13306         }
13307
13308         template<class fp16type>
13309         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13310         {
13311                 const fp16type  x                       (*in[0]);
13312                 const fp16type  y                       (*in[1]);
13313                 const double    xd                      (x.asDouble());
13314                 const double    yd                      (y.asDouble());
13315                 const double    unspecUlp       (16.0);
13316                 const double    ulpCnt          (de::inRange(deAbs(yd), deLdExp(1, -14), deLdExp(1, 14)) ? 2.5 : unspecUlp);
13317                 double                  result          (0.0);
13318
13319                 if (y.isZero())
13320                         return false;
13321
13322                 if (getFlavor() == 0)
13323                 {
13324                         result = (xd / yd);
13325                 }
13326                 else if (getFlavor() == 1)
13327                 {
13328                         const double    invyd   (1.0 / yd);
13329                         const fp16type  invy    (invyd);
13330
13331                         result = (xd * invy.asDouble());
13332                 }
13333                 else
13334                 {
13335                         TCU_THROW(InternalError, "Unknown flavor");
13336                 }
13337
13338                 out[0] = fp16type(result).bits();
13339                 min[0] = getMin(result, ulpCnt);
13340                 max[0] = getMax(result, ulpCnt);
13341
13342                 return true;
13343         }
13344 };
13345
13346 struct fp16Atan2 : public fp16PerComponent
13347 {
13348         fp16Atan2() : fp16PerComponent()
13349         {
13350                 flavorNames.push_back("DoubleCalc");
13351                 flavorNames.push_back("DoubleCalc_PI");
13352         }
13353
13354         virtual double getULPs(vector<const deFloat16*>& in)
13355         {
13356                 DE_UNREF(in);
13357
13358                 return 2 * 5.0; // This is not a precision test. Value is not from spec
13359         }
13360
13361         template<class fp16type>
13362         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13363         {
13364                 const fp16type  x               (*in[0]);
13365                 const fp16type  y               (*in[1]);
13366                 const double    xd              (x.asDouble());
13367                 const double    yd              (y.asDouble());
13368                 double                  result  (0.0);
13369
13370                 if (x.isZero() && y.isZero())
13371                         return false;
13372
13373                 if (getFlavor() == 0)
13374                 {
13375                         result  = deAtan2(xd, yd);
13376                 }
13377                 else if (getFlavor() == 1)
13378                 {
13379                         const double    ulps    (2.0 * 5.0); // This is not a precision test. Value is not from spec
13380                         const double    eps             (floatFormat16.ulp(DE_PI_DOUBLE, ulps));
13381
13382                         result  = deAtan2(xd, yd);
13383
13384                         if (de::inRange(deAbs(result), DE_PI_DOUBLE - eps, DE_PI_DOUBLE + eps))
13385                                 result  = -result;
13386                 }
13387                 else
13388                 {
13389                         TCU_THROW(InternalError, "Unknown flavor");
13390                 }
13391
13392                 out[0] = fp16type(result).bits();
13393                 min[0] = getMin(result, getULPs(in));
13394                 max[0] = getMax(result, getULPs(in));
13395
13396                 return true;
13397         }
13398 };
13399
13400 struct fp16Pow : public fp16PerComponent
13401 {
13402         fp16Pow() : fp16PerComponent()
13403         {
13404                 flavorNames.push_back("Pow");
13405                 flavorNames.push_back("PowLog2");
13406                 flavorNames.push_back("PowLog2FP16");
13407         }
13408
13409         template<class fp16type>
13410         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13411         {
13412                 const fp16type  x               (*in[0]);
13413                 const fp16type  y               (*in[1]);
13414                 const double    xd              (x.asDouble());
13415                 const double    yd              (y.asDouble());
13416                 const double    logxeps (de::inRange(deAbs(xd), 0.5, 2.0) ? deLdExp(1.0, -7) : floatFormat16.ulp(deLog2(xd), 3.0));
13417                 const double    ulps1   (1.0 + 4.0 * deAbs(yd * (deLog2(xd) - logxeps)));
13418                 const double    ulps2   (1.0 + 4.0 * deAbs(yd * (deLog2(xd) + logxeps)));
13419                 const double    ulps    (deMax(deAbs(ulps1), deAbs(ulps2)));
13420                 double                  result  (0.0);
13421
13422                 if (xd < 0.0)
13423                         return false;
13424
13425                 if (x.isZero() && yd <= 0.0)
13426                         return false;
13427
13428                 if (getFlavor() == 0)
13429                 {
13430                         result = dePow(xd, yd);
13431                 }
13432                 else if (getFlavor() == 1)
13433                 {
13434                         const double    l2d     (deLog2(xd));
13435                         const double    e2d     (deExp2(yd * l2d));
13436
13437                         result = e2d;
13438                 }
13439                 else if (getFlavor() == 2)
13440                 {
13441                         const double    l2d     (deLog2(xd));
13442                         const fp16type  l2      (l2d);
13443                         const double    e2d     (deExp2(yd * l2.asDouble()));
13444                         const fp16type  e2      (e2d);
13445
13446                         result = e2.asDouble();
13447                 }
13448                 else
13449                 {
13450                         TCU_THROW(InternalError, "Unknown flavor");
13451                 }
13452
13453                 out[0] = fp16type(result).bits();
13454                 min[0] = getMin(result, ulps);
13455                 max[0] = getMax(result, ulps);
13456
13457                 return true;
13458         }
13459 };
13460
13461 struct fp16FMin : public fp16PerComponent
13462 {
13463         template<class fp16type>
13464         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13465         {
13466                 const fp16type  x               (*in[0]);
13467                 const fp16type  y               (*in[1]);
13468                 const double    xd              (x.asDouble());
13469                 const double    yd              (y.asDouble());
13470                 const double    result  (deMin(xd, yd));
13471
13472                 if (x.isNaN() || y.isNaN())
13473                         return false;
13474
13475                 out[0] = fp16type(result).bits();
13476                 min[0] = getMin(result, getULPs(in));
13477                 max[0] = getMax(result, getULPs(in));
13478
13479                 return true;
13480         }
13481 };
13482
13483 struct fp16FMax : public fp16PerComponent
13484 {
13485         template<class fp16type>
13486         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13487         {
13488                 const fp16type  x               (*in[0]);
13489                 const fp16type  y               (*in[1]);
13490                 const double    xd              (x.asDouble());
13491                 const double    yd              (y.asDouble());
13492                 const double    result  (deMax(xd, yd));
13493
13494                 if (x.isNaN() || y.isNaN())
13495                         return false;
13496
13497                 out[0] = fp16type(result).bits();
13498                 min[0] = getMin(result, getULPs(in));
13499                 max[0] = getMax(result, getULPs(in));
13500
13501                 return true;
13502         }
13503 };
13504
13505 struct fp16Step : public fp16PerComponent
13506 {
13507         template<class fp16type>
13508         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13509         {
13510                 const fp16type  edge    (*in[0]);
13511                 const fp16type  x               (*in[1]);
13512                 const double    edged   (edge.asDouble());
13513                 const double    xd              (x.asDouble());
13514                 const double    result  (deStep(edged, xd));
13515
13516                 out[0] = fp16type(result).bits();
13517                 min[0] = getMin(result, getULPs(in));
13518                 max[0] = getMax(result, getULPs(in));
13519
13520                 return true;
13521         }
13522 };
13523
13524 struct fp16Ldexp : public fp16PerComponent
13525 {
13526         template<class fp16type>
13527         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13528         {
13529                 const fp16type  x               (*in[0]);
13530                 const fp16type  y               (*in[1]);
13531                 const double    xd              (x.asDouble());
13532                 const int               yd              (static_cast<int>(deTrunc(y.asDouble())));
13533                 const double    result  (deLdExp(xd, yd));
13534
13535                 if (y.isNaN() || y.isInf() || y.isDenorm() || yd < -14 || yd > 15)
13536                         return false;
13537
13538                 // Spec: "If this product is too large to be represented in the floating-point type, the result is undefined."
13539                 if (fp16type(result).isInf())
13540                         return false;
13541
13542                 out[0] = fp16type(result).bits();
13543                 min[0] = getMin(result, getULPs(in));
13544                 max[0] = getMax(result, getULPs(in));
13545
13546                 return true;
13547         }
13548 };
13549
13550 struct fp16FClamp : public fp16PerComponent
13551 {
13552         template<class fp16type>
13553         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13554         {
13555                 const fp16type  x               (*in[0]);
13556                 const fp16type  minVal  (*in[1]);
13557                 const fp16type  maxVal  (*in[2]);
13558                 const double    xd              (x.asDouble());
13559                 const double    minVald (minVal.asDouble());
13560                 const double    maxVald (maxVal.asDouble());
13561                 const double    result  (deClamp(xd, minVald, maxVald));
13562
13563                 if (minVal.isNaN() || maxVal.isNaN() || minVald > maxVald)
13564                         return false;
13565
13566                 out[0] = fp16type(result).bits();
13567                 min[0] = getMin(result, getULPs(in));
13568                 max[0] = getMax(result, getULPs(in));
13569
13570                 return true;
13571         }
13572 };
13573
13574 struct fp16FMix : public fp16PerComponent
13575 {
13576         fp16FMix() : fp16PerComponent()
13577         {
13578                 flavorNames.push_back("DoubleCalc");
13579                 flavorNames.push_back("EmulatingFP16");
13580                 flavorNames.push_back("EmulatingFP16YminusX");
13581         }
13582
13583         template<class fp16type>
13584         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13585         {
13586                 const fp16type  x               (*in[0]);
13587                 const fp16type  y               (*in[1]);
13588                 const fp16type  a               (*in[2]);
13589                 const double    ulps    (8.0); // This is not a precision test. Value is not from spec
13590                 double                  result  (0.0);
13591
13592                 if (getFlavor() == 0)
13593                 {
13594                         const double    xd              (x.asDouble());
13595                         const double    yd              (y.asDouble());
13596                         const double    ad              (a.asDouble());
13597                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13598                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13599                         const double    eps             (xeps + yeps);
13600
13601                         result = deMix(xd, yd, ad);
13602                         min[0] = result - eps;
13603                         max[0] = result + eps;
13604                 }
13605                 else if (getFlavor() == 1)
13606                 {
13607                         const double    xd              (x.asDouble());
13608                         const double    yd              (y.asDouble());
13609                         const double    ad              (a.asDouble());
13610                         const fp16type  am              (1.0 - ad);
13611                         const double    amd             (am.asDouble());
13612                         const fp16type  xam             (xd * amd);
13613                         const double    xamd    (xam.asDouble());
13614                         const fp16type  ya              (yd * ad);
13615                         const double    yad             (ya.asDouble());
13616                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13617                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13618                         const double    eps             (xeps + yeps);
13619
13620                         result = xamd + yad;
13621                         min[0] = result - eps;
13622                         max[0] = result + eps;
13623                 }
13624                 else if (getFlavor() == 2)
13625                 {
13626                         const double    xd              (x.asDouble());
13627                         const double    yd              (y.asDouble());
13628                         const double    ad              (a.asDouble());
13629                         const fp16type  ymx             (yd - xd);
13630                         const double    ymxd    (ymx.asDouble());
13631                         const fp16type  ymxa    (ymxd * ad);
13632                         const double    ymxad   (ymxa.asDouble());
13633                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13634                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13635                         const double    eps             (xeps + yeps);
13636
13637                         result = xd + ymxad;
13638                         min[0] = result - eps;
13639                         max[0] = result + eps;
13640                 }
13641                 else
13642                 {
13643                         TCU_THROW(InternalError, "Unknown flavor");
13644                 }
13645
13646                 out[0] = fp16type(result).bits();
13647
13648                 return true;
13649         }
13650 };
13651
13652 struct fp16SmoothStep : public fp16PerComponent
13653 {
13654         fp16SmoothStep() : fp16PerComponent()
13655         {
13656                 flavorNames.push_back("FloatCalc");
13657                 flavorNames.push_back("EmulatingFP16");
13658                 flavorNames.push_back("EmulatingFP16WClamp");
13659         }
13660
13661         virtual double getULPs(vector<const deFloat16*>& in)
13662         {
13663                 DE_UNREF(in);
13664
13665                 return 4.0; // This is not a precision test. Value is not from spec
13666         }
13667
13668         template<class fp16type>
13669         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13670         {
13671                 const fp16type  edge0   (*in[0]);
13672                 const fp16type  edge1   (*in[1]);
13673                 const fp16type  x               (*in[2]);
13674                 double                  result  (0.0);
13675
13676                 if (edge0.isNaN() || edge1.isNaN() || x.isNaN() || edge0.asDouble() >= edge1.asDouble())
13677                         return false;
13678
13679                 if (edge0.isInf() || edge1.isInf() || x.isInf())
13680                         return false;
13681
13682                 if (getFlavor() == 0)
13683                 {
13684                         const float     edge0d  (edge0.asFloat());
13685                         const float     edge1d  (edge1.asFloat());
13686                         const float     xd              (x.asFloat());
13687                         const float     sstep   (deFloatSmoothStep(edge0d, edge1d, xd));
13688
13689                         result = sstep;
13690                 }
13691                 else if (getFlavor() == 1)
13692                 {
13693                         const double    edge0d  (edge0.asDouble());
13694                         const double    edge1d  (edge1.asDouble());
13695                         const double    xd              (x.asDouble());
13696
13697                         if (xd <= edge0d)
13698                                 result = 0.0;
13699                         else if (xd >= edge1d)
13700                                 result = 1.0;
13701                         else
13702                         {
13703                                 const fp16type  a       (xd - edge0d);
13704                                 const fp16type  b       (edge1d - edge0d);
13705                                 const fp16type  t       (a.asDouble() / b.asDouble());
13706                                 const fp16type  t2      (2.0 * t.asDouble());
13707                                 const fp16type  t3      (3.0 - t2.asDouble());
13708                                 const fp16type  t4      (t.asDouble() * t3.asDouble());
13709                                 const fp16type  t5      (t.asDouble() * t4.asDouble());
13710
13711                                 result = t5.asDouble();
13712                         }
13713                 }
13714                 else if (getFlavor() == 2)
13715                 {
13716                         const double    edge0d  (edge0.asDouble());
13717                         const double    edge1d  (edge1.asDouble());
13718                         const double    xd              (x.asDouble());
13719                         const fp16type  a       (xd - edge0d);
13720                         const fp16type  b       (edge1d - edge0d);
13721                         const fp16type  bi      (1.0 / b.asDouble());
13722                         const fp16type  t0      (a.asDouble() * bi.asDouble());
13723                         const double    tc      (deClamp(t0.asDouble(), 0.0, 1.0));
13724                         const fp16type  t       (tc);
13725                         const fp16type  t2      (2.0 * t.asDouble());
13726                         const fp16type  t3      (3.0 - t2.asDouble());
13727                         const fp16type  t4      (t.asDouble() * t3.asDouble());
13728                         const fp16type  t5      (t.asDouble() * t4.asDouble());
13729
13730                         result = t5.asDouble();
13731                 }
13732                 else
13733                 {
13734                         TCU_THROW(InternalError, "Unknown flavor");
13735                 }
13736
13737                 out[0] = fp16type(result).bits();
13738                 min[0] = getMin(result, getULPs(in));
13739                 max[0] = getMax(result, getULPs(in));
13740
13741                 return true;
13742         }
13743 };
13744
13745 struct fp16Fma : public fp16PerComponent
13746 {
13747         virtual double getULPs(vector<const deFloat16*>& in)
13748         {
13749                 DE_UNREF(in);
13750
13751                 return 16.0;
13752         }
13753
13754         template<class fp16type>
13755         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13756         {
13757                 DE_ASSERT(in.size() == 3);
13758                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
13759                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
13760                 DE_ASSERT(getArgCompCount(2) == getOutCompCount());
13761                 DE_ASSERT(getOutCompCount() > 0);
13762
13763                 const fp16type  a               (*in[0]);
13764                 const fp16type  b               (*in[1]);
13765                 const fp16type  c               (*in[2]);
13766                 const double    ad              (a.asDouble());
13767                 const double    bd              (b.asDouble());
13768                 const double    cd              (c.asDouble());
13769                 const double    result  (deMadd(ad, bd, cd));
13770
13771                 out[0] = fp16type(result).bits();
13772                 min[0] = getMin(result, getULPs(in));
13773                 max[0] = getMax(result, getULPs(in));
13774
13775                 return true;
13776         }
13777 };
13778
13779
13780 struct fp16AllComponents : public fp16PerComponent
13781 {
13782         bool            callOncePerComponent    ()      { return false; }
13783 };
13784
13785 struct fp16Length : public fp16AllComponents
13786 {
13787         fp16Length() : fp16AllComponents()
13788         {
13789                 flavorNames.push_back("EmulatingFP16");
13790                 flavorNames.push_back("DoubleCalc");
13791         }
13792
13793         virtual double getULPs(vector<const deFloat16*>& in)
13794         {
13795                 DE_UNREF(in);
13796
13797                 return 4.0;
13798         }
13799
13800         template<class fp16type>
13801         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13802         {
13803                 DE_ASSERT(getOutCompCount() == 1);
13804                 DE_ASSERT(in.size() == 1);
13805
13806                 double  result  (0.0);
13807
13808                 if (getFlavor() == 0)
13809                 {
13810                         fp16type        r       (0.0);
13811
13812                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13813                         {
13814                                 const fp16type  x       (in[0][componentNdx]);
13815                                 const fp16type  q       (x.asDouble() * x.asDouble());
13816
13817                                 r = fp16type(r.asDouble() + q.asDouble());
13818                         }
13819
13820                         result = deSqrt(r.asDouble());
13821
13822                         out[0] = fp16type(result).bits();
13823                 }
13824                 else if (getFlavor() == 1)
13825                 {
13826                         double  r       (0.0);
13827
13828                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13829                         {
13830                                 const fp16type  x       (in[0][componentNdx]);
13831                                 const double    q       (x.asDouble() * x.asDouble());
13832
13833                                 r += q;
13834                         }
13835
13836                         result = deSqrt(r);
13837
13838                         out[0] = fp16type(result).bits();
13839                 }
13840                 else
13841                 {
13842                         TCU_THROW(InternalError, "Unknown flavor");
13843                 }
13844
13845                 min[0] = getMin(result, getULPs(in));
13846                 max[0] = getMax(result, getULPs(in));
13847
13848                 return true;
13849         }
13850 };
13851
13852 struct fp16Distance : public fp16AllComponents
13853 {
13854         fp16Distance() : fp16AllComponents()
13855         {
13856                 flavorNames.push_back("EmulatingFP16");
13857                 flavorNames.push_back("DoubleCalc");
13858         }
13859
13860         virtual double getULPs(vector<const deFloat16*>& in)
13861         {
13862                 DE_UNREF(in);
13863
13864                 return 4.0;
13865         }
13866
13867         template<class fp16type>
13868         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13869         {
13870                 DE_ASSERT(getOutCompCount() == 1);
13871                 DE_ASSERT(in.size() == 2);
13872                 DE_ASSERT(getArgCompCount(0) == getArgCompCount(1));
13873
13874                 double  result  (0.0);
13875
13876                 if (getFlavor() == 0)
13877                 {
13878                         fp16type        r       (0.0);
13879
13880                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13881                         {
13882                                 const fp16type  x       (in[0][componentNdx]);
13883                                 const fp16type  y       (in[1][componentNdx]);
13884                                 const fp16type  d       (x.asDouble() - y.asDouble());
13885                                 const fp16type  q       (d.asDouble() * d.asDouble());
13886
13887                                 r = fp16type(r.asDouble() + q.asDouble());
13888                         }
13889
13890                         result = deSqrt(r.asDouble());
13891                 }
13892                 else if (getFlavor() == 1)
13893                 {
13894                         double  r       (0.0);
13895
13896                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13897                         {
13898                                 const fp16type  x       (in[0][componentNdx]);
13899                                 const fp16type  y       (in[1][componentNdx]);
13900                                 const double    d       (x.asDouble() - y.asDouble());
13901                                 const double    q       (d * d);
13902
13903                                 r += q;
13904                         }
13905
13906                         result = deSqrt(r);
13907                 }
13908                 else
13909                 {
13910                         TCU_THROW(InternalError, "Unknown flavor");
13911                 }
13912
13913                 out[0] = fp16type(result).bits();
13914                 min[0] = getMin(result, getULPs(in));
13915                 max[0] = getMax(result, getULPs(in));
13916
13917                 return true;
13918         }
13919 };
13920
13921 struct fp16Cross : public fp16AllComponents
13922 {
13923         fp16Cross() : fp16AllComponents()
13924         {
13925                 flavorNames.push_back("EmulatingFP16");
13926                 flavorNames.push_back("DoubleCalc");
13927         }
13928
13929         virtual double getULPs(vector<const deFloat16*>& in)
13930         {
13931                 DE_UNREF(in);
13932
13933                 return 4.0;
13934         }
13935
13936         template<class fp16type>
13937         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13938         {
13939                 DE_ASSERT(getOutCompCount() == 3);
13940                 DE_ASSERT(in.size() == 2);
13941                 DE_ASSERT(getArgCompCount(0) == 3);
13942                 DE_ASSERT(getArgCompCount(1) == 3);
13943
13944                 if (getFlavor() == 0)
13945                 {
13946                         const fp16type  x0              (in[0][0]);
13947                         const fp16type  x1              (in[0][1]);
13948                         const fp16type  x2              (in[0][2]);
13949                         const fp16type  y0              (in[1][0]);
13950                         const fp16type  y1              (in[1][1]);
13951                         const fp16type  y2              (in[1][2]);
13952                         const fp16type  x1y2    (x1.asDouble() * y2.asDouble());
13953                         const fp16type  y1x2    (y1.asDouble() * x2.asDouble());
13954                         const fp16type  x2y0    (x2.asDouble() * y0.asDouble());
13955                         const fp16type  y2x0    (y2.asDouble() * x0.asDouble());
13956                         const fp16type  x0y1    (x0.asDouble() * y1.asDouble());
13957                         const fp16type  y0x1    (y0.asDouble() * x1.asDouble());
13958
13959                         out[0] = fp16type(x1y2.asDouble() - y1x2.asDouble()).bits();
13960                         out[1] = fp16type(x2y0.asDouble() - y2x0.asDouble()).bits();
13961                         out[2] = fp16type(x0y1.asDouble() - y0x1.asDouble()).bits();
13962                 }
13963                 else if (getFlavor() == 1)
13964                 {
13965                         const fp16type  x0              (in[0][0]);
13966                         const fp16type  x1              (in[0][1]);
13967                         const fp16type  x2              (in[0][2]);
13968                         const fp16type  y0              (in[1][0]);
13969                         const fp16type  y1              (in[1][1]);
13970                         const fp16type  y2              (in[1][2]);
13971                         const double    x1y2    (x1.asDouble() * y2.asDouble());
13972                         const double    y1x2    (y1.asDouble() * x2.asDouble());
13973                         const double    x2y0    (x2.asDouble() * y0.asDouble());
13974                         const double    y2x0    (y2.asDouble() * x0.asDouble());
13975                         const double    x0y1    (x0.asDouble() * y1.asDouble());
13976                         const double    y0x1    (y0.asDouble() * x1.asDouble());
13977
13978                         out[0] = fp16type(x1y2 - y1x2).bits();
13979                         out[1] = fp16type(x2y0 - y2x0).bits();
13980                         out[2] = fp16type(x0y1 - y0x1).bits();
13981                 }
13982                 else
13983                 {
13984                         TCU_THROW(InternalError, "Unknown flavor");
13985                 }
13986
13987                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
13988                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
13989                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
13990                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
13991
13992                 return true;
13993         }
13994 };
13995
13996 struct fp16Normalize : public fp16AllComponents
13997 {
13998         fp16Normalize() : fp16AllComponents()
13999         {
14000                 flavorNames.push_back("EmulatingFP16");
14001                 flavorNames.push_back("DoubleCalc");
14002
14003                 // flavorNames will be extended later
14004         }
14005
14006         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)
14007         {
14008                 DE_ASSERT(argCompCount[argNo] == 0); // Once only
14009
14010                 if (argNo == 0 && argCompCount[argNo] == 0)
14011                 {
14012                         const size_t            maxPermutationsCount    = 24u; // Equal to 4!
14013                         std::vector<int>        indices;
14014
14015                         for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14016                                 indices.push_back(static_cast<int>(componentNdx));
14017
14018                         m_permutations.reserve(maxPermutationsCount);
14019
14020                         permutationsFlavorStart = flavorNames.size();
14021
14022                         do
14023                         {
14024                                 tcu::UVec4      permutation;
14025                                 std::string     name            = "Permutted_";
14026
14027                                 for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14028                                 {
14029                                         permutation[static_cast<int>(componentNdx)] = indices[componentNdx];
14030                                         name += de::toString(indices[componentNdx]);
14031                                 }
14032
14033                                 m_permutations.push_back(permutation);
14034                                 flavorNames.push_back(name);
14035
14036                         } while(std::next_permutation(indices.begin(), indices.end()));
14037
14038                         permutationsFlavorEnd = flavorNames.size();
14039                 }
14040
14041                 fp16AllComponents::setArgCompCount(argNo, compCount);
14042         }
14043         virtual double getULPs(vector<const deFloat16*>& in)
14044         {
14045                 DE_UNREF(in);
14046
14047                 return 8.0;
14048         }
14049
14050         template<class fp16type>
14051         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14052         {
14053                 DE_ASSERT(in.size() == 1);
14054                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14055
14056                 if (getFlavor() == 0)
14057                 {
14058                         fp16type        r(0.0);
14059
14060                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14061                         {
14062                                 const fp16type  x       (in[0][componentNdx]);
14063                                 const fp16type  q       (x.asDouble() * x.asDouble());
14064
14065                                 r = fp16type(r.asDouble() + q.asDouble());
14066                         }
14067
14068                         r = fp16type(deSqrt(r.asDouble()));
14069
14070                         if (r.isZero())
14071                                 return false;
14072
14073                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14074                         {
14075                                 const fp16type  x       (in[0][componentNdx]);
14076
14077                                 out[componentNdx] = fp16type(x.asDouble() / r.asDouble()).bits();
14078                         }
14079                 }
14080                 else if (getFlavor() == 1)
14081                 {
14082                         double  r(0.0);
14083
14084                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14085                         {
14086                                 const fp16type  x       (in[0][componentNdx]);
14087                                 const double    q       (x.asDouble() * x.asDouble());
14088
14089                                 r += q;
14090                         }
14091
14092                         r = deSqrt(r);
14093
14094                         if (r == 0)
14095                                 return false;
14096
14097                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14098                         {
14099                                 const fp16type  x       (in[0][componentNdx]);
14100
14101                                 out[componentNdx] = fp16type(x.asDouble() / r).bits();
14102                         }
14103                 }
14104                 else if (de::inBounds<size_t>(getFlavor(), permutationsFlavorStart, permutationsFlavorEnd))
14105                 {
14106                         const int                       compCount               (static_cast<int>(getArgCompCount(0)));
14107                         const size_t            permutationNdx  (getFlavor() - permutationsFlavorStart);
14108                         const tcu::UVec4&       permutation             (m_permutations[permutationNdx]);
14109                         fp16type                        r                               (0.0);
14110
14111                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14112                         {
14113                                 const size_t    componentNdx    (permutation[permComponentNdx]);
14114                                 const fp16type  x                               (in[0][componentNdx]);
14115                                 const fp16type  q                               (x.asDouble() * x.asDouble());
14116
14117                                 r = fp16type(r.asDouble() + q.asDouble());
14118                         }
14119
14120                         r = fp16type(deSqrt(r.asDouble()));
14121
14122                         if (r.isZero())
14123                                 return false;
14124
14125                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14126                         {
14127                                 const size_t    componentNdx    (permutation[permComponentNdx]);
14128                                 const fp16type  x                               (in[0][componentNdx]);
14129
14130                                 out[componentNdx] = fp16type(x.asDouble() / r.asDouble()).bits();
14131                         }
14132                 }
14133                 else
14134                 {
14135                         TCU_THROW(InternalError, "Unknown flavor");
14136                 }
14137
14138                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14139                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14140                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14141                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14142
14143                 return true;
14144         }
14145
14146 private:
14147         std::vector<tcu::UVec4> m_permutations;
14148         size_t                                  permutationsFlavorStart;
14149         size_t                                  permutationsFlavorEnd;
14150 };
14151
14152 struct fp16FaceForward : public fp16AllComponents
14153 {
14154         virtual double getULPs(vector<const deFloat16*>& in)
14155         {
14156                 DE_UNREF(in);
14157
14158                 return 4.0;
14159         }
14160
14161         template<class fp16type>
14162         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14163         {
14164                 DE_ASSERT(in.size() == 3);
14165                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14166                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14167                 DE_ASSERT(getArgCompCount(2) == getOutCompCount());
14168
14169                 fp16type        dp(0.0);
14170
14171                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14172                 {
14173                         const fp16type  x       (in[1][componentNdx]);
14174                         const fp16type  y       (in[2][componentNdx]);
14175                         const double    xd      (x.asDouble());
14176                         const double    yd      (y.asDouble());
14177                         const fp16type  q       (xd * yd);
14178
14179                         dp = fp16type(dp.asDouble() + q.asDouble());
14180                 }
14181
14182                 if (dp.isNaN() || dp.isZero())
14183                         return false;
14184
14185                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14186                 {
14187                         const fp16type  n       (in[0][componentNdx]);
14188
14189                         out[componentNdx] = (dp.signBit() == 1) ? n.bits() : fp16type(-n.asDouble()).bits();
14190                 }
14191
14192                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14193                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14194                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14195                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14196
14197                 return true;
14198         }
14199 };
14200
14201 struct fp16Reflect : public fp16AllComponents
14202 {
14203         fp16Reflect() : fp16AllComponents()
14204         {
14205                 flavorNames.push_back("EmulatingFP16");
14206                 flavorNames.push_back("EmulatingFP16+KeepZeroSign");
14207                 flavorNames.push_back("FloatCalc");
14208                 flavorNames.push_back("FloatCalc+KeepZeroSign");
14209                 flavorNames.push_back("EmulatingFP16+2Nfirst");
14210                 flavorNames.push_back("EmulatingFP16+2Ifirst");
14211         }
14212
14213         virtual double getULPs(vector<const deFloat16*>& in)
14214         {
14215                 DE_UNREF(in);
14216
14217                 return 256.0; // This is not a precision test. Value is not from spec
14218         }
14219
14220         template<class fp16type>
14221         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14222         {
14223                 DE_ASSERT(in.size() == 2);
14224                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14225                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14226
14227                 if (getFlavor() < 4)
14228                 {
14229                         const bool      keepZeroSign    ((flavor & 1) != 0 ? true : false);
14230                         const bool      floatCalc               ((flavor & 2) != 0 ? true : false);
14231
14232                         if (floatCalc)
14233                         {
14234                                 float   dp(0.0f);
14235
14236                                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14237                                 {
14238                                         const fp16type  i       (in[0][componentNdx]);
14239                                         const fp16type  n       (in[1][componentNdx]);
14240                                         const float             id      (i.asFloat());
14241                                         const float             nd      (n.asFloat());
14242                                         const float             qd      (id * nd);
14243
14244                                         if (keepZeroSign)
14245                                                 dp = (componentNdx == 0) ? qd : dp + qd;
14246                                         else
14247                                                 dp = dp + qd;
14248                                 }
14249
14250                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14251                                 {
14252                                         const fp16type  i               (in[0][componentNdx]);
14253                                         const fp16type  n               (in[1][componentNdx]);
14254                                         const float             dpnd    (dp * n.asFloat());
14255                                         const float             dpn2d   (2.0f * dpnd);
14256                                         const float             idpn2d  (i.asFloat() - dpn2d);
14257                                         const fp16type  result  (idpn2d);
14258
14259                                         out[componentNdx] = result.bits();
14260                                 }
14261                         }
14262                         else
14263                         {
14264                                 fp16type        dp(0.0);
14265
14266                                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14267                                 {
14268                                         const fp16type  i       (in[0][componentNdx]);
14269                                         const fp16type  n       (in[1][componentNdx]);
14270                                         const double    id      (i.asDouble());
14271                                         const double    nd      (n.asDouble());
14272                                         const fp16type  q       (id * nd);
14273
14274                                         if (keepZeroSign)
14275                                                 dp = (componentNdx == 0) ? q : fp16type(dp.asDouble() + q.asDouble());
14276                                         else
14277                                                 dp = fp16type(dp.asDouble() + q.asDouble());
14278                                 }
14279
14280                                 if (dp.isNaN())
14281                                         return false;
14282
14283                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14284                                 {
14285                                         const fp16type  i               (in[0][componentNdx]);
14286                                         const fp16type  n               (in[1][componentNdx]);
14287                                         const fp16type  dpn             (dp.asDouble() * n.asDouble());
14288                                         const fp16type  dpn2    (2 * dpn.asDouble());
14289                                         const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
14290
14291                                         out[componentNdx] = idpn2.bits();
14292                                 }
14293                         }
14294                 }
14295                 else if (getFlavor() == 4)
14296                 {
14297                         fp16type        dp(0.0);
14298
14299                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14300                         {
14301                                 const fp16type  i       (in[0][componentNdx]);
14302                                 const fp16type  n       (in[1][componentNdx]);
14303                                 const double    id      (i.asDouble());
14304                                 const double    nd      (n.asDouble());
14305                                 const fp16type  q       (id * nd);
14306
14307                                 dp = fp16type(dp.asDouble() + q.asDouble());
14308                         }
14309
14310                         if (dp.isNaN())
14311                                 return false;
14312
14313                         for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14314                         {
14315                                 const fp16type  i               (in[0][componentNdx]);
14316                                 const fp16type  n               (in[1][componentNdx]);
14317                                 const fp16type  n2              (2 * n.asDouble());
14318                                 const fp16type  dpn2    (dp.asDouble() * n2.asDouble());
14319                                 const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
14320
14321                                 out[componentNdx] = idpn2.bits();
14322                         }
14323                 }
14324                 else if (getFlavor() == 5)
14325                 {
14326                         fp16type        dp2(0.0);
14327
14328                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14329                         {
14330                                 const fp16type  i       (in[0][componentNdx]);
14331                                 const fp16type  n       (in[1][componentNdx]);
14332                                 const fp16type  i2      (2.0 * i.asDouble());
14333                                 const double    i2d     (i2.asDouble());
14334                                 const double    nd      (n.asDouble());
14335                                 const fp16type  q       (i2d * nd);
14336
14337                                 dp2 = fp16type(dp2.asDouble() + q.asDouble());
14338                         }
14339
14340                         if (dp2.isNaN())
14341                                 return false;
14342
14343                         for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14344                         {
14345                                 const fp16type  i               (in[0][componentNdx]);
14346                                 const fp16type  n               (in[1][componentNdx]);
14347                                 const fp16type  dpn2    (dp2.asDouble() * n.asDouble());
14348                                 const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
14349
14350                                 out[componentNdx] = idpn2.bits();
14351                         }
14352                 }
14353                 else
14354                 {
14355                         TCU_THROW(InternalError, "Unknown flavor");
14356                 }
14357
14358                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14359                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14360                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14361                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14362
14363                 return true;
14364         }
14365 };
14366
14367 struct fp16Refract : public fp16AllComponents
14368 {
14369         fp16Refract() : fp16AllComponents()
14370         {
14371                 flavorNames.push_back("EmulatingFP16");
14372                 flavorNames.push_back("EmulatingFP16+KeepZeroSign");
14373                 flavorNames.push_back("FloatCalc");
14374                 flavorNames.push_back("FloatCalc+KeepZeroSign");
14375         }
14376
14377         virtual double getULPs(vector<const deFloat16*>& in)
14378         {
14379                 DE_UNREF(in);
14380
14381                 return 8192.0; // This is not a precision test. Value is not from spec
14382         }
14383
14384         template<class fp16type>
14385         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14386         {
14387                 DE_ASSERT(in.size() == 3);
14388                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14389                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14390                 DE_ASSERT(getArgCompCount(2) == 1);
14391
14392                 const bool              keepZeroSign    ((flavor & 1) != 0 ? true : false);
14393                 const bool              doubleCalc              ((flavor & 2) != 0 ? true : false);
14394                 const fp16type  eta                             (*in[2]);
14395
14396                 if (doubleCalc)
14397                 {
14398                         double  dp      (0.0);
14399
14400                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14401                         {
14402                                 const fp16type  i       (in[0][componentNdx]);
14403                                 const fp16type  n       (in[1][componentNdx]);
14404                                 const double    id      (i.asDouble());
14405                                 const double    nd      (n.asDouble());
14406                                 const double    qd      (id * nd);
14407
14408                                 if (keepZeroSign)
14409                                         dp = (componentNdx == 0) ? qd : dp + qd;
14410                                 else
14411                                         dp = dp + qd;
14412                         }
14413
14414                         const double    eta2    (eta.asDouble() * eta.asDouble());
14415                         const double    dp2             (dp * dp);
14416                         const double    dp1             (1.0 - dp2);
14417                         const double    dpe             (eta2 * dp1);
14418                         const double    k               (1.0 - dpe);
14419
14420                         if (k < 0.0)
14421                         {
14422                                 const fp16type  zero    (0.0);
14423
14424                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14425                                         out[componentNdx] = zero.bits();
14426                         }
14427                         else
14428                         {
14429                                 const double    sk      (deSqrt(k));
14430
14431                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14432                                 {
14433                                         const fp16type  i               (in[0][componentNdx]);
14434                                         const fp16type  n               (in[1][componentNdx]);
14435                                         const double    etai    (i.asDouble() * eta.asDouble());
14436                                         const double    etadp   (eta.asDouble() * dp);
14437                                         const double    etadpk  (etadp + sk);
14438                                         const double    etadpkn (etadpk * n.asDouble());
14439                                         const double    full    (etai - etadpkn);
14440                                         const fp16type  result  (full);
14441
14442                                         if (result.isInf())
14443                                                 return false;
14444
14445                                         out[componentNdx] = result.bits();
14446                                 }
14447                         }
14448                 }
14449                 else
14450                 {
14451                         fp16type        dp      (0.0);
14452
14453                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14454                         {
14455                                 const fp16type  i       (in[0][componentNdx]);
14456                                 const fp16type  n       (in[1][componentNdx]);
14457                                 const double    id      (i.asDouble());
14458                                 const double    nd      (n.asDouble());
14459                                 const fp16type  q       (id * nd);
14460
14461                                 if (keepZeroSign)
14462                                         dp = (componentNdx == 0) ? q : fp16type(dp.asDouble() + q.asDouble());
14463                                 else
14464                                         dp = fp16type(dp.asDouble() + q.asDouble());
14465                         }
14466
14467                         if (dp.isNaN())
14468                                 return false;
14469
14470                         const fp16type  eta2(eta.asDouble() * eta.asDouble());
14471                         const fp16type  dp2     (dp.asDouble() * dp.asDouble());
14472                         const fp16type  dp1     (1.0 - dp2.asDouble());
14473                         const fp16type  dpe     (eta2.asDouble() * dp1.asDouble());
14474                         const fp16type  k       (1.0 - dpe.asDouble());
14475
14476                         if (k.asDouble() < 0.0)
14477                         {
14478                                 const fp16type  zero    (0.0);
14479
14480                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14481                                         out[componentNdx] = zero.bits();
14482                         }
14483                         else
14484                         {
14485                                 const fp16type  sk      (deSqrt(k.asDouble()));
14486
14487                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14488                                 {
14489                                         const fp16type  i               (in[0][componentNdx]);
14490                                         const fp16type  n               (in[1][componentNdx]);
14491                                         const fp16type  etai    (i.asDouble() * eta.asDouble());
14492                                         const fp16type  etadp   (eta.asDouble() * dp.asDouble());
14493                                         const fp16type  etadpk  (etadp.asDouble() + sk.asDouble());
14494                                         const fp16type  etadpkn (etadpk.asDouble() * n.asDouble());
14495                                         const fp16type  full    (etai.asDouble() - etadpkn.asDouble());
14496
14497                                         if (full.isNaN() || full.isInf())
14498                                                 return false;
14499
14500                                         out[componentNdx] = full.bits();
14501                                 }
14502                         }
14503                 }
14504
14505                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14506                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14507                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14508                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14509
14510                 return true;
14511         }
14512 };
14513
14514 struct fp16Dot : public fp16AllComponents
14515 {
14516         fp16Dot() : fp16AllComponents()
14517         {
14518                 flavorNames.push_back("EmulatingFP16");
14519                 flavorNames.push_back("FloatCalc");
14520                 flavorNames.push_back("DoubleCalc");
14521
14522                 // flavorNames will be extended later
14523         }
14524
14525         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)
14526         {
14527                 DE_ASSERT(argCompCount[argNo] == 0); // Once only
14528
14529                 if (argNo == 0 && argCompCount[argNo] == 0)
14530                 {
14531                         const size_t            maxPermutationsCount    = 24u; // Equal to 4!
14532                         std::vector<int>        indices;
14533
14534                         for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14535                                 indices.push_back(static_cast<int>(componentNdx));
14536
14537                         m_permutations.reserve(maxPermutationsCount);
14538
14539                         permutationsFlavorStart = flavorNames.size();
14540
14541                         do
14542                         {
14543                                 tcu::UVec4      permutation;
14544                                 std::string     name            = "Permutted_";
14545
14546                                 for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14547                                 {
14548                                         permutation[static_cast<int>(componentNdx)] = indices[componentNdx];
14549                                         name += de::toString(indices[componentNdx]);
14550                                 }
14551
14552                                 m_permutations.push_back(permutation);
14553                                 flavorNames.push_back(name);
14554
14555                         } while(std::next_permutation(indices.begin(), indices.end()));
14556
14557                         permutationsFlavorEnd = flavorNames.size();
14558                 }
14559
14560                 fp16AllComponents::setArgCompCount(argNo, compCount);
14561         }
14562
14563         virtual double  getULPs(vector<const deFloat16*>& in)
14564         {
14565                 DE_UNREF(in);
14566
14567                 return 16.0; // This is not a precision test. Value is not from spec
14568         }
14569
14570         template<class fp16type>
14571         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14572         {
14573                 DE_ASSERT(in.size() == 2);
14574                 DE_ASSERT(getArgCompCount(0) == getArgCompCount(1));
14575                 DE_ASSERT(getOutCompCount() == 1);
14576
14577                 double  result  (0.0);
14578                 double  eps             (0.0);
14579
14580                 if (getFlavor() == 0)
14581                 {
14582                         fp16type        dp      (0.0);
14583
14584                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14585                         {
14586                                 const fp16type  x       (in[0][componentNdx]);
14587                                 const fp16type  y       (in[1][componentNdx]);
14588                                 const fp16type  q       (x.asDouble() * y.asDouble());
14589
14590                                 dp = fp16type(dp.asDouble() + q.asDouble());
14591                                 eps += floatFormat16.ulp(q.asDouble(), 2.0);
14592                         }
14593
14594                         result = dp.asDouble();
14595                 }
14596                 else if (getFlavor() == 1)
14597                 {
14598                         float   dp      (0.0);
14599
14600                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14601                         {
14602                                 const fp16type  x       (in[0][componentNdx]);
14603                                 const fp16type  y       (in[1][componentNdx]);
14604                                 const float             q       (x.asFloat() * y.asFloat());
14605
14606                                 dp += q;
14607                                 eps += floatFormat16.ulp(static_cast<double>(q), 2.0);
14608                         }
14609
14610                         result = dp;
14611                 }
14612                 else if (getFlavor() == 2)
14613                 {
14614                         double  dp      (0.0);
14615
14616                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14617                         {
14618                                 const fp16type  x       (in[0][componentNdx]);
14619                                 const fp16type  y       (in[1][componentNdx]);
14620                                 const double    q       (x.asDouble() * y.asDouble());
14621
14622                                 dp += q;
14623                                 eps += floatFormat16.ulp(q, 2.0);
14624                         }
14625
14626                         result = dp;
14627                 }
14628                 else if (de::inBounds<size_t>(getFlavor(), permutationsFlavorStart, permutationsFlavorEnd))
14629                 {
14630                         const int                       compCount               (static_cast<int>(getArgCompCount(1)));
14631                         const size_t            permutationNdx  (getFlavor() - permutationsFlavorStart);
14632                         const tcu::UVec4&       permutation             (m_permutations[permutationNdx]);
14633                         fp16type                        dp                              (0.0);
14634
14635                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14636                         {
14637                                 const size_t            componentNdx    (permutation[permComponentNdx]);
14638                                 const fp16type          x                               (in[0][componentNdx]);
14639                                 const fp16type          y                               (in[1][componentNdx]);
14640                                 const fp16type          q                               (x.asDouble() * y.asDouble());
14641
14642                                 dp = fp16type(dp.asDouble() + q.asDouble());
14643                                 eps += floatFormat16.ulp(q.asDouble(), 2.0);
14644                         }
14645
14646                         result = dp.asDouble();
14647                 }
14648                 else
14649                 {
14650                         TCU_THROW(InternalError, "Unknown flavor");
14651                 }
14652
14653                 out[0] = fp16type(result).bits();
14654                 min[0] = result - eps;
14655                 max[0] = result + eps;
14656
14657                 return true;
14658         }
14659
14660 private:
14661         std::vector<tcu::UVec4> m_permutations;
14662         size_t                                  permutationsFlavorStart;
14663         size_t                                  permutationsFlavorEnd;
14664 };
14665
14666 struct fp16VectorTimesScalar : public fp16AllComponents
14667 {
14668         virtual double getULPs(vector<const deFloat16*>& in)
14669         {
14670                 DE_UNREF(in);
14671
14672                 return 2.0;
14673         }
14674
14675         template<class fp16type>
14676         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14677         {
14678                 DE_ASSERT(in.size() == 2);
14679                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14680                 DE_ASSERT(getArgCompCount(1) == 1);
14681
14682                 fp16type        s       (*in[1]);
14683
14684                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14685                 {
14686                         const fp16type  x          (in[0][componentNdx]);
14687                         const double    result (s.asDouble() * x.asDouble());
14688                         const fp16type  m          (result);
14689
14690                         out[componentNdx] = m.bits();
14691                         min[componentNdx] = getMin(result, getULPs(in));
14692                         max[componentNdx] = getMax(result, getULPs(in));
14693                 }
14694
14695                 return true;
14696         }
14697 };
14698
14699 struct fp16MatrixBase : public fp16AllComponents
14700 {
14701         deUint32                getComponentValidity                    ()
14702         {
14703                 return static_cast<deUint32>(-1);
14704         }
14705
14706         inline size_t   getNdx                                                  (const size_t rowCount, const size_t col, const size_t row)
14707         {
14708                 const size_t minComponentCount  = 0;
14709                 const size_t maxComponentCount  = 3;
14710                 const size_t alignedRowsCount   = (rowCount == 3) ? 4 : rowCount;
14711
14712                 DE_ASSERT(de::inRange(rowCount, minComponentCount + 1, maxComponentCount + 1));
14713                 DE_ASSERT(de::inRange(col, minComponentCount, maxComponentCount));
14714                 DE_ASSERT(de::inBounds(row, minComponentCount, rowCount));
14715                 DE_UNREF(minComponentCount);
14716                 DE_UNREF(maxComponentCount);
14717
14718                 return col * alignedRowsCount + row;
14719         }
14720
14721         deUint32                getComponentMatrixValidityMask  (size_t cols, size_t rows)
14722         {
14723                 deUint32        result  = 0u;
14724
14725                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14726                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14727                         {
14728                                 const size_t bitNdx = getNdx(rows, colNdx, rowNdx);
14729
14730                                 DE_ASSERT(bitNdx < sizeof(result) * 8);
14731
14732                                 result |= (1<<bitNdx);
14733                         }
14734
14735                 return result;
14736         }
14737 };
14738
14739 template<size_t cols, size_t rows>
14740 struct fp16Transpose : public fp16MatrixBase
14741 {
14742         virtual double getULPs(vector<const deFloat16*>& in)
14743         {
14744                 DE_UNREF(in);
14745
14746                 return 1.0;
14747         }
14748
14749         deUint32        getComponentValidity    ()
14750         {
14751                 return getComponentMatrixValidityMask(rows, cols);
14752         }
14753
14754         template<class fp16type>
14755         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14756         {
14757                 DE_ASSERT(in.size() == 1);
14758
14759                 const size_t            alignedCols     = (cols == 3) ? 4 : cols;
14760                 const size_t            alignedRows     = (rows == 3) ? 4 : rows;
14761                 vector<deFloat16>       output          (alignedCols * alignedRows, 0);
14762
14763                 DE_ASSERT(output.size() == alignedCols * alignedRows);
14764
14765                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14766                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14767                                 output[rowNdx * alignedCols + colNdx] = in[0][colNdx * alignedRows + rowNdx];
14768
14769                 deMemcpy(out, &output[0], sizeof(deFloat16) * output.size());
14770                 deMemcpy(min, &output[0], sizeof(deFloat16) * output.size());
14771                 deMemcpy(max, &output[0], sizeof(deFloat16) * output.size());
14772
14773                 return true;
14774         }
14775 };
14776
14777 template<size_t cols, size_t rows>
14778 struct fp16MatrixTimesScalar : public fp16MatrixBase
14779 {
14780         virtual double getULPs(vector<const deFloat16*>& in)
14781         {
14782                 DE_UNREF(in);
14783
14784                 return 4.0;
14785         }
14786
14787         deUint32        getComponentValidity    ()
14788         {
14789                 return getComponentMatrixValidityMask(cols, rows);
14790         }
14791
14792         template<class fp16type>
14793         bool calc(vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14794         {
14795                 DE_ASSERT(in.size() == 2);
14796                 DE_ASSERT(getArgCompCount(1) == 1);
14797
14798                 const fp16type  y                       (in[1][0]);
14799                 const float             scalar          (y.asFloat());
14800                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
14801                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
14802
14803                 DE_ASSERT(getArgCompCount(0) == alignedCols * alignedRows);
14804                 DE_ASSERT(getOutCompCount() == alignedCols * alignedRows);
14805                 DE_UNREF(alignedCols);
14806
14807                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14808                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14809                         {
14810                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
14811                                 const fp16type  x       (in[0][ndx]);
14812                                 const double    result  (scalar * x.asFloat());
14813
14814                                 out[ndx] = fp16type(result).bits();
14815                                 min[ndx] = getMin(result, getULPs(in));
14816                                 max[ndx] = getMax(result, getULPs(in));
14817                         }
14818
14819                 return true;
14820         }
14821 };
14822
14823 template<size_t cols, size_t rows>
14824 struct fp16VectorTimesMatrix : public fp16MatrixBase
14825 {
14826         fp16VectorTimesMatrix() : fp16MatrixBase()
14827         {
14828                 flavorNames.push_back("EmulatingFP16");
14829                 flavorNames.push_back("FloatCalc");
14830         }
14831
14832         virtual double getULPs (vector<const deFloat16*>& in)
14833         {
14834                 DE_UNREF(in);
14835
14836                 return (8.0 * cols);
14837         }
14838
14839         deUint32 getComponentValidity ()
14840         {
14841                 return getComponentMatrixValidityMask(cols, 1);
14842         }
14843
14844         template<class fp16type>
14845         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14846         {
14847                 DE_ASSERT(in.size() == 2);
14848
14849                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
14850                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
14851
14852                 DE_ASSERT(getOutCompCount() == cols);
14853                 DE_ASSERT(getArgCompCount(0) == rows);
14854                 DE_ASSERT(getArgCompCount(1) == alignedCols * alignedRows);
14855                 DE_UNREF(alignedCols);
14856
14857                 if (getFlavor() == 0)
14858                 {
14859                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14860                         {
14861                                 fp16type        s       (fp16type::zero(1));
14862
14863                                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14864                                 {
14865                                         const fp16type  v       (in[0][rowNdx]);
14866                                         const float             vf      (v.asFloat());
14867                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
14868                                         const fp16type  x       (in[1][ndx]);
14869                                         const float             xf      (x.asFloat());
14870                                         const fp16type  m       (vf * xf);
14871
14872                                         s = fp16type(s.asFloat() + m.asFloat());
14873                                 }
14874
14875                                 out[colNdx] = s.bits();
14876                                 min[colNdx] = getMin(s.asDouble(), getULPs(in));
14877                                 max[colNdx] = getMax(s.asDouble(), getULPs(in));
14878                         }
14879                 }
14880                 else if (getFlavor() == 1)
14881                 {
14882                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14883                         {
14884                                 float   s       (0.0f);
14885
14886                                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14887                                 {
14888                                         const fp16type  v       (in[0][rowNdx]);
14889                                         const float             vf      (v.asFloat());
14890                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
14891                                         const fp16type  x       (in[1][ndx]);
14892                                         const float             xf      (x.asFloat());
14893                                         const float             m       (vf * xf);
14894
14895                                         s += m;
14896                                 }
14897
14898                                 out[colNdx] = fp16type(s).bits();
14899                                 min[colNdx] = getMin(static_cast<double>(s), getULPs(in));
14900                                 max[colNdx] = getMax(static_cast<double>(s), getULPs(in));
14901                         }
14902                 }
14903                 else
14904                 {
14905                         TCU_THROW(InternalError, "Unknown flavor");
14906                 }
14907
14908                 return true;
14909         }
14910 };
14911
14912 template<size_t cols, size_t rows>
14913 struct fp16MatrixTimesVector : public fp16MatrixBase
14914 {
14915         fp16MatrixTimesVector() : fp16MatrixBase()
14916         {
14917                 flavorNames.push_back("EmulatingFP16");
14918                 flavorNames.push_back("FloatCalc");
14919         }
14920
14921         virtual double getULPs (vector<const deFloat16*>& in)
14922         {
14923                 DE_UNREF(in);
14924
14925                 return (8.0 * rows);
14926         }
14927
14928         deUint32 getComponentValidity ()
14929         {
14930                 return getComponentMatrixValidityMask(rows, 1);
14931         }
14932
14933         template<class fp16type>
14934         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14935         {
14936                 DE_ASSERT(in.size() == 2);
14937
14938                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
14939                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
14940
14941                 DE_ASSERT(getOutCompCount() == rows);
14942                 DE_ASSERT(getArgCompCount(0) == alignedCols * alignedRows);
14943                 DE_ASSERT(getArgCompCount(1) == cols);
14944                 DE_UNREF(alignedCols);
14945
14946                 if (getFlavor() == 0)
14947                 {
14948                         for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14949                         {
14950                                 fp16type        s       (fp16type::zero(1));
14951
14952                                 for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14953                                 {
14954                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
14955                                         const fp16type  x       (in[0][ndx]);
14956                                         const float             xf      (x.asFloat());
14957                                         const fp16type  v       (in[1][colNdx]);
14958                                         const float             vf      (v.asFloat());
14959                                         const fp16type  m       (vf * xf);
14960
14961                                         s = fp16type(s.asFloat() + m.asFloat());
14962                                 }
14963
14964                                 out[rowNdx] = s.bits();
14965                                 min[rowNdx] = getMin(s.asDouble(), getULPs(in));
14966                                 max[rowNdx] = getMax(s.asDouble(), getULPs(in));
14967                         }
14968                 }
14969                 else if (getFlavor() == 1)
14970                 {
14971                         for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14972                         {
14973                                 float   s       (0.0f);
14974
14975                                 for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14976                                 {
14977                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
14978                                         const fp16type  x       (in[0][ndx]);
14979                                         const float             xf      (x.asFloat());
14980                                         const fp16type  v       (in[1][colNdx]);
14981                                         const float             vf      (v.asFloat());
14982                                         const float             m       (vf * xf);
14983
14984                                         s += m;
14985                                 }
14986
14987                                 out[rowNdx] = fp16type(s).bits();
14988                                 min[rowNdx] = getMin(static_cast<double>(s), getULPs(in));
14989                                 max[rowNdx] = getMax(static_cast<double>(s), getULPs(in));
14990                         }
14991                 }
14992                 else
14993                 {
14994                         TCU_THROW(InternalError, "Unknown flavor");
14995                 }
14996
14997                 return true;
14998         }
14999 };
15000
15001 template<size_t colsL, size_t rowsL, size_t colsR, size_t rowsR>
15002 struct fp16MatrixTimesMatrix : public fp16MatrixBase
15003 {
15004         fp16MatrixTimesMatrix() : fp16MatrixBase()
15005         {
15006                 flavorNames.push_back("EmulatingFP16");
15007                 flavorNames.push_back("FloatCalc");
15008         }
15009
15010         virtual double getULPs (vector<const deFloat16*>& in)
15011         {
15012                 DE_UNREF(in);
15013
15014                 return 32.0;
15015         }
15016
15017         deUint32 getComponentValidity ()
15018         {
15019                 return getComponentMatrixValidityMask(colsR, rowsL);
15020         }
15021
15022         template<class fp16type>
15023         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15024         {
15025                 DE_STATIC_ASSERT(colsL == rowsR);
15026
15027                 DE_ASSERT(in.size() == 2);
15028
15029                 const size_t    alignedColsL    = (colsL == 3) ? 4 : colsL;
15030                 const size_t    alignedRowsL    = (rowsL == 3) ? 4 : rowsL;
15031                 const size_t    alignedColsR    = (colsR == 3) ? 4 : colsR;
15032                 const size_t    alignedRowsR    = (rowsR == 3) ? 4 : rowsR;
15033
15034                 DE_ASSERT(getOutCompCount() == alignedColsR * alignedRowsL);
15035                 DE_ASSERT(getArgCompCount(0) == alignedColsL * alignedRowsL);
15036                 DE_ASSERT(getArgCompCount(1) == alignedColsR * alignedRowsR);
15037                 DE_UNREF(alignedColsL);
15038                 DE_UNREF(alignedColsR);
15039
15040                 if (getFlavor() == 0)
15041                 {
15042                         for (size_t rowNdx = 0; rowNdx < rowsL; ++rowNdx)
15043                         {
15044                                 for (size_t colNdx = 0; colNdx < colsR; ++colNdx)
15045                                 {
15046                                         const size_t    ndx     (colNdx * alignedRowsL + rowNdx);
15047                                         fp16type                s       (fp16type::zero(1));
15048
15049                                         for (size_t commonNdx = 0; commonNdx < colsL; ++commonNdx)
15050                                         {
15051                                                 const size_t    ndxl    (commonNdx * alignedRowsL + rowNdx);
15052                                                 const fp16type  l               (in[0][ndxl]);
15053                                                 const float             lf              (l.asFloat());
15054                                                 const size_t    ndxr    (colNdx * alignedRowsR + commonNdx);
15055                                                 const fp16type  r               (in[1][ndxr]);
15056                                                 const float             rf              (r.asFloat());
15057                                                 const fp16type  m               (lf * rf);
15058
15059                                                 s = fp16type(s.asFloat() + m.asFloat());
15060                                         }
15061
15062                                         out[ndx] = s.bits();
15063                                         min[ndx] = getMin(s.asDouble(), getULPs(in));
15064                                         max[ndx] = getMax(s.asDouble(), getULPs(in));
15065                                 }
15066                         }
15067                 }
15068                 else if (getFlavor() == 1)
15069                 {
15070                         for (size_t rowNdx = 0; rowNdx < rowsL; ++rowNdx)
15071                         {
15072                                 for (size_t colNdx = 0; colNdx < colsR; ++colNdx)
15073                                 {
15074                                         const size_t    ndx     (colNdx * alignedRowsL + rowNdx);
15075                                         float                   s       (0.0f);
15076
15077                                         for (size_t commonNdx = 0; commonNdx < colsL; ++commonNdx)
15078                                         {
15079                                                 const size_t    ndxl    (commonNdx * alignedRowsL + rowNdx);
15080                                                 const fp16type  l               (in[0][ndxl]);
15081                                                 const float             lf              (l.asFloat());
15082                                                 const size_t    ndxr    (colNdx * alignedRowsR + commonNdx);
15083                                                 const fp16type  r               (in[1][ndxr]);
15084                                                 const float             rf              (r.asFloat());
15085                                                 const float             m               (lf * rf);
15086
15087                                                 s += m;
15088                                         }
15089
15090                                         out[ndx] = fp16type(s).bits();
15091                                         min[ndx] = getMin(static_cast<double>(s), getULPs(in));
15092                                         max[ndx] = getMax(static_cast<double>(s), getULPs(in));
15093                                 }
15094                         }
15095                 }
15096                 else
15097                 {
15098                         TCU_THROW(InternalError, "Unknown flavor");
15099                 }
15100
15101                 return true;
15102         }
15103 };
15104
15105 template<size_t cols, size_t rows>
15106 struct fp16OuterProduct : public fp16MatrixBase
15107 {
15108         virtual double getULPs (vector<const deFloat16*>& in)
15109         {
15110                 DE_UNREF(in);
15111
15112                 return 2.0;
15113         }
15114
15115         deUint32 getComponentValidity ()
15116         {
15117                 return getComponentMatrixValidityMask(cols, rows);
15118         }
15119
15120         template<class fp16type>
15121         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15122         {
15123                 DE_ASSERT(in.size() == 2);
15124
15125                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15126                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15127
15128                 DE_ASSERT(getArgCompCount(0) == rows);
15129                 DE_ASSERT(getArgCompCount(1) == cols);
15130                 DE_ASSERT(getOutCompCount() == alignedCols * alignedRows);
15131                 DE_UNREF(alignedCols);
15132
15133                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15134                 {
15135                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15136                         {
15137                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
15138                                 const fp16type  x       (in[0][rowNdx]);
15139                                 const float             xf      (x.asFloat());
15140                                 const fp16type  y       (in[1][colNdx]);
15141                                 const float             yf      (y.asFloat());
15142                                 const fp16type  m       (xf * yf);
15143
15144                                 out[ndx] = m.bits();
15145                                 min[ndx] = getMin(m.asDouble(), getULPs(in));
15146                                 max[ndx] = getMax(m.asDouble(), getULPs(in));
15147                         }
15148                 }
15149
15150                 return true;
15151         }
15152 };
15153
15154 template<size_t size>
15155 struct fp16Determinant;
15156
15157 template<>
15158 struct fp16Determinant<2> : public fp16MatrixBase
15159 {
15160         virtual double getULPs (vector<const deFloat16*>& in)
15161         {
15162                 DE_UNREF(in);
15163
15164                 return 128.0; // This is not a precision test. Value is not from spec
15165         }
15166
15167         deUint32 getComponentValidity ()
15168         {
15169                 return 1;
15170         }
15171
15172         template<class fp16type>
15173         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15174         {
15175                 const size_t    cols            = 2;
15176                 const size_t    rows            = 2;
15177                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15178                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15179
15180                 DE_ASSERT(in.size() == 1);
15181                 DE_ASSERT(getOutCompCount() == 1);
15182                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15183                 DE_UNREF(alignedCols);
15184                 DE_UNREF(alignedRows);
15185
15186                 // [ a b ]
15187                 // [ c d ]
15188                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15189                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15190                 const float             c               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15191                 const float             d               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15192                 const float             ad              (a * d);
15193                 const fp16type  adf16   (ad);
15194                 const float             bc              (b * c);
15195                 const fp16type  bcf16   (bc);
15196                 const float             r               (adf16.asFloat() - bcf16.asFloat());
15197                 const fp16type  rf16    (r);
15198
15199                 out[0] = rf16.bits();
15200                 min[0] = getMin(r, getULPs(in));
15201                 max[0] = getMax(r, getULPs(in));
15202
15203                 return true;
15204         }
15205 };
15206
15207 template<>
15208 struct fp16Determinant<3> : public fp16MatrixBase
15209 {
15210         virtual double getULPs (vector<const deFloat16*>& in)
15211         {
15212                 DE_UNREF(in);
15213
15214                 return 128.0; // This is not a precision test. Value is not from spec
15215         }
15216
15217         deUint32 getComponentValidity ()
15218         {
15219                 return 1;
15220         }
15221
15222         template<class fp16type>
15223         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15224         {
15225                 const size_t    cols            = 3;
15226                 const size_t    rows            = 3;
15227                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15228                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15229
15230                 DE_ASSERT(in.size() == 1);
15231                 DE_ASSERT(getOutCompCount() == 1);
15232                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15233                 DE_UNREF(alignedCols);
15234                 DE_UNREF(alignedRows);
15235
15236                 // [ a b c ]
15237                 // [ d e f ]
15238                 // [ g h i ]
15239                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15240                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15241                 const float             c               (fp16type(in[0][getNdx(rows, 2, 0)]).asFloat());
15242                 const float             d               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15243                 const float             e               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15244                 const float             f               (fp16type(in[0][getNdx(rows, 2, 1)]).asFloat());
15245                 const float             g               (fp16type(in[0][getNdx(rows, 0, 2)]).asFloat());
15246                 const float             h               (fp16type(in[0][getNdx(rows, 1, 2)]).asFloat());
15247                 const float             i               (fp16type(in[0][getNdx(rows, 2, 2)]).asFloat());
15248                 const fp16type  aei             (a * e * i);
15249                 const fp16type  bfg             (b * f * g);
15250                 const fp16type  cdh             (c * d * h);
15251                 const fp16type  ceg             (c * e * g);
15252                 const fp16type  bdi             (b * d * i);
15253                 const fp16type  afh             (a * f * h);
15254                 const float             r               (aei.asFloat() + bfg.asFloat() + cdh.asFloat() - ceg.asFloat() - bdi.asFloat() - afh.asFloat());
15255                 const fp16type  rf16    (r);
15256
15257                 out[0] = rf16.bits();
15258                 min[0] = getMin(r, getULPs(in));
15259                 max[0] = getMax(r, getULPs(in));
15260
15261                 return true;
15262         }
15263 };
15264
15265 template<>
15266 struct fp16Determinant<4> : public fp16MatrixBase
15267 {
15268         virtual double getULPs (vector<const deFloat16*>& in)
15269         {
15270                 DE_UNREF(in);
15271
15272                 return 128.0; // This is not a precision test. Value is not from spec
15273         }
15274
15275         deUint32 getComponentValidity ()
15276         {
15277                 return 1;
15278         }
15279
15280         template<class fp16type>
15281         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15282         {
15283                 const size_t    rows            = 4;
15284                 const size_t    cols            = 4;
15285                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15286                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15287
15288                 DE_ASSERT(in.size() == 1);
15289                 DE_ASSERT(getOutCompCount() == 1);
15290                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15291                 DE_UNREF(alignedCols);
15292                 DE_UNREF(alignedRows);
15293
15294                 // [ a b c d ]
15295                 // [ e f g h ]
15296                 // [ i j k l ]
15297                 // [ m n o p ]
15298                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15299                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15300                 const float             c               (fp16type(in[0][getNdx(rows, 2, 0)]).asFloat());
15301                 const float             d               (fp16type(in[0][getNdx(rows, 3, 0)]).asFloat());
15302                 const float             e               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15303                 const float             f               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15304                 const float             g               (fp16type(in[0][getNdx(rows, 2, 1)]).asFloat());
15305                 const float             h               (fp16type(in[0][getNdx(rows, 3, 1)]).asFloat());
15306                 const float             i               (fp16type(in[0][getNdx(rows, 0, 2)]).asFloat());
15307                 const float             j               (fp16type(in[0][getNdx(rows, 1, 2)]).asFloat());
15308                 const float             k               (fp16type(in[0][getNdx(rows, 2, 2)]).asFloat());
15309                 const float             l               (fp16type(in[0][getNdx(rows, 3, 2)]).asFloat());
15310                 const float             m               (fp16type(in[0][getNdx(rows, 0, 3)]).asFloat());
15311                 const float             n               (fp16type(in[0][getNdx(rows, 1, 3)]).asFloat());
15312                 const float             o               (fp16type(in[0][getNdx(rows, 2, 3)]).asFloat());
15313                 const float             p               (fp16type(in[0][getNdx(rows, 3, 3)]).asFloat());
15314
15315                 // [ f g h ]
15316                 // [ j k l ]
15317                 // [ n o p ]
15318                 const fp16type  fkp             (f * k * p);
15319                 const fp16type  gln             (g * l * n);
15320                 const fp16type  hjo             (h * j * o);
15321                 const fp16type  hkn             (h * k * n);
15322                 const fp16type  gjp             (g * j * p);
15323                 const fp16type  flo             (f * l * o);
15324                 const fp16type  detA    (a * (fkp.asFloat() + gln.asFloat() + hjo.asFloat() - hkn.asFloat() - gjp.asFloat() - flo.asFloat()));
15325
15326                 // [ e g h ]
15327                 // [ i k l ]
15328                 // [ m o p ]
15329                 const fp16type  ekp             (e * k * p);
15330                 const fp16type  glm             (g * l * m);
15331                 const fp16type  hio             (h * i * o);
15332                 const fp16type  hkm             (h * k * m);
15333                 const fp16type  gip             (g * i * p);
15334                 const fp16type  elo             (e * l * o);
15335                 const fp16type  detB    (b * (ekp.asFloat() + glm.asFloat() + hio.asFloat() - hkm.asFloat() - gip.asFloat() - elo.asFloat()));
15336
15337                 // [ e f h ]
15338                 // [ i j l ]
15339                 // [ m n p ]
15340                 const fp16type  ejp             (e * j * p);
15341                 const fp16type  flm             (f * l * m);
15342                 const fp16type  hin             (h * i * n);
15343                 const fp16type  hjm             (h * j * m);
15344                 const fp16type  fip             (f * i * p);
15345                 const fp16type  eln             (e * l * n);
15346                 const fp16type  detC    (c * (ejp.asFloat() + flm.asFloat() + hin.asFloat() - hjm.asFloat() - fip.asFloat() - eln.asFloat()));
15347
15348                 // [ e f g ]
15349                 // [ i j k ]
15350                 // [ m n o ]
15351                 const fp16type  ejo             (e * j * o);
15352                 const fp16type  fkm             (f * k * m);
15353                 const fp16type  gin             (g * i * n);
15354                 const fp16type  gjm             (g * j * m);
15355                 const fp16type  fio             (f * i * o);
15356                 const fp16type  ekn             (e * k * n);
15357                 const fp16type  detD    (d * (ejo.asFloat() + fkm.asFloat() + gin.asFloat() - gjm.asFloat() - fio.asFloat() - ekn.asFloat()));
15358
15359                 const float             r               (detA.asFloat() - detB.asFloat() + detC.asFloat() - detD.asFloat());
15360                 const fp16type  rf16    (r);
15361
15362                 out[0] = rf16.bits();
15363                 min[0] = getMin(r, getULPs(in));
15364                 max[0] = getMax(r, getULPs(in));
15365
15366                 return true;
15367         }
15368 };
15369
15370 template<size_t size>
15371 struct fp16Inverse;
15372
15373 template<>
15374 struct fp16Inverse<2> : public fp16MatrixBase
15375 {
15376         virtual double getULPs (vector<const deFloat16*>& in)
15377         {
15378                 DE_UNREF(in);
15379
15380                 return 128.0; // This is not a precision test. Value is not from spec
15381         }
15382
15383         deUint32 getComponentValidity ()
15384         {
15385                 return getComponentMatrixValidityMask(2, 2);
15386         }
15387
15388         template<class fp16type>
15389         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15390         {
15391                 const size_t    cols            = 2;
15392                 const size_t    rows            = 2;
15393                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15394                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15395
15396                 DE_ASSERT(in.size() == 1);
15397                 DE_ASSERT(getOutCompCount() == alignedRows * alignedCols);
15398                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15399                 DE_UNREF(alignedCols);
15400
15401                 // [ a b ]
15402                 // [ c d ]
15403                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15404                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15405                 const float             c               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15406                 const float             d               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15407                 const float             ad              (a * d);
15408                 const fp16type  adf16   (ad);
15409                 const float             bc              (b * c);
15410                 const fp16type  bcf16   (bc);
15411                 const float             det             (adf16.asFloat() - bcf16.asFloat());
15412                 const fp16type  det16   (det);
15413
15414                 out[0] = fp16type( d / det16.asFloat()).bits();
15415                 out[1] = fp16type(-c / det16.asFloat()).bits();
15416                 out[2] = fp16type(-b / det16.asFloat()).bits();
15417                 out[3] = fp16type( a / det16.asFloat()).bits();
15418
15419                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15420                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15421                         {
15422                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
15423                                 const fp16type  s       (out[ndx]);
15424
15425                                 min[ndx] = getMin(s.asDouble(), getULPs(in));
15426                                 max[ndx] = getMax(s.asDouble(), getULPs(in));
15427                         }
15428
15429                 return true;
15430         }
15431 };
15432
15433 inline std::string fp16ToString(deFloat16 val)
15434 {
15435         return tcu::toHex<4>(val).toString() + " (" + de::floatToString(tcu::Float16(val).asFloat(), 10) + ")";
15436 }
15437
15438 template <size_t RES_COMPONENTS, size_t ARG0_COMPONENTS, size_t ARG1_COMPONENTS, size_t ARG2_COMPONENTS, class TestedArithmeticFunction>
15439 bool compareFP16ArithmeticFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
15440 {
15441         if (inputs.size() < 1 || inputs.size() > 3 || outputAllocs.size() != 1 || expectedOutputs.size() != 1)
15442                 return false;
15443
15444         const size_t    resultStep                      = (RES_COMPONENTS == 3) ? 4 : RES_COMPONENTS;
15445         const size_t    iterationsCount         = expectedOutputs[0].getByteSize() / (sizeof(deFloat16) * resultStep);
15446         const size_t    inputsSteps[3]          =
15447         {
15448                 (ARG0_COMPONENTS == 3) ? 4 : ARG0_COMPONENTS,
15449                 (ARG1_COMPONENTS == 3) ? 4 : ARG1_COMPONENTS,
15450                 (ARG2_COMPONENTS == 3) ? 4 : ARG2_COMPONENTS,
15451         };
15452
15453         DE_ASSERT(expectedOutputs[0].getByteSize() > 0);
15454         DE_ASSERT(expectedOutputs[0].getByteSize() == sizeof(deFloat16) * iterationsCount * resultStep);
15455
15456         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15457         {
15458                 DE_ASSERT(inputs[inputNdx].getByteSize() > 0);
15459                 DE_ASSERT(inputs[inputNdx].getByteSize() == sizeof(deFloat16) * iterationsCount * inputsSteps[inputNdx]);
15460         }
15461
15462         const deFloat16* const          outputAsFP16                                    = (const deFloat16*)outputAllocs[0]->getHostPtr();
15463         TestedArithmeticFunction        func;
15464
15465         func.setOutCompCount(RES_COMPONENTS);
15466         func.setArgCompCount(0, ARG0_COMPONENTS);
15467         func.setArgCompCount(1, ARG1_COMPONENTS);
15468         func.setArgCompCount(2, ARG2_COMPONENTS);
15469
15470         const bool                                      callOncePerComponent                    = func.callOncePerComponent();
15471         const deUint32                          componentValidityMask                   = func.getComponentValidity();
15472         const size_t                            denormModesCount                                = 2;
15473         const char*                                     denormModes[denormModesCount]   = { "keep denormal numbers", "flush to zero" };
15474         const size_t                            successfulRunsPerComponent              = denormModesCount * func.getFlavorCount();
15475         bool                                            success                                                 = true;
15476         size_t                                          validatedCount                                  = 0;
15477
15478         vector<deUint8> inputBytes[3];
15479
15480         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15481                 inputs[inputNdx].getBytes(inputBytes[inputNdx]);
15482
15483         const deFloat16* const                  inputsAsFP16[3]                 =
15484         {
15485                 inputs.size() >= 1 ? (const deFloat16*)&inputBytes[0][0] : DE_NULL,
15486                 inputs.size() >= 2 ? (const deFloat16*)&inputBytes[1][0] : DE_NULL,
15487                 inputs.size() >= 3 ? (const deFloat16*)&inputBytes[2][0] : DE_NULL,
15488         };
15489
15490         for (size_t idx = 0; idx < iterationsCount; ++idx)
15491         {
15492                 std::vector<size_t>                     successfulRuns          (RES_COMPONENTS, successfulRunsPerComponent);
15493                 std::vector<std::string>        errors                          (RES_COMPONENTS);
15494                 bool                                            iterationValidated      (true);
15495
15496                 for (size_t denormNdx = 0; denormNdx < 2; ++denormNdx)
15497                 {
15498                         for (size_t flavorNdx = 0; flavorNdx < func.getFlavorCount(); ++flavorNdx)
15499                         {
15500                                 func.setFlavor(flavorNdx);
15501
15502                                 const deFloat16*                        iterationOutputFP16             = &outputAsFP16[idx * resultStep];
15503                                 vector<deFloat16>                       iterationCalculatedFP16 (resultStep, 0);
15504                                 vector<double>                          iterationEdgeMin                (resultStep, 0.0);
15505                                 vector<double>                          iterationEdgeMax                (resultStep, 0.0);
15506                                 vector<const deFloat16*>        arguments;
15507
15508                                 for (size_t componentNdx = 0; componentNdx < RES_COMPONENTS; ++componentNdx)
15509                                 {
15510                                         std::string     error;
15511                                         bool            reportError = false;
15512
15513                                         if (callOncePerComponent || componentNdx == 0)
15514                                         {
15515                                                 bool funcCallResult;
15516
15517                                                 arguments.clear();
15518
15519                                                 for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15520                                                         arguments.push_back(&inputsAsFP16[inputNdx][idx * inputsSteps[inputNdx] + componentNdx]);
15521
15522                                                 if (denormNdx == 0)
15523                                                         funcCallResult = func.template calc<tcu::Float16>(arguments, &iterationCalculatedFP16[componentNdx], &iterationEdgeMin[componentNdx], &iterationEdgeMax[componentNdx]);
15524                                                 else
15525                                                         funcCallResult = func.template calc<tcu::Float16Denormless>(arguments, &iterationCalculatedFP16[componentNdx], &iterationEdgeMin[componentNdx], &iterationEdgeMax[componentNdx]);
15526
15527                                                 if (!funcCallResult)
15528                                                 {
15529                                                         iterationValidated = false;
15530
15531                                                         if (callOncePerComponent)
15532                                                                 continue;
15533                                                         else
15534                                                                 break;
15535                                                 }
15536                                         }
15537
15538                                         if ((componentValidityMask != 0) && (componentValidityMask & (1<<componentNdx)) == 0)
15539                                                 continue;
15540
15541                                         reportError = !compare16BitFloat(iterationCalculatedFP16[componentNdx], iterationOutputFP16[componentNdx], error);
15542
15543                                         if (reportError)
15544                                         {
15545                                                 tcu::Float16 expected   (iterationCalculatedFP16[componentNdx]);
15546                                                 tcu::Float16 outputted  (iterationOutputFP16[componentNdx]);
15547
15548                                                 if (reportError && expected.isNaN())
15549                                                         reportError = false;
15550
15551                                                 if (reportError && !expected.isNaN() && !outputted.isNaN())
15552                                                 {
15553                                                         if (reportError && !expected.isInf() && !outputted.isInf())
15554                                                         {
15555                                                                 // Ignore rounding
15556                                                                 if (expected.bits() == outputted.bits() + 1 || expected.bits() + 1 == outputted.bits())
15557                                                                         reportError = false;
15558                                                         }
15559
15560                                                         if (reportError && expected.isInf())
15561                                                         {
15562                                                                 // RTZ rounding mode returns +/-65504 instead of Inf on overflow
15563                                                                 if (expected.sign() == 1 && outputted.bits() == 0x7bff && iterationEdgeMin[componentNdx] <= std::numeric_limits<double>::max())
15564                                                                         reportError = false;
15565                                                                 else if (expected.sign() == -1 && outputted.bits() == 0xfbff && iterationEdgeMax[componentNdx] >= -std::numeric_limits<double>::max())
15566                                                                         reportError = false;
15567                                                         }
15568
15569                                                         if (reportError)
15570                                                         {
15571                                                                 const double    outputtedDouble = outputted.asDouble();
15572
15573                                                                 DE_ASSERT(iterationEdgeMin[componentNdx] <= iterationEdgeMax[componentNdx]);
15574
15575                                                                 if (de::inRange(outputtedDouble, iterationEdgeMin[componentNdx], iterationEdgeMax[componentNdx]))
15576                                                                         reportError = false;
15577                                                         }
15578                                                 }
15579
15580                                                 if (reportError)
15581                                                 {
15582                                                         const size_t            inputsComps[3]  =
15583                                                         {
15584                                                                 ARG0_COMPONENTS,
15585                                                                 ARG1_COMPONENTS,
15586                                                                 ARG2_COMPONENTS,
15587                                                         };
15588                                                         string                          inputsValues    ("Inputs:");
15589                                                         string                          flavorName              (func.getFlavorCount() == 1 ? "" : string(" flavor ") + de::toString(flavorNdx) + " (" + func.getCurrentFlavorName() + ")");
15590                                                         std::stringstream       errStream;
15591
15592                                                         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15593                                                         {
15594                                                                 const size_t    inputCompsCount = inputsComps[inputNdx];
15595
15596                                                                 inputsValues += " [" + de::toString(inputNdx) + "]=(";
15597
15598                                                                 for (size_t compNdx = 0; compNdx < inputCompsCount; ++compNdx)
15599                                                                 {
15600                                                                         const deFloat16 inputComponentValue = inputsAsFP16[inputNdx][idx * inputsSteps[inputNdx] + compNdx];
15601
15602                                                                         inputsValues += fp16ToString(inputComponentValue) + ((compNdx + 1 == inputCompsCount) ? ")": ", ");
15603                                                                 }
15604                                                         }
15605
15606                                                         errStream       << "At"
15607                                                                                 << " iteration " << de::toString(idx)
15608                                                                                 << " component " << de::toString(componentNdx)
15609                                                                                 << " denormMode " << de::toString(denormNdx)
15610                                                                                 << " (" << denormModes[denormNdx] << ")"
15611                                                                                 << " " << flavorName
15612                                                                                 << " " << inputsValues
15613                                                                                 << " outputted:" + fp16ToString(iterationOutputFP16[componentNdx])
15614                                                                                 << " expected:" + fp16ToString(iterationCalculatedFP16[componentNdx])
15615                                                                                 << " or in range: [" << iterationEdgeMin[componentNdx] << ", " << iterationEdgeMax[componentNdx] << "]."
15616                                                                                 << " " << error << "."
15617                                                                                 << std::endl;
15618
15619                                                         errors[componentNdx] += errStream.str();
15620
15621                                                         successfulRuns[componentNdx]--;
15622                                                 }
15623                                         }
15624                                 }
15625                         }
15626                 }
15627
15628                 for (size_t componentNdx = 0; componentNdx < RES_COMPONENTS; ++componentNdx)
15629                 {
15630                         // Check if any component has total failure
15631                         if (successfulRuns[componentNdx] == 0)
15632                         {
15633                                 // Test failed in all denorm modes and all flavors for certain component: dump errors
15634                                 log << TestLog::Message << errors[componentNdx] << TestLog::EndMessage;
15635
15636                                 success = false;
15637                         }
15638                 }
15639
15640                 if (iterationValidated)
15641                         validatedCount++;
15642         }
15643
15644         if (validatedCount < 16)
15645                 TCU_THROW(InternalError, "Too few samples has been validated.");
15646
15647         return success;
15648 }
15649
15650 // IEEE-754 floating point numbers:
15651 // +--------+------+----------+-------------+
15652 // | binary | sign | exponent | significand |
15653 // +--------+------+----------+-------------+
15654 // | 16-bit |  1   |    5     |     10      |
15655 // +--------+------+----------+-------------+
15656 // | 32-bit |  1   |    8     |     23      |
15657 // +--------+------+----------+-------------+
15658 //
15659 // 16-bit floats:
15660 //
15661 // 0   000 00   00 0000 0001 (0x0001: 2e-24:         minimum positive denormalized)
15662 // 0   000 00   11 1111 1111 (0x03ff: 2e-14 - 2e-24: maximum positive denormalized)
15663 // 0   000 01   00 0000 0000 (0x0400: 2e-14:         minimum positive normalized)
15664 // 0   111 10   11 1111 1111 (0x7bff: 65504:         maximum positive normalized)
15665 //
15666 // 0   000 00   00 0000 0000 (0x0000: +0)
15667 // 0   111 11   00 0000 0000 (0x7c00: +Inf)
15668 // 0   000 00   11 1111 0000 (0x03f0: +Denorm)
15669 // 0   000 01   00 0000 0001 (0x0401: +Norm)
15670 // 0   111 11   00 0000 1111 (0x7c0f: +SNaN)
15671 // 0   111 11   11 1111 0000 (0x7ff0: +QNaN)
15672 // Generate and return 16-bit floats and their corresponding 32-bit values.
15673 //
15674 // The first 14 number pairs are manually picked, while the rest are randomly generated.
15675 // Expected count to be at least 14 (numPicks).
15676 vector<deFloat16> getFloat16a (de::Random& rnd, deUint32 count)
15677 {
15678         vector<deFloat16>       float16;
15679
15680         float16.reserve(count);
15681
15682         // Zero
15683         float16.push_back(deUint16(0x0000));
15684         float16.push_back(deUint16(0x8000));
15685         // Infinity
15686         float16.push_back(deUint16(0x7c00));
15687         float16.push_back(deUint16(0xfc00));
15688         // Normalized
15689         float16.push_back(deUint16(0x0401));
15690         float16.push_back(deUint16(0x8401));
15691         // Some normal number
15692         float16.push_back(deUint16(0x14cb));
15693         float16.push_back(deUint16(0x94cb));
15694         // Min/max positive normal
15695         float16.push_back(deUint16(0x0400));
15696         float16.push_back(deUint16(0x7bff));
15697         // Min/max negative normal
15698         float16.push_back(deUint16(0x8400));
15699         float16.push_back(deUint16(0xfbff));
15700         // PI
15701         float16.push_back(deUint16(0x4248)); // 3.140625
15702         float16.push_back(deUint16(0xb248)); // -3.140625
15703         // PI/2
15704         float16.push_back(deUint16(0x3e48)); // 1.5703125
15705         float16.push_back(deUint16(0xbe48)); // -1.5703125
15706         float16.push_back(deUint16(0x3c00)); // 1.0
15707         float16.push_back(deUint16(0x3800)); // 0.5
15708         // Some useful constants
15709         float16.push_back(tcu::Float16(-2.5f).bits());
15710         float16.push_back(tcu::Float16(-1.0f).bits());
15711         float16.push_back(tcu::Float16( 0.4f).bits());
15712         float16.push_back(tcu::Float16( 2.5f).bits());
15713
15714         const deUint32          numPicks        = static_cast<deUint32>(float16.size());
15715
15716         DE_ASSERT(count >= numPicks);
15717         count -= numPicks;
15718
15719         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
15720         {
15721                 int                     sign            = (rnd.getUint16() % 2 == 0) ? +1 : -1;
15722                 int                     exponent        = (rnd.getUint16() % 29) - 14 + 1;
15723                 deUint16        mantissa        = static_cast<deUint16>(2 * (rnd.getUint16() % 512));
15724
15725                 // Exclude power of -14 to avoid denorms
15726                 DE_ASSERT(de::inRange(exponent, -13, 15));
15727
15728                 float16.push_back(tcu::Float16::constructBits(sign, exponent, mantissa).bits());
15729         }
15730
15731         return float16;
15732 }
15733
15734 static inline vector<deFloat16> getInputData1 (deUint32 seed, size_t count, size_t argNo)
15735 {
15736         DE_UNREF(argNo);
15737
15738         de::Random      rnd(seed);
15739
15740         return getFloat16a(rnd, static_cast<deUint32>(count));
15741 }
15742
15743 static inline vector<deFloat16> getInputData2 (deUint32 seed, size_t count, size_t argNo)
15744 {
15745         de::Random      rnd             (seed);
15746         size_t          newCount = static_cast<size_t>(deSqrt(double(count)));
15747
15748         DE_ASSERT(newCount * newCount == count);
15749
15750         vector<deFloat16>       float16 = getFloat16a(rnd, static_cast<deUint32>(newCount));
15751
15752         return squarize(float16, static_cast<deUint32>(argNo));
15753 }
15754
15755 static inline vector<deFloat16> getInputData3 (deUint32 seed, size_t count, size_t argNo)
15756 {
15757         if (argNo == 0 || argNo == 1)
15758                 return getInputData2(seed, count, argNo);
15759         else
15760                 return getInputData1(seed<<argNo, count, argNo);
15761 }
15762
15763 vector<deFloat16> getInputData (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15764 {
15765         DE_UNREF(stride);
15766
15767         vector<deFloat16>       result;
15768
15769         switch (argCount)
15770         {
15771                 case 1:result = getInputData1(seed, count, argNo); break;
15772                 case 2:result = getInputData2(seed, count, argNo); break;
15773                 case 3:result = getInputData3(seed, count, argNo); break;
15774                 default: TCU_THROW(InternalError, "Invalid argument count specified");
15775         }
15776
15777         if (compCount == 3)
15778         {
15779                 const size_t            newCount = (3 * count) / 4;
15780                 vector<deFloat16>       newResult;
15781
15782                 newResult.reserve(result.size());
15783
15784                 for (size_t ndx = 0; ndx < newCount; ++ndx)
15785                 {
15786                         newResult.push_back(result[ndx]);
15787
15788                         if (ndx % 3 == 2)
15789                                 newResult.push_back(0);
15790                 }
15791
15792                 result = newResult;
15793         }
15794
15795         DE_ASSERT(result.size() == count);
15796
15797         return result;
15798 }
15799
15800 // Generator for functions requiring data in range [1, inf]
15801 vector<deFloat16> getInputDataAC (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15802 {
15803         vector<deFloat16>       result;
15804
15805         result = getInputData(seed, count, compCount, stride, argCount, argNo);
15806
15807         // Filter out values below 1.0 from upper half of numbers
15808         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15809         {
15810                 const float f = tcu::Float16(result[idx]).asFloat();
15811
15812                 if (f < 1.0f)
15813                         result[idx] = tcu::Float16(1.0f - f).bits();
15814         }
15815
15816         return result;
15817 }
15818
15819 // Generator for functions requiring data in range [-1, 1]
15820 vector<deFloat16> getInputDataA (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15821 {
15822         vector<deFloat16>       result;
15823
15824         result = getInputData(seed, count, compCount, stride, argCount, argNo);
15825
15826         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15827         {
15828                 const float f = tcu::Float16(result[idx]).asFloat();
15829
15830                 if (!de::inRange(f, -1.0f, 1.0f))
15831                         result[idx] = tcu::Float16(deFloatFrac(f)).bits();
15832         }
15833
15834         return result;
15835 }
15836
15837 // Generator for functions requiring data in range [-pi, pi]
15838 vector<deFloat16> getInputDataPI (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15839 {
15840         vector<deFloat16>       result;
15841
15842         result = getInputData(seed, count, compCount, stride, argCount, argNo);
15843
15844         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15845         {
15846                 const float f = tcu::Float16(result[idx]).asFloat();
15847
15848                 if (!de::inRange(f, -DE_PI, DE_PI))
15849                         result[idx] = tcu::Float16(fmodf(f, DE_PI)).bits();
15850         }
15851
15852         return result;
15853 }
15854
15855 // Generator for functions requiring data in range [0, inf]
15856 vector<deFloat16> getInputDataP (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15857 {
15858         vector<deFloat16>       result;
15859
15860         result = getInputData(seed, count, compCount, stride, argCount, argNo);
15861
15862         if (argNo == 0)
15863         {
15864                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15865                         result[idx] &= static_cast<deFloat16>(~0x8000);
15866         }
15867
15868         return result;
15869 }
15870
15871 vector<deFloat16> getInputDataV (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15872 {
15873         DE_UNREF(stride);
15874         DE_UNREF(argCount);
15875
15876         vector<deFloat16>       result;
15877
15878         if (argNo == 0)
15879                 result = getInputData2(seed, count, argNo);
15880         else
15881         {
15882                 const size_t            alignedCount    = (compCount == 3) ? 4 : compCount;
15883                 const size_t            newCountX               = static_cast<size_t>(deSqrt(double(count * alignedCount)));
15884                 const size_t            newCountY               = count / newCountX;
15885                 de::Random                      rnd                             (seed);
15886                 vector<deFloat16>       float16                 = getFloat16a(rnd, static_cast<deUint32>(newCountX));
15887
15888                 DE_ASSERT(newCountX * newCountX == alignedCount * count);
15889
15890                 for (size_t numIdx = 0; numIdx < newCountX; ++numIdx)
15891                 {
15892                         const vector<deFloat16> tmp(newCountY, float16[numIdx]);
15893
15894                         result.insert(result.end(), tmp.begin(), tmp.end());
15895                 }
15896         }
15897
15898         DE_ASSERT(result.size() == count);
15899
15900         return result;
15901 }
15902
15903 vector<deFloat16> getInputDataM (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15904 {
15905         DE_UNREF(compCount);
15906         DE_UNREF(stride);
15907         DE_UNREF(argCount);
15908
15909         de::Random                      rnd             (seed << argNo);
15910         vector<deFloat16>       result;
15911
15912         result = getFloat16a(rnd, static_cast<deUint32>(count));
15913
15914         DE_ASSERT(result.size() == count);
15915
15916         return result;
15917 }
15918
15919 vector<deFloat16> getInputDataD (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15920 {
15921         DE_UNREF(compCount);
15922         DE_UNREF(argCount);
15923
15924         de::Random                      rnd             (seed << argNo);
15925         vector<deFloat16>       result;
15926
15927         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
15928         {
15929                 int num = (rnd.getUint16() % 16) - 8;
15930
15931                 result.push_back(tcu::Float16(float(num)).bits());
15932         }
15933
15934         result[0 * stride] = deUint16(0x7c00); // +Inf
15935         result[1 * stride] = deUint16(0xfc00); // -Inf
15936
15937         DE_ASSERT(result.size() == count);
15938
15939         return result;
15940 }
15941
15942 // Generator for smoothstep function
15943 vector<deFloat16> getInputDataSS (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15944 {
15945         vector<deFloat16>       result;
15946
15947         result = getInputDataD(seed, count, compCount, stride, argCount, argNo);
15948
15949         if (argNo == 0)
15950         {
15951                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15952                 {
15953                         const float f = tcu::Float16(result[idx]).asFloat();
15954
15955                         if (f > 4.0f)
15956                                 result[idx] = tcu::Float16(-f).bits();
15957                 }
15958         }
15959
15960         if (argNo == 1)
15961         {
15962                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15963                 {
15964                         const float f = tcu::Float16(result[idx]).asFloat();
15965
15966                         if (f < 4.0f)
15967                                 result[idx] = tcu::Float16(-f).bits();
15968                 }
15969         }
15970
15971         return result;
15972 }
15973
15974 // Generates normalized vectors for arguments 0 and 1
15975 vector<deFloat16> getInputDataN (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15976 {
15977         DE_UNREF(compCount);
15978         DE_UNREF(argCount);
15979
15980         de::Random                      rnd             (seed << argNo);
15981         vector<deFloat16>       result;
15982
15983         if (argNo == 0 || argNo == 1)
15984         {
15985                 // The input parameters for the incident vector I and the surface normal N must already be normalized
15986                 for (size_t numIdx = 0; numIdx < count; numIdx += stride)
15987                 {
15988                         vector <float>  unnormolized;
15989                         float                   sum                             = 0;
15990
15991                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
15992                                 unnormolized.push_back(float((rnd.getUint16() % 16) - 8));
15993
15994                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
15995                                 sum += unnormolized[compIdx] * unnormolized[compIdx];
15996
15997                         sum = deFloatSqrt(sum);
15998                         if (sum == 0.0f)
15999                                 unnormolized[0] = sum = 1.0f;
16000
16001                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
16002                                 result.push_back(tcu::Float16(unnormolized[compIdx] / sum).bits());
16003
16004                         for (size_t compIdx = compCount; compIdx < stride; ++compIdx)
16005                                 result.push_back(0);
16006                 }
16007         }
16008         else
16009         {
16010                 // Input parameter eta
16011                 for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
16012                 {
16013                         int num = (rnd.getUint16() % 16) - 8;
16014
16015                         result.push_back(tcu::Float16(float(num)).bits());
16016                 }
16017         }
16018
16019         DE_ASSERT(result.size() == count);
16020
16021         return result;
16022 }
16023
16024 // Data generator for complex matrix functions like determinant and inverse
16025 vector<deFloat16> getInputDataC (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16026 {
16027         DE_UNREF(compCount);
16028         DE_UNREF(stride);
16029         DE_UNREF(argCount);
16030
16031         de::Random                      rnd             (seed << argNo);
16032         vector<deFloat16>       result;
16033
16034         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
16035         {
16036                 int num = (rnd.getUint16() % 16) - 8;
16037
16038                 result.push_back(tcu::Float16(float(num)).bits());
16039         }
16040
16041         DE_ASSERT(result.size() == count);
16042
16043         return result;
16044 }
16045
16046 struct Math16TestType
16047 {
16048         const char*             typePrefix;
16049         const size_t    typeComponents;
16050         const size_t    typeArrayStride;
16051         const size_t    typeStructStride;
16052 };
16053
16054 enum Math16DataTypes
16055 {
16056         NONE    = 0,
16057         SCALAR  = 1,
16058         VEC2    = 2,
16059         VEC3    = 3,
16060         VEC4    = 4,
16061         MAT2X2,
16062         MAT2X3,
16063         MAT2X4,
16064         MAT3X2,
16065         MAT3X3,
16066         MAT3X4,
16067         MAT4X2,
16068         MAT4X3,
16069         MAT4X4,
16070         MATH16_TYPE_LAST
16071 };
16072
16073 struct Math16ArgFragments
16074 {
16075         const char*     bodies;
16076         const char*     variables;
16077         const char*     decorations;
16078         const char*     funcVariables;
16079 };
16080
16081 typedef vector<deFloat16> Math16GetInputData (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo);
16082
16083 struct Math16TestFunc
16084 {
16085         const char*                                     funcName;
16086         const char*                                     funcSuffix;
16087         size_t                                          funcArgsCount;
16088         size_t                                          typeResult;
16089         size_t                                          typeArg0;
16090         size_t                                          typeArg1;
16091         size_t                                          typeArg2;
16092         Math16GetInputData*                     getInputDataFunc;
16093         VerifyIOFunc                            verifyFunc;
16094 };
16095
16096 template<class SpecResource>
16097 void createFloat16ArithmeticFuncTest (tcu::TestContext& testCtx, tcu::TestCaseGroup& testGroup, const size_t testTypeIdx, const Math16TestFunc& testFunc)
16098 {
16099         const int                                       testSpecificSeed                        = deStringHash(testGroup.getName());
16100         const int                                       seed                                            = testCtx.getCommandLine().getBaseSeed() ^ testSpecificSeed;
16101         const size_t                            numDataPointsByAxis                     = 32;
16102         const size_t                            numDataPoints                           = numDataPointsByAxis * numDataPointsByAxis;
16103         const char*                                     componentType                           = "f16";
16104         const Math16TestType            testTypes[MATH16_TYPE_LAST]     =
16105         {
16106                 { "",           0,       0,                                              0,                                             },
16107                 { "",           1,       1 * sizeof(deFloat16),  2 * sizeof(deFloat16)  },
16108                 { "v2",         2,       2 * sizeof(deFloat16),  2 * sizeof(deFloat16)  },
16109                 { "v3",         3,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
16110                 { "v4",         4,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
16111                 { "m2x2",       0,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
16112                 { "m2x3",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16113                 { "m2x4",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16114                 { "m3x2",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16115                 { "m3x3",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16116                 { "m3x4",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16117                 { "m4x2",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16118                 { "m4x3",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16119                 { "m4x4",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16120         };
16121
16122         DE_ASSERT(testTypeIdx == testTypes[testTypeIdx].typeComponents);
16123
16124
16125         const StringTemplate preMain
16126         (
16127                 "     %c_i32_ndp  = OpConstant %i32 ${num_data_points}\n"
16128
16129                 "        %f16     = OpTypeFloat 16\n"
16130                 "        %v2f16   = OpTypeVector %f16 2\n"
16131                 "        %v3f16   = OpTypeVector %f16 3\n"
16132                 "        %v4f16   = OpTypeVector %f16 4\n"
16133                 "        %m2x2f16 = OpTypeMatrix %v2f16 2\n"
16134                 "        %m2x3f16 = OpTypeMatrix %v3f16 2\n"
16135                 "        %m2x4f16 = OpTypeMatrix %v4f16 2\n"
16136                 "        %m3x2f16 = OpTypeMatrix %v2f16 3\n"
16137                 "        %m3x3f16 = OpTypeMatrix %v3f16 3\n"
16138                 "        %m3x4f16 = OpTypeMatrix %v4f16 3\n"
16139                 "        %m4x2f16 = OpTypeMatrix %v2f16 4\n"
16140                 "        %m4x3f16 = OpTypeMatrix %v3f16 4\n"
16141                 "        %m4x4f16 = OpTypeMatrix %v4f16 4\n"
16142
16143                 "     %up_f16     = OpTypePointer Uniform %f16    \n"
16144                 "     %up_v2f16   = OpTypePointer Uniform %v2f16  \n"
16145                 "     %up_v3f16   = OpTypePointer Uniform %v3f16  \n"
16146                 "     %up_v4f16   = OpTypePointer Uniform %v4f16  \n"
16147                 "     %up_m2x2f16 = OpTypePointer Uniform %m2x2f16\n"
16148                 "     %up_m2x3f16 = OpTypePointer Uniform %m2x3f16\n"
16149                 "     %up_m2x4f16 = OpTypePointer Uniform %m2x4f16\n"
16150                 "     %up_m3x2f16 = OpTypePointer Uniform %m3x2f16\n"
16151                 "     %up_m3x3f16 = OpTypePointer Uniform %m3x3f16\n"
16152                 "     %up_m3x4f16 = OpTypePointer Uniform %m3x4f16\n"
16153                 "     %up_m4x2f16 = OpTypePointer Uniform %m4x2f16\n"
16154                 "     %up_m4x3f16 = OpTypePointer Uniform %m4x3f16\n"
16155                 "     %up_m4x4f16 = OpTypePointer Uniform %m4x4f16\n"
16156
16157                 "     %ra_f16     = OpTypeArray %f16     %c_i32_ndp\n"
16158                 "     %ra_v2f16   = OpTypeArray %v2f16   %c_i32_ndp\n"
16159                 "     %ra_v3f16   = OpTypeArray %v3f16   %c_i32_ndp\n"
16160                 "     %ra_v4f16   = OpTypeArray %v4f16   %c_i32_ndp\n"
16161                 "     %ra_m2x2f16 = OpTypeArray %m2x2f16 %c_i32_ndp\n"
16162                 "     %ra_m2x3f16 = OpTypeArray %m2x3f16 %c_i32_ndp\n"
16163                 "     %ra_m2x4f16 = OpTypeArray %m2x4f16 %c_i32_ndp\n"
16164                 "     %ra_m3x2f16 = OpTypeArray %m3x2f16 %c_i32_ndp\n"
16165                 "     %ra_m3x3f16 = OpTypeArray %m3x3f16 %c_i32_ndp\n"
16166                 "     %ra_m3x4f16 = OpTypeArray %m3x4f16 %c_i32_ndp\n"
16167                 "     %ra_m4x2f16 = OpTypeArray %m4x2f16 %c_i32_ndp\n"
16168                 "     %ra_m4x3f16 = OpTypeArray %m4x3f16 %c_i32_ndp\n"
16169                 "     %ra_m4x4f16 = OpTypeArray %m4x4f16 %c_i32_ndp\n"
16170
16171                 "   %SSBO_f16     = OpTypeStruct %ra_f16    \n"
16172                 "   %SSBO_v2f16   = OpTypeStruct %ra_v2f16  \n"
16173                 "   %SSBO_v3f16   = OpTypeStruct %ra_v3f16  \n"
16174                 "   %SSBO_v4f16   = OpTypeStruct %ra_v4f16  \n"
16175                 "   %SSBO_m2x2f16 = OpTypeStruct %ra_m2x2f16\n"
16176                 "   %SSBO_m2x3f16 = OpTypeStruct %ra_m2x3f16\n"
16177                 "   %SSBO_m2x4f16 = OpTypeStruct %ra_m2x4f16\n"
16178                 "   %SSBO_m3x2f16 = OpTypeStruct %ra_m3x2f16\n"
16179                 "   %SSBO_m3x3f16 = OpTypeStruct %ra_m3x3f16\n"
16180                 "   %SSBO_m3x4f16 = OpTypeStruct %ra_m3x4f16\n"
16181                 "   %SSBO_m4x2f16 = OpTypeStruct %ra_m4x2f16\n"
16182                 "   %SSBO_m4x3f16 = OpTypeStruct %ra_m4x3f16\n"
16183                 "   %SSBO_m4x4f16 = OpTypeStruct %ra_m4x4f16\n"
16184
16185                 "%up_SSBO_f16     = OpTypePointer Uniform %SSBO_f16    \n"
16186                 "%up_SSBO_v2f16   = OpTypePointer Uniform %SSBO_v2f16  \n"
16187                 "%up_SSBO_v3f16   = OpTypePointer Uniform %SSBO_v3f16  \n"
16188                 "%up_SSBO_v4f16   = OpTypePointer Uniform %SSBO_v4f16  \n"
16189                 "%up_SSBO_m2x2f16 = OpTypePointer Uniform %SSBO_m2x2f16\n"
16190                 "%up_SSBO_m2x3f16 = OpTypePointer Uniform %SSBO_m2x3f16\n"
16191                 "%up_SSBO_m2x4f16 = OpTypePointer Uniform %SSBO_m2x4f16\n"
16192                 "%up_SSBO_m3x2f16 = OpTypePointer Uniform %SSBO_m3x2f16\n"
16193                 "%up_SSBO_m3x3f16 = OpTypePointer Uniform %SSBO_m3x3f16\n"
16194                 "%up_SSBO_m3x4f16 = OpTypePointer Uniform %SSBO_m3x4f16\n"
16195                 "%up_SSBO_m4x2f16 = OpTypePointer Uniform %SSBO_m4x2f16\n"
16196                 "%up_SSBO_m4x3f16 = OpTypePointer Uniform %SSBO_m4x3f16\n"
16197                 "%up_SSBO_m4x4f16 = OpTypePointer Uniform %SSBO_m4x4f16\n"
16198
16199                 "       %fp_v2i32 = OpTypePointer Function %v2i32\n"
16200                 "       %fp_v3i32 = OpTypePointer Function %v3i32\n"
16201                 "       %fp_v4i32 = OpTypePointer Function %v4i32\n"
16202                 "${arg_vars}"
16203         );
16204
16205         const StringTemplate decoration
16206         (
16207                 "OpDecorate %ra_f16     ArrayStride 2 \n"
16208                 "OpDecorate %ra_v2f16   ArrayStride 4 \n"
16209                 "OpDecorate %ra_v3f16   ArrayStride 8 \n"
16210                 "OpDecorate %ra_v4f16   ArrayStride 8 \n"
16211                 "OpDecorate %ra_m2x2f16 ArrayStride 8 \n"
16212                 "OpDecorate %ra_m2x3f16 ArrayStride 16\n"
16213                 "OpDecorate %ra_m2x4f16 ArrayStride 16\n"
16214                 "OpDecorate %ra_m3x2f16 ArrayStride 16\n"
16215                 "OpDecorate %ra_m3x3f16 ArrayStride 32\n"
16216                 "OpDecorate %ra_m3x4f16 ArrayStride 32\n"
16217                 "OpDecorate %ra_m4x2f16 ArrayStride 16\n"
16218                 "OpDecorate %ra_m4x3f16 ArrayStride 32\n"
16219                 "OpDecorate %ra_m4x4f16 ArrayStride 32\n"
16220
16221                 "OpMemberDecorate %SSBO_f16     0 Offset 0\n"
16222                 "OpMemberDecorate %SSBO_v2f16   0 Offset 0\n"
16223                 "OpMemberDecorate %SSBO_v3f16   0 Offset 0\n"
16224                 "OpMemberDecorate %SSBO_v4f16   0 Offset 0\n"
16225                 "OpMemberDecorate %SSBO_m2x2f16 0 Offset 0\n"
16226                 "OpMemberDecorate %SSBO_m2x3f16 0 Offset 0\n"
16227                 "OpMemberDecorate %SSBO_m2x4f16 0 Offset 0\n"
16228                 "OpMemberDecorate %SSBO_m3x2f16 0 Offset 0\n"
16229                 "OpMemberDecorate %SSBO_m3x3f16 0 Offset 0\n"
16230                 "OpMemberDecorate %SSBO_m3x4f16 0 Offset 0\n"
16231                 "OpMemberDecorate %SSBO_m4x2f16 0 Offset 0\n"
16232                 "OpMemberDecorate %SSBO_m4x3f16 0 Offset 0\n"
16233                 "OpMemberDecorate %SSBO_m4x4f16 0 Offset 0\n"
16234
16235                 "OpDecorate %SSBO_f16     BufferBlock\n"
16236                 "OpDecorate %SSBO_v2f16   BufferBlock\n"
16237                 "OpDecorate %SSBO_v3f16   BufferBlock\n"
16238                 "OpDecorate %SSBO_v4f16   BufferBlock\n"
16239                 "OpDecorate %SSBO_m2x2f16 BufferBlock\n"
16240                 "OpDecorate %SSBO_m2x3f16 BufferBlock\n"
16241                 "OpDecorate %SSBO_m2x4f16 BufferBlock\n"
16242                 "OpDecorate %SSBO_m3x2f16 BufferBlock\n"
16243                 "OpDecorate %SSBO_m3x3f16 BufferBlock\n"
16244                 "OpDecorate %SSBO_m3x4f16 BufferBlock\n"
16245                 "OpDecorate %SSBO_m4x2f16 BufferBlock\n"
16246                 "OpDecorate %SSBO_m4x3f16 BufferBlock\n"
16247                 "OpDecorate %SSBO_m4x4f16 BufferBlock\n"
16248
16249                 "OpMemberDecorate %SSBO_m2x2f16 0 ColMajor\n"
16250                 "OpMemberDecorate %SSBO_m2x3f16 0 ColMajor\n"
16251                 "OpMemberDecorate %SSBO_m2x4f16 0 ColMajor\n"
16252                 "OpMemberDecorate %SSBO_m3x2f16 0 ColMajor\n"
16253                 "OpMemberDecorate %SSBO_m3x3f16 0 ColMajor\n"
16254                 "OpMemberDecorate %SSBO_m3x4f16 0 ColMajor\n"
16255                 "OpMemberDecorate %SSBO_m4x2f16 0 ColMajor\n"
16256                 "OpMemberDecorate %SSBO_m4x3f16 0 ColMajor\n"
16257                 "OpMemberDecorate %SSBO_m4x4f16 0 ColMajor\n"
16258
16259                 "OpMemberDecorate %SSBO_m2x2f16 0 MatrixStride 4\n"
16260                 "OpMemberDecorate %SSBO_m2x3f16 0 MatrixStride 8\n"
16261                 "OpMemberDecorate %SSBO_m2x4f16 0 MatrixStride 8\n"
16262                 "OpMemberDecorate %SSBO_m3x2f16 0 MatrixStride 4\n"
16263                 "OpMemberDecorate %SSBO_m3x3f16 0 MatrixStride 8\n"
16264                 "OpMemberDecorate %SSBO_m3x4f16 0 MatrixStride 8\n"
16265                 "OpMemberDecorate %SSBO_m4x2f16 0 MatrixStride 4\n"
16266                 "OpMemberDecorate %SSBO_m4x3f16 0 MatrixStride 8\n"
16267                 "OpMemberDecorate %SSBO_m4x4f16 0 MatrixStride 8\n"
16268
16269                 "${arg_decorations}"
16270         );
16271
16272         const StringTemplate testFun
16273         (
16274                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
16275                 "    %param = OpFunctionParameter %v4f32\n"
16276                 "    %entry = OpLabel\n"
16277
16278                 "        %i = OpVariable %fp_i32 Function\n"
16279                 "${arg_infunc_vars}"
16280                 "             OpStore %i %c_i32_0\n"
16281                 "             OpBranch %loop\n"
16282
16283                 "     %loop = OpLabel\n"
16284                 "    %i_cmp = OpLoad %i32 %i\n"
16285                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
16286                 "             OpLoopMerge %merge %next None\n"
16287                 "             OpBranchConditional %lt %write %merge\n"
16288
16289                 "    %write = OpLabel\n"
16290                 "      %ndx = OpLoad %i32 %i\n"
16291
16292                 "${arg_func_call}"
16293
16294                 "             OpBranch %next\n"
16295
16296                 "     %next = OpLabel\n"
16297                 "    %i_cur = OpLoad %i32 %i\n"
16298                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
16299                 "             OpStore %i %i_new\n"
16300                 "             OpBranch %loop\n"
16301
16302                 "    %merge = OpLabel\n"
16303                 "             OpReturnValue %param\n"
16304                 "             OpFunctionEnd\n"
16305         );
16306
16307         const Math16ArgFragments        argFragment1    =
16308         {
16309                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16310                 " %val_src0 = OpLoad %${t0} %src0\n"
16311                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0\n"
16312                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16313                 "             OpStore %dst %val_dst\n",
16314                 "",
16315                 "",
16316                 "",
16317         };
16318
16319         const Math16ArgFragments        argFragment2    =
16320         {
16321                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16322                 " %val_src0 = OpLoad %${t0} %src0\n"
16323                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16324                 " %val_src1 = OpLoad %${t1} %src1\n"
16325                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1\n"
16326                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16327                 "             OpStore %dst %val_dst\n",
16328                 "",
16329                 "",
16330                 "",
16331         };
16332
16333         const Math16ArgFragments        argFragment3    =
16334         {
16335                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16336                 " %val_src0 = OpLoad %${t0} %src0\n"
16337                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16338                 " %val_src1 = OpLoad %${t1} %src1\n"
16339                 "     %src2 = OpAccessChain %up_${t2} %ssbo_src2 %c_i32_0 %ndx\n"
16340                 " %val_src2 = OpLoad %${t2} %src2\n"
16341                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1 %val_src2\n"
16342                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16343                 "             OpStore %dst %val_dst\n",
16344                 "",
16345                 "",
16346                 "",
16347         };
16348
16349         const Math16ArgFragments        argFragmentLdExp        =
16350         {
16351                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16352                 " %val_src0 = OpLoad %${t0} %src0\n"
16353                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16354                 " %val_src1 = OpLoad %${t1} %src1\n"
16355                 "%val_src1i = OpConvertFToS %${dr}i32 %val_src1\n"
16356                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1i\n"
16357                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16358                 "             OpStore %dst %val_dst\n",
16359
16360                 "",
16361
16362                 "",
16363
16364                 "",
16365         };
16366
16367         const Math16ArgFragments        argFragmentModfFrac     =
16368         {
16369                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16370                 " %val_src0 = OpLoad %${t0} %src0\n"
16371                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %tmp\n"
16372                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16373                 "             OpStore %dst %val_dst\n",
16374
16375                 "   %fp_tmp = OpTypePointer Function %${tr}\n",
16376
16377                 "",
16378
16379                 "      %tmp = OpVariable %fp_tmp Function\n",
16380         };
16381
16382         const Math16ArgFragments        argFragmentModfInt      =
16383         {
16384                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16385                 " %val_src0 = OpLoad %${t0} %src0\n"
16386                 "%val_dummy = ${op} %${tr} ${ext_inst} %val_src0 %tmp\n"
16387                 "     %tmp0 = OpAccessChain %fp_tmp %tmp\n"
16388                 "  %val_dst = OpLoad %${tr} %tmp0\n"
16389                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16390                 "             OpStore %dst %val_dst\n",
16391
16392                 "   %fp_tmp = OpTypePointer Function %${tr}\n",
16393
16394                 "",
16395
16396                 "      %tmp = OpVariable %fp_tmp Function\n",
16397         };
16398
16399         const Math16ArgFragments        argFragmentModfStruct   =
16400         {
16401                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16402                 " %val_src0 = OpLoad %${t0} %src0\n"
16403                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16404                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16405                 "             OpStore %tmp_ptr_s %val_tmp\n"
16406                 "%tmp_ptr_l = OpAccessChain %fp_${tr} %tmp %c_${struct_member}\n"
16407                 "  %val_dst = OpLoad %${tr} %tmp_ptr_l\n"
16408                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16409                 "             OpStore %dst %val_dst\n",
16410
16411                 "  %fp_${tr} = OpTypePointer Function %${tr}\n"
16412                 "   %st_tmp = OpTypeStruct %${tr} %${tr}\n"
16413                 "   %fp_tmp = OpTypePointer Function %st_tmp\n"
16414                 "   %c_frac = OpConstant %i32 0\n"
16415                 "    %c_int = OpConstant %i32 1\n",
16416
16417                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16418                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16419
16420                 "      %tmp = OpVariable %fp_tmp Function\n",
16421         };
16422
16423         const Math16ArgFragments        argFragmentFrexpStructS =
16424         {
16425                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16426                 " %val_src0 = OpLoad %${t0} %src0\n"
16427                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16428                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16429                 "             OpStore %tmp_ptr_s %val_tmp\n"
16430                 "%tmp_ptr_l = OpAccessChain %fp_${tr} %tmp %c_i32_0\n"
16431                 "  %val_dst = OpLoad %${tr} %tmp_ptr_l\n"
16432                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16433                 "             OpStore %dst %val_dst\n",
16434
16435                 "  %fp_${tr} = OpTypePointer Function %${tr}\n"
16436                 "   %st_tmp = OpTypeStruct %${tr} %${dr}i32\n"
16437                 "   %fp_tmp = OpTypePointer Function %st_tmp\n",
16438
16439                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16440                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16441
16442                 "      %tmp = OpVariable %fp_tmp Function\n",
16443         };
16444
16445         const Math16ArgFragments        argFragmentFrexpStructE =
16446         {
16447                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16448                 " %val_src0 = OpLoad %${t0} %src0\n"
16449                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16450                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16451                 "             OpStore %tmp_ptr_s %val_tmp\n"
16452                 "%tmp_ptr_l = OpAccessChain %fp_${dr}i32 %tmp %c_i32_1\n"
16453                 "%val_dst_i = OpLoad %${dr}i32 %tmp_ptr_l\n"
16454                 "  %val_dst = OpConvertSToF %${tr} %val_dst_i\n"
16455                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16456                 "             OpStore %dst %val_dst\n",
16457
16458                 "   %st_tmp = OpTypeStruct %${tr} %${dr}i32\n"
16459                 "   %fp_tmp = OpTypePointer Function %st_tmp\n",
16460
16461                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16462                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16463
16464                 "      %tmp = OpVariable %fp_tmp Function\n",
16465         };
16466
16467         const Math16ArgFragments        argFragmentFrexpS               =
16468         {
16469                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16470                 " %val_src0 = OpLoad %${t0} %src0\n"
16471                 "  %out_exp = OpAccessChain %fp_${dr}i32 %tmp\n"
16472                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %out_exp\n"
16473                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16474                 "             OpStore %dst %val_dst\n",
16475
16476                 "",
16477
16478                 "",
16479
16480                 "      %tmp = OpVariable %fp_${dr}i32 Function\n",
16481         };
16482
16483         const Math16ArgFragments        argFragmentFrexpE               =
16484         {
16485                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16486                 " %val_src0 = OpLoad %${t0} %src0\n"
16487                 "  %out_exp = OpAccessChain %fp_${dr}i32 %tmp\n"
16488                 "%val_dummy = ${op} %${tr} ${ext_inst} %val_src0 %out_exp\n"
16489                 "%val_dst_i = OpLoad %${dr}i32 %out_exp\n"
16490                 "  %val_dst = OpConvertSToF %${tr} %val_dst_i\n"
16491                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16492                 "             OpStore %dst %val_dst\n",
16493
16494                 "",
16495
16496                 "",
16497
16498                 "      %tmp = OpVariable %fp_${dr}i32 Function\n",
16499         };
16500
16501         const Math16TestType&           testType                                = testTypes[testTypeIdx];
16502         const string                            funcNameString                  = string(testFunc.funcName) + string(testFunc.funcSuffix);
16503         const string                            testName                                = de::toLower(funcNameString);
16504         const Math16ArgFragments*       argFragments                    = DE_NULL;
16505         const size_t                            typeStructStride                = testType.typeStructStride;
16506         const bool                                      extInst                                 = !(testFunc.funcName[0] == 'O' && testFunc.funcName[1] == 'p');
16507         const size_t                            numFloatsPerArg0Type    = testTypes[testFunc.typeArg0].typeArrayStride / sizeof(deFloat16);
16508         const size_t                            iterations                              = numDataPoints / numFloatsPerArg0Type;
16509         const size_t                            numFloatsPerResultType  = testTypes[testFunc.typeResult].typeArrayStride / sizeof(deFloat16);
16510         const vector<deFloat16>         float16DummyOutput              (iterations * numFloatsPerResultType, 0);
16511         VulkanFeatures                          features;
16512         SpecResource                            specResource;
16513         map<string, string>                     specs;
16514         map<string, string>                     fragments;
16515         vector<string>                          extensions;
16516         string                                          funcCall;
16517         string                                          funcVariables;
16518         string                                          variables;
16519         string                                          declarations;
16520         string                                          decorations;
16521
16522         switch (testFunc.funcArgsCount)
16523         {
16524                 case 1:
16525                 {
16526                         argFragments = &argFragment1;
16527
16528                         if (funcNameString == "ModfFrac")               argFragments = &argFragmentModfFrac;
16529                         if (funcNameString == "ModfInt")                argFragments = &argFragmentModfInt;
16530                         if (funcNameString == "ModfStructFrac") argFragments = &argFragmentModfStruct;
16531                         if (funcNameString == "ModfStructInt")  argFragments = &argFragmentModfStruct;
16532                         if (funcNameString == "FrexpS")                 argFragments = &argFragmentFrexpS;
16533                         if (funcNameString == "FrexpE")                 argFragments = &argFragmentFrexpE;
16534                         if (funcNameString == "FrexpStructS")   argFragments = &argFragmentFrexpStructS;
16535                         if (funcNameString == "FrexpStructE")   argFragments = &argFragmentFrexpStructE;
16536
16537                         break;
16538                 }
16539                 case 2:
16540                 {
16541                         argFragments = &argFragment2;
16542
16543                         if (funcNameString == "Ldexp")                  argFragments = &argFragmentLdExp;
16544
16545                         break;
16546                 }
16547                 case 3:
16548                 {
16549                         argFragments = &argFragment3;
16550
16551                         break;
16552                 }
16553                 default:
16554                 {
16555                         TCU_THROW(InternalError, "Invalid number of arguments");
16556                 }
16557         }
16558
16559         if (testFunc.funcArgsCount == 1)
16560         {
16561                 variables +=
16562                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16563                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16564
16565                 decorations +=
16566                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16567                         "OpDecorate %ssbo_src0 Binding 0\n"
16568                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16569                         "OpDecorate %ssbo_dst Binding 1\n";
16570         }
16571         else if (testFunc.funcArgsCount == 2)
16572         {
16573                 variables +=
16574                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16575                         " %ssbo_src1 = OpVariable %up_SSBO_${t1} Uniform\n"
16576                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16577
16578                 decorations +=
16579                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16580                         "OpDecorate %ssbo_src0 Binding 0\n"
16581                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
16582                         "OpDecorate %ssbo_src1 Binding 1\n"
16583                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16584                         "OpDecorate %ssbo_dst Binding 2\n";
16585         }
16586         else if (testFunc.funcArgsCount == 3)
16587         {
16588                 variables +=
16589                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16590                         " %ssbo_src1 = OpVariable %up_SSBO_${t1} Uniform\n"
16591                         " %ssbo_src2 = OpVariable %up_SSBO_${t2} Uniform\n"
16592                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16593
16594                 decorations +=
16595                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16596                         "OpDecorate %ssbo_src0 Binding 0\n"
16597                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
16598                         "OpDecorate %ssbo_src1 Binding 1\n"
16599                         "OpDecorate %ssbo_src2 DescriptorSet 0\n"
16600                         "OpDecorate %ssbo_src2 Binding 2\n"
16601                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16602                         "OpDecorate %ssbo_dst Binding 3\n";
16603         }
16604         else
16605         {
16606                 TCU_THROW(InternalError, "Invalid number of function arguments");
16607         }
16608
16609         variables       += argFragments->variables;
16610         decorations     += argFragments->decorations;
16611
16612         specs["dr"]                                     = testTypes[testFunc.typeResult].typePrefix;
16613         specs["d0"]                                     = testTypes[testFunc.typeArg0].typePrefix;
16614         specs["d1"]                                     = testTypes[testFunc.typeArg1].typePrefix;
16615         specs["d2"]                                     = testTypes[testFunc.typeArg2].typePrefix;
16616         specs["tr"]                                     = string(testTypes[testFunc.typeResult].typePrefix) + componentType;
16617         specs["t0"]                                     = string(testTypes[testFunc.typeArg0].typePrefix) + componentType;
16618         specs["t1"]                                     = string(testTypes[testFunc.typeArg1].typePrefix) + componentType;
16619         specs["t2"]                                     = string(testTypes[testFunc.typeArg2].typePrefix) + componentType;
16620         specs["struct_stride"]          = de::toString(typeStructStride);
16621         specs["op"]                                     = extInst ? "OpExtInst" : testFunc.funcName;
16622         specs["ext_inst"]                       = extInst ? string("%ext_import ") + testFunc.funcName : "";
16623         specs["struct_member"]          = de::toLower(testFunc.funcSuffix);
16624
16625         variables                                       = StringTemplate(variables).specialize(specs);
16626         decorations                                     = StringTemplate(decorations).specialize(specs);
16627         funcVariables                           = StringTemplate(argFragments->funcVariables).specialize(specs);
16628         funcCall                                        = StringTemplate(argFragments->bodies).specialize(specs);
16629
16630         specs["num_data_points"]        = de::toString(iterations);
16631         specs["arg_vars"]                       = variables;
16632         specs["arg_decorations"]        = decorations;
16633         specs["arg_infunc_vars"]        = funcVariables;
16634         specs["arg_func_call"]          = funcCall;
16635
16636         fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"\n%ext_import = OpExtInstImport \"GLSL.std.450\"";
16637         fragments["capability"]         = "OpCapability Matrix\nOpCapability StorageUniformBufferBlock16";
16638         fragments["decoration"]         = decoration.specialize(specs);
16639         fragments["pre_main"]           = preMain.specialize(specs);
16640         fragments["testfun"]            = testFun.specialize(specs);
16641
16642         for (size_t inputArgNdx = 0; inputArgNdx < testFunc.funcArgsCount; ++inputArgNdx)
16643         {
16644                 const size_t                    numFloatsPerItem        = (inputArgNdx == 0) ? testTypes[testFunc.typeArg0].typeArrayStride / sizeof(deFloat16)
16645                                                                                                         : (inputArgNdx == 1) ? testTypes[testFunc.typeArg1].typeArrayStride / sizeof(deFloat16)
16646                                                                                                         : (inputArgNdx == 2) ? testTypes[testFunc.typeArg2].typeArrayStride / sizeof(deFloat16)
16647                                                                                                         : -1;
16648                 const vector<deFloat16> inputData                       = testFunc.getInputDataFunc(seed, numFloatsPerItem * iterations, testTypeIdx, numFloatsPerItem, testFunc.funcArgsCount, inputArgNdx);
16649
16650                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(inputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
16651         }
16652
16653         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16DummyOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
16654         specResource.verifyIO = testFunc.verifyFunc;
16655
16656         extensions.push_back("VK_KHR_16bit_storage");
16657         extensions.push_back("VK_KHR_shader_float16_int8");
16658
16659         features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
16660         features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
16661
16662         finalizeTestsCreation(specResource, fragments, testCtx, testGroup, testName, features, extensions, IVec3(1, 1, 1));
16663 }
16664
16665 template<size_t C, class SpecResource>
16666 tcu::TestCaseGroup* createFloat16ArithmeticSet (tcu::TestContext& testCtx)
16667 {
16668         DE_STATIC_ASSERT(C >= 1 && C <= 4);
16669
16670         const std::string                               testGroupName   (string("arithmetic_") + de::toString(C));
16671         de::MovePtr<tcu::TestCaseGroup> testGroup               (new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Float 16 arithmetic and related tests"));
16672         const Math16TestFunc                    testFuncs[]             =
16673         {
16674                 {       "OpFNegate",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16OpFNegate>                                       },
16675                 {       "Round",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Round>                                           },
16676                 {       "RoundEven",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16RoundEven>                                       },
16677                 {       "Trunc",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Trunc>                                           },
16678                 {       "FAbs",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FAbs>                                            },
16679                 {       "FSign",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FSign>                                           },
16680                 {       "Floor",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Floor>                                           },
16681                 {       "Ceil",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Ceil>                                            },
16682                 {       "Fract",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Fract>                                           },
16683                 {       "Radians",                              "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Radians>                                         },
16684                 {       "Degrees",                              "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Degrees>                                         },
16685                 {       "Sin",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sin>                                                     },
16686                 {       "Cos",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Cos>                                                     },
16687                 {       "Tan",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Tan>                                                     },
16688                 {       "Asin",                                 "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Asin>                                            },
16689                 {       "Acos",                                 "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Acos>                                            },
16690                 {       "Atan",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Atan>                                            },
16691                 {       "Sinh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sinh>                                            },
16692                 {       "Cosh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Cosh>                                            },
16693                 {       "Tanh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Tanh>                                            },
16694                 {       "Asinh",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Asinh>                                           },
16695                 {       "Acosh",                                "",                     1,      C,              C,              0,              0, &getInputDataAC,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Acosh>                                           },
16696                 {       "Atanh",                                "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Atanh>                                           },
16697                 {       "Exp",                                  "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Exp>                                                     },
16698                 {       "Log",                                  "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Log>                                                     },
16699                 {       "Exp2",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Exp2>                                            },
16700                 {       "Log2",                                 "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Log2>                                            },
16701                 {       "Sqrt",                                 "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sqrt>                                            },
16702                 {       "InverseSqrt",                  "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16InverseSqrt>                                     },
16703                 {       "Modf",                                 "Frac",         1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfFrac>                                        },
16704                 {       "Modf",                                 "Int",          1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfInt>                                         },
16705                 {       "ModfStruct",                   "Frac",         1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfFrac>                                        },
16706                 {       "ModfStruct",                   "Int",          1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfInt>                                         },
16707                 {       "Frexp",                                "S",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpS>                                          },
16708                 {       "Frexp",                                "E",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpE>                                          },
16709                 {       "FrexpStruct",                  "S",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpS>                                          },
16710                 {       "FrexpStruct",                  "E",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpE>                                          },
16711                 {       "OpFAdd",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFAdd>                                          },
16712                 {       "OpFSub",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFSub>                                          },
16713                 {       "OpFMul",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFMul>                                          },
16714                 {       "OpFDiv",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFDiv>                                          },
16715                 {       "Atan2",                                "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Atan2>                                           },
16716                 {       "Pow",                                  "",                     2,      C,              C,              C,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Pow>                                                     },
16717                 {       "FMin",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16FMin>                                            },
16718                 {       "FMax",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16FMax>                                            },
16719                 {       "Step",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Step>                                            },
16720                 {       "Ldexp",                                "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Ldexp>                                           },
16721                 {       "FClamp",                               "",                     3,      C,              C,              C,              C, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FClamp>                                          },
16722                 {       "FMix",                                 "",                     3,      C,              C,              C,              C, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FMix>                                            },
16723                 {       "SmoothStep",                   "",                     3,      C,              C,              C,              C, &getInputDataSS,     compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16SmoothStep>                                      },
16724                 {       "Fma",                                  "",                     3,      C,              C,              C,              C, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16Fma>                                                     },
16725                 {       "Length",                               "",                     1,      1,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  1,  C,  0,  0, fp16Length>                                          },
16726                 {       "Distance",                             "",                     2,      1,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  1,  C,  C,  0, fp16Distance>                                        },
16727                 {       "Cross",                                "",                     2,      C,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Cross>                                           },
16728                 {       "Normalize",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Normalize>                                       },
16729                 {       "FaceForward",                  "",                     3,      C,              C,              C,              C, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FaceForward>                                     },
16730                 {       "Reflect",                              "",                     2,      C,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Reflect>                                         },
16731                 {       "Refract",                              "",                     3,      C,              C,              C,              1, &getInputDataN,      compareFP16ArithmeticFunc<  C,  C,  C,  1, fp16Refract>                                         },
16732                 {       "OpDot",                                "",                     2,      1,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  1,  C,  C,  0, fp16Dot>                                                     },
16733                 {       "OpVectorTimesScalar",  "",                     2,      C,              C,              1,              0, &getInputDataV,      compareFP16ArithmeticFunc<  C,  C,  1,  0, fp16VectorTimesScalar>                       },
16734         };
16735
16736         for (deUint32 testFuncIdx = 0; testFuncIdx < DE_LENGTH_OF_ARRAY(testFuncs); ++testFuncIdx)
16737         {
16738                 const Math16TestFunc&   testFunc                = testFuncs[testFuncIdx];
16739                 const string                    funcNameString  = testFunc.funcName;
16740
16741                 if ((C != 3) && funcNameString == "Cross")
16742                         continue;
16743
16744                 if ((C < 2) && funcNameString == "OpDot")
16745                         continue;
16746
16747                 if ((C < 2) && funcNameString == "OpVectorTimesScalar")
16748                         continue;
16749
16750                 createFloat16ArithmeticFuncTest<SpecResource>(testCtx, *testGroup.get(), C, testFunc);
16751         }
16752
16753         return testGroup.release();
16754 }
16755
16756 template<class SpecResource>
16757 tcu::TestCaseGroup* createFloat16ArithmeticSet (tcu::TestContext& testCtx)
16758 {
16759         const std::string                               testGroupName   ("arithmetic");
16760         de::MovePtr<tcu::TestCaseGroup> testGroup               (new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Float 16 arithmetic and related tests"));
16761         const Math16TestFunc                    testFuncs[]             =
16762         {
16763                 {       "OpTranspose",                  "2x2",          1,      MAT2X2, MAT2X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  4,  4,  0,  0, fp16Transpose<2,2> >                         },
16764                 {       "OpTranspose",                  "3x2",          1,      MAT2X3, MAT3X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<3,2> >                         },
16765                 {       "OpTranspose",                  "4x2",          1,      MAT2X4, MAT4X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<4,2> >                         },
16766                 {       "OpTranspose",                  "2x3",          1,      MAT3X2, MAT2X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<2,3> >                         },
16767                 {       "OpTranspose",                  "3x3",          1,      MAT3X3, MAT3X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<3,3> >                         },
16768                 {       "OpTranspose",                  "4x3",          1,      MAT3X4, MAT4X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<4,3> >                         },
16769                 {       "OpTranspose",                  "2x4",          1,      MAT4X2, MAT2X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<2,4> >                         },
16770                 {       "OpTranspose",                  "3x4",          1,      MAT4X3, MAT3X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<3,4> >                         },
16771                 {       "OpTranspose",                  "4x4",          1,      MAT4X4, MAT4X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<4,4> >                         },
16772                 {       "OpMatrixTimesScalar",  "2x2",          2,      MAT2X2, MAT2X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4,  1,  0, fp16MatrixTimesScalar<2,2> >         },
16773                 {       "OpMatrixTimesScalar",  "2x3",          2,      MAT2X3, MAT2X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<2,3> >         },
16774                 {       "OpMatrixTimesScalar",  "2x4",          2,      MAT2X4, MAT2X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<2,4> >         },
16775                 {       "OpMatrixTimesScalar",  "3x2",          2,      MAT3X2, MAT3X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<3,2> >         },
16776                 {       "OpMatrixTimesScalar",  "3x3",          2,      MAT3X3, MAT3X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<3,3> >         },
16777                 {       "OpMatrixTimesScalar",  "3x4",          2,      MAT3X4, MAT3X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<3,4> >         },
16778                 {       "OpMatrixTimesScalar",  "4x2",          2,      MAT4X2, MAT4X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<4,2> >         },
16779                 {       "OpMatrixTimesScalar",  "4x3",          2,      MAT4X3, MAT4X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<4,3> >         },
16780                 {       "OpMatrixTimesScalar",  "4x4",          2,      MAT4X4, MAT4X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<4,4> >         },
16781                 {       "OpVectorTimesMatrix",  "2x2",          2,      VEC2,   VEC2,   MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  2,  4,  0, fp16VectorTimesMatrix<2,2> >         },
16782                 {       "OpVectorTimesMatrix",  "2x3",          2,      VEC2,   VEC3,   MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  3,  8,  0, fp16VectorTimesMatrix<2,3> >         },
16783                 {       "OpVectorTimesMatrix",  "2x4",          2,      VEC2,   VEC4,   MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  4,  8,  0, fp16VectorTimesMatrix<2,4> >         },
16784                 {       "OpVectorTimesMatrix",  "3x2",          2,      VEC3,   VEC2,   MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  2,  8,  0, fp16VectorTimesMatrix<3,2> >         },
16785                 {       "OpVectorTimesMatrix",  "3x3",          2,      VEC3,   VEC3,   MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  3, 16,  0, fp16VectorTimesMatrix<3,3> >         },
16786                 {       "OpVectorTimesMatrix",  "3x4",          2,      VEC3,   VEC4,   MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  4, 16,  0, fp16VectorTimesMatrix<3,4> >         },
16787                 {       "OpVectorTimesMatrix",  "4x2",          2,      VEC4,   VEC2,   MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  2,  8,  0, fp16VectorTimesMatrix<4,2> >         },
16788                 {       "OpVectorTimesMatrix",  "4x3",          2,      VEC4,   VEC3,   MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  3, 16,  0, fp16VectorTimesMatrix<4,3> >         },
16789                 {       "OpVectorTimesMatrix",  "4x4",          2,      VEC4,   VEC4,   MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4, 16,  0, fp16VectorTimesMatrix<4,4> >         },
16790                 {       "OpMatrixTimesVector",  "2x2",          2,      VEC2,   MAT2X2, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  4,  2,  0, fp16MatrixTimesVector<2,2> >         },
16791                 {       "OpMatrixTimesVector",  "2x3",          2,      VEC3,   MAT2X3, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  8,  2,  0, fp16MatrixTimesVector<2,3> >         },
16792                 {       "OpMatrixTimesVector",  "2x4",          2,      VEC4,   MAT2X4, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  2,  0, fp16MatrixTimesVector<2,4> >         },
16793                 {       "OpMatrixTimesVector",  "3x2",          2,      VEC2,   MAT3X2, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  8,  3,  0, fp16MatrixTimesVector<3,2> >         },
16794                 {       "OpMatrixTimesVector",  "3x3",          2,      VEC3,   MAT3X3, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3, 16,  3,  0, fp16MatrixTimesVector<3,3> >         },
16795                 {       "OpMatrixTimesVector",  "3x4",          2,      VEC4,   MAT3X4, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4, 16,  3,  0, fp16MatrixTimesVector<3,4> >         },
16796                 {       "OpMatrixTimesVector",  "4x2",          2,      VEC2,   MAT4X2, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  8,  4,  0, fp16MatrixTimesVector<4,2> >         },
16797                 {       "OpMatrixTimesVector",  "4x3",          2,      VEC3,   MAT4X3, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3, 16,  4,  0, fp16MatrixTimesVector<4,3> >         },
16798                 {       "OpMatrixTimesVector",  "4x4",          2,      VEC4,   MAT4X4, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4, 16,  4,  0, fp16MatrixTimesVector<4,4> >         },
16799                 {       "OpMatrixTimesMatrix",  "2x2_2x2",      2,      MAT2X2, MAT2X2, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4,  4,  0, fp16MatrixTimesMatrix<2,2,2,2> >     },
16800                 {       "OpMatrixTimesMatrix",  "2x2_3x2",      2,      MAT3X2, MAT2X2, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  8,  0, fp16MatrixTimesMatrix<2,2,3,2> >     },
16801                 {       "OpMatrixTimesMatrix",  "2x2_4x2",      2,      MAT4X2, MAT2X2, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  8,  0, fp16MatrixTimesMatrix<2,2,4,2> >     },
16802                 {       "OpMatrixTimesMatrix",  "2x3_2x2",      2,      MAT2X3, MAT2X3, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  4,  0, fp16MatrixTimesMatrix<2,3,2,2> >     },
16803                 {       "OpMatrixTimesMatrix",  "2x3_3x2",      2,      MAT3X3, MAT2X3, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,3,3,2> >     },
16804                 {       "OpMatrixTimesMatrix",  "2x3_4x2",      2,      MAT4X3, MAT2X3, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,3,4,2> >     },
16805                 {       "OpMatrixTimesMatrix",  "2x4_2x2",      2,      MAT2X4, MAT2X4, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  4,  0, fp16MatrixTimesMatrix<2,4,2,2> >     },
16806                 {       "OpMatrixTimesMatrix",  "2x4_3x2",      2,      MAT3X4, MAT2X4, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,4,3,2> >     },
16807                 {       "OpMatrixTimesMatrix",  "2x4_4x2",      2,      MAT4X4, MAT2X4, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,4,4,2> >     },
16808                 {       "OpMatrixTimesMatrix",  "3x2_2x3",      2,      MAT2X2, MAT3X2, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  8,  0, fp16MatrixTimesMatrix<3,2,2,3> >     },
16809                 {       "OpMatrixTimesMatrix",  "3x2_3x3",      2,      MAT3X2, MAT3X2, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<3,2,3,3> >     },
16810                 {       "OpMatrixTimesMatrix",  "3x2_4x3",      2,      MAT4X2, MAT3X2, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<3,2,4,3> >     },
16811                 {       "OpMatrixTimesMatrix",  "3x3_2x3",      2,      MAT2X3, MAT3X3, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<3,3,2,3> >     },
16812                 {       "OpMatrixTimesMatrix",  "3x3_3x3",      2,      MAT3X3, MAT3X3, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,3,3,3> >     },
16813                 {       "OpMatrixTimesMatrix",  "3x3_4x3",      2,      MAT4X3, MAT3X3, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,3,4,3> >     },
16814                 {       "OpMatrixTimesMatrix",  "3x4_2x3",      2,      MAT2X4, MAT3X4, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<3,4,2,3> >     },
16815                 {       "OpMatrixTimesMatrix",  "3x4_3x3",      2,      MAT3X4, MAT3X4, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,4,3,3> >     },
16816                 {       "OpMatrixTimesMatrix",  "3x4_4x3",      2,      MAT4X4, MAT3X4, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,4,4,3> >     },
16817                 {       "OpMatrixTimesMatrix",  "4x2_2x4",      2,      MAT2X2, MAT4X2, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  8,  0, fp16MatrixTimesMatrix<4,2,2,4> >     },
16818                 {       "OpMatrixTimesMatrix",  "4x2_3x4",      2,      MAT3X2, MAT4X2, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<4,2,3,4> >     },
16819                 {       "OpMatrixTimesMatrix",  "4x2_4x4",      2,      MAT4X2, MAT4X2, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<4,2,4,4> >     },
16820                 {       "OpMatrixTimesMatrix",  "4x3_2x4",      2,      MAT2X3, MAT4X3, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<4,3,2,4> >     },
16821                 {       "OpMatrixTimesMatrix",  "4x3_3x4",      2,      MAT3X3, MAT4X3, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,3,3,4> >     },
16822                 {       "OpMatrixTimesMatrix",  "4x3_4x4",      2,      MAT4X3, MAT4X3, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,3,4,4> >     },
16823                 {       "OpMatrixTimesMatrix",  "4x4_2x4",      2,      MAT2X4, MAT4X4, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<4,4,2,4> >     },
16824                 {       "OpMatrixTimesMatrix",  "4x4_3x4",      2,      MAT3X4, MAT4X4, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,4,3,4> >     },
16825                 {       "OpMatrixTimesMatrix",  "4x4_4x4",      2,      MAT4X4, MAT4X4, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,4,4,4> >     },
16826                 {       "OpOuterProduct",               "2x2",          2,      MAT2X2, VEC2,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  2,  2,  0, fp16OuterProduct<2,2> >                      },
16827                 {       "OpOuterProduct",               "2x3",          2,      MAT2X3, VEC3,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  3,  2,  0, fp16OuterProduct<2,3> >                      },
16828                 {       "OpOuterProduct",               "2x4",          2,      MAT2X4, VEC4,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  2,  0, fp16OuterProduct<2,4> >                      },
16829                 {       "OpOuterProduct",               "3x2",          2,      MAT3X2, VEC2,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  2,  3,  0, fp16OuterProduct<3,2> >                      },
16830                 {       "OpOuterProduct",               "3x3",          2,      MAT3X3, VEC3,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  3,  3,  0, fp16OuterProduct<3,3> >                      },
16831                 {       "OpOuterProduct",               "3x4",          2,      MAT3X4, VEC4,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  4,  3,  0, fp16OuterProduct<3,4> >                      },
16832                 {       "OpOuterProduct",               "4x2",          2,      MAT4X2, VEC2,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  2,  4,  0, fp16OuterProduct<4,2> >                      },
16833                 {       "OpOuterProduct",               "4x3",          2,      MAT4X3, VEC3,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  3,  4,  0, fp16OuterProduct<4,3> >                      },
16834                 {       "OpOuterProduct",               "4x4",          2,      MAT4X4, VEC4,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  4,  4,  0, fp16OuterProduct<4,4> >                      },
16835                 {       "Determinant",                  "2x2",          1,      SCALAR, MAT2X2, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1,  4,  0,  0, fp16Determinant<2> >                         },
16836                 {       "Determinant",                  "3x3",          1,      SCALAR, MAT3X3, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1, 16,  0,  0, fp16Determinant<3> >                         },
16837                 {       "Determinant",                  "4x4",          1,      SCALAR, MAT4X4, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1, 16,  0,  0, fp16Determinant<4> >                         },
16838                 {       "MatrixInverse",                "2x2",          1,      MAT2X2, MAT2X2, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  4,  4,  0,  0, fp16Inverse<2> >                                     },
16839         };
16840
16841         for (deUint32 testFuncIdx = 0; testFuncIdx < DE_LENGTH_OF_ARRAY(testFuncs); ++testFuncIdx)
16842         {
16843                 const Math16TestFunc&   testFunc        = testFuncs[testFuncIdx];
16844
16845                 createFloat16ArithmeticFuncTest<SpecResource>(testCtx, *testGroup.get(), 0, testFunc);
16846         }
16847
16848         return testGroup.release();
16849 }
16850
16851 const string getNumberTypeName (const NumberType type)
16852 {
16853         if (type == NUMBERTYPE_INT32)
16854         {
16855                 return "int";
16856         }
16857         else if (type == NUMBERTYPE_UINT32)
16858         {
16859                 return "uint";
16860         }
16861         else if (type == NUMBERTYPE_FLOAT32)
16862         {
16863                 return "float";
16864         }
16865         else
16866         {
16867                 DE_ASSERT(false);
16868                 return "";
16869         }
16870 }
16871
16872 deInt32 getInt(de::Random& rnd)
16873 {
16874         return rnd.getInt(std::numeric_limits<int>::min(), std::numeric_limits<int>::max());
16875 }
16876
16877 const string repeatString (const string& str, int times)
16878 {
16879         string filler;
16880         for (int i = 0; i < times; ++i)
16881         {
16882                 filler += str;
16883         }
16884         return filler;
16885 }
16886
16887 const string getRandomConstantString (const NumberType type, de::Random& rnd)
16888 {
16889         if (type == NUMBERTYPE_INT32)
16890         {
16891                 return numberToString<deInt32>(getInt(rnd));
16892         }
16893         else if (type == NUMBERTYPE_UINT32)
16894         {
16895                 return numberToString<deUint32>(rnd.getUint32());
16896         }
16897         else if (type == NUMBERTYPE_FLOAT32)
16898         {
16899                 return numberToString<float>(rnd.getFloat());
16900         }
16901         else
16902         {
16903                 DE_ASSERT(false);
16904                 return "";
16905         }
16906 }
16907
16908 void createVectorCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16909 {
16910         map<string, string> params;
16911
16912         // Vec2 to Vec4
16913         for (int width = 2; width <= 4; ++width)
16914         {
16915                 const string randomConst = numberToString(getInt(rnd));
16916                 const string widthStr = numberToString(width);
16917                 const string composite_type = "${customType}vec" + widthStr;
16918                 const int index = rnd.getInt(0, width-1);
16919
16920                 params["type"]                  = "vec";
16921                 params["name"]                  = params["type"] + "_" + widthStr;
16922                 params["compositeDecl"]         = composite_type + " = OpTypeVector ${customType} " + widthStr +"\n";
16923                 params["compositeType"]         = composite_type;
16924                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
16925                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct " + composite_type + repeatString(" %filler", width) + "\n";
16926                 params["indexes"]               = numberToString(index);
16927                 testCases.push_back(params);
16928         }
16929 }
16930
16931 void createArrayCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16932 {
16933         const int limit = 10;
16934         map<string, string> params;
16935
16936         for (int width = 2; width <= limit; ++width)
16937         {
16938                 string randomConst = numberToString(getInt(rnd));
16939                 string widthStr = numberToString(width);
16940                 int index = rnd.getInt(0, width-1);
16941
16942                 params["type"]                  = "array";
16943                 params["name"]                  = params["type"] + "_" + widthStr;
16944                 params["compositeDecl"]         = string("%arraywidth = OpConstant %u32 " + widthStr + "\n")
16945                                                                                         +        "%composite = OpTypeArray ${customType} %arraywidth\n";
16946                 params["compositeType"]         = "%composite";
16947                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
16948                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
16949                 params["indexes"]               = numberToString(index);
16950                 testCases.push_back(params);
16951         }
16952 }
16953
16954 void createStructCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16955 {
16956         const int limit = 10;
16957         map<string, string> params;
16958
16959         for (int width = 2; width <= limit; ++width)
16960         {
16961                 string randomConst = numberToString(getInt(rnd));
16962                 int index = rnd.getInt(0, width-1);
16963
16964                 params["type"]                  = "struct";
16965                 params["name"]                  = params["type"] + "_" + numberToString(width);
16966                 params["compositeDecl"]         = "%composite = OpTypeStruct" + repeatString(" ${customType}", width) + "\n";
16967                 params["compositeType"]         = "%composite";
16968                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
16969                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
16970                 params["indexes"]               = numberToString(index);
16971                 testCases.push_back(params);
16972         }
16973 }
16974
16975 void createMatrixCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16976 {
16977         map<string, string> params;
16978
16979         // Vec2 to Vec4
16980         for (int width = 2; width <= 4; ++width)
16981         {
16982                 string widthStr = numberToString(width);
16983
16984                 for (int column = 2 ; column <= 4; ++column)
16985                 {
16986                         int index_0 = rnd.getInt(0, column-1);
16987                         int index_1 = rnd.getInt(0, width-1);
16988                         string columnStr = numberToString(column);
16989
16990                         params["type"]          = "matrix";
16991                         params["name"]          = params["type"] + "_" + widthStr + "x" + columnStr;
16992                         params["compositeDecl"] = string("%vectype   = OpTypeVector ${customType} " + widthStr + "\n")
16993                                                                                                 +        "%composite = OpTypeMatrix %vectype " + columnStr + "\n";
16994                         params["compositeType"] = "%composite";
16995
16996                         params["filler"]        = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n"
16997                                                                                                 +        "%fillerVec = OpConstantComposite %vectype" + repeatString(" %filler", width) + "\n";
16998
16999                         params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %fillerVec", column) + "\n";
17000                         params["indexes"]       = numberToString(index_0) + " " + numberToString(index_1);
17001                         testCases.push_back(params);
17002                 }
17003         }
17004 }
17005
17006 void createCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
17007 {
17008         createVectorCompositeCases(testCases, rnd, type);
17009         createArrayCompositeCases(testCases, rnd, type);
17010         createStructCompositeCases(testCases, rnd, type);
17011         // Matrix only supports float types
17012         if (type == NUMBERTYPE_FLOAT32)
17013         {
17014                 createMatrixCompositeCases(testCases, rnd, type);
17015         }
17016 }
17017
17018 const string getAssemblyTypeDeclaration (const NumberType type)
17019 {
17020         switch (type)
17021         {
17022                 case NUMBERTYPE_INT32:          return "OpTypeInt 32 1";
17023                 case NUMBERTYPE_UINT32:         return "OpTypeInt 32 0";
17024                 case NUMBERTYPE_FLOAT32:        return "OpTypeFloat 32";
17025                 default:                        DE_ASSERT(false); return "";
17026         }
17027 }
17028
17029 const string getAssemblyTypeName (const NumberType type)
17030 {
17031         switch (type)
17032         {
17033                 case NUMBERTYPE_INT32:          return "%i32";
17034                 case NUMBERTYPE_UINT32:         return "%u32";
17035                 case NUMBERTYPE_FLOAT32:        return "%f32";
17036                 default:                        DE_ASSERT(false); return "";
17037         }
17038 }
17039
17040 const string specializeCompositeInsertShaderTemplate (const NumberType type, const map<string, string>& params)
17041 {
17042         map<string, string>     parameters(params);
17043
17044         const string customType = getAssemblyTypeName(type);
17045         map<string, string> substCustomType;
17046         substCustomType["customType"] = customType;
17047         parameters["compositeDecl"] = StringTemplate(parameters.at("compositeDecl")).specialize(substCustomType);
17048         parameters["compositeType"] = StringTemplate(parameters.at("compositeType")).specialize(substCustomType);
17049         parameters["compositeConstruct"] = StringTemplate(parameters.at("compositeConstruct")).specialize(substCustomType);
17050         parameters["filler"] = StringTemplate(parameters.at("filler")).specialize(substCustomType);
17051         parameters["customType"] = customType;
17052         parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
17053
17054         if (parameters.at("compositeType") != "%u32vec3")
17055         {
17056                 parameters["u32vec3Decl"] = "%u32vec3   = OpTypeVector %u32 3\n";
17057         }
17058
17059         return StringTemplate(
17060                 "OpCapability Shader\n"
17061                 "OpCapability Matrix\n"
17062                 "OpMemoryModel Logical GLSL450\n"
17063                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17064                 "OpExecutionMode %main LocalSize 1 1 1\n"
17065
17066                 "OpSource GLSL 430\n"
17067                 "OpName %main           \"main\"\n"
17068                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17069
17070                 // Decorators
17071                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17072                 "OpDecorate %buf BufferBlock\n"
17073                 "OpDecorate %indata DescriptorSet 0\n"
17074                 "OpDecorate %indata Binding 0\n"
17075                 "OpDecorate %outdata DescriptorSet 0\n"
17076                 "OpDecorate %outdata Binding 1\n"
17077                 "OpDecorate %customarr ArrayStride 4\n"
17078                 "${compositeDecorator}"
17079                 "OpMemberDecorate %buf 0 Offset 0\n"
17080
17081                 // General types
17082                 "%void      = OpTypeVoid\n"
17083                 "%voidf     = OpTypeFunction %void\n"
17084                 "%u32       = OpTypeInt 32 0\n"
17085                 "%i32       = OpTypeInt 32 1\n"
17086                 "%f32       = OpTypeFloat 32\n"
17087
17088                 // Composite declaration
17089                 "${compositeDecl}"
17090
17091                 // Constants
17092                 "${filler}"
17093
17094                 "${u32vec3Decl:opt}"
17095                 "%uvec3ptr  = OpTypePointer Input %u32vec3\n"
17096
17097                 // Inherited from custom
17098                 "%customptr = OpTypePointer Uniform ${customType}\n"
17099                 "%customarr = OpTypeRuntimeArray ${customType}\n"
17100                 "%buf       = OpTypeStruct %customarr\n"
17101                 "%bufptr    = OpTypePointer Uniform %buf\n"
17102
17103                 "%indata    = OpVariable %bufptr Uniform\n"
17104                 "%outdata   = OpVariable %bufptr Uniform\n"
17105
17106                 "%id        = OpVariable %uvec3ptr Input\n"
17107                 "%zero      = OpConstant %i32 0\n"
17108
17109                 "%main      = OpFunction %void None %voidf\n"
17110                 "%label     = OpLabel\n"
17111                 "%idval     = OpLoad %u32vec3 %id\n"
17112                 "%x         = OpCompositeExtract %u32 %idval 0\n"
17113
17114                 "%inloc     = OpAccessChain %customptr %indata %zero %x\n"
17115                 "%outloc    = OpAccessChain %customptr %outdata %zero %x\n"
17116                 // Read the input value
17117                 "%inval     = OpLoad ${customType} %inloc\n"
17118                 // Create the composite and fill it
17119                 "${compositeConstruct}"
17120                 // Insert the input value to a place
17121                 "%instance2 = OpCompositeInsert ${compositeType} %inval %instance ${indexes}\n"
17122                 // Read back the value from the position
17123                 "%out_val   = OpCompositeExtract ${customType} %instance2 ${indexes}\n"
17124                 // Store it in the output position
17125                 "             OpStore %outloc %out_val\n"
17126                 "             OpReturn\n"
17127                 "             OpFunctionEnd\n"
17128         ).specialize(parameters);
17129 }
17130
17131 template<typename T>
17132 BufferSp createCompositeBuffer(T number)
17133 {
17134         return BufferSp(new Buffer<T>(vector<T>(1, number)));
17135 }
17136
17137 tcu::TestCaseGroup* createOpCompositeInsertGroup (tcu::TestContext& testCtx)
17138 {
17139         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "opcompositeinsert", "Test the OpCompositeInsert instruction"));
17140         de::Random                                              rnd             (deStringHash(group->getName()));
17141
17142         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17143         {
17144                 NumberType                                              numberType              = NumberType(type);
17145                 const string                                    typeName                = getNumberTypeName(numberType);
17146                 const string                                    description             = "Test the OpCompositeInsert instruction with " + typeName + "s";
17147                 de::MovePtr<tcu::TestCaseGroup> subGroup                (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17148                 vector<map<string, string> >    testCases;
17149
17150                 createCompositeCases(testCases, rnd, numberType);
17151
17152                 for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
17153                 {
17154                         ComputeShaderSpec       spec;
17155
17156                         spec.assembly = specializeCompositeInsertShaderTemplate(numberType, *test);
17157
17158                         switch (numberType)
17159                         {
17160                                 case NUMBERTYPE_INT32:
17161                                 {
17162                                         deInt32 number = getInt(rnd);
17163                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17164                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17165                                         break;
17166                                 }
17167                                 case NUMBERTYPE_UINT32:
17168                                 {
17169                                         deUint32 number = rnd.getUint32();
17170                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17171                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17172                                         break;
17173                                 }
17174                                 case NUMBERTYPE_FLOAT32:
17175                                 {
17176                                         float number = rnd.getFloat();
17177                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
17178                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
17179                                         break;
17180                                 }
17181                                 default:
17182                                         DE_ASSERT(false);
17183                         }
17184
17185                         spec.numWorkGroups = IVec3(1, 1, 1);
17186                         subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpCompositeInsert test", spec));
17187                 }
17188                 group->addChild(subGroup.release());
17189         }
17190         return group.release();
17191 }
17192
17193 struct AssemblyStructInfo
17194 {
17195         AssemblyStructInfo (const deUint32 comp, const deUint32 idx)
17196         : components    (comp)
17197         , index                 (idx)
17198         {}
17199
17200         deUint32 components;
17201         deUint32 index;
17202 };
17203
17204 const string specializeInBoundsShaderTemplate (const NumberType type, const AssemblyStructInfo& structInfo, const map<string, string>& params)
17205 {
17206         // Create the full index string
17207         string                          fullIndex       = numberToString(structInfo.index) + " " + params.at("indexes");
17208         // Convert it to list of indexes
17209         vector<string>          indexes         = de::splitString(fullIndex, ' ');
17210
17211         map<string, string>     parameters      (params);
17212         parameters["structType"]        = repeatString(" ${compositeType}", structInfo.components);
17213         parameters["structConstruct"]   = repeatString(" %instance", structInfo.components);
17214         parameters["insertIndexes"]     = fullIndex;
17215
17216         // In matrix cases the last two index is the CompositeExtract indexes
17217         const deUint32 extractIndexes = (parameters["type"] == "matrix") ? 2 : 1;
17218
17219         // Construct the extractIndex
17220         for (vector<string>::const_iterator index = indexes.end() - extractIndexes; index != indexes.end(); ++index)
17221         {
17222                 parameters["extractIndexes"] += " " + *index;
17223         }
17224
17225         // Remove the last 1 or 2 element depends on matrix case or not
17226         indexes.erase(indexes.end() - extractIndexes, indexes.end());
17227
17228         deUint32 id = 0;
17229         // Generate AccessChain index expressions (except for the last one, because we use ptr to the composite)
17230         for (vector<string>::const_iterator index = indexes.begin(); index != indexes.end(); ++index)
17231         {
17232                 string indexId = "%index_" + numberToString(id++);
17233                 parameters["accessChainConstDeclaration"] += indexId + "   = OpConstant %u32 " + *index + "\n";
17234                 parameters["accessChainIndexes"] += " " + indexId;
17235         }
17236
17237         parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
17238
17239         const string customType = getAssemblyTypeName(type);
17240         map<string, string> substCustomType;
17241         substCustomType["customType"] = customType;
17242         parameters["compositeDecl"] = StringTemplate(parameters.at("compositeDecl")).specialize(substCustomType);
17243         parameters["compositeType"] = StringTemplate(parameters.at("compositeType")).specialize(substCustomType);
17244         parameters["compositeConstruct"] = StringTemplate(parameters.at("compositeConstruct")).specialize(substCustomType);
17245         parameters["filler"] = StringTemplate(parameters.at("filler")).specialize(substCustomType);
17246         parameters["customType"] = customType;
17247
17248         const string compositeType = parameters.at("compositeType");
17249         map<string, string> substCompositeType;
17250         substCompositeType["compositeType"] = compositeType;
17251         parameters["structType"] = StringTemplate(parameters.at("structType")).specialize(substCompositeType);
17252         if (compositeType != "%u32vec3")
17253         {
17254                 parameters["u32vec3Decl"] = "%u32vec3   = OpTypeVector %u32 3\n";
17255         }
17256
17257         return StringTemplate(
17258                 "OpCapability Shader\n"
17259                 "OpCapability Matrix\n"
17260                 "OpMemoryModel Logical GLSL450\n"
17261                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17262                 "OpExecutionMode %main LocalSize 1 1 1\n"
17263
17264                 "OpSource GLSL 430\n"
17265                 "OpName %main           \"main\"\n"
17266                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17267                 // Decorators
17268                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17269                 "OpDecorate %buf BufferBlock\n"
17270                 "OpDecorate %indata DescriptorSet 0\n"
17271                 "OpDecorate %indata Binding 0\n"
17272                 "OpDecorate %outdata DescriptorSet 0\n"
17273                 "OpDecorate %outdata Binding 1\n"
17274                 "OpDecorate %customarr ArrayStride 4\n"
17275                 "${compositeDecorator}"
17276                 "OpMemberDecorate %buf 0 Offset 0\n"
17277                 // General types
17278                 "%void      = OpTypeVoid\n"
17279                 "%voidf     = OpTypeFunction %void\n"
17280                 "%i32       = OpTypeInt 32 1\n"
17281                 "%u32       = OpTypeInt 32 0\n"
17282                 "%f32       = OpTypeFloat 32\n"
17283                 // Custom types
17284                 "${compositeDecl}"
17285                 // %u32vec3 if not already declared in ${compositeDecl}
17286                 "${u32vec3Decl:opt}"
17287                 "%uvec3ptr  = OpTypePointer Input %u32vec3\n"
17288                 // Inherited from composite
17289                 "%composite_p = OpTypePointer Function ${compositeType}\n"
17290                 "%struct_t  = OpTypeStruct${structType}\n"
17291                 "%struct_p  = OpTypePointer Function %struct_t\n"
17292                 // Constants
17293                 "${filler}"
17294                 "${accessChainConstDeclaration}"
17295                 // Inherited from custom
17296                 "%customptr = OpTypePointer Uniform ${customType}\n"
17297                 "%customarr = OpTypeRuntimeArray ${customType}\n"
17298                 "%buf       = OpTypeStruct %customarr\n"
17299                 "%bufptr    = OpTypePointer Uniform %buf\n"
17300                 "%indata    = OpVariable %bufptr Uniform\n"
17301                 "%outdata   = OpVariable %bufptr Uniform\n"
17302
17303                 "%id        = OpVariable %uvec3ptr Input\n"
17304                 "%zero      = OpConstant %u32 0\n"
17305                 "%main      = OpFunction %void None %voidf\n"
17306                 "%label     = OpLabel\n"
17307                 "%struct_v  = OpVariable %struct_p Function\n"
17308                 "%idval     = OpLoad %u32vec3 %id\n"
17309                 "%x         = OpCompositeExtract %u32 %idval 0\n"
17310                 // Create the input/output type
17311                 "%inloc     = OpInBoundsAccessChain %customptr %indata %zero %x\n"
17312                 "%outloc    = OpInBoundsAccessChain %customptr %outdata %zero %x\n"
17313                 // Read the input value
17314                 "%inval     = OpLoad ${customType} %inloc\n"
17315                 // Create the composite and fill it
17316                 "${compositeConstruct}"
17317                 // Create the struct and fill it with the composite
17318                 "%struct    = OpCompositeConstruct %struct_t${structConstruct}\n"
17319                 // Insert the value
17320                 "%comp_obj  = OpCompositeInsert %struct_t %inval %struct ${insertIndexes}\n"
17321                 // Store the object
17322                 "             OpStore %struct_v %comp_obj\n"
17323                 // Get deepest possible composite pointer
17324                 "%inner_ptr = OpInBoundsAccessChain %composite_p %struct_v${accessChainIndexes}\n"
17325                 "%read_obj  = OpLoad ${compositeType} %inner_ptr\n"
17326                 // Read back the stored value
17327                 "%read_val  = OpCompositeExtract ${customType} %read_obj${extractIndexes}\n"
17328                 "             OpStore %outloc %read_val\n"
17329                 "             OpReturn\n"
17330                 "             OpFunctionEnd\n"
17331         ).specialize(parameters);
17332 }
17333
17334 tcu::TestCaseGroup* createOpInBoundsAccessChainGroup (tcu::TestContext& testCtx)
17335 {
17336         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opinboundsaccesschain", "Test the OpInBoundsAccessChain instruction"));
17337         de::Random                                              rnd                             (deStringHash(group->getName()));
17338
17339         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17340         {
17341                 NumberType                                              numberType      = NumberType(type);
17342                 const string                                    typeName        = getNumberTypeName(numberType);
17343                 const string                                    description     = "Test the OpInBoundsAccessChain instruction with " + typeName + "s";
17344                 de::MovePtr<tcu::TestCaseGroup> subGroup        (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17345
17346                 vector<map<string, string> >    testCases;
17347                 createCompositeCases(testCases, rnd, numberType);
17348
17349                 for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
17350                 {
17351                         ComputeShaderSpec       spec;
17352
17353                         // Number of components inside of a struct
17354                         deUint32 structComponents = rnd.getInt(2, 8);
17355                         // Component index value
17356                         deUint32 structIndex = rnd.getInt(0, structComponents - 1);
17357                         AssemblyStructInfo structInfo(structComponents, structIndex);
17358
17359                         spec.assembly = specializeInBoundsShaderTemplate(numberType, structInfo, *test);
17360
17361                         switch (numberType)
17362                         {
17363                                 case NUMBERTYPE_INT32:
17364                                 {
17365                                         deInt32 number = getInt(rnd);
17366                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17367                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17368                                         break;
17369                                 }
17370                                 case NUMBERTYPE_UINT32:
17371                                 {
17372                                         deUint32 number = rnd.getUint32();
17373                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17374                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17375                                         break;
17376                                 }
17377                                 case NUMBERTYPE_FLOAT32:
17378                                 {
17379                                         float number = rnd.getFloat();
17380                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
17381                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
17382                                         break;
17383                                 }
17384                                 default:
17385                                         DE_ASSERT(false);
17386                         }
17387                         spec.numWorkGroups = IVec3(1, 1, 1);
17388                         subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpInBoundsAccessChain test", spec));
17389                 }
17390                 group->addChild(subGroup.release());
17391         }
17392         return group.release();
17393 }
17394
17395 // If the params missing, uninitialized case
17396 const string specializeDefaultOutputShaderTemplate (const NumberType type, const map<string, string>& params = map<string, string>())
17397 {
17398         map<string, string> parameters(params);
17399
17400         parameters["customType"]        = getAssemblyTypeName(type);
17401
17402         // Declare the const value, and use it in the initializer
17403         if (params.find("constValue") != params.end())
17404         {
17405                 parameters["variableInitializer"]       = " %const";
17406         }
17407         // Uninitialized case
17408         else
17409         {
17410                 parameters["commentDecl"]       = ";";
17411         }
17412
17413         return StringTemplate(
17414                 "OpCapability Shader\n"
17415                 "OpMemoryModel Logical GLSL450\n"
17416                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17417                 "OpExecutionMode %main LocalSize 1 1 1\n"
17418                 "OpSource GLSL 430\n"
17419                 "OpName %main           \"main\"\n"
17420                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17421                 // Decorators
17422                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17423                 "OpDecorate %indata DescriptorSet 0\n"
17424                 "OpDecorate %indata Binding 0\n"
17425                 "OpDecorate %outdata DescriptorSet 0\n"
17426                 "OpDecorate %outdata Binding 1\n"
17427                 "OpDecorate %in_arr ArrayStride 4\n"
17428                 "OpDecorate %in_buf BufferBlock\n"
17429                 "OpMemberDecorate %in_buf 0 Offset 0\n"
17430                 // Base types
17431                 "%void       = OpTypeVoid\n"
17432                 "%voidf      = OpTypeFunction %void\n"
17433                 "%u32        = OpTypeInt 32 0\n"
17434                 "%i32        = OpTypeInt 32 1\n"
17435                 "%f32        = OpTypeFloat 32\n"
17436                 "%uvec3      = OpTypeVector %u32 3\n"
17437                 "%uvec3ptr   = OpTypePointer Input %uvec3\n"
17438                 "${commentDecl:opt}%const      = OpConstant ${customType} ${constValue:opt}\n"
17439                 // Derived types
17440                 "%in_ptr     = OpTypePointer Uniform ${customType}\n"
17441                 "%in_arr     = OpTypeRuntimeArray ${customType}\n"
17442                 "%in_buf     = OpTypeStruct %in_arr\n"
17443                 "%in_bufptr  = OpTypePointer Uniform %in_buf\n"
17444                 "%indata     = OpVariable %in_bufptr Uniform\n"
17445                 "%outdata    = OpVariable %in_bufptr Uniform\n"
17446                 "%id         = OpVariable %uvec3ptr Input\n"
17447                 "%var_ptr    = OpTypePointer Function ${customType}\n"
17448                 // Constants
17449                 "%zero       = OpConstant %i32 0\n"
17450                 // Main function
17451                 "%main       = OpFunction %void None %voidf\n"
17452                 "%label      = OpLabel\n"
17453                 "%out_var    = OpVariable %var_ptr Function${variableInitializer:opt}\n"
17454                 "%idval      = OpLoad %uvec3 %id\n"
17455                 "%x          = OpCompositeExtract %u32 %idval 0\n"
17456                 "%inloc      = OpAccessChain %in_ptr %indata %zero %x\n"
17457                 "%outloc     = OpAccessChain %in_ptr %outdata %zero %x\n"
17458
17459                 "%outval     = OpLoad ${customType} %out_var\n"
17460                 "              OpStore %outloc %outval\n"
17461                 "              OpReturn\n"
17462                 "              OpFunctionEnd\n"
17463         ).specialize(parameters);
17464 }
17465
17466 bool compareFloats (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
17467 {
17468         DE_ASSERT(outputAllocs.size() != 0);
17469         DE_ASSERT(outputAllocs.size() == expectedOutputs.size());
17470
17471         // Use custom epsilon because of the float->string conversion
17472         const float     epsilon = 0.00001f;
17473
17474         for (size_t outputNdx = 0; outputNdx < outputAllocs.size(); ++outputNdx)
17475         {
17476                 vector<deUint8> expectedBytes;
17477                 float                   expected;
17478                 float                   actual;
17479
17480                 expectedOutputs[outputNdx].getBytes(expectedBytes);
17481                 memcpy(&expected, &expectedBytes.front(), expectedBytes.size());
17482                 memcpy(&actual, outputAllocs[outputNdx]->getHostPtr(), expectedBytes.size());
17483
17484                 // Test with epsilon
17485                 if (fabs(expected - actual) > epsilon)
17486                 {
17487                         log << TestLog::Message << "Error: The actual and expected values not matching."
17488                                 << " Expected: " << expected << " Actual: " << actual << " Epsilon: " << epsilon << TestLog::EndMessage;
17489                         return false;
17490                 }
17491         }
17492         return true;
17493 }
17494
17495 // Checks if the driver crash with uninitialized cases
17496 bool passthruVerify (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
17497 {
17498         DE_ASSERT(outputAllocs.size() != 0);
17499         DE_ASSERT(outputAllocs.size() == expectedOutputs.size());
17500
17501         // Copy and discard the result.
17502         for (size_t outputNdx = 0; outputNdx < outputAllocs.size(); ++outputNdx)
17503         {
17504                 vector<deUint8> expectedBytes;
17505                 expectedOutputs[outputNdx].getBytes(expectedBytes);
17506
17507                 const size_t    width                   = expectedBytes.size();
17508                 vector<char>    data                    (width);
17509
17510                 memcpy(&data[0], outputAllocs[outputNdx]->getHostPtr(), width);
17511         }
17512         return true;
17513 }
17514
17515 tcu::TestCaseGroup* createShaderDefaultOutputGroup (tcu::TestContext& testCtx)
17516 {
17517         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "shader_default_output", "Test shader default output."));
17518         de::Random                                              rnd             (deStringHash(group->getName()));
17519
17520         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17521         {
17522                 NumberType                                              numberType      = NumberType(type);
17523                 const string                                    typeName        = getNumberTypeName(numberType);
17524                 const string                                    description     = "Test the OpVariable initializer with " + typeName + ".";
17525                 de::MovePtr<tcu::TestCaseGroup> subGroup        (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17526
17527                 // 2 similar subcases (initialized and uninitialized)
17528                 for (int subCase = 0; subCase < 2; ++subCase)
17529                 {
17530                         ComputeShaderSpec spec;
17531                         spec.numWorkGroups = IVec3(1, 1, 1);
17532
17533                         map<string, string>                             params;
17534
17535                         switch (numberType)
17536                         {
17537                                 case NUMBERTYPE_INT32:
17538                                 {
17539                                         deInt32 number = getInt(rnd);
17540                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17541                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17542                                         params["constValue"] = numberToString(number);
17543                                         break;
17544                                 }
17545                                 case NUMBERTYPE_UINT32:
17546                                 {
17547                                         deUint32 number = rnd.getUint32();
17548                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17549                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17550                                         params["constValue"] = numberToString(number);
17551                                         break;
17552                                 }
17553                                 case NUMBERTYPE_FLOAT32:
17554                                 {
17555                                         float number = rnd.getFloat();
17556                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
17557                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
17558                                         spec.verifyIO = &compareFloats;
17559                                         params["constValue"] = numberToString(number);
17560                                         break;
17561                                 }
17562                                 default:
17563                                         DE_ASSERT(false);
17564                         }
17565
17566                         // Initialized subcase
17567                         if (!subCase)
17568                         {
17569                                 spec.assembly = specializeDefaultOutputShaderTemplate(numberType, params);
17570                                 subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "initialized", "OpVariable initializer tests.", spec));
17571                         }
17572                         // Uninitialized subcase
17573                         else
17574                         {
17575                                 spec.assembly = specializeDefaultOutputShaderTemplate(numberType);
17576                                 spec.verifyIO = &passthruVerify;
17577                                 subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "uninitialized", "OpVariable initializer tests.", spec));
17578                         }
17579                 }
17580                 group->addChild(subGroup.release());
17581         }
17582         return group.release();
17583 }
17584
17585 tcu::TestCaseGroup* createOpNopTests (tcu::TestContext& testCtx)
17586 {
17587         de::MovePtr<tcu::TestCaseGroup> testGroup (new tcu::TestCaseGroup(testCtx, "opnop", "Test OpNop"));
17588         RGBA                                                    defaultColors[4];
17589         map<string, string>                             opNopFragments;
17590
17591         getDefaultColors(defaultColors);
17592
17593         opNopFragments["testfun"]               =
17594                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17595                 "%param1 = OpFunctionParameter %v4f32\n"
17596                 "%label_testfun = OpLabel\n"
17597                 "OpNop\n"
17598                 "OpNop\n"
17599                 "OpNop\n"
17600                 "OpNop\n"
17601                 "OpNop\n"
17602                 "OpNop\n"
17603                 "OpNop\n"
17604                 "OpNop\n"
17605                 "%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17606                 "%b = OpFAdd %f32 %a %a\n"
17607                 "OpNop\n"
17608                 "%c = OpFSub %f32 %b %a\n"
17609                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
17610                 "OpNop\n"
17611                 "OpNop\n"
17612                 "OpReturnValue %ret\n"
17613                 "OpFunctionEnd\n";
17614
17615         createTestsForAllStages("opnop", defaultColors, defaultColors, opNopFragments, testGroup.get());
17616
17617         return testGroup.release();
17618 }
17619
17620 tcu::TestCaseGroup* createOpNameTests (tcu::TestContext& testCtx)
17621 {
17622         de::MovePtr<tcu::TestCaseGroup> testGroup       (new tcu::TestCaseGroup(testCtx, "opname","Test OpName"));
17623         RGBA                                                    defaultColors[4];
17624         map<string, string>                             opNameFragments;
17625
17626         getDefaultColors(defaultColors);
17627
17628         opNameFragments["testfun"] =
17629                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17630                 "%param1     = OpFunctionParameter %v4f32\n"
17631                 "%label_func = OpLabel\n"
17632                 "%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17633                 "%b          = OpFAdd %f32 %a %a\n"
17634                 "%c          = OpFSub %f32 %b %a\n"
17635                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
17636                 "OpReturnValue %ret\n"
17637                 "OpFunctionEnd\n";
17638
17639         opNameFragments["debug"] =
17640                 "OpName %BP_main \"not_main\"";
17641
17642         createTestsForAllStages("opname", defaultColors, defaultColors, opNameFragments, testGroup.get());
17643
17644         return testGroup.release();
17645 }
17646
17647 tcu::TestCaseGroup* createFloat16Tests (tcu::TestContext& testCtx)
17648 {
17649         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "float16", "Float 16 tests"));
17650
17651         testGroup->addChild(createOpConstantFloat16Tests(testCtx));
17652         testGroup->addChild(createFloat16LogicalSet<GraphicsResources>(testCtx, TEST_WITH_NAN));
17653         testGroup->addChild(createFloat16LogicalSet<GraphicsResources>(testCtx, TEST_WITHOUT_NAN));
17654         testGroup->addChild(createFloat16FuncSet<GraphicsResources>(testCtx));
17655         testGroup->addChild(createDerivativeTests<256, 1>(testCtx));
17656         testGroup->addChild(createDerivativeTests<256, 2>(testCtx));
17657         testGroup->addChild(createDerivativeTests<256, 4>(testCtx));
17658         testGroup->addChild(createFloat16VectorExtractSet<GraphicsResources>(testCtx));
17659         testGroup->addChild(createFloat16VectorInsertSet<GraphicsResources>(testCtx));
17660         testGroup->addChild(createFloat16VectorShuffleSet<GraphicsResources>(testCtx));
17661         testGroup->addChild(createFloat16CompositeConstructSet<GraphicsResources>(testCtx));
17662         testGroup->addChild(createFloat16CompositeInsertExtractSet<GraphicsResources>(testCtx, "OpCompositeExtract"));
17663         testGroup->addChild(createFloat16CompositeInsertExtractSet<GraphicsResources>(testCtx, "OpCompositeInsert"));
17664         testGroup->addChild(createFloat16ArithmeticSet<GraphicsResources>(testCtx));
17665         testGroup->addChild(createFloat16ArithmeticSet<1, GraphicsResources>(testCtx));
17666         testGroup->addChild(createFloat16ArithmeticSet<2, GraphicsResources>(testCtx));
17667         testGroup->addChild(createFloat16ArithmeticSet<3, GraphicsResources>(testCtx));
17668         testGroup->addChild(createFloat16ArithmeticSet<4, GraphicsResources>(testCtx));
17669
17670         return testGroup.release();
17671 }
17672
17673 tcu::TestCaseGroup* createFloat16Group (tcu::TestContext& testCtx)
17674 {
17675         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "float16", "Float 16 tests"));
17676
17677         testGroup->addChild(createFloat16OpConstantCompositeGroup(testCtx));
17678         testGroup->addChild(createFloat16LogicalSet<ComputeShaderSpec>(testCtx, TEST_WITH_NAN));
17679         testGroup->addChild(createFloat16LogicalSet<ComputeShaderSpec>(testCtx, TEST_WITHOUT_NAN));
17680         testGroup->addChild(createFloat16FuncSet<ComputeShaderSpec>(testCtx));
17681         testGroup->addChild(createFloat16VectorExtractSet<ComputeShaderSpec>(testCtx));
17682         testGroup->addChild(createFloat16VectorInsertSet<ComputeShaderSpec>(testCtx));
17683         testGroup->addChild(createFloat16VectorShuffleSet<ComputeShaderSpec>(testCtx));
17684         testGroup->addChild(createFloat16CompositeConstructSet<ComputeShaderSpec>(testCtx));
17685         testGroup->addChild(createFloat16CompositeInsertExtractSet<ComputeShaderSpec>(testCtx, "OpCompositeExtract"));
17686         testGroup->addChild(createFloat16CompositeInsertExtractSet<ComputeShaderSpec>(testCtx, "OpCompositeInsert"));
17687         testGroup->addChild(createFloat16ArithmeticSet<ComputeShaderSpec>(testCtx));
17688         testGroup->addChild(createFloat16ArithmeticSet<1, ComputeShaderSpec>(testCtx));
17689         testGroup->addChild(createFloat16ArithmeticSet<2, ComputeShaderSpec>(testCtx));
17690         testGroup->addChild(createFloat16ArithmeticSet<3, ComputeShaderSpec>(testCtx));
17691         testGroup->addChild(createFloat16ArithmeticSet<4, ComputeShaderSpec>(testCtx));
17692
17693         return testGroup.release();
17694 }
17695
17696 tcu::TestCaseGroup* createBoolMixedBitSizeGroup (tcu::TestContext& testCtx)
17697 {
17698         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "mixed_bitsize", "Tests boolean operands produced from instructions of different bit-sizes"));
17699
17700         de::Random                                              rnd                             (deStringHash(group->getName()));
17701         const int               numElements             = 100;
17702         vector<float>   inputData               (numElements, 0);
17703         vector<float>   outputData              (numElements, 0);
17704         fillRandomScalars(rnd, 0.0f, 100.0f, &inputData[0], 100);
17705
17706         const StringTemplate                    shaderTemplate  (
17707                 "${CAPS}\n"
17708                 "OpMemoryModel Logical GLSL450\n"
17709                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17710                 "OpExecutionMode %main LocalSize 1 1 1\n"
17711                 "OpSource GLSL 430\n"
17712                 "OpName %main           \"main\"\n"
17713                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17714
17715                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17716
17717                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
17718
17719                 "%id        = OpVariable %uvec3ptr Input\n"
17720                 "${CONST}\n"
17721                 "%main      = OpFunction %void None %voidf\n"
17722                 "%label     = OpLabel\n"
17723                 "%idval     = OpLoad %uvec3 %id\n"
17724                 "%x         = OpCompositeExtract %u32 %idval 0\n"
17725                 "%inloc     = OpAccessChain %f32ptr %indata %c0i32 %x\n"
17726
17727                 "${TEST}\n"
17728
17729                 "%outloc    = OpAccessChain %f32ptr %outdata %c0i32 %x\n"
17730                 "             OpStore %outloc %res\n"
17731                 "             OpReturn\n"
17732                 "             OpFunctionEnd\n"
17733         );
17734
17735         // Each test case produces 4 boolean values, and we want each of these values
17736         // to come froma different combination of the available bit-sizes, so compute
17737         // all possible combinations here.
17738         vector<deUint32>        widths;
17739         widths.push_back(32);
17740         widths.push_back(16);
17741         widths.push_back(8);
17742
17743         vector<IVec4>   cases;
17744         for (size_t width0 = 0; width0 < widths.size(); width0++)
17745         {
17746                 for (size_t width1 = 0; width1 < widths.size(); width1++)
17747                 {
17748                         for (size_t width2 = 0; width2 < widths.size(); width2++)
17749                         {
17750                                 for (size_t width3 = 0; width3 < widths.size(); width3++)
17751                                 {
17752                                         cases.push_back(IVec4(widths[width0], widths[width1], widths[width2], widths[width3]));
17753                                 }
17754                         }
17755                 }
17756         }
17757
17758         for (size_t caseNdx = 0; caseNdx < cases.size(); caseNdx++)
17759         {
17760                 /// Skip cases where all bitsizes are the same, we are only interested in testing booleans produced from instructions with different native bit-sizes
17761                 if (cases[caseNdx][0] == cases[caseNdx][1] && cases[caseNdx][0] == cases[caseNdx][2] && cases[caseNdx][0] == cases[caseNdx][3])
17762                         continue;
17763
17764                 map<string, string>     specializations;
17765                 ComputeShaderSpec       spec;
17766
17767                 // Inject appropriate capabilities and reference constants depending
17768                 // on the bit-sizes required by this test case
17769                 bool hasFloat32 = cases[caseNdx][0] == 32 || cases[caseNdx][1] == 32 || cases[caseNdx][2] == 32 || cases[caseNdx][3] == 32;
17770                 bool hasFloat16 = cases[caseNdx][0] == 16 || cases[caseNdx][1] == 16 || cases[caseNdx][2] == 16 || cases[caseNdx][3] == 16;
17771                 bool hasInt8    = cases[caseNdx][0] == 8 || cases[caseNdx][1] == 8 || cases[caseNdx][2] == 8 || cases[caseNdx][3] == 8;
17772
17773                 string capsStr  = "OpCapability Shader\n";
17774                 string constStr =
17775                         "%c0i32     = OpConstant %i32 0\n"
17776                         "%c1f32     = OpConstant %f32 1.0\n"
17777                         "%c0f32     = OpConstant %f32 0.0\n";
17778
17779                 if (hasFloat32)
17780                 {
17781                         constStr        +=
17782                                 "%c10f32    = OpConstant %f32 10.0\n"
17783                                 "%c25f32    = OpConstant %f32 25.0\n"
17784                                 "%c50f32    = OpConstant %f32 50.0\n"
17785                                 "%c90f32    = OpConstant %f32 90.0\n";
17786                 }
17787
17788                 if (hasFloat16)
17789                 {
17790                         capsStr         += "OpCapability Float16\n";
17791                         constStr        +=
17792                                 "%f16       = OpTypeFloat 16\n"
17793                                 "%c10f16    = OpConstant %f16 10.0\n"
17794                                 "%c25f16    = OpConstant %f16 25.0\n"
17795                                 "%c50f16    = OpConstant %f16 50.0\n"
17796                                 "%c90f16    = OpConstant %f16 90.0\n";
17797                 }
17798
17799                 if (hasInt8)
17800                 {
17801                         capsStr         += "OpCapability Int8\n";
17802                         constStr        +=
17803                                 "%i8        = OpTypeInt 8 1\n"
17804                                 "%c10i8     = OpConstant %i8 10\n"
17805                                 "%c25i8     = OpConstant %i8 25\n"
17806                                 "%c50i8     = OpConstant %i8 50\n"
17807                                 "%c90i8     = OpConstant %i8 90\n";
17808                 }
17809
17810                 // Each invocation reads a different float32 value as input. Depending on
17811                 // the bit-sizes required by the particular test case, we also produce
17812                 // float16 and/or and int8 values by converting from the 32-bit float.
17813                 string testStr  = "";
17814                 testStr                 += "%inval32   = OpLoad %f32 %inloc\n";
17815                 if (hasFloat16)
17816                         testStr         += "%inval16   = OpFConvert %f16 %inval32\n";
17817                 if (hasInt8)
17818                         testStr         += "%inval8    = OpConvertFToS %i8 %inval32\n";
17819
17820                 // Because conversions from Float to Int round towards 0 we want our "greater" comparisons to be >=,
17821                 // that way a float32/float16 comparison such as 50.6f >= 50.0f will preserve its result
17822                 // when converted to int8, since FtoS(50.6f) results in 50. For "less" comparisons, it is the
17823                 // other way around, so in this case we want < instead of <=.
17824                 if (cases[caseNdx][0] == 32)
17825                         testStr         += "%cmp1      = OpFOrdGreaterThanEqual %bool %inval32 %c25f32\n";
17826                 else if (cases[caseNdx][0] == 16)
17827                         testStr         += "%cmp1      = OpFOrdGreaterThanEqual %bool %inval16 %c25f16\n";
17828                 else
17829                         testStr         += "%cmp1      = OpSGreaterThanEqual %bool %inval8 %c25i8\n";
17830
17831                 if (cases[caseNdx][1] == 32)
17832                         testStr         += "%cmp2      = OpFOrdLessThan %bool %inval32 %c50f32\n";
17833                 else if (cases[caseNdx][1] == 16)
17834                         testStr         += "%cmp2      = OpFOrdLessThan %bool %inval16 %c50f16\n";
17835                 else
17836                         testStr         += "%cmp2      = OpSLessThan %bool %inval8 %c50i8\n";
17837
17838                 if (cases[caseNdx][2] == 32)
17839                         testStr         += "%cmp3      = OpFOrdLessThan %bool %inval32 %c10f32\n";
17840                 else if (cases[caseNdx][2] == 16)
17841                         testStr         += "%cmp3      = OpFOrdLessThan %bool %inval16 %c10f16\n";
17842                 else
17843                         testStr         += "%cmp3      = OpSLessThan %bool %inval8 %c10i8\n";
17844
17845                 if (cases[caseNdx][3] == 32)
17846                         testStr         += "%cmp4      = OpFOrdGreaterThanEqual %bool %inval32 %c90f32\n";
17847                 else if (cases[caseNdx][3] == 16)
17848                         testStr         += "%cmp4      = OpFOrdGreaterThanEqual %bool %inval16 %c90f16\n";
17849                 else
17850                         testStr         += "%cmp4      = OpSGreaterThanEqual %bool %inval8 %c90i8\n";
17851
17852                 testStr                 += "%and1      = OpLogicalAnd %bool %cmp1 %cmp2\n";
17853                 testStr                 += "%or1       = OpLogicalOr %bool %cmp3 %cmp4\n";
17854                 testStr                 += "%or2       = OpLogicalOr %bool %and1 %or1\n";
17855                 testStr                 += "%not1      = OpLogicalNot %bool %or2\n";
17856                 testStr                 += "%res       = OpSelect %f32 %not1 %c1f32 %c0f32\n";
17857
17858                 specializations["CAPS"]         = capsStr;
17859                 specializations["CONST"]        = constStr;
17860                 specializations["TEST"]         = testStr;
17861
17862                 // Compute expected result by evaluating the boolean expression computed in the shader for each input value
17863                 for (size_t ndx = 0; ndx < numElements; ++ndx)
17864                         outputData[ndx] = !((inputData[ndx] >= 25.0f && inputData[ndx] < 50.0f) || (inputData[ndx] < 10.0f || inputData[ndx] >= 90.0f));
17865
17866                 spec.assembly = shaderTemplate.specialize(specializations);
17867                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputData)));
17868                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputData)));
17869                 spec.numWorkGroups = IVec3(numElements, 1, 1);
17870                 if (hasFloat16)
17871                         spec.requestedVulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_FLOAT16;
17872                 if (hasInt8)
17873                         spec.requestedVulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_INT8;
17874                 spec.extensions.push_back("VK_KHR_shader_float16_int8");
17875
17876                 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]);
17877                 group->addChild(new SpvAsmComputeShaderCase(testCtx, testName.c_str(), "", spec));
17878         }
17879
17880         return group.release();
17881 }
17882
17883 tcu::TestCaseGroup* createBoolGroup (tcu::TestContext& testCtx)
17884 {
17885         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "bool", "Boolean tests"));
17886
17887         testGroup->addChild(createBoolMixedBitSizeGroup(testCtx));
17888
17889         return testGroup.release();
17890 }
17891
17892 tcu::TestCaseGroup* createOpNameAbuseTests (tcu::TestContext& testCtx)
17893 {
17894         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "opname_abuse", "OpName abuse tests"));
17895         vector<CaseParameter>                   abuseCases;
17896         RGBA                                                    defaultColors[4];
17897         map<string, string>                             opNameFragments;
17898
17899         getOpNameAbuseCases(abuseCases);
17900         getDefaultColors(defaultColors);
17901
17902         opNameFragments["testfun"] =
17903                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17904                 "%param1     = OpFunctionParameter %v4f32\n"
17905                 "%label_func = OpLabel\n"
17906                 "%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17907                 "%b          = OpFAdd %f32 %a %a\n"
17908                 "%c          = OpFSub %f32 %b %a\n"
17909                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
17910                 "OpReturnValue %ret\n"
17911                 "OpFunctionEnd\n";
17912
17913         for (unsigned int i = 0; i < abuseCases.size(); i++)
17914         {
17915                 string casename;
17916                 casename = string("main") + abuseCases[i].name;
17917
17918                 opNameFragments["debug"] =
17919                         "OpName %BP_main \"" + abuseCases[i].param + "\"";
17920
17921                 createTestsForAllStages(casename, defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17922         }
17923
17924         for (unsigned int i = 0; i < abuseCases.size(); i++)
17925         {
17926                 string casename;
17927                 casename = string("b") + abuseCases[i].name;
17928
17929                 opNameFragments["debug"] =
17930                         "OpName %b \"" + abuseCases[i].param + "\"";
17931
17932                 createTestsForAllStages(casename, defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17933         }
17934
17935         {
17936                 opNameFragments["debug"] =
17937                         "OpName %test_code \"name1\"\n"
17938                         "OpName %param1    \"name2\"\n"
17939                         "OpName %a         \"name3\"\n"
17940                         "OpName %b         \"name4\"\n"
17941                         "OpName %c         \"name5\"\n"
17942                         "OpName %ret       \"name6\"\n";
17943
17944                 createTestsForAllStages("everything_named", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17945         }
17946
17947         {
17948                 opNameFragments["debug"] =
17949                         "OpName %test_code \"the_same\"\n"
17950                         "OpName %param1    \"the_same\"\n"
17951                         "OpName %a         \"the_same\"\n"
17952                         "OpName %b         \"the_same\"\n"
17953                         "OpName %c         \"the_same\"\n"
17954                         "OpName %ret       \"the_same\"\n";
17955
17956                 createTestsForAllStages("everything_named_the_same", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17957         }
17958
17959         {
17960                 opNameFragments["debug"] =
17961                         "OpName %BP_main \"to_be\"\n"
17962                         "OpName %BP_main \"or_not\"\n"
17963                         "OpName %BP_main \"to_be\"\n";
17964
17965                 createTestsForAllStages("main_has_multiple_names", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17966         }
17967
17968         {
17969                 opNameFragments["debug"] =
17970                         "OpName %b \"to_be\"\n"
17971                         "OpName %b \"or_not\"\n"
17972                         "OpName %b \"to_be\"\n";
17973
17974                 createTestsForAllStages("b_has_multiple_names", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17975         }
17976
17977         return abuseGroup.release();
17978 }
17979
17980
17981 tcu::TestCaseGroup* createOpMemberNameAbuseTests (tcu::TestContext& testCtx)
17982 {
17983         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "opmembername_abuse", "OpName abuse tests"));
17984         vector<CaseParameter>                   abuseCases;
17985         RGBA                                                    defaultColors[4];
17986         map<string, string>                             opMemberNameFragments;
17987
17988         getOpNameAbuseCases(abuseCases);
17989         getDefaultColors(defaultColors);
17990
17991         opMemberNameFragments["pre_main"] =
17992                 "%f3str = OpTypeStruct %f32 %f32 %f32\n";
17993
17994         opMemberNameFragments["testfun"] =
17995                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17996                 "%param1     = OpFunctionParameter %v4f32\n"
17997                 "%label_func = OpLabel\n"
17998                 "%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17999                 "%b          = OpFAdd %f32 %a %a\n"
18000                 "%c          = OpFSub %f32 %b %a\n"
18001                 "%cstr       = OpCompositeConstruct %f3str %c %c %c\n"
18002                 "%d          = OpCompositeExtract %f32 %cstr 0\n"
18003                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %d %c_i32_0\n"
18004                 "OpReturnValue %ret\n"
18005                 "OpFunctionEnd\n";
18006
18007         for (unsigned int i = 0; i < abuseCases.size(); i++)
18008         {
18009                 string casename;
18010                 casename = string("f3str_x") + abuseCases[i].name;
18011
18012                 opMemberNameFragments["debug"] =
18013                         "OpMemberName %f3str 0 \"" + abuseCases[i].param + "\"";
18014
18015                 createTestsForAllStages(casename, defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18016         }
18017
18018         {
18019                 opMemberNameFragments["debug"] =
18020                         "OpMemberName %f3str 0 \"name1\"\n"
18021                         "OpMemberName %f3str 1 \"name2\"\n"
18022                         "OpMemberName %f3str 2 \"name3\"\n";
18023
18024                 createTestsForAllStages("everything_named", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18025         }
18026
18027         {
18028                 opMemberNameFragments["debug"] =
18029                         "OpMemberName %f3str 0 \"the_same\"\n"
18030                         "OpMemberName %f3str 1 \"the_same\"\n"
18031                         "OpMemberName %f3str 2 \"the_same\"\n";
18032
18033                 createTestsForAllStages("everything_named_the_same", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18034         }
18035
18036         {
18037                 opMemberNameFragments["debug"] =
18038                         "OpMemberName %f3str 0 \"to_be\"\n"
18039                         "OpMemberName %f3str 1 \"or_not\"\n"
18040                         "OpMemberName %f3str 0 \"to_be\"\n"
18041                         "OpMemberName %f3str 2 \"makes_no\"\n"
18042                         "OpMemberName %f3str 0 \"difference\"\n"
18043                         "OpMemberName %f3str 0 \"to_me\"\n";
18044
18045
18046                 createTestsForAllStages("f3str_x_has_multiple_names", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18047         }
18048
18049         return abuseGroup.release();
18050 }
18051
18052 vector<deUint32> getSparseIdsAbuseData (const deUint32 numDataPoints, const deUint32 seed)
18053 {
18054         vector<deUint32>        result;
18055         de::Random                      rnd             (seed);
18056
18057         result.reserve(numDataPoints);
18058
18059         for (deUint32 dataPointNdx = 0; dataPointNdx < numDataPoints; ++dataPointNdx)
18060                 result.push_back(rnd.getUint32());
18061
18062         return result;
18063 }
18064
18065 vector<deUint32> getSparseIdsAbuseResults (const vector<deUint32>& inData1, const vector<deUint32>& inData2)
18066 {
18067         vector<deUint32>        result;
18068
18069         result.reserve(inData1.size());
18070
18071         for (size_t dataPointNdx = 0; dataPointNdx < inData1.size(); ++dataPointNdx)
18072                 result.push_back(inData1[dataPointNdx] + inData2[dataPointNdx]);
18073
18074         return result;
18075 }
18076
18077 template<class SpecResource>
18078 void createSparseIdsAbuseTest (tcu::TestContext& testCtx, de::MovePtr<tcu::TestCaseGroup>& testGroup)
18079 {
18080         const deUint32                  numDataPoints   = 16;
18081         const std::string               testName                ("sparse_ids");
18082         const deUint32                  seed                    (deStringHash(testName.c_str()));
18083         const vector<deUint32>  inData1                 (getSparseIdsAbuseData(numDataPoints, seed + 1));
18084         const vector<deUint32>  inData2                 (getSparseIdsAbuseData(numDataPoints, seed + 2));
18085         const vector<deUint32>  outData                 (getSparseIdsAbuseResults(inData1, inData2));
18086         const StringTemplate    preMain
18087         (
18088                 "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
18089                 "   %up_u32 = OpTypePointer Uniform %u32\n"
18090                 "   %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
18091                 "   %SSBO32 = OpTypeStruct %ra_u32\n"
18092                 "%up_SSBO32 = OpTypePointer Uniform %SSBO32\n"
18093                 "%ssbo_src0 = OpVariable %up_SSBO32 Uniform\n"
18094                 "%ssbo_src1 = OpVariable %up_SSBO32 Uniform\n"
18095                 " %ssbo_dst = OpVariable %up_SSBO32 Uniform\n"
18096         );
18097         const StringTemplate    decoration
18098         (
18099                 "OpDecorate %ra_u32 ArrayStride 4\n"
18100                 "OpMemberDecorate %SSBO32 0 Offset 0\n"
18101                 "OpDecorate %SSBO32 BufferBlock\n"
18102                 "OpDecorate %ssbo_src0 DescriptorSet 0\n"
18103                 "OpDecorate %ssbo_src0 Binding 0\n"
18104                 "OpDecorate %ssbo_src1 DescriptorSet 0\n"
18105                 "OpDecorate %ssbo_src1 Binding 1\n"
18106                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
18107                 "OpDecorate %ssbo_dst Binding 2\n"
18108         );
18109         const StringTemplate    testFun
18110         (
18111                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
18112                 "    %param = OpFunctionParameter %v4f32\n"
18113
18114                 "    %entry = OpLabel\n"
18115                 "        %i = OpVariable %fp_i32 Function\n"
18116                 "             OpStore %i %c_i32_0\n"
18117                 "             OpBranch %loop\n"
18118
18119                 "     %loop = OpLabel\n"
18120                 "    %i_cmp = OpLoad %i32 %i\n"
18121                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
18122                 "             OpLoopMerge %merge %next None\n"
18123                 "             OpBranchConditional %lt %write %merge\n"
18124
18125                 "    %write = OpLabel\n"
18126                 "      %ndx = OpLoad %i32 %i\n"
18127
18128                 "      %127 = OpAccessChain %up_u32 %ssbo_src0 %c_i32_0 %ndx\n"
18129                 "      %128 = OpLoad %u32 %127\n"
18130
18131                 // The test relies on SPIR-V compiler option SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS set in assembleSpirV()
18132                 "  %4194000 = OpAccessChain %up_u32 %ssbo_src1 %c_i32_0 %ndx\n"
18133                 "  %4194001 = OpLoad %u32 %4194000\n"
18134
18135                 "  %2097151 = OpIAdd %u32 %128 %4194001\n"
18136                 "  %2097152 = OpAccessChain %up_u32 %ssbo_dst %c_i32_0 %ndx\n"
18137                 "             OpStore %2097152 %2097151\n"
18138                 "             OpBranch %next\n"
18139
18140                 "     %next = OpLabel\n"
18141                 "    %i_cur = OpLoad %i32 %i\n"
18142                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
18143                 "             OpStore %i %i_new\n"
18144                 "             OpBranch %loop\n"
18145
18146                 "    %merge = OpLabel\n"
18147                 "             OpReturnValue %param\n"
18148
18149                 "             OpFunctionEnd\n"
18150         );
18151         SpecResource                    specResource;
18152         map<string, string>             specs;
18153         VulkanFeatures                  features;
18154         map<string, string>             fragments;
18155         vector<string>                  extensions;
18156
18157         specs["num_data_points"]        = de::toString(numDataPoints);
18158
18159         fragments["decoration"]         = decoration.specialize(specs);
18160         fragments["pre_main"]           = preMain.specialize(specs);
18161         fragments["testfun"]            = testFun.specialize(specs);
18162
18163         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18164         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18165         specResource.outputs.push_back(Resource(BufferSp(new Uint32Buffer(outData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18166
18167         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
18168 }
18169
18170 vector<deUint32> getLotsIdsAbuseData (const deUint32 numDataPoints, const deUint32 seed)
18171 {
18172         vector<deUint32>        result;
18173         de::Random                      rnd             (seed);
18174
18175         result.reserve(numDataPoints);
18176
18177         // Fixed value
18178         result.push_back(1u);
18179
18180         // Random values
18181         for (deUint32 dataPointNdx = 1; dataPointNdx < numDataPoints; ++dataPointNdx)
18182                 result.push_back(rnd.getUint8());
18183
18184         return result;
18185 }
18186
18187 vector<deUint32> getLotsIdsAbuseResults (const vector<deUint32>& inData1, const vector<deUint32>& inData2, const deUint32 count)
18188 {
18189         vector<deUint32>        result;
18190
18191         result.reserve(inData1.size());
18192
18193         for (size_t dataPointNdx = 0; dataPointNdx < inData1.size(); ++dataPointNdx)
18194                 result.push_back(inData1[dataPointNdx] + count * inData2[dataPointNdx]);
18195
18196         return result;
18197 }
18198
18199 template<class SpecResource>
18200 void createLotsIdsAbuseTest (tcu::TestContext& testCtx, de::MovePtr<tcu::TestCaseGroup>& testGroup)
18201 {
18202         const deUint32                  numDataPoints   = 16;
18203         const deUint32                  firstNdx                = 100u;
18204         const deUint32                  sequenceCount   = 10000u;
18205         const std::string               testName                ("lots_ids");
18206         const deUint32                  seed                    (deStringHash(testName.c_str()));
18207         const vector<deUint32>  inData1                 (getLotsIdsAbuseData(numDataPoints, seed + 1));
18208         const vector<deUint32>  inData2                 (getLotsIdsAbuseData(numDataPoints, seed + 2));
18209         const vector<deUint32>  outData                 (getLotsIdsAbuseResults(inData1, inData2, sequenceCount));
18210         const StringTemplate preMain
18211         (
18212                 "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
18213                 "   %up_u32 = OpTypePointer Uniform %u32\n"
18214                 "   %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
18215                 "   %SSBO32 = OpTypeStruct %ra_u32\n"
18216                 "%up_SSBO32 = OpTypePointer Uniform %SSBO32\n"
18217                 "%ssbo_src0 = OpVariable %up_SSBO32 Uniform\n"
18218                 "%ssbo_src1 = OpVariable %up_SSBO32 Uniform\n"
18219                 " %ssbo_dst = OpVariable %up_SSBO32 Uniform\n"
18220         );
18221         const StringTemplate decoration
18222         (
18223                 "OpDecorate %ra_u32 ArrayStride 4\n"
18224                 "OpMemberDecorate %SSBO32 0 Offset 0\n"
18225                 "OpDecorate %SSBO32 BufferBlock\n"
18226                 "OpDecorate %ssbo_src0 DescriptorSet 0\n"
18227                 "OpDecorate %ssbo_src0 Binding 0\n"
18228                 "OpDecorate %ssbo_src1 DescriptorSet 0\n"
18229                 "OpDecorate %ssbo_src1 Binding 1\n"
18230                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
18231                 "OpDecorate %ssbo_dst Binding 2\n"
18232         );
18233         const StringTemplate testFun
18234         (
18235                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
18236                 "    %param = OpFunctionParameter %v4f32\n"
18237
18238                 "    %entry = OpLabel\n"
18239                 "        %i = OpVariable %fp_i32 Function\n"
18240                 "             OpStore %i %c_i32_0\n"
18241                 "             OpBranch %loop\n"
18242
18243                 "     %loop = OpLabel\n"
18244                 "    %i_cmp = OpLoad %i32 %i\n"
18245                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
18246                 "             OpLoopMerge %merge %next None\n"
18247                 "             OpBranchConditional %lt %write %merge\n"
18248
18249                 "    %write = OpLabel\n"
18250                 "      %ndx = OpLoad %i32 %i\n"
18251
18252                 "       %90 = OpAccessChain %up_u32 %ssbo_src1 %c_i32_0 %ndx\n"
18253                 "       %91 = OpLoad %u32 %90\n"
18254
18255                 "       %98 = OpAccessChain %up_u32 %ssbo_src0 %c_i32_0 %ndx\n"
18256                 "       %${zeroth_id} = OpLoad %u32 %98\n"
18257
18258                 "${seq}\n"
18259
18260                 // The test relies on SPIR-V compiler option SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS set in assembleSpirV()
18261                 "      %dst = OpAccessChain %up_u32 %ssbo_dst %c_i32_0 %ndx\n"
18262                 "             OpStore %dst %${last_id}\n"
18263                 "             OpBranch %next\n"
18264
18265                 "     %next = OpLabel\n"
18266                 "    %i_cur = OpLoad %i32 %i\n"
18267                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
18268                 "             OpStore %i %i_new\n"
18269                 "             OpBranch %loop\n"
18270
18271                 "    %merge = OpLabel\n"
18272                 "             OpReturnValue %param\n"
18273
18274                 "             OpFunctionEnd\n"
18275         );
18276         deUint32                                lastId                  = firstNdx;
18277         SpecResource                    specResource;
18278         map<string, string>             specs;
18279         VulkanFeatures                  features;
18280         map<string, string>             fragments;
18281         vector<string>                  extensions;
18282         std::string                             sequence;
18283
18284         for (deUint32 sequenceNdx = 0; sequenceNdx < sequenceCount; ++sequenceNdx)
18285         {
18286                 const deUint32          sequenceId              = sequenceNdx + firstNdx;
18287                 const std::string       sequenceIdStr   = de::toString(sequenceId);
18288
18289                 sequence += "%" + sequenceIdStr + " = OpIAdd %u32 %91 %" + de::toString(sequenceId - 1) + "\n";
18290                 lastId = sequenceId;
18291
18292                 if (sequenceNdx == 0)
18293                         sequence.reserve((10 + sequence.length()) * sequenceCount);
18294         }
18295
18296         specs["num_data_points"]        = de::toString(numDataPoints);
18297         specs["zeroth_id"]                      = de::toString(firstNdx - 1);
18298         specs["last_id"]                        = de::toString(lastId);
18299         specs["seq"]                            = sequence;
18300
18301         fragments["decoration"]         = decoration.specialize(specs);
18302         fragments["pre_main"]           = preMain.specialize(specs);
18303         fragments["testfun"]            = testFun.specialize(specs);
18304
18305         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18306         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18307         specResource.outputs.push_back(Resource(BufferSp(new Uint32Buffer(outData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18308
18309         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
18310 }
18311
18312 tcu::TestCaseGroup* createSpirvIdsAbuseTests (tcu::TestContext& testCtx)
18313 {
18314         de::MovePtr<tcu::TestCaseGroup> testGroup       (new tcu::TestCaseGroup(testCtx, "spirv_ids_abuse", "SPIR-V abuse tests"));
18315
18316         createSparseIdsAbuseTest<GraphicsResources>(testCtx, testGroup);
18317         createLotsIdsAbuseTest<GraphicsResources>(testCtx, testGroup);
18318
18319         return testGroup.release();
18320 }
18321
18322 tcu::TestCaseGroup* createSpirvIdsAbuseGroup (tcu::TestContext& testCtx)
18323 {
18324         de::MovePtr<tcu::TestCaseGroup> testGroup       (new tcu::TestCaseGroup(testCtx, "spirv_ids_abuse", "SPIR-V abuse tests"));
18325
18326         createSparseIdsAbuseTest<ComputeShaderSpec>(testCtx, testGroup);
18327         createLotsIdsAbuseTest<ComputeShaderSpec>(testCtx, testGroup);
18328
18329         return testGroup.release();
18330 }
18331
18332 tcu::TestCaseGroup* createInstructionTests (tcu::TestContext& testCtx)
18333 {
18334         const bool testComputePipeline = true;
18335
18336         de::MovePtr<tcu::TestCaseGroup> instructionTests        (new tcu::TestCaseGroup(testCtx, "instruction", "Instructions with special opcodes/operands"));
18337         de::MovePtr<tcu::TestCaseGroup> computeTests            (new tcu::TestCaseGroup(testCtx, "compute", "Compute Instructions with special opcodes/operands"));
18338         de::MovePtr<tcu::TestCaseGroup> graphicsTests           (new tcu::TestCaseGroup(testCtx, "graphics", "Graphics Instructions with special opcodes/operands"));
18339
18340         computeTests->addChild(createSpivVersionCheckTests(testCtx, testComputePipeline));
18341         computeTests->addChild(createLocalSizeGroup(testCtx));
18342         computeTests->addChild(createOpNopGroup(testCtx));
18343         computeTests->addChild(createOpFUnordGroup(testCtx, TEST_WITHOUT_NAN));
18344         computeTests->addChild(createOpFUnordGroup(testCtx, TEST_WITH_NAN));
18345         computeTests->addChild(createOpAtomicGroup(testCtx, false));
18346         computeTests->addChild(createOpAtomicGroup(testCtx, true));                                     // Using new StorageBuffer decoration
18347         computeTests->addChild(createOpAtomicGroup(testCtx, false, 1024, true));        // Return value validation
18348         computeTests->addChild(createOpLineGroup(testCtx));
18349         computeTests->addChild(createOpModuleProcessedGroup(testCtx));
18350         computeTests->addChild(createOpNoLineGroup(testCtx));
18351         computeTests->addChild(createOpConstantNullGroup(testCtx));
18352         computeTests->addChild(createOpConstantCompositeGroup(testCtx));
18353         computeTests->addChild(createOpConstantUsageGroup(testCtx));
18354         computeTests->addChild(createSpecConstantGroup(testCtx));
18355         computeTests->addChild(createOpSourceGroup(testCtx));
18356         computeTests->addChild(createOpSourceExtensionGroup(testCtx));
18357         computeTests->addChild(createDecorationGroupGroup(testCtx));
18358         computeTests->addChild(createOpPhiGroup(testCtx));
18359         computeTests->addChild(createLoopControlGroup(testCtx));
18360         computeTests->addChild(createFunctionControlGroup(testCtx));
18361         computeTests->addChild(createSelectionControlGroup(testCtx));
18362         computeTests->addChild(createBlockOrderGroup(testCtx));
18363         computeTests->addChild(createMultipleShaderGroup(testCtx));
18364         computeTests->addChild(createMemoryAccessGroup(testCtx));
18365         computeTests->addChild(createOpCopyMemoryGroup(testCtx));
18366         computeTests->addChild(createOpCopyObjectGroup(testCtx));
18367         computeTests->addChild(createNoContractionGroup(testCtx));
18368         computeTests->addChild(createOpUndefGroup(testCtx));
18369         computeTests->addChild(createOpUnreachableGroup(testCtx));
18370         computeTests->addChild(createOpQuantizeToF16Group(testCtx));
18371         computeTests->addChild(createOpFRemGroup(testCtx));
18372         computeTests->addChild(createOpSRemComputeGroup(testCtx, QP_TEST_RESULT_PASS));
18373         computeTests->addChild(createOpSRemComputeGroup64(testCtx, QP_TEST_RESULT_PASS));
18374         computeTests->addChild(createOpSModComputeGroup(testCtx, QP_TEST_RESULT_PASS));
18375         computeTests->addChild(createOpSModComputeGroup64(testCtx, QP_TEST_RESULT_PASS));
18376         computeTests->addChild(createConvertComputeTests(testCtx, "OpSConvert", "sconvert"));
18377         computeTests->addChild(createConvertComputeTests(testCtx, "OpUConvert", "uconvert"));
18378         computeTests->addChild(createConvertComputeTests(testCtx, "OpFConvert", "fconvert"));
18379         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertSToF", "convertstof"));
18380         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertFToS", "convertftos"));
18381         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertUToF", "convertutof"));
18382         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertFToU", "convertftou"));
18383         computeTests->addChild(createOpCompositeInsertGroup(testCtx));
18384         computeTests->addChild(createOpInBoundsAccessChainGroup(testCtx));
18385         computeTests->addChild(createShaderDefaultOutputGroup(testCtx));
18386         computeTests->addChild(createOpNMinGroup(testCtx));
18387         computeTests->addChild(createOpNMaxGroup(testCtx));
18388         computeTests->addChild(createOpNClampGroup(testCtx));
18389         {
18390                 de::MovePtr<tcu::TestCaseGroup> computeAndroidTests     (new tcu::TestCaseGroup(testCtx, "android", "Android CTS Tests"));
18391
18392                 computeAndroidTests->addChild(createOpSRemComputeGroup(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18393                 computeAndroidTests->addChild(createOpSModComputeGroup(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18394
18395                 computeTests->addChild(computeAndroidTests.release());
18396         }
18397
18398         computeTests->addChild(create8BitStorageComputeGroup(testCtx));
18399         computeTests->addChild(create16BitStorageComputeGroup(testCtx));
18400         computeTests->addChild(createFloatControlsComputeGroup(testCtx));
18401         computeTests->addChild(createUboMatrixPaddingComputeGroup(testCtx));
18402         computeTests->addChild(createCompositeInsertComputeGroup(testCtx));
18403         computeTests->addChild(createVariableInitComputeGroup(testCtx));
18404         computeTests->addChild(createConditionalBranchComputeGroup(testCtx));
18405         computeTests->addChild(createIndexingComputeGroup(testCtx));
18406         computeTests->addChild(createVariablePointersComputeGroup(testCtx));
18407         computeTests->addChild(createPhysicalPointersComputeGroup(testCtx));
18408         computeTests->addChild(createImageSamplerComputeGroup(testCtx));
18409         computeTests->addChild(createOpNameGroup(testCtx));
18410         computeTests->addChild(createOpMemberNameGroup(testCtx));
18411         computeTests->addChild(createPointerParameterComputeGroup(testCtx));
18412         computeTests->addChild(createFloat16Group(testCtx));
18413         computeTests->addChild(createBoolGroup(testCtx));
18414         computeTests->addChild(createWorkgroupMemoryComputeGroup(testCtx));
18415         computeTests->addChild(createSpirvIdsAbuseGroup(testCtx));
18416         computeTests->addChild(createSignedIntCompareGroup(testCtx));
18417
18418         graphicsTests->addChild(createCrossStageInterfaceTests(testCtx));
18419         graphicsTests->addChild(createSpivVersionCheckTests(testCtx, !testComputePipeline));
18420         graphicsTests->addChild(createOpNopTests(testCtx));
18421         graphicsTests->addChild(createOpSourceTests(testCtx));
18422         graphicsTests->addChild(createOpSourceContinuedTests(testCtx));
18423         graphicsTests->addChild(createOpModuleProcessedTests(testCtx));
18424         graphicsTests->addChild(createOpLineTests(testCtx));
18425         graphicsTests->addChild(createOpNoLineTests(testCtx));
18426         graphicsTests->addChild(createOpConstantNullTests(testCtx));
18427         graphicsTests->addChild(createOpConstantCompositeTests(testCtx));
18428         graphicsTests->addChild(createMemoryAccessTests(testCtx));
18429         graphicsTests->addChild(createOpUndefTests(testCtx));
18430         graphicsTests->addChild(createSelectionBlockOrderTests(testCtx));
18431         graphicsTests->addChild(createModuleTests(testCtx));
18432         graphicsTests->addChild(createSwitchBlockOrderTests(testCtx));
18433         graphicsTests->addChild(createOpPhiTests(testCtx));
18434         graphicsTests->addChild(createNoContractionTests(testCtx));
18435         graphicsTests->addChild(createOpQuantizeTests(testCtx));
18436         graphicsTests->addChild(createLoopTests(testCtx));
18437         graphicsTests->addChild(createSpecConstantTests(testCtx));
18438         graphicsTests->addChild(createSpecConstantOpQuantizeToF16Group(testCtx));
18439         graphicsTests->addChild(createBarrierTests(testCtx));
18440         graphicsTests->addChild(createDecorationGroupTests(testCtx));
18441         graphicsTests->addChild(createFRemTests(testCtx));
18442         graphicsTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
18443         graphicsTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
18444
18445         {
18446                 de::MovePtr<tcu::TestCaseGroup> graphicsAndroidTests    (new tcu::TestCaseGroup(testCtx, "android", "Android CTS Tests"));
18447
18448                 graphicsAndroidTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18449                 graphicsAndroidTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18450
18451                 graphicsTests->addChild(graphicsAndroidTests.release());
18452         }
18453         graphicsTests->addChild(createOpNameTests(testCtx));
18454         graphicsTests->addChild(createOpNameAbuseTests(testCtx));
18455         graphicsTests->addChild(createOpMemberNameAbuseTests(testCtx));
18456
18457         graphicsTests->addChild(create8BitStorageGraphicsGroup(testCtx));
18458         graphicsTests->addChild(create16BitStorageGraphicsGroup(testCtx));
18459         graphicsTests->addChild(createFloatControlsGraphicsGroup(testCtx));
18460         graphicsTests->addChild(createUboMatrixPaddingGraphicsGroup(testCtx));
18461         graphicsTests->addChild(createCompositeInsertGraphicsGroup(testCtx));
18462         graphicsTests->addChild(createVariableInitGraphicsGroup(testCtx));
18463         graphicsTests->addChild(createConditionalBranchGraphicsGroup(testCtx));
18464         graphicsTests->addChild(createIndexingGraphicsGroup(testCtx));
18465         graphicsTests->addChild(createVariablePointersGraphicsGroup(testCtx));
18466         graphicsTests->addChild(createImageSamplerGraphicsGroup(testCtx));
18467         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpSConvert", "sconvert"));
18468         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpUConvert", "uconvert"));
18469         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpFConvert", "fconvert"));
18470         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertSToF", "convertstof"));
18471         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertFToS", "convertftos"));
18472         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertUToF", "convertutof"));
18473         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertFToU", "convertftou"));
18474         graphicsTests->addChild(createPointerParameterGraphicsGroup(testCtx));
18475         graphicsTests->addChild(createVaryingNameGraphicsGroup(testCtx));
18476         graphicsTests->addChild(createFloat16Tests(testCtx));
18477         graphicsTests->addChild(createSpirvIdsAbuseTests(testCtx));
18478
18479         instructionTests->addChild(computeTests.release());
18480         instructionTests->addChild(graphicsTests.release());
18481
18482         return instructionTests.release();
18483 }
18484
18485 } // SpirVAssembly
18486 } // vkt