Add tests for OpFUnord with NaN
[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
75 #include <cmath>
76 #include <limits>
77 #include <map>
78 #include <string>
79 #include <sstream>
80 #include <utility>
81 #include <stack>
82
83 namespace vkt
84 {
85 namespace SpirVAssembly
86 {
87
88 namespace
89 {
90
91 using namespace vk;
92 using std::map;
93 using std::string;
94 using std::vector;
95 using tcu::IVec3;
96 using tcu::IVec4;
97 using tcu::RGBA;
98 using tcu::TestLog;
99 using tcu::TestStatus;
100 using tcu::Vec4;
101 using de::UniquePtr;
102 using tcu::StringTemplate;
103 using tcu::Vec4;
104
105 const bool TEST_WITH_NAN        = true;
106 const bool TEST_WITHOUT_NAN     = false;
107
108 template<typename T>
109 static void fillRandomScalars (de::Random& rnd, T minValue, T maxValue, void* dst, int numValues, int offset = 0)
110 {
111         T* const typedPtr = (T*)dst;
112         for (int ndx = 0; ndx < numValues; ndx++)
113                 typedPtr[offset + ndx] = randomScalar<T>(rnd, minValue, maxValue);
114 }
115
116 // Filter is a function that returns true if a value should pass, false otherwise.
117 template<typename T, typename FilterT>
118 static void fillRandomScalars (de::Random& rnd, T minValue, T maxValue, void* dst, int numValues, FilterT filter, int offset = 0)
119 {
120         T* const typedPtr = (T*)dst;
121         T value;
122         for (int ndx = 0; ndx < numValues; ndx++)
123         {
124                 do
125                         value = randomScalar<T>(rnd, minValue, maxValue);
126                 while (!filter(value));
127
128                 typedPtr[offset + ndx] = value;
129         }
130 }
131
132 // Gets a 64-bit integer with a more logarithmic distribution
133 deInt64 randomInt64LogDistributed (de::Random& rnd)
134 {
135         deInt64 val = rnd.getUint64();
136         val &= (1ull << rnd.getInt(1, 63)) - 1;
137         if (rnd.getBool())
138                 val = -val;
139         return val;
140 }
141
142 static void fillRandomInt64sLogDistributed (de::Random& rnd, vector<deInt64>& dst, int numValues)
143 {
144         for (int ndx = 0; ndx < numValues; ndx++)
145                 dst[ndx] = randomInt64LogDistributed(rnd);
146 }
147
148 template<typename FilterT>
149 static void fillRandomInt64sLogDistributed (de::Random& rnd, vector<deInt64>& dst, int numValues, FilterT filter)
150 {
151         for (int ndx = 0; ndx < numValues; ndx++)
152         {
153                 deInt64 value;
154                 do {
155                         value = randomInt64LogDistributed(rnd);
156                 } while (!filter(value));
157                 dst[ndx] = value;
158         }
159 }
160
161 inline bool filterNonNegative (const deInt64 value)
162 {
163         return value >= 0;
164 }
165
166 inline bool filterPositive (const deInt64 value)
167 {
168         return value > 0;
169 }
170
171 inline bool filterNotZero (const deInt64 value)
172 {
173         return value != 0;
174 }
175
176 static void floorAll (vector<float>& values)
177 {
178         for (size_t i = 0; i < values.size(); i++)
179                 values[i] = deFloatFloor(values[i]);
180 }
181
182 static void floorAll (vector<Vec4>& values)
183 {
184         for (size_t i = 0; i < values.size(); i++)
185                 values[i] = floor(values[i]);
186 }
187
188 struct CaseParameter
189 {
190         const char*             name;
191         string                  param;
192
193         CaseParameter   (const char* case_, const string& param_) : name(case_), param(param_) {}
194 };
195
196 // Assembly code used for testing LocalSize, OpNop, OpConstant{Null|Composite}, Op[No]Line, OpSource[Continued], OpSourceExtension, OpUndef is based on GLSL source code:
197 //
198 // #version 430
199 //
200 // layout(std140, set = 0, binding = 0) readonly buffer Input {
201 //   float elements[];
202 // } input_data;
203 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
204 //   float elements[];
205 // } output_data;
206 //
207 // layout (local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
208 //
209 // void main() {
210 //   uint x = gl_GlobalInvocationID.x;
211 //   output_data.elements[x] = -input_data.elements[x];
212 // }
213
214 static string getAsmForLocalSizeTest(bool useLiteralLocalSize, bool useSpecConstantWorkgroupSize, IVec3 workGroupSize, deUint32 ndx)
215 {
216         std::ostringstream out;
217         out << getComputeAsmShaderPreambleWithoutLocalSize();
218
219         if (useLiteralLocalSize)
220         {
221                 out << "OpExecutionMode %main LocalSize "
222                         << workGroupSize.x() << " " << workGroupSize.y() << " " << workGroupSize.z() << "\n";
223         }
224
225         out << "OpSource GLSL 430\n"
226                 "OpName %main           \"main\"\n"
227                 "OpName %id             \"gl_GlobalInvocationID\"\n"
228                 "OpDecorate %id BuiltIn GlobalInvocationId\n";
229
230         if (useSpecConstantWorkgroupSize)
231         {
232                 out << "OpDecorate %spec_0 SpecId 100\n"
233                         << "OpDecorate %spec_1 SpecId 101\n"
234                         << "OpDecorate %spec_2 SpecId 102\n"
235                         << "OpDecorate %gl_WorkGroupSize BuiltIn WorkgroupSize\n";
236         }
237
238         out << getComputeAsmInputOutputBufferTraits()
239                 << getComputeAsmCommonTypes()
240                 << getComputeAsmInputOutputBuffer()
241                 << "%id        = OpVariable %uvec3ptr Input\n"
242                 << "%zero      = OpConstant %i32 0 \n";
243
244         if (useSpecConstantWorkgroupSize)
245         {
246                 out     << "%spec_0   = OpSpecConstant %u32 "<< workGroupSize.x() << "\n"
247                         << "%spec_1   = OpSpecConstant %u32 "<< workGroupSize.y() << "\n"
248                         << "%spec_2   = OpSpecConstant %u32 "<< workGroupSize.z() << "\n"
249                         << "%gl_WorkGroupSize = OpSpecConstantComposite %uvec3 %spec_0 %spec_1 %spec_2\n";
250         }
251
252         out << "%main      = OpFunction %void None %voidf\n"
253                 << "%label     = OpLabel\n"
254                 << "%idval     = OpLoad %uvec3 %id\n"
255                 << "%ndx         = OpCompositeExtract %u32 %idval " << ndx << "\n"
256
257                         "%inloc     = OpAccessChain %f32ptr %indata %zero %ndx\n"
258                         "%inval     = OpLoad %f32 %inloc\n"
259                         "%neg       = OpFNegate %f32 %inval\n"
260                         "%outloc    = OpAccessChain %f32ptr %outdata %zero %ndx\n"
261                         "             OpStore %outloc %neg\n"
262                         "             OpReturn\n"
263                         "             OpFunctionEnd\n";
264         return out.str();
265 }
266
267 tcu::TestCaseGroup* createLocalSizeGroup (tcu::TestContext& testCtx)
268 {
269         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "localsize", ""));
270         ComputeShaderSpec                               spec;
271         de::Random                                              rnd                             (deStringHash(group->getName()));
272         const deUint32                                  numElements             = 64u;
273         vector<float>                                   positiveFloats  (numElements, 0);
274         vector<float>                                   negativeFloats  (numElements, 0);
275
276         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
277
278         for (size_t ndx = 0; ndx < numElements; ++ndx)
279                 negativeFloats[ndx] = -positiveFloats[ndx];
280
281         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
282         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
283
284         spec.numWorkGroups = IVec3(numElements, 1, 1);
285
286         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, 1, 1), 0u);
287         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize", "", spec));
288
289         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, 1, 1), 0u);
290         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize", "", spec));
291
292         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, 1, 1), 0u);
293         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize", "", spec));
294
295         spec.numWorkGroups = IVec3(1, 1, 1);
296
297         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(numElements, 1, 1), 0u);
298         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_x", "", spec));
299
300         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(numElements, 1, 1), 0u);
301         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_x", "", spec));
302
303         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(numElements, 1, 1), 0u);
304         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_x", "", spec));
305
306         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, numElements, 1), 1u);
307         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_y", "", spec));
308
309         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, numElements, 1), 1u);
310         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_y", "", spec));
311
312         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, numElements, 1), 1u);
313         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_y", "", spec));
314
315         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, 1, numElements), 2u);
316         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_z", "", spec));
317
318         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, 1, numElements), 2u);
319         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_z", "", spec));
320
321         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, 1, numElements), 2u);
322         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_z", "", spec));
323
324         return group.release();
325 }
326
327 tcu::TestCaseGroup* createOpNopGroup (tcu::TestContext& testCtx)
328 {
329         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnop", "Test the OpNop instruction"));
330         ComputeShaderSpec                               spec;
331         de::Random                                              rnd                             (deStringHash(group->getName()));
332         const int                                               numElements             = 100;
333         vector<float>                                   positiveFloats  (numElements, 0);
334         vector<float>                                   negativeFloats  (numElements, 0);
335
336         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
337
338         for (size_t ndx = 0; ndx < numElements; ++ndx)
339                 negativeFloats[ndx] = -positiveFloats[ndx];
340
341         spec.assembly =
342                 string(getComputeAsmShaderPreamble()) +
343
344                 "OpSource GLSL 430\n"
345                 "OpName %main           \"main\"\n"
346                 "OpName %id             \"gl_GlobalInvocationID\"\n"
347
348                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
349
350                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes())
351
352                 + string(getComputeAsmInputOutputBuffer()) +
353
354                 "%id        = OpVariable %uvec3ptr Input\n"
355                 "%zero      = OpConstant %i32 0\n"
356
357                 "%main      = OpFunction %void None %voidf\n"
358                 "%label     = OpLabel\n"
359                 "%idval     = OpLoad %uvec3 %id\n"
360                 "%x         = OpCompositeExtract %u32 %idval 0\n"
361
362                 "             OpNop\n" // Inside a function body
363
364                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
365                 "%inval     = OpLoad %f32 %inloc\n"
366                 "%neg       = OpFNegate %f32 %inval\n"
367                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
368                 "             OpStore %outloc %neg\n"
369                 "             OpReturn\n"
370                 "             OpFunctionEnd\n";
371         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
372         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
373         spec.numWorkGroups = IVec3(numElements, 1, 1);
374
375         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpNop appearing at different places", spec));
376
377         return group.release();
378 }
379
380 template<bool nanSupported>
381 bool compareFUnord (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
382 {
383         if (outputAllocs.size() != 1)
384                 return false;
385
386         vector<deUint8> input1Bytes;
387         vector<deUint8> input2Bytes;
388         vector<deUint8> expectedBytes;
389
390         inputs[0].getBytes(input1Bytes);
391         inputs[1].getBytes(input2Bytes);
392         expectedOutputs[0].getBytes(expectedBytes);
393
394         const deInt32* const    expectedOutputAsInt             = reinterpret_cast<const deInt32*>(&expectedBytes.front());
395         const deInt32* const    outputAsInt                             = static_cast<const deInt32*>(outputAllocs[0]->getHostPtr());
396         const float* const              input1AsFloat                   = reinterpret_cast<const float*>(&input1Bytes.front());
397         const float* const              input2AsFloat                   = reinterpret_cast<const float*>(&input2Bytes.front());
398         bool returnValue                                                                = true;
399
400         for (size_t idx = 0; idx < expectedBytes.size() / sizeof(deInt32); ++idx)
401         {
402                 if (!nanSupported && (tcu::Float32(input1AsFloat[idx]).isNaN() || tcu::Float32(input2AsFloat[idx]).isNaN()))
403                         continue;
404
405                 if (outputAsInt[idx] != expectedOutputAsInt[idx])
406                 {
407                         log << TestLog::Message << "ERROR: Sub-case failed. inputs: " << input1AsFloat[idx] << "," << input2AsFloat[idx] << " output: " << outputAsInt[idx]<< " expected output: " << expectedOutputAsInt[idx] << TestLog::EndMessage;
408                         returnValue = false;
409                 }
410         }
411         return returnValue;
412 }
413
414 typedef VkBool32 (*compareFuncType) (float, float);
415
416 struct OpFUnordCase
417 {
418         const char*             name;
419         const char*             opCode;
420         compareFuncType compareFunc;
421
422                                         OpFUnordCase                    (const char* _name, const char* _opCode, compareFuncType _compareFunc)
423                                                 : name                          (_name)
424                                                 , opCode                        (_opCode)
425                                                 , compareFunc           (_compareFunc) {}
426 };
427
428 #define ADD_OPFUNORD_CASE(NAME, OPCODE, OPERATOR) \
429 do { \
430         struct compare_##NAME { static VkBool32 compare(float x, float y) { return (x OPERATOR y) ? VK_TRUE : VK_FALSE; } }; \
431         cases.push_back(OpFUnordCase(#NAME, OPCODE, compare_##NAME::compare)); \
432 } while (deGetFalse())
433
434 tcu::TestCaseGroup* createOpFUnordGroup (tcu::TestContext& testCtx, const bool testWithNan)
435 {
436         const string                                    nan                             = testWithNan ? "_nan" : "";
437         const string                                    groupName               = "opfunord" + nan;
438         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Test the OpFUnord* opcodes"));
439         de::Random                                              rnd                             (deStringHash(group->getName()));
440         const int                                               numElements             = 100;
441         vector<OpFUnordCase>                    cases;
442         string                                                  extensions              = testWithNan ? "OpExtension \"SPV_KHR_float_controls\"\n" : "";
443         string                                                  capabilities    = testWithNan ? "OpCapability SignedZeroInfNanPreserve\n" : "";
444         string                                                  exeModes                = testWithNan ? "OpExecutionMode %main SignedZeroInfNanPreserve 32\n" : "";
445         const StringTemplate                    shaderTemplate  (
446                 string(getComputeAsmShaderPreamble(capabilities, extensions, exeModes)) +
447                 "OpSource GLSL 430\n"
448                 "OpName %main           \"main\"\n"
449                 "OpName %id             \"gl_GlobalInvocationID\"\n"
450
451                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
452
453                 "OpDecorate %buf BufferBlock\n"
454                 "OpDecorate %buf2 BufferBlock\n"
455                 "OpDecorate %indata1 DescriptorSet 0\n"
456                 "OpDecorate %indata1 Binding 0\n"
457                 "OpDecorate %indata2 DescriptorSet 0\n"
458                 "OpDecorate %indata2 Binding 1\n"
459                 "OpDecorate %outdata DescriptorSet 0\n"
460                 "OpDecorate %outdata Binding 2\n"
461                 "OpDecorate %f32arr ArrayStride 4\n"
462                 "OpDecorate %i32arr ArrayStride 4\n"
463                 "OpMemberDecorate %buf 0 Offset 0\n"
464                 "OpMemberDecorate %buf2 0 Offset 0\n"
465
466                 + string(getComputeAsmCommonTypes()) +
467
468                 "%buf        = OpTypeStruct %f32arr\n"
469                 "%bufptr     = OpTypePointer Uniform %buf\n"
470                 "%indata1    = OpVariable %bufptr Uniform\n"
471                 "%indata2    = OpVariable %bufptr Uniform\n"
472
473                 "%buf2       = OpTypeStruct %i32arr\n"
474                 "%buf2ptr    = OpTypePointer Uniform %buf2\n"
475                 "%outdata    = OpVariable %buf2ptr Uniform\n"
476
477                 "%id        = OpVariable %uvec3ptr Input\n"
478                 "%zero      = OpConstant %i32 0\n"
479                 "%consti1   = OpConstant %i32 1\n"
480                 "%constf1   = OpConstant %f32 1.0\n"
481
482                 "%main      = OpFunction %void None %voidf\n"
483                 "%label     = OpLabel\n"
484                 "%idval     = OpLoad %uvec3 %id\n"
485                 "%x         = OpCompositeExtract %u32 %idval 0\n"
486
487                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
488                 "%inval1    = OpLoad %f32 %inloc1\n"
489                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
490                 "%inval2    = OpLoad %f32 %inloc2\n"
491                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
492
493                 "%result    = ${OPCODE} %bool %inval1 %inval2\n"
494                 "%int_res   = OpSelect %i32 %result %consti1 %zero\n"
495                 "             OpStore %outloc %int_res\n"
496
497                 "             OpReturn\n"
498                 "             OpFunctionEnd\n");
499
500         ADD_OPFUNORD_CASE(equal, "OpFUnordEqual", ==);
501         ADD_OPFUNORD_CASE(less, "OpFUnordLessThan", <);
502         ADD_OPFUNORD_CASE(lessequal, "OpFUnordLessThanEqual", <=);
503         ADD_OPFUNORD_CASE(greater, "OpFUnordGreaterThan", >);
504         ADD_OPFUNORD_CASE(greaterequal, "OpFUnordGreaterThanEqual", >=);
505         ADD_OPFUNORD_CASE(notequal, "OpFUnordNotEqual", !=);
506
507         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
508         {
509                 map<string, string>                     specializations;
510                 ComputeShaderSpec                       spec;
511                 const float                                     NaN                             = std::numeric_limits<float>::quiet_NaN();
512                 vector<float>                           inputFloats1    (numElements, 0);
513                 vector<float>                           inputFloats2    (numElements, 0);
514                 vector<deInt32>                         expectedInts    (numElements, 0);
515
516                 specializations["OPCODE"]       = cases[caseNdx].opCode;
517                 spec.assembly                           = shaderTemplate.specialize(specializations);
518
519                 fillRandomScalars(rnd, 1.f, 100.f, &inputFloats1[0], numElements);
520                 for (size_t ndx = 0; ndx < numElements; ++ndx)
521                 {
522                         switch (ndx % 6)
523                         {
524                                 case 0:         inputFloats2[ndx] = inputFloats1[ndx] + 1.0f; break;
525                                 case 1:         inputFloats2[ndx] = inputFloats1[ndx] - 1.0f; break;
526                                 case 2:         inputFloats2[ndx] = inputFloats1[ndx]; break;
527                                 case 3:         inputFloats2[ndx] = NaN; break;
528                                 case 4:         inputFloats2[ndx] = inputFloats1[ndx];  inputFloats1[ndx] = NaN; break;
529                                 case 5:         inputFloats2[ndx] = NaN;                                inputFloats1[ndx] = NaN; break;
530                         }
531                         expectedInts[ndx] = tcu::Float32(inputFloats1[ndx]).isNaN() || tcu::Float32(inputFloats2[ndx]).isNaN() || cases[caseNdx].compareFunc(inputFloats1[ndx], inputFloats2[ndx]);
532                 }
533
534                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
535                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
536                 spec.outputs.push_back(BufferSp(new Int32Buffer(expectedInts)));
537                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
538                 spec.verifyIO           = testWithNan ? &compareFUnord<true> : &compareFUnord<false>;
539
540                 if (testWithNan)
541                 {
542                         spec.extensions.push_back("VK_KHR_shader_float_controls");
543                         spec.requestedVulkanFeatures.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat32 = DE_TRUE;
544                 }
545
546                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
547         }
548
549         return group.release();
550 }
551
552 struct OpAtomicCase
553 {
554         const char*             name;
555         const char*             assembly;
556         const char*             retValAssembly;
557         OpAtomicType    opAtomic;
558         deInt32                 numOutputElements;
559
560                                         OpAtomicCase(const char* _name, const char* _assembly, const char* _retValAssembly, OpAtomicType _opAtomic, deInt32 _numOutputElements)
561                                                 : name                          (_name)
562                                                 , assembly                      (_assembly)
563                                                 , retValAssembly        (_retValAssembly)
564                                                 , opAtomic                      (_opAtomic)
565                                                 , numOutputElements     (_numOutputElements) {}
566 };
567
568 tcu::TestCaseGroup* createOpAtomicGroup (tcu::TestContext& testCtx, bool useStorageBuffer, int numElements = 65535, bool verifyReturnValues = false)
569 {
570         std::string                                             groupName                       ("opatomic");
571         if (useStorageBuffer)
572                 groupName += "_storage_buffer";
573         if (verifyReturnValues)
574                 groupName += "_return_values";
575         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Test the OpAtomic* opcodes"));
576         vector<OpAtomicCase>                    cases;
577
578         const StringTemplate                    shaderTemplate  (
579
580                 string("OpCapability Shader\n") +
581                 (useStorageBuffer ? "OpExtension \"SPV_KHR_storage_buffer_storage_class\"\n" : "") +
582                 "OpMemoryModel Logical GLSL450\n"
583                 "OpEntryPoint GLCompute %main \"main\" %id\n"
584                 "OpExecutionMode %main LocalSize 1 1 1\n" +
585
586                 "OpSource GLSL 430\n"
587                 "OpName %main           \"main\"\n"
588                 "OpName %id             \"gl_GlobalInvocationID\"\n"
589
590                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
591
592                 "OpDecorate %buf ${BLOCK_DECORATION}\n"
593                 "OpDecorate %indata DescriptorSet 0\n"
594                 "OpDecorate %indata Binding 0\n"
595                 "OpDecorate %i32arr ArrayStride 4\n"
596                 "OpMemberDecorate %buf 0 Offset 0\n"
597
598                 "OpDecorate %sumbuf ${BLOCK_DECORATION}\n"
599                 "OpDecorate %sum DescriptorSet 0\n"
600                 "OpDecorate %sum Binding 1\n"
601                 "OpMemberDecorate %sumbuf 0 Coherent\n"
602                 "OpMemberDecorate %sumbuf 0 Offset 0\n"
603
604                 "${RETVAL_BUF_DECORATE}"
605
606                 + getComputeAsmCommonTypes("${BLOCK_POINTER_TYPE}") +
607
608                 "%buf       = OpTypeStruct %i32arr\n"
609                 "%bufptr    = OpTypePointer ${BLOCK_POINTER_TYPE} %buf\n"
610                 "%indata    = OpVariable %bufptr ${BLOCK_POINTER_TYPE}\n"
611
612                 "%sumbuf    = OpTypeStruct %i32arr\n"
613                 "%sumbufptr = OpTypePointer ${BLOCK_POINTER_TYPE} %sumbuf\n"
614                 "%sum       = OpVariable %sumbufptr ${BLOCK_POINTER_TYPE}\n"
615
616                 "${RETVAL_BUF_DECL}"
617
618                 "%id        = OpVariable %uvec3ptr Input\n"
619                 "%minusone  = OpConstant %i32 -1\n"
620                 "%zero      = OpConstant %i32 0\n"
621                 "%one       = OpConstant %u32 1\n"
622                 "%two       = OpConstant %i32 2\n"
623
624                 "%main      = OpFunction %void None %voidf\n"
625                 "%label     = OpLabel\n"
626                 "%idval     = OpLoad %uvec3 %id\n"
627                 "%x         = OpCompositeExtract %u32 %idval 0\n"
628
629                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
630                 "%inval     = OpLoad %i32 %inloc\n"
631
632                 "%outloc    = OpAccessChain %i32ptr %sum %zero ${INDEX}\n"
633                 "${INSTRUCTION}"
634                 "${RETVAL_ASSEMBLY}"
635
636                 "             OpReturn\n"
637                 "             OpFunctionEnd\n");
638
639         #define ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, NUM_OUTPUT_ELEMENTS) \
640         do { \
641                 DE_ASSERT((NUM_OUTPUT_ELEMENTS) == 1 || (NUM_OUTPUT_ELEMENTS) == numElements); \
642                 cases.push_back(OpAtomicCase(#NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, NUM_OUTPUT_ELEMENTS)); \
643         } while (deGetFalse())
644         #define ADD_OPATOMIC_CASE_1(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, 1)
645         #define ADD_OPATOMIC_CASE_N(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, numElements)
646
647         ADD_OPATOMIC_CASE_1(iadd,       "%retv      = OpAtomicIAdd %i32 %outloc %one %zero %inval\n",
648                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IADD );
649         ADD_OPATOMIC_CASE_1(isub,       "%retv      = OpAtomicISub %i32 %outloc %one %zero %inval\n",
650                                                                 "             OpStore %retloc %retv\n", OPATOMIC_ISUB );
651         ADD_OPATOMIC_CASE_1(iinc,       "%retv      = OpAtomicIIncrement %i32 %outloc %one %zero\n",
652                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IINC );
653         ADD_OPATOMIC_CASE_1(idec,       "%retv      = OpAtomicIDecrement %i32 %outloc %one %zero\n",
654                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IDEC );
655         if (!verifyReturnValues)
656         {
657                 ADD_OPATOMIC_CASE_N(load,       "%inval2    = OpAtomicLoad %i32 %inloc %one %zero\n"
658                                                                         "             OpStore %outloc %inval2\n", "", OPATOMIC_LOAD );
659                 ADD_OPATOMIC_CASE_N(store,      "             OpAtomicStore %outloc %one %zero %inval\n", "", OPATOMIC_STORE );
660         }
661
662         ADD_OPATOMIC_CASE_N(compex, "%even      = OpSMod %i32 %inval %two\n"
663                                                                 "             OpStore %outloc %even\n"
664                                                                 "%retv      = OpAtomicCompareExchange %i32 %outloc %one %zero %zero %minusone %zero\n",
665                                                                 "                         OpStore %retloc %retv\n", OPATOMIC_COMPEX );
666
667
668         #undef ADD_OPATOMIC_CASE
669         #undef ADD_OPATOMIC_CASE_1
670         #undef ADD_OPATOMIC_CASE_N
671
672         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
673         {
674                 map<string, string>                     specializations;
675                 ComputeShaderSpec                       spec;
676                 vector<deInt32>                         inputInts               (numElements, 0);
677                 vector<deInt32>                         expected                (cases[caseNdx].numOutputElements, -1);
678
679                 specializations["INDEX"]                                = (cases[caseNdx].numOutputElements == 1) ? "%zero" : "%x";
680                 specializations["INSTRUCTION"]                  = cases[caseNdx].assembly;
681                 specializations["BLOCK_DECORATION"]             = useStorageBuffer ? "Block" : "BufferBlock";
682                 specializations["BLOCK_POINTER_TYPE"]   = useStorageBuffer ? "StorageBuffer" : "Uniform";
683
684                 if (verifyReturnValues)
685                 {
686                         const StringTemplate blockDecoration    (
687                                 "\n"
688                                 "OpDecorate %retbuf ${BLOCK_DECORATION}\n"
689                                 "OpDecorate %ret DescriptorSet 0\n"
690                                 "OpDecorate %ret Binding 2\n"
691                                 "OpMemberDecorate %retbuf 0 Offset 0\n\n");
692
693                         const StringTemplate blockDeclaration   (
694                                 "\n"
695                                 "%retbuf    = OpTypeStruct %i32arr\n"
696                                 "%retbufptr = OpTypePointer ${BLOCK_POINTER_TYPE} %retbuf\n"
697                                 "%ret       = OpVariable %retbufptr ${BLOCK_POINTER_TYPE}\n\n");
698
699                         specializations["RETVAL_ASSEMBLY"] =
700                                 "%retloc    = OpAccessChain %i32ptr %ret %zero %x\n"
701                                 + std::string(cases[caseNdx].retValAssembly);
702
703                         specializations["RETVAL_BUF_DECORATE"]  = blockDecoration.specialize(specializations);
704                         specializations["RETVAL_BUF_DECL"]              = blockDeclaration.specialize(specializations);
705                 }
706                 else
707                 {
708                         specializations["RETVAL_ASSEMBLY"]              = "";
709                         specializations["RETVAL_BUF_DECORATE"]  = "";
710                         specializations["RETVAL_BUF_DECL"]              = "";
711                 }
712
713                 spec.assembly                                                   = shaderTemplate.specialize(specializations);
714
715                 if (useStorageBuffer)
716                         spec.extensions.push_back("VK_KHR_storage_buffer_storage_class");
717
718                 spec.inputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_INPUT)));
719                 spec.outputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_EXPECTED)));
720                 if (verifyReturnValues)
721                         spec.outputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_ATOMIC_RET)));
722                 spec.numWorkGroups = IVec3(numElements, 1, 1);
723
724                 if (verifyReturnValues)
725                 {
726                         switch (cases[caseNdx].opAtomic)
727                         {
728                                 case OPATOMIC_IADD:
729                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IADD>;
730                                         break;
731                                 case OPATOMIC_ISUB:
732                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_ISUB>;
733                                         break;
734                                 case OPATOMIC_IINC:
735                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IINC>;
736                                         break;
737                                 case OPATOMIC_IDEC:
738                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IDEC>;
739                                         break;
740                                 case OPATOMIC_COMPEX:
741                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_COMPEX>;
742                                         break;
743                                 default:
744                                         DE_FATAL("Unsupported OpAtomic type for return value verification");
745                         }
746                 }
747                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
748         }
749
750         return group.release();
751 }
752
753 tcu::TestCaseGroup* createOpLineGroup (tcu::TestContext& testCtx)
754 {
755         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opline", "Test the OpLine instruction"));
756         ComputeShaderSpec                               spec;
757         de::Random                                              rnd                             (deStringHash(group->getName()));
758         const int                                               numElements             = 100;
759         vector<float>                                   positiveFloats  (numElements, 0);
760         vector<float>                                   negativeFloats  (numElements, 0);
761
762         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
763
764         for (size_t ndx = 0; ndx < numElements; ++ndx)
765                 negativeFloats[ndx] = -positiveFloats[ndx];
766
767         spec.assembly =
768                 string(getComputeAsmShaderPreamble()) +
769
770                 "%fname1 = OpString \"negateInputs.comp\"\n"
771                 "%fname2 = OpString \"negateInputs\"\n"
772
773                 "OpSource GLSL 430\n"
774                 "OpName %main           \"main\"\n"
775                 "OpName %id             \"gl_GlobalInvocationID\"\n"
776
777                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
778
779                 + string(getComputeAsmInputOutputBufferTraits()) +
780
781                 "OpLine %fname1 0 0\n" // At the earliest possible position
782
783                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
784
785                 "OpLine %fname1 0 1\n" // Multiple OpLines in sequence
786                 "OpLine %fname2 1 0\n" // Different filenames
787                 "OpLine %fname1 1000 100000\n"
788
789                 "%id        = OpVariable %uvec3ptr Input\n"
790                 "%zero      = OpConstant %i32 0\n"
791
792                 "OpLine %fname1 1 1\n" // Before a function
793
794                 "%main      = OpFunction %void None %voidf\n"
795                 "%label     = OpLabel\n"
796
797                 "OpLine %fname1 1 1\n" // In a function
798
799                 "%idval     = OpLoad %uvec3 %id\n"
800                 "%x         = OpCompositeExtract %u32 %idval 0\n"
801                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
802                 "%inval     = OpLoad %f32 %inloc\n"
803                 "%neg       = OpFNegate %f32 %inval\n"
804                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
805                 "             OpStore %outloc %neg\n"
806                 "             OpReturn\n"
807                 "             OpFunctionEnd\n";
808         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
809         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
810         spec.numWorkGroups = IVec3(numElements, 1, 1);
811
812         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpLine appearing at different places", spec));
813
814         return group.release();
815 }
816
817 bool veryfiBinaryShader (const ProgramBinary& binary)
818 {
819         const size_t    paternCount                     = 3u;
820         bool paternsCheck[paternCount]          =
821         {
822                 false, false, false
823         };
824         const string patersns[paternCount]      =
825         {
826                 "VULKAN CTS",
827                 "Negative values",
828                 "Date: 2017/09/21"
829         };
830         size_t                  paternNdx               = 0u;
831
832         for (size_t ndx = 0u; ndx < binary.getSize(); ++ndx)
833         {
834                 if (false == paternsCheck[paternNdx] &&
835                         patersns[paternNdx][0] == static_cast<char>(binary.getBinary()[ndx]) &&
836                         deMemoryEqual((const char*)&binary.getBinary()[ndx], &patersns[paternNdx][0], patersns[paternNdx].length()))
837                 {
838                         paternsCheck[paternNdx]= true;
839                         paternNdx++;
840                         if (paternNdx == paternCount)
841                                 break;
842                 }
843         }
844
845         for (size_t ndx = 0u; ndx < paternCount; ++ndx)
846         {
847                 if (!paternsCheck[ndx])
848                         return false;
849         }
850
851         return true;
852 }
853
854 tcu::TestCaseGroup* createOpModuleProcessedGroup (tcu::TestContext& testCtx)
855 {
856         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opmoduleprocessed", "Test the OpModuleProcessed instruction"));
857         ComputeShaderSpec                               spec;
858         de::Random                                              rnd                             (deStringHash(group->getName()));
859         const int                                               numElements             = 10;
860         vector<float>                                   positiveFloats  (numElements, 0);
861         vector<float>                                   negativeFloats  (numElements, 0);
862
863         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
864
865         for (size_t ndx = 0; ndx < numElements; ++ndx)
866                 negativeFloats[ndx] = -positiveFloats[ndx];
867
868         spec.assembly =
869                 string(getComputeAsmShaderPreamble()) +
870                 "%fname = OpString \"negateInputs.comp\"\n"
871
872                 "OpSource GLSL 430\n"
873                 "OpName %main           \"main\"\n"
874                 "OpName %id             \"gl_GlobalInvocationID\"\n"
875                 "OpModuleProcessed \"VULKAN CTS\"\n"                                    //OpModuleProcessed;
876                 "OpModuleProcessed \"Negative values\"\n"
877                 "OpModuleProcessed \"Date: 2017/09/21\"\n"
878                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
879
880                 + string(getComputeAsmInputOutputBufferTraits())
881
882                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
883
884                 "OpLine %fname 0 1\n"
885
886                 "OpLine %fname 1000 1\n"
887
888                 "%id        = OpVariable %uvec3ptr Input\n"
889                 "%zero      = OpConstant %i32 0\n"
890                 "%main      = OpFunction %void None %voidf\n"
891
892                 "%label     = OpLabel\n"
893                 "%idval     = OpLoad %uvec3 %id\n"
894                 "%x         = OpCompositeExtract %u32 %idval 0\n"
895
896                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
897                 "%inval     = OpLoad %f32 %inloc\n"
898                 "%neg       = OpFNegate %f32 %inval\n"
899                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
900                 "             OpStore %outloc %neg\n"
901                 "             OpReturn\n"
902                 "             OpFunctionEnd\n";
903         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
904         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
905         spec.numWorkGroups = IVec3(numElements, 1, 1);
906         spec.verifyBinary = veryfiBinaryShader;
907         spec.spirvVersion = SPIRV_VERSION_1_3;
908
909         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpModuleProcessed Tests", spec));
910
911         return group.release();
912 }
913
914 tcu::TestCaseGroup* createOpNoLineGroup (tcu::TestContext& testCtx)
915 {
916         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnoline", "Test the OpNoLine instruction"));
917         ComputeShaderSpec                               spec;
918         de::Random                                              rnd                             (deStringHash(group->getName()));
919         const int                                               numElements             = 100;
920         vector<float>                                   positiveFloats  (numElements, 0);
921         vector<float>                                   negativeFloats  (numElements, 0);
922
923         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
924
925         for (size_t ndx = 0; ndx < numElements; ++ndx)
926                 negativeFloats[ndx] = -positiveFloats[ndx];
927
928         spec.assembly =
929                 string(getComputeAsmShaderPreamble()) +
930
931                 "%fname = OpString \"negateInputs.comp\"\n"
932
933                 "OpSource GLSL 430\n"
934                 "OpName %main           \"main\"\n"
935                 "OpName %id             \"gl_GlobalInvocationID\"\n"
936
937                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
938
939                 + string(getComputeAsmInputOutputBufferTraits()) +
940
941                 "OpNoLine\n" // At the earliest possible position, without preceding OpLine
942
943                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
944
945                 "OpLine %fname 0 1\n"
946                 "OpNoLine\n" // Immediately following a preceding OpLine
947
948                 "OpLine %fname 1000 1\n"
949
950                 "%id        = OpVariable %uvec3ptr Input\n"
951                 "%zero      = OpConstant %i32 0\n"
952
953                 "OpNoLine\n" // Contents after the previous OpLine
954
955                 "%main      = OpFunction %void None %voidf\n"
956                 "%label     = OpLabel\n"
957                 "%idval     = OpLoad %uvec3 %id\n"
958                 "%x         = OpCompositeExtract %u32 %idval 0\n"
959
960                 "OpNoLine\n" // Multiple OpNoLine
961                 "OpNoLine\n"
962                 "OpNoLine\n"
963
964                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
965                 "%inval     = OpLoad %f32 %inloc\n"
966                 "%neg       = OpFNegate %f32 %inval\n"
967                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
968                 "             OpStore %outloc %neg\n"
969                 "             OpReturn\n"
970                 "             OpFunctionEnd\n";
971         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
972         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
973         spec.numWorkGroups = IVec3(numElements, 1, 1);
974
975         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpNoLine appearing at different places", spec));
976
977         return group.release();
978 }
979
980 // Compare instruction for the contraction compute case.
981 // Returns true if the output is what is expected from the test case.
982 bool compareNoContractCase(const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
983 {
984         if (outputAllocs.size() != 1)
985                 return false;
986
987         // Only size is needed because we are not comparing the exact values.
988         size_t byteSize = expectedOutputs[0].getByteSize();
989
990         const float*    outputAsFloat   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
991
992         for(size_t i = 0; i < byteSize / sizeof(float); ++i) {
993                 if (outputAsFloat[i] != 0.f &&
994                         outputAsFloat[i] != -ldexp(1, -24)) {
995                         return false;
996                 }
997         }
998
999         return true;
1000 }
1001
1002 tcu::TestCaseGroup* createNoContractionGroup (tcu::TestContext& testCtx)
1003 {
1004         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
1005         vector<CaseParameter>                   cases;
1006         const int                                               numElements             = 100;
1007         vector<float>                                   inputFloats1    (numElements, 0);
1008         vector<float>                                   inputFloats2    (numElements, 0);
1009         vector<float>                                   outputFloats    (numElements, 0);
1010         const StringTemplate                    shaderTemplate  (
1011                 string(getComputeAsmShaderPreamble()) +
1012
1013                 "OpName %main           \"main\"\n"
1014                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1015
1016                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1017
1018                 "${DECORATION}\n"
1019
1020                 "OpDecorate %buf BufferBlock\n"
1021                 "OpDecorate %indata1 DescriptorSet 0\n"
1022                 "OpDecorate %indata1 Binding 0\n"
1023                 "OpDecorate %indata2 DescriptorSet 0\n"
1024                 "OpDecorate %indata2 Binding 1\n"
1025                 "OpDecorate %outdata DescriptorSet 0\n"
1026                 "OpDecorate %outdata Binding 2\n"
1027                 "OpDecorate %f32arr ArrayStride 4\n"
1028                 "OpMemberDecorate %buf 0 Offset 0\n"
1029
1030                 + string(getComputeAsmCommonTypes()) +
1031
1032                 "%buf        = OpTypeStruct %f32arr\n"
1033                 "%bufptr     = OpTypePointer Uniform %buf\n"
1034                 "%indata1    = OpVariable %bufptr Uniform\n"
1035                 "%indata2    = OpVariable %bufptr Uniform\n"
1036                 "%outdata    = OpVariable %bufptr Uniform\n"
1037
1038                 "%id         = OpVariable %uvec3ptr Input\n"
1039                 "%zero       = OpConstant %i32 0\n"
1040                 "%c_f_m1     = OpConstant %f32 -1.\n"
1041
1042                 "%main       = OpFunction %void None %voidf\n"
1043                 "%label      = OpLabel\n"
1044                 "%idval      = OpLoad %uvec3 %id\n"
1045                 "%x          = OpCompositeExtract %u32 %idval 0\n"
1046                 "%inloc1     = OpAccessChain %f32ptr %indata1 %zero %x\n"
1047                 "%inval1     = OpLoad %f32 %inloc1\n"
1048                 "%inloc2     = OpAccessChain %f32ptr %indata2 %zero %x\n"
1049                 "%inval2     = OpLoad %f32 %inloc2\n"
1050                 "%mul        = OpFMul %f32 %inval1 %inval2\n"
1051                 "%add        = OpFAdd %f32 %mul %c_f_m1\n"
1052                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
1053                 "              OpStore %outloc %add\n"
1054                 "              OpReturn\n"
1055                 "              OpFunctionEnd\n");
1056
1057         cases.push_back(CaseParameter("multiplication", "OpDecorate %mul NoContraction"));
1058         cases.push_back(CaseParameter("addition",               "OpDecorate %add NoContraction"));
1059         cases.push_back(CaseParameter("both",                   "OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"));
1060
1061         for (size_t ndx = 0; ndx < numElements; ++ndx)
1062         {
1063                 inputFloats1[ndx]       = 1.f + std::ldexp(1.f, -23); // 1 + 2^-23.
1064                 inputFloats2[ndx]       = 1.f - std::ldexp(1.f, -23); // 1 - 2^-23.
1065                 // Result for (1 + 2^-23) * (1 - 2^-23) - 1. With NoContraction, the multiplication will be
1066                 // conducted separately and the result is rounded to 1, or 0x1.fffffcp-1
1067                 // So the final result will be 0.f or 0x1p-24.
1068                 // If the operation is combined into a precise fused multiply-add, then the result would be
1069                 // 2^-46 (0xa8800000).
1070                 outputFloats[ndx]       = 0.f;
1071         }
1072
1073         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
1074         {
1075                 map<string, string>             specializations;
1076                 ComputeShaderSpec               spec;
1077
1078                 specializations["DECORATION"] = cases[caseNdx].param;
1079                 spec.assembly = shaderTemplate.specialize(specializations);
1080                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1081                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1082                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1083                 spec.numWorkGroups = IVec3(numElements, 1, 1);
1084                 // Check against the two possible answers based on rounding mode.
1085                 spec.verifyIO = &compareNoContractCase;
1086
1087                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
1088         }
1089         return group.release();
1090 }
1091
1092 bool compareFRem(const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1093 {
1094         if (outputAllocs.size() != 1)
1095                 return false;
1096
1097         vector<deUint8> expectedBytes;
1098         expectedOutputs[0].getBytes(expectedBytes);
1099
1100         const float*    expectedOutputAsFloat   = reinterpret_cast<const float*>(&expectedBytes.front());
1101         const float*    outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1102
1103         for (size_t idx = 0; idx < expectedBytes.size() / sizeof(float); ++idx)
1104         {
1105                 const float f0 = expectedOutputAsFloat[idx];
1106                 const float f1 = outputAsFloat[idx];
1107                 // \todo relative error needs to be fairly high because FRem may be implemented as
1108                 // (roughly) frac(a/b)*b, so LSB errors can be magnified. But this should be fine for now.
1109                 if (deFloatAbs((f1 - f0) / f0) > 0.02)
1110                         return false;
1111         }
1112
1113         return true;
1114 }
1115
1116 tcu::TestCaseGroup* createOpFRemGroup (tcu::TestContext& testCtx)
1117 {
1118         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opfrem", "Test the OpFRem instruction"));
1119         ComputeShaderSpec                               spec;
1120         de::Random                                              rnd                             (deStringHash(group->getName()));
1121         const int                                               numElements             = 200;
1122         vector<float>                                   inputFloats1    (numElements, 0);
1123         vector<float>                                   inputFloats2    (numElements, 0);
1124         vector<float>                                   outputFloats    (numElements, 0);
1125
1126         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1127         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats2[0], numElements);
1128
1129         for (size_t ndx = 0; ndx < numElements; ++ndx)
1130         {
1131                 // Guard against divisors near zero.
1132                 if (std::fabs(inputFloats2[ndx]) < 1e-3)
1133                         inputFloats2[ndx] = 8.f;
1134
1135                 // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1136                 outputFloats[ndx] = std::fmod(inputFloats1[ndx], inputFloats2[ndx]);
1137         }
1138
1139         spec.assembly =
1140                 string(getComputeAsmShaderPreamble()) +
1141
1142                 "OpName %main           \"main\"\n"
1143                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1144
1145                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1146
1147                 "OpDecorate %buf BufferBlock\n"
1148                 "OpDecorate %indata1 DescriptorSet 0\n"
1149                 "OpDecorate %indata1 Binding 0\n"
1150                 "OpDecorate %indata2 DescriptorSet 0\n"
1151                 "OpDecorate %indata2 Binding 1\n"
1152                 "OpDecorate %outdata DescriptorSet 0\n"
1153                 "OpDecorate %outdata Binding 2\n"
1154                 "OpDecorate %f32arr ArrayStride 4\n"
1155                 "OpMemberDecorate %buf 0 Offset 0\n"
1156
1157                 + string(getComputeAsmCommonTypes()) +
1158
1159                 "%buf        = OpTypeStruct %f32arr\n"
1160                 "%bufptr     = OpTypePointer Uniform %buf\n"
1161                 "%indata1    = OpVariable %bufptr Uniform\n"
1162                 "%indata2    = OpVariable %bufptr Uniform\n"
1163                 "%outdata    = OpVariable %bufptr Uniform\n"
1164
1165                 "%id        = OpVariable %uvec3ptr Input\n"
1166                 "%zero      = OpConstant %i32 0\n"
1167
1168                 "%main      = OpFunction %void None %voidf\n"
1169                 "%label     = OpLabel\n"
1170                 "%idval     = OpLoad %uvec3 %id\n"
1171                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1172                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1173                 "%inval1    = OpLoad %f32 %inloc1\n"
1174                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1175                 "%inval2    = OpLoad %f32 %inloc2\n"
1176                 "%rem       = OpFRem %f32 %inval1 %inval2\n"
1177                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1178                 "             OpStore %outloc %rem\n"
1179                 "             OpReturn\n"
1180                 "             OpFunctionEnd\n";
1181
1182         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1183         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1184         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1185         spec.numWorkGroups = IVec3(numElements, 1, 1);
1186         spec.verifyIO = &compareFRem;
1187
1188         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1189
1190         return group.release();
1191 }
1192
1193 bool compareNMin (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1194 {
1195         if (outputAllocs.size() != 1)
1196                 return false;
1197
1198         const BufferSp&                 expectedOutput                  (expectedOutputs[0].getBuffer());
1199         std::vector<deUint8>    data;
1200         expectedOutput->getBytes(data);
1201
1202         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1203         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1204
1205         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float); ++idx)
1206         {
1207                 const float f0 = expectedOutputAsFloat[idx];
1208                 const float f1 = outputAsFloat[idx];
1209
1210                 // For NMin, we accept NaN as output if both inputs were NaN.
1211                 // Otherwise the NaN is the wrong choise, as on architectures that
1212                 // do not handle NaN, those are huge values.
1213                 if (!(tcu::Float32(f1).isNaN() && tcu::Float32(f0).isNaN()) && deFloatAbs(f1 - f0) > 0.00001f)
1214                         return false;
1215         }
1216
1217         return true;
1218 }
1219
1220 tcu::TestCaseGroup* createOpNMinGroup (tcu::TestContext& testCtx)
1221 {
1222         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnmin", "Test the OpNMin instruction"));
1223         ComputeShaderSpec                               spec;
1224         de::Random                                              rnd                             (deStringHash(group->getName()));
1225         const int                                               numElements             = 200;
1226         vector<float>                                   inputFloats1    (numElements, 0);
1227         vector<float>                                   inputFloats2    (numElements, 0);
1228         vector<float>                                   outputFloats    (numElements, 0);
1229
1230         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1231         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1232
1233         // Make the first case a full-NAN case.
1234         inputFloats1[0] = TCU_NAN;
1235         inputFloats2[0] = TCU_NAN;
1236
1237         for (size_t ndx = 0; ndx < numElements; ++ndx)
1238         {
1239                 // By default, pick the smallest
1240                 outputFloats[ndx] = std::min(inputFloats1[ndx], inputFloats2[ndx]);
1241
1242                 // Make half of the cases NaN cases
1243                 if ((ndx & 1) == 0)
1244                 {
1245                         // Alternate between the NaN operand
1246                         if ((ndx & 2) == 0)
1247                         {
1248                                 outputFloats[ndx] = inputFloats2[ndx];
1249                                 inputFloats1[ndx] = TCU_NAN;
1250                         }
1251                         else
1252                         {
1253                                 outputFloats[ndx] = inputFloats1[ndx];
1254                                 inputFloats2[ndx] = TCU_NAN;
1255                         }
1256                 }
1257         }
1258
1259         spec.assembly =
1260                 "OpCapability Shader\n"
1261                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1262                 "OpMemoryModel Logical GLSL450\n"
1263                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1264                 "OpExecutionMode %main LocalSize 1 1 1\n"
1265
1266                 "OpName %main           \"main\"\n"
1267                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1268
1269                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1270
1271                 "OpDecorate %buf BufferBlock\n"
1272                 "OpDecorate %indata1 DescriptorSet 0\n"
1273                 "OpDecorate %indata1 Binding 0\n"
1274                 "OpDecorate %indata2 DescriptorSet 0\n"
1275                 "OpDecorate %indata2 Binding 1\n"
1276                 "OpDecorate %outdata DescriptorSet 0\n"
1277                 "OpDecorate %outdata Binding 2\n"
1278                 "OpDecorate %f32arr ArrayStride 4\n"
1279                 "OpMemberDecorate %buf 0 Offset 0\n"
1280
1281                 + string(getComputeAsmCommonTypes()) +
1282
1283                 "%buf        = OpTypeStruct %f32arr\n"
1284                 "%bufptr     = OpTypePointer Uniform %buf\n"
1285                 "%indata1    = OpVariable %bufptr Uniform\n"
1286                 "%indata2    = OpVariable %bufptr Uniform\n"
1287                 "%outdata    = OpVariable %bufptr Uniform\n"
1288
1289                 "%id        = OpVariable %uvec3ptr Input\n"
1290                 "%zero      = OpConstant %i32 0\n"
1291
1292                 "%main      = OpFunction %void None %voidf\n"
1293                 "%label     = OpLabel\n"
1294                 "%idval     = OpLoad %uvec3 %id\n"
1295                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1296                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1297                 "%inval1    = OpLoad %f32 %inloc1\n"
1298                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1299                 "%inval2    = OpLoad %f32 %inloc2\n"
1300                 "%rem       = OpExtInst %f32 %std450 NMin %inval1 %inval2\n"
1301                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1302                 "             OpStore %outloc %rem\n"
1303                 "             OpReturn\n"
1304                 "             OpFunctionEnd\n";
1305
1306         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1307         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1308         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1309         spec.numWorkGroups = IVec3(numElements, 1, 1);
1310         spec.verifyIO = &compareNMin;
1311
1312         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1313
1314         return group.release();
1315 }
1316
1317 bool compareNMax (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1318 {
1319         if (outputAllocs.size() != 1)
1320                 return false;
1321
1322         const BufferSp&                 expectedOutput                  = expectedOutputs[0].getBuffer();
1323         std::vector<deUint8>    data;
1324         expectedOutput->getBytes(data);
1325
1326         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1327         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1328
1329         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float); ++idx)
1330         {
1331                 const float f0 = expectedOutputAsFloat[idx];
1332                 const float f1 = outputAsFloat[idx];
1333
1334                 // For NMax, NaN is considered acceptable result, since in
1335                 // architectures that do not handle NaNs, those are huge values.
1336                 if (!tcu::Float32(f1).isNaN() && deFloatAbs(f1 - f0) > 0.00001f)
1337                         return false;
1338         }
1339
1340         return true;
1341 }
1342
1343 tcu::TestCaseGroup* createOpNMaxGroup (tcu::TestContext& testCtx)
1344 {
1345         de::MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "opnmax", "Test the OpNMax instruction"));
1346         ComputeShaderSpec                               spec;
1347         de::Random                                              rnd                             (deStringHash(group->getName()));
1348         const int                                               numElements             = 200;
1349         vector<float>                                   inputFloats1    (numElements, 0);
1350         vector<float>                                   inputFloats2    (numElements, 0);
1351         vector<float>                                   outputFloats    (numElements, 0);
1352
1353         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1354         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1355
1356         // Make the first case a full-NAN case.
1357         inputFloats1[0] = TCU_NAN;
1358         inputFloats2[0] = TCU_NAN;
1359
1360         for (size_t ndx = 0; ndx < numElements; ++ndx)
1361         {
1362                 // By default, pick the biggest
1363                 outputFloats[ndx] = std::max(inputFloats1[ndx], inputFloats2[ndx]);
1364
1365                 // Make half of the cases NaN cases
1366                 if ((ndx & 1) == 0)
1367                 {
1368                         // Alternate between the NaN operand
1369                         if ((ndx & 2) == 0)
1370                         {
1371                                 outputFloats[ndx] = inputFloats2[ndx];
1372                                 inputFloats1[ndx] = TCU_NAN;
1373                         }
1374                         else
1375                         {
1376                                 outputFloats[ndx] = inputFloats1[ndx];
1377                                 inputFloats2[ndx] = TCU_NAN;
1378                         }
1379                 }
1380         }
1381
1382         spec.assembly =
1383                 "OpCapability Shader\n"
1384                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1385                 "OpMemoryModel Logical GLSL450\n"
1386                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1387                 "OpExecutionMode %main LocalSize 1 1 1\n"
1388
1389                 "OpName %main           \"main\"\n"
1390                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1391
1392                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1393
1394                 "OpDecorate %buf BufferBlock\n"
1395                 "OpDecorate %indata1 DescriptorSet 0\n"
1396                 "OpDecorate %indata1 Binding 0\n"
1397                 "OpDecorate %indata2 DescriptorSet 0\n"
1398                 "OpDecorate %indata2 Binding 1\n"
1399                 "OpDecorate %outdata DescriptorSet 0\n"
1400                 "OpDecorate %outdata Binding 2\n"
1401                 "OpDecorate %f32arr ArrayStride 4\n"
1402                 "OpMemberDecorate %buf 0 Offset 0\n"
1403
1404                 + string(getComputeAsmCommonTypes()) +
1405
1406                 "%buf        = OpTypeStruct %f32arr\n"
1407                 "%bufptr     = OpTypePointer Uniform %buf\n"
1408                 "%indata1    = OpVariable %bufptr Uniform\n"
1409                 "%indata2    = OpVariable %bufptr Uniform\n"
1410                 "%outdata    = OpVariable %bufptr Uniform\n"
1411
1412                 "%id        = OpVariable %uvec3ptr Input\n"
1413                 "%zero      = OpConstant %i32 0\n"
1414
1415                 "%main      = OpFunction %void None %voidf\n"
1416                 "%label     = OpLabel\n"
1417                 "%idval     = OpLoad %uvec3 %id\n"
1418                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1419                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1420                 "%inval1    = OpLoad %f32 %inloc1\n"
1421                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1422                 "%inval2    = OpLoad %f32 %inloc2\n"
1423                 "%rem       = OpExtInst %f32 %std450 NMax %inval1 %inval2\n"
1424                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1425                 "             OpStore %outloc %rem\n"
1426                 "             OpReturn\n"
1427                 "             OpFunctionEnd\n";
1428
1429         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1430         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1431         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1432         spec.numWorkGroups = IVec3(numElements, 1, 1);
1433         spec.verifyIO = &compareNMax;
1434
1435         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1436
1437         return group.release();
1438 }
1439
1440 bool compareNClamp (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1441 {
1442         if (outputAllocs.size() != 1)
1443                 return false;
1444
1445         const BufferSp&                 expectedOutput                  = expectedOutputs[0].getBuffer();
1446         std::vector<deUint8>    data;
1447         expectedOutput->getBytes(data);
1448
1449         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1450         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1451
1452         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float) / 2; ++idx)
1453         {
1454                 const float e0 = expectedOutputAsFloat[idx * 2];
1455                 const float e1 = expectedOutputAsFloat[idx * 2 + 1];
1456                 const float res = outputAsFloat[idx];
1457
1458                 // For NClamp, we have two possible outcomes based on
1459                 // whether NaNs are handled or not.
1460                 // If either min or max value is NaN, the result is undefined,
1461                 // so this test doesn't stress those. If the clamped value is
1462                 // NaN, and NaNs are handled, the result is min; if NaNs are not
1463                 // handled, they are big values that result in max.
1464                 // If all three parameters are NaN, the result should be NaN.
1465                 if (!((tcu::Float32(e0).isNaN() && tcu::Float32(res).isNaN()) ||
1466                          (deFloatAbs(e0 - res) < 0.00001f) ||
1467                          (deFloatAbs(e1 - res) < 0.00001f)))
1468                         return false;
1469         }
1470
1471         return true;
1472 }
1473
1474 tcu::TestCaseGroup* createOpNClampGroup (tcu::TestContext& testCtx)
1475 {
1476         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnclamp", "Test the OpNClamp instruction"));
1477         ComputeShaderSpec                               spec;
1478         de::Random                                              rnd                             (deStringHash(group->getName()));
1479         const int                                               numElements             = 200;
1480         vector<float>                                   inputFloats1    (numElements, 0);
1481         vector<float>                                   inputFloats2    (numElements, 0);
1482         vector<float>                                   inputFloats3    (numElements, 0);
1483         vector<float>                                   outputFloats    (numElements * 2, 0);
1484
1485         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1486         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1487         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats3[0], numElements);
1488
1489         for (size_t ndx = 0; ndx < numElements; ++ndx)
1490         {
1491                 // Results are only defined if max value is bigger than min value.
1492                 if (inputFloats2[ndx] > inputFloats3[ndx])
1493                 {
1494                         float t = inputFloats2[ndx];
1495                         inputFloats2[ndx] = inputFloats3[ndx];
1496                         inputFloats3[ndx] = t;
1497                 }
1498
1499                 // By default, do the clamp, setting both possible answers
1500                 float defaultRes = std::min(std::max(inputFloats1[ndx], inputFloats2[ndx]), inputFloats3[ndx]);
1501
1502                 float maxResA = std::max(inputFloats1[ndx], inputFloats2[ndx]);
1503                 float maxResB = maxResA;
1504
1505                 // Alternate between the NaN cases
1506                 if (ndx & 1)
1507                 {
1508                         inputFloats1[ndx] = TCU_NAN;
1509                         // If NaN is handled, the result should be same as the clamp minimum.
1510                         // If NaN is not handled, the result should clamp to the clamp maximum.
1511                         maxResA = inputFloats2[ndx];
1512                         maxResB = inputFloats3[ndx];
1513                 }
1514                 else
1515                 {
1516                         // Not a NaN case - only one legal result.
1517                         maxResA = defaultRes;
1518                         maxResB = defaultRes;
1519                 }
1520
1521                 outputFloats[ndx * 2] = maxResA;
1522                 outputFloats[ndx * 2 + 1] = maxResB;
1523         }
1524
1525         // Make the first case a full-NAN case.
1526         inputFloats1[0] = TCU_NAN;
1527         inputFloats2[0] = TCU_NAN;
1528         inputFloats3[0] = TCU_NAN;
1529         outputFloats[0] = TCU_NAN;
1530         outputFloats[1] = TCU_NAN;
1531
1532         spec.assembly =
1533                 "OpCapability Shader\n"
1534                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1535                 "OpMemoryModel Logical GLSL450\n"
1536                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1537                 "OpExecutionMode %main LocalSize 1 1 1\n"
1538
1539                 "OpName %main           \"main\"\n"
1540                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1541
1542                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1543
1544                 "OpDecorate %buf BufferBlock\n"
1545                 "OpDecorate %indata1 DescriptorSet 0\n"
1546                 "OpDecorate %indata1 Binding 0\n"
1547                 "OpDecorate %indata2 DescriptorSet 0\n"
1548                 "OpDecorate %indata2 Binding 1\n"
1549                 "OpDecorate %indata3 DescriptorSet 0\n"
1550                 "OpDecorate %indata3 Binding 2\n"
1551                 "OpDecorate %outdata DescriptorSet 0\n"
1552                 "OpDecorate %outdata Binding 3\n"
1553                 "OpDecorate %f32arr ArrayStride 4\n"
1554                 "OpMemberDecorate %buf 0 Offset 0\n"
1555
1556                 + string(getComputeAsmCommonTypes()) +
1557
1558                 "%buf        = OpTypeStruct %f32arr\n"
1559                 "%bufptr     = OpTypePointer Uniform %buf\n"
1560                 "%indata1    = OpVariable %bufptr Uniform\n"
1561                 "%indata2    = OpVariable %bufptr Uniform\n"
1562                 "%indata3    = OpVariable %bufptr Uniform\n"
1563                 "%outdata    = OpVariable %bufptr Uniform\n"
1564
1565                 "%id        = OpVariable %uvec3ptr Input\n"
1566                 "%zero      = OpConstant %i32 0\n"
1567
1568                 "%main      = OpFunction %void None %voidf\n"
1569                 "%label     = OpLabel\n"
1570                 "%idval     = OpLoad %uvec3 %id\n"
1571                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1572                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1573                 "%inval1    = OpLoad %f32 %inloc1\n"
1574                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1575                 "%inval2    = OpLoad %f32 %inloc2\n"
1576                 "%inloc3    = OpAccessChain %f32ptr %indata3 %zero %x\n"
1577                 "%inval3    = OpLoad %f32 %inloc3\n"
1578                 "%rem       = OpExtInst %f32 %std450 NClamp %inval1 %inval2 %inval3\n"
1579                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1580                 "             OpStore %outloc %rem\n"
1581                 "             OpReturn\n"
1582                 "             OpFunctionEnd\n";
1583
1584         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1585         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1586         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
1587         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1588         spec.numWorkGroups = IVec3(numElements, 1, 1);
1589         spec.verifyIO = &compareNClamp;
1590
1591         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1592
1593         return group.release();
1594 }
1595
1596 tcu::TestCaseGroup* createOpSRemComputeGroup (tcu::TestContext& testCtx, qpTestResult negFailResult)
1597 {
1598         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsrem", "Test the OpSRem instruction"));
1599         de::Random                                              rnd                             (deStringHash(group->getName()));
1600         const int                                               numElements             = 200;
1601
1602         const struct CaseParams
1603         {
1604                 const char*             name;
1605                 const char*             failMessage;            // customized status message
1606                 qpTestResult    failResult;                     // override status on failure
1607                 int                             op1Min, op1Max;         // operand ranges
1608                 int                             op2Min, op2Max;
1609         } cases[] =
1610         {
1611                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    0,              65536,  0,              100 },
1612                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  -65536, 65536,  -100,   100 },  // see below
1613         };
1614         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1615
1616         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1617         {
1618                 const CaseParams&       params          = cases[caseNdx];
1619                 ComputeShaderSpec       spec;
1620                 vector<deInt32>         inputInts1      (numElements, 0);
1621                 vector<deInt32>         inputInts2      (numElements, 0);
1622                 vector<deInt32>         outputInts      (numElements, 0);
1623
1624                 fillRandomScalars(rnd, params.op1Min, params.op1Max, &inputInts1[0], numElements);
1625                 fillRandomScalars(rnd, params.op2Min, params.op2Max, &inputInts2[0], numElements, filterNotZero);
1626
1627                 for (int ndx = 0; ndx < numElements; ++ndx)
1628                 {
1629                         // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1630                         outputInts[ndx] = inputInts1[ndx] % inputInts2[ndx];
1631                 }
1632
1633                 spec.assembly =
1634                         string(getComputeAsmShaderPreamble()) +
1635
1636                         "OpName %main           \"main\"\n"
1637                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1638
1639                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1640
1641                         "OpDecorate %buf BufferBlock\n"
1642                         "OpDecorate %indata1 DescriptorSet 0\n"
1643                         "OpDecorate %indata1 Binding 0\n"
1644                         "OpDecorate %indata2 DescriptorSet 0\n"
1645                         "OpDecorate %indata2 Binding 1\n"
1646                         "OpDecorate %outdata DescriptorSet 0\n"
1647                         "OpDecorate %outdata Binding 2\n"
1648                         "OpDecorate %i32arr ArrayStride 4\n"
1649                         "OpMemberDecorate %buf 0 Offset 0\n"
1650
1651                         + string(getComputeAsmCommonTypes()) +
1652
1653                         "%buf        = OpTypeStruct %i32arr\n"
1654                         "%bufptr     = OpTypePointer Uniform %buf\n"
1655                         "%indata1    = OpVariable %bufptr Uniform\n"
1656                         "%indata2    = OpVariable %bufptr Uniform\n"
1657                         "%outdata    = OpVariable %bufptr Uniform\n"
1658
1659                         "%id        = OpVariable %uvec3ptr Input\n"
1660                         "%zero      = OpConstant %i32 0\n"
1661
1662                         "%main      = OpFunction %void None %voidf\n"
1663                         "%label     = OpLabel\n"
1664                         "%idval     = OpLoad %uvec3 %id\n"
1665                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1666                         "%inloc1    = OpAccessChain %i32ptr %indata1 %zero %x\n"
1667                         "%inval1    = OpLoad %i32 %inloc1\n"
1668                         "%inloc2    = OpAccessChain %i32ptr %indata2 %zero %x\n"
1669                         "%inval2    = OpLoad %i32 %inloc2\n"
1670                         "%rem       = OpSRem %i32 %inval1 %inval2\n"
1671                         "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
1672                         "             OpStore %outloc %rem\n"
1673                         "             OpReturn\n"
1674                         "             OpFunctionEnd\n";
1675
1676                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts1)));
1677                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts2)));
1678                 spec.outputs.push_back  (BufferSp(new Int32Buffer(outputInts)));
1679                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1680                 spec.failResult                 = params.failResult;
1681                 spec.failMessage                = params.failMessage;
1682
1683                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1684         }
1685
1686         return group.release();
1687 }
1688
1689 tcu::TestCaseGroup* createOpSRemComputeGroup64 (tcu::TestContext& testCtx, qpTestResult negFailResult)
1690 {
1691         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsrem64", "Test the 64-bit OpSRem instruction"));
1692         de::Random                                              rnd                             (deStringHash(group->getName()));
1693         const int                                               numElements             = 200;
1694
1695         const struct CaseParams
1696         {
1697                 const char*             name;
1698                 const char*             failMessage;            // customized status message
1699                 qpTestResult    failResult;                     // override status on failure
1700                 bool                    positive;
1701         } cases[] =
1702         {
1703                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    true },
1704                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  false },        // see below
1705         };
1706         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1707
1708         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1709         {
1710                 const CaseParams&       params          = cases[caseNdx];
1711                 ComputeShaderSpec       spec;
1712                 vector<deInt64>         inputInts1      (numElements, 0);
1713                 vector<deInt64>         inputInts2      (numElements, 0);
1714                 vector<deInt64>         outputInts      (numElements, 0);
1715
1716                 if (params.positive)
1717                 {
1718                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements, filterNonNegative);
1719                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterPositive);
1720                 }
1721                 else
1722                 {
1723                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements);
1724                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterNotZero);
1725                 }
1726
1727                 for (int ndx = 0; ndx < numElements; ++ndx)
1728                 {
1729                         // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1730                         outputInts[ndx] = inputInts1[ndx] % inputInts2[ndx];
1731                 }
1732
1733                 spec.assembly =
1734                         "OpCapability Int64\n"
1735
1736                         + string(getComputeAsmShaderPreamble()) +
1737
1738                         "OpName %main           \"main\"\n"
1739                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1740
1741                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1742
1743                         "OpDecorate %buf BufferBlock\n"
1744                         "OpDecorate %indata1 DescriptorSet 0\n"
1745                         "OpDecorate %indata1 Binding 0\n"
1746                         "OpDecorate %indata2 DescriptorSet 0\n"
1747                         "OpDecorate %indata2 Binding 1\n"
1748                         "OpDecorate %outdata DescriptorSet 0\n"
1749                         "OpDecorate %outdata Binding 2\n"
1750                         "OpDecorate %i64arr ArrayStride 8\n"
1751                         "OpMemberDecorate %buf 0 Offset 0\n"
1752
1753                         + string(getComputeAsmCommonTypes())
1754                         + string(getComputeAsmCommonInt64Types()) +
1755
1756                         "%buf        = OpTypeStruct %i64arr\n"
1757                         "%bufptr     = OpTypePointer Uniform %buf\n"
1758                         "%indata1    = OpVariable %bufptr Uniform\n"
1759                         "%indata2    = OpVariable %bufptr Uniform\n"
1760                         "%outdata    = OpVariable %bufptr Uniform\n"
1761
1762                         "%id        = OpVariable %uvec3ptr Input\n"
1763                         "%zero      = OpConstant %i64 0\n"
1764
1765                         "%main      = OpFunction %void None %voidf\n"
1766                         "%label     = OpLabel\n"
1767                         "%idval     = OpLoad %uvec3 %id\n"
1768                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1769                         "%inloc1    = OpAccessChain %i64ptr %indata1 %zero %x\n"
1770                         "%inval1    = OpLoad %i64 %inloc1\n"
1771                         "%inloc2    = OpAccessChain %i64ptr %indata2 %zero %x\n"
1772                         "%inval2    = OpLoad %i64 %inloc2\n"
1773                         "%rem       = OpSRem %i64 %inval1 %inval2\n"
1774                         "%outloc    = OpAccessChain %i64ptr %outdata %zero %x\n"
1775                         "             OpStore %outloc %rem\n"
1776                         "             OpReturn\n"
1777                         "             OpFunctionEnd\n";
1778
1779                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts1)));
1780                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts2)));
1781                 spec.outputs.push_back  (BufferSp(new Int64Buffer(outputInts)));
1782                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1783                 spec.failResult                 = params.failResult;
1784                 spec.failMessage                = params.failMessage;
1785
1786                 spec.requestedVulkanFeatures.coreFeatures.shaderInt64 = VK_TRUE;
1787
1788                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1789         }
1790
1791         return group.release();
1792 }
1793
1794 tcu::TestCaseGroup* createOpSModComputeGroup (tcu::TestContext& testCtx, qpTestResult negFailResult)
1795 {
1796         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsmod", "Test the OpSMod instruction"));
1797         de::Random                                              rnd                             (deStringHash(group->getName()));
1798         const int                                               numElements             = 200;
1799
1800         const struct CaseParams
1801         {
1802                 const char*             name;
1803                 const char*             failMessage;            // customized status message
1804                 qpTestResult    failResult;                     // override status on failure
1805                 int                             op1Min, op1Max;         // operand ranges
1806                 int                             op2Min, op2Max;
1807         } cases[] =
1808         {
1809                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    0,              65536,  0,              100 },
1810                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  -65536, 65536,  -100,   100 },  // see below
1811         };
1812         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1813
1814         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1815         {
1816                 const CaseParams&       params          = cases[caseNdx];
1817
1818                 ComputeShaderSpec       spec;
1819                 vector<deInt32>         inputInts1      (numElements, 0);
1820                 vector<deInt32>         inputInts2      (numElements, 0);
1821                 vector<deInt32>         outputInts      (numElements, 0);
1822
1823                 fillRandomScalars(rnd, params.op1Min, params.op1Max, &inputInts1[0], numElements);
1824                 fillRandomScalars(rnd, params.op2Min, params.op2Max, &inputInts2[0], numElements, filterNotZero);
1825
1826                 for (int ndx = 0; ndx < numElements; ++ndx)
1827                 {
1828                         deInt32 rem = inputInts1[ndx] % inputInts2[ndx];
1829                         if (rem == 0)
1830                         {
1831                                 outputInts[ndx] = 0;
1832                         }
1833                         else if ((inputInts1[ndx] >= 0) == (inputInts2[ndx] >= 0))
1834                         {
1835                                 // They have the same sign
1836                                 outputInts[ndx] = rem;
1837                         }
1838                         else
1839                         {
1840                                 // They have opposite sign.  The remainder operation takes the
1841                                 // sign inputInts1[ndx] but OpSMod is supposed to take ths sign
1842                                 // of inputInts2[ndx].  Adding inputInts2[ndx] will ensure that
1843                                 // the result has the correct sign and that it is still
1844                                 // congruent to inputInts1[ndx] modulo inputInts2[ndx]
1845                                 //
1846                                 // See also http://mathforum.org/library/drmath/view/52343.html
1847                                 outputInts[ndx] = rem + inputInts2[ndx];
1848                         }
1849                 }
1850
1851                 spec.assembly =
1852                         string(getComputeAsmShaderPreamble()) +
1853
1854                         "OpName %main           \"main\"\n"
1855                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1856
1857                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1858
1859                         "OpDecorate %buf BufferBlock\n"
1860                         "OpDecorate %indata1 DescriptorSet 0\n"
1861                         "OpDecorate %indata1 Binding 0\n"
1862                         "OpDecorate %indata2 DescriptorSet 0\n"
1863                         "OpDecorate %indata2 Binding 1\n"
1864                         "OpDecorate %outdata DescriptorSet 0\n"
1865                         "OpDecorate %outdata Binding 2\n"
1866                         "OpDecorate %i32arr ArrayStride 4\n"
1867                         "OpMemberDecorate %buf 0 Offset 0\n"
1868
1869                         + string(getComputeAsmCommonTypes()) +
1870
1871                         "%buf        = OpTypeStruct %i32arr\n"
1872                         "%bufptr     = OpTypePointer Uniform %buf\n"
1873                         "%indata1    = OpVariable %bufptr Uniform\n"
1874                         "%indata2    = OpVariable %bufptr Uniform\n"
1875                         "%outdata    = OpVariable %bufptr Uniform\n"
1876
1877                         "%id        = OpVariable %uvec3ptr Input\n"
1878                         "%zero      = OpConstant %i32 0\n"
1879
1880                         "%main      = OpFunction %void None %voidf\n"
1881                         "%label     = OpLabel\n"
1882                         "%idval     = OpLoad %uvec3 %id\n"
1883                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1884                         "%inloc1    = OpAccessChain %i32ptr %indata1 %zero %x\n"
1885                         "%inval1    = OpLoad %i32 %inloc1\n"
1886                         "%inloc2    = OpAccessChain %i32ptr %indata2 %zero %x\n"
1887                         "%inval2    = OpLoad %i32 %inloc2\n"
1888                         "%rem       = OpSMod %i32 %inval1 %inval2\n"
1889                         "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
1890                         "             OpStore %outloc %rem\n"
1891                         "             OpReturn\n"
1892                         "             OpFunctionEnd\n";
1893
1894                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts1)));
1895                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts2)));
1896                 spec.outputs.push_back  (BufferSp(new Int32Buffer(outputInts)));
1897                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1898                 spec.failResult                 = params.failResult;
1899                 spec.failMessage                = params.failMessage;
1900
1901                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1902         }
1903
1904         return group.release();
1905 }
1906
1907 tcu::TestCaseGroup* createOpSModComputeGroup64 (tcu::TestContext& testCtx, qpTestResult negFailResult)
1908 {
1909         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsmod64", "Test the OpSMod instruction"));
1910         de::Random                                              rnd                             (deStringHash(group->getName()));
1911         const int                                               numElements             = 200;
1912
1913         const struct CaseParams
1914         {
1915                 const char*             name;
1916                 const char*             failMessage;            // customized status message
1917                 qpTestResult    failResult;                     // override status on failure
1918                 bool                    positive;
1919         } cases[] =
1920         {
1921                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    true },
1922                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  false },        // see below
1923         };
1924         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1925
1926         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1927         {
1928                 const CaseParams&       params          = cases[caseNdx];
1929
1930                 ComputeShaderSpec       spec;
1931                 vector<deInt64>         inputInts1      (numElements, 0);
1932                 vector<deInt64>         inputInts2      (numElements, 0);
1933                 vector<deInt64>         outputInts      (numElements, 0);
1934
1935
1936                 if (params.positive)
1937                 {
1938                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements, filterNonNegative);
1939                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterPositive);
1940                 }
1941                 else
1942                 {
1943                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements);
1944                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterNotZero);
1945                 }
1946
1947                 for (int ndx = 0; ndx < numElements; ++ndx)
1948                 {
1949                         deInt64 rem = inputInts1[ndx] % inputInts2[ndx];
1950                         if (rem == 0)
1951                         {
1952                                 outputInts[ndx] = 0;
1953                         }
1954                         else if ((inputInts1[ndx] >= 0) == (inputInts2[ndx] >= 0))
1955                         {
1956                                 // They have the same sign
1957                                 outputInts[ndx] = rem;
1958                         }
1959                         else
1960                         {
1961                                 // They have opposite sign.  The remainder operation takes the
1962                                 // sign inputInts1[ndx] but OpSMod is supposed to take ths sign
1963                                 // of inputInts2[ndx].  Adding inputInts2[ndx] will ensure that
1964                                 // the result has the correct sign and that it is still
1965                                 // congruent to inputInts1[ndx] modulo inputInts2[ndx]
1966                                 //
1967                                 // See also http://mathforum.org/library/drmath/view/52343.html
1968                                 outputInts[ndx] = rem + inputInts2[ndx];
1969                         }
1970                 }
1971
1972                 spec.assembly =
1973                         "OpCapability Int64\n"
1974
1975                         + string(getComputeAsmShaderPreamble()) +
1976
1977                         "OpName %main           \"main\"\n"
1978                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1979
1980                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1981
1982                         "OpDecorate %buf BufferBlock\n"
1983                         "OpDecorate %indata1 DescriptorSet 0\n"
1984                         "OpDecorate %indata1 Binding 0\n"
1985                         "OpDecorate %indata2 DescriptorSet 0\n"
1986                         "OpDecorate %indata2 Binding 1\n"
1987                         "OpDecorate %outdata DescriptorSet 0\n"
1988                         "OpDecorate %outdata Binding 2\n"
1989                         "OpDecorate %i64arr ArrayStride 8\n"
1990                         "OpMemberDecorate %buf 0 Offset 0\n"
1991
1992                         + string(getComputeAsmCommonTypes())
1993                         + string(getComputeAsmCommonInt64Types()) +
1994
1995                         "%buf        = OpTypeStruct %i64arr\n"
1996                         "%bufptr     = OpTypePointer Uniform %buf\n"
1997                         "%indata1    = OpVariable %bufptr Uniform\n"
1998                         "%indata2    = OpVariable %bufptr Uniform\n"
1999                         "%outdata    = OpVariable %bufptr Uniform\n"
2000
2001                         "%id        = OpVariable %uvec3ptr Input\n"
2002                         "%zero      = OpConstant %i64 0\n"
2003
2004                         "%main      = OpFunction %void None %voidf\n"
2005                         "%label     = OpLabel\n"
2006                         "%idval     = OpLoad %uvec3 %id\n"
2007                         "%x         = OpCompositeExtract %u32 %idval 0\n"
2008                         "%inloc1    = OpAccessChain %i64ptr %indata1 %zero %x\n"
2009                         "%inval1    = OpLoad %i64 %inloc1\n"
2010                         "%inloc2    = OpAccessChain %i64ptr %indata2 %zero %x\n"
2011                         "%inval2    = OpLoad %i64 %inloc2\n"
2012                         "%rem       = OpSMod %i64 %inval1 %inval2\n"
2013                         "%outloc    = OpAccessChain %i64ptr %outdata %zero %x\n"
2014                         "             OpStore %outloc %rem\n"
2015                         "             OpReturn\n"
2016                         "             OpFunctionEnd\n";
2017
2018                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts1)));
2019                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts2)));
2020                 spec.outputs.push_back  (BufferSp(new Int64Buffer(outputInts)));
2021                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
2022                 spec.failResult                 = params.failResult;
2023                 spec.failMessage                = params.failMessage;
2024
2025                 spec.requestedVulkanFeatures.coreFeatures.shaderInt64 = VK_TRUE;
2026
2027                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
2028         }
2029
2030         return group.release();
2031 }
2032
2033 // Copy contents in the input buffer to the output buffer.
2034 tcu::TestCaseGroup* createOpCopyMemoryGroup (tcu::TestContext& testCtx)
2035 {
2036         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opcopymemory", "Test the OpCopyMemory instruction"));
2037         de::Random                                              rnd                             (deStringHash(group->getName()));
2038         const int                                               numElements             = 100;
2039
2040         // 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.
2041         ComputeShaderSpec                               spec1;
2042         vector<Vec4>                                    inputFloats1    (numElements);
2043         vector<Vec4>                                    outputFloats1   (numElements);
2044
2045         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats1[0], numElements * 4);
2046
2047         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2048         floorAll(inputFloats1);
2049
2050         for (size_t ndx = 0; ndx < numElements; ++ndx)
2051                 outputFloats1[ndx] = inputFloats1[ndx] + Vec4(0.f, 0.5f, 1.5f, 2.5f);
2052
2053         spec1.assembly =
2054                 string(getComputeAsmShaderPreamble()) +
2055
2056                 "OpName %main           \"main\"\n"
2057                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2058
2059                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2060                 "OpDecorate %vec4arr ArrayStride 16\n"
2061
2062                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2063
2064                 "%vec4       = OpTypeVector %f32 4\n"
2065                 "%vec4ptr_u  = OpTypePointer Uniform %vec4\n"
2066                 "%vec4ptr_f  = OpTypePointer Function %vec4\n"
2067                 "%vec4arr    = OpTypeRuntimeArray %vec4\n"
2068                 "%buf        = OpTypeStruct %vec4arr\n"
2069                 "%bufptr     = OpTypePointer Uniform %buf\n"
2070                 "%indata     = OpVariable %bufptr Uniform\n"
2071                 "%outdata    = OpVariable %bufptr Uniform\n"
2072
2073                 "%id         = OpVariable %uvec3ptr Input\n"
2074                 "%zero       = OpConstant %i32 0\n"
2075                 "%c_f_0      = OpConstant %f32 0.\n"
2076                 "%c_f_0_5    = OpConstant %f32 0.5\n"
2077                 "%c_f_1_5    = OpConstant %f32 1.5\n"
2078                 "%c_f_2_5    = OpConstant %f32 2.5\n"
2079                 "%c_vec4     = OpConstantComposite %vec4 %c_f_0 %c_f_0_5 %c_f_1_5 %c_f_2_5\n"
2080
2081                 "%main       = OpFunction %void None %voidf\n"
2082                 "%label      = OpLabel\n"
2083                 "%v_vec4     = OpVariable %vec4ptr_f Function\n"
2084                 "%idval      = OpLoad %uvec3 %id\n"
2085                 "%x          = OpCompositeExtract %u32 %idval 0\n"
2086                 "%inloc      = OpAccessChain %vec4ptr_u %indata %zero %x\n"
2087                 "%outloc     = OpAccessChain %vec4ptr_u %outdata %zero %x\n"
2088                 "              OpCopyMemory %v_vec4 %inloc\n"
2089                 "%v_vec4_val = OpLoad %vec4 %v_vec4\n"
2090                 "%add        = OpFAdd %vec4 %v_vec4_val %c_vec4\n"
2091                 "              OpStore %outloc %add\n"
2092                 "              OpReturn\n"
2093                 "              OpFunctionEnd\n";
2094
2095         spec1.inputs.push_back(BufferSp(new Vec4Buffer(inputFloats1)));
2096         spec1.outputs.push_back(BufferSp(new Vec4Buffer(outputFloats1)));
2097         spec1.numWorkGroups = IVec3(numElements, 1, 1);
2098
2099         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector", "OpCopyMemory elements of vector type", spec1));
2100
2101         // The following case copies a float[100] variable from the input buffer to the output buffer.
2102         ComputeShaderSpec                               spec2;
2103         vector<float>                                   inputFloats2    (numElements);
2104         vector<float>                                   outputFloats2   (numElements);
2105
2106         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats2[0], numElements);
2107
2108         for (size_t ndx = 0; ndx < numElements; ++ndx)
2109                 outputFloats2[ndx] = inputFloats2[ndx];
2110
2111         spec2.assembly =
2112                 string(getComputeAsmShaderPreamble()) +
2113
2114                 "OpName %main           \"main\"\n"
2115                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2116
2117                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2118                 "OpDecorate %f32arr100 ArrayStride 4\n"
2119
2120                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2121
2122                 "%hundred        = OpConstant %u32 100\n"
2123                 "%f32arr100      = OpTypeArray %f32 %hundred\n"
2124                 "%f32arr100ptr_f = OpTypePointer Function %f32arr100\n"
2125                 "%f32arr100ptr_u = OpTypePointer Uniform %f32arr100\n"
2126                 "%buf            = OpTypeStruct %f32arr100\n"
2127                 "%bufptr         = OpTypePointer Uniform %buf\n"
2128                 "%indata         = OpVariable %bufptr Uniform\n"
2129                 "%outdata        = OpVariable %bufptr Uniform\n"
2130
2131                 "%id             = OpVariable %uvec3ptr Input\n"
2132                 "%zero           = OpConstant %i32 0\n"
2133
2134                 "%main           = OpFunction %void None %voidf\n"
2135                 "%label          = OpLabel\n"
2136                 "%var            = OpVariable %f32arr100ptr_f Function\n"
2137                 "%inarr          = OpAccessChain %f32arr100ptr_u %indata %zero\n"
2138                 "%outarr         = OpAccessChain %f32arr100ptr_u %outdata %zero\n"
2139                 "                  OpCopyMemory %var %inarr\n"
2140                 "                  OpCopyMemory %outarr %var\n"
2141                 "                  OpReturn\n"
2142                 "                  OpFunctionEnd\n";
2143
2144         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
2145         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
2146         spec2.numWorkGroups = IVec3(1, 1, 1);
2147
2148         group->addChild(new SpvAsmComputeShaderCase(testCtx, "array", "OpCopyMemory elements of array type", spec2));
2149
2150         // The following case copies a struct{vec4, vec4, vec4, vec4} variable from the input buffer to the output buffer.
2151         ComputeShaderSpec                               spec3;
2152         vector<float>                                   inputFloats3    (16);
2153         vector<float>                                   outputFloats3   (16);
2154
2155         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats3[0], 16);
2156
2157         for (size_t ndx = 0; ndx < 16; ++ndx)
2158                 outputFloats3[ndx] = inputFloats3[ndx];
2159
2160         spec3.assembly =
2161                 string(getComputeAsmShaderPreamble()) +
2162
2163                 "OpName %main           \"main\"\n"
2164                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2165
2166                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2167                 //"OpMemberDecorate %buf 0 Offset 0\n"  - exists in getComputeAsmInputOutputBufferTraits
2168                 "OpMemberDecorate %buf 1 Offset 16\n"
2169                 "OpMemberDecorate %buf 2 Offset 32\n"
2170                 "OpMemberDecorate %buf 3 Offset 48\n"
2171
2172                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2173
2174                 "%vec4      = OpTypeVector %f32 4\n"
2175                 "%buf       = OpTypeStruct %vec4 %vec4 %vec4 %vec4\n"
2176                 "%bufptr    = OpTypePointer Uniform %buf\n"
2177                 "%indata    = OpVariable %bufptr Uniform\n"
2178                 "%outdata   = OpVariable %bufptr Uniform\n"
2179                 "%vec4stptr = OpTypePointer Function %buf\n"
2180
2181                 "%id        = OpVariable %uvec3ptr Input\n"
2182                 "%zero      = OpConstant %i32 0\n"
2183
2184                 "%main      = OpFunction %void None %voidf\n"
2185                 "%label     = OpLabel\n"
2186                 "%var       = OpVariable %vec4stptr Function\n"
2187                 "             OpCopyMemory %var %indata\n"
2188                 "             OpCopyMemory %outdata %var\n"
2189                 "             OpReturn\n"
2190                 "             OpFunctionEnd\n";
2191
2192         spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
2193         spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
2194         spec3.numWorkGroups = IVec3(1, 1, 1);
2195
2196         group->addChild(new SpvAsmComputeShaderCase(testCtx, "struct", "OpCopyMemory elements of struct type", spec3));
2197
2198         // The following case negates multiple float variables from the input buffer and stores the results to the output buffer.
2199         ComputeShaderSpec                               spec4;
2200         vector<float>                                   inputFloats4    (numElements);
2201         vector<float>                                   outputFloats4   (numElements);
2202
2203         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats4[0], numElements);
2204
2205         for (size_t ndx = 0; ndx < numElements; ++ndx)
2206                 outputFloats4[ndx] = -inputFloats4[ndx];
2207
2208         spec4.assembly =
2209                 string(getComputeAsmShaderPreamble()) +
2210
2211                 "OpName %main           \"main\"\n"
2212                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2213
2214                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2215
2216                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2217
2218                 "%f32ptr_f  = OpTypePointer Function %f32\n"
2219                 "%id        = OpVariable %uvec3ptr Input\n"
2220                 "%zero      = OpConstant %i32 0\n"
2221
2222                 "%main      = OpFunction %void None %voidf\n"
2223                 "%label     = OpLabel\n"
2224                 "%var       = OpVariable %f32ptr_f Function\n"
2225                 "%idval     = OpLoad %uvec3 %id\n"
2226                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2227                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
2228                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
2229                 "             OpCopyMemory %var %inloc\n"
2230                 "%val       = OpLoad %f32 %var\n"
2231                 "%neg       = OpFNegate %f32 %val\n"
2232                 "             OpStore %outloc %neg\n"
2233                 "             OpReturn\n"
2234                 "             OpFunctionEnd\n";
2235
2236         spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
2237         spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
2238         spec4.numWorkGroups = IVec3(numElements, 1, 1);
2239
2240         group->addChild(new SpvAsmComputeShaderCase(testCtx, "float", "OpCopyMemory elements of float type", spec4));
2241
2242         return group.release();
2243 }
2244
2245 tcu::TestCaseGroup* createOpCopyObjectGroup (tcu::TestContext& testCtx)
2246 {
2247         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opcopyobject", "Test the OpCopyObject instruction"));
2248         ComputeShaderSpec                               spec;
2249         de::Random                                              rnd                             (deStringHash(group->getName()));
2250         const int                                               numElements             = 100;
2251         vector<float>                                   inputFloats             (numElements, 0);
2252         vector<float>                                   outputFloats    (numElements, 0);
2253
2254         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
2255
2256         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2257         floorAll(inputFloats);
2258
2259         for (size_t ndx = 0; ndx < numElements; ++ndx)
2260                 outputFloats[ndx] = inputFloats[ndx] + 7.5f;
2261
2262         spec.assembly =
2263                 string(getComputeAsmShaderPreamble()) +
2264
2265                 "OpName %main           \"main\"\n"
2266                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2267
2268                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2269
2270                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2271
2272                 "%fmat     = OpTypeMatrix %fvec3 3\n"
2273                 "%three    = OpConstant %u32 3\n"
2274                 "%farr     = OpTypeArray %f32 %three\n"
2275                 "%fst      = OpTypeStruct %f32 %f32\n"
2276
2277                 + string(getComputeAsmInputOutputBuffer()) +
2278
2279                 "%id            = OpVariable %uvec3ptr Input\n"
2280                 "%zero          = OpConstant %i32 0\n"
2281                 "%c_f           = OpConstant %f32 1.5\n"
2282                 "%c_fvec3       = OpConstantComposite %fvec3 %c_f %c_f %c_f\n"
2283                 "%c_fmat        = OpConstantComposite %fmat %c_fvec3 %c_fvec3 %c_fvec3\n"
2284                 "%c_farr        = OpConstantComposite %farr %c_f %c_f %c_f\n"
2285                 "%c_fst         = OpConstantComposite %fst %c_f %c_f\n"
2286
2287                 "%main          = OpFunction %void None %voidf\n"
2288                 "%label         = OpLabel\n"
2289                 "%c_f_copy      = OpCopyObject %f32   %c_f\n"
2290                 "%c_fvec3_copy  = OpCopyObject %fvec3 %c_fvec3\n"
2291                 "%c_fmat_copy   = OpCopyObject %fmat  %c_fmat\n"
2292                 "%c_farr_copy   = OpCopyObject %farr  %c_farr\n"
2293                 "%c_fst_copy    = OpCopyObject %fst   %c_fst\n"
2294                 "%fvec3_elem    = OpCompositeExtract %f32 %c_fvec3_copy 0\n"
2295                 "%fmat_elem     = OpCompositeExtract %f32 %c_fmat_copy 1 2\n"
2296                 "%farr_elem     = OpCompositeExtract %f32 %c_farr_copy 2\n"
2297                 "%fst_elem      = OpCompositeExtract %f32 %c_fst_copy 1\n"
2298                 // Add up. 1.5 * 5 = 7.5.
2299                 "%add1          = OpFAdd %f32 %c_f_copy %fvec3_elem\n"
2300                 "%add2          = OpFAdd %f32 %add1     %fmat_elem\n"
2301                 "%add3          = OpFAdd %f32 %add2     %farr_elem\n"
2302                 "%add4          = OpFAdd %f32 %add3     %fst_elem\n"
2303
2304                 "%idval         = OpLoad %uvec3 %id\n"
2305                 "%x             = OpCompositeExtract %u32 %idval 0\n"
2306                 "%inloc         = OpAccessChain %f32ptr %indata %zero %x\n"
2307                 "%outloc        = OpAccessChain %f32ptr %outdata %zero %x\n"
2308                 "%inval         = OpLoad %f32 %inloc\n"
2309                 "%add           = OpFAdd %f32 %add4 %inval\n"
2310                 "                 OpStore %outloc %add\n"
2311                 "                 OpReturn\n"
2312                 "                 OpFunctionEnd\n";
2313         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2314         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2315         spec.numWorkGroups = IVec3(numElements, 1, 1);
2316
2317         group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "OpCopyObject on different types", spec));
2318
2319         return group.release();
2320 }
2321 // Assembly code used for testing OpUnreachable is based on GLSL source code:
2322 //
2323 // #version 430
2324 //
2325 // layout(std140, set = 0, binding = 0) readonly buffer Input {
2326 //   float elements[];
2327 // } input_data;
2328 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
2329 //   float elements[];
2330 // } output_data;
2331 //
2332 // void not_called_func() {
2333 //   // place OpUnreachable here
2334 // }
2335 //
2336 // uint modulo4(uint val) {
2337 //   switch (val % uint(4)) {
2338 //     case 0:  return 3;
2339 //     case 1:  return 2;
2340 //     case 2:  return 1;
2341 //     case 3:  return 0;
2342 //     default: return 100; // place OpUnreachable here
2343 //   }
2344 // }
2345 //
2346 // uint const5() {
2347 //   return 5;
2348 //   // place OpUnreachable here
2349 // }
2350 //
2351 // void main() {
2352 //   uint x = gl_GlobalInvocationID.x;
2353 //   if (const5() > modulo4(1000)) {
2354 //     output_data.elements[x] = -input_data.elements[x];
2355 //   } else {
2356 //     // place OpUnreachable here
2357 //     output_data.elements[x] = input_data.elements[x];
2358 //   }
2359 // }
2360
2361 tcu::TestCaseGroup* createOpUnreachableGroup (tcu::TestContext& testCtx)
2362 {
2363         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opunreachable", "Test the OpUnreachable instruction"));
2364         ComputeShaderSpec                               spec;
2365         de::Random                                              rnd                             (deStringHash(group->getName()));
2366         const int                                               numElements             = 100;
2367         vector<float>                                   positiveFloats  (numElements, 0);
2368         vector<float>                                   negativeFloats  (numElements, 0);
2369
2370         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
2371
2372         for (size_t ndx = 0; ndx < numElements; ++ndx)
2373                 negativeFloats[ndx] = -positiveFloats[ndx];
2374
2375         spec.assembly =
2376                 string(getComputeAsmShaderPreamble()) +
2377
2378                 "OpSource GLSL 430\n"
2379                 "OpName %main            \"main\"\n"
2380                 "OpName %func_not_called_func \"not_called_func(\"\n"
2381                 "OpName %func_modulo4         \"modulo4(u1;\"\n"
2382                 "OpName %func_const5          \"const5(\"\n"
2383                 "OpName %id                   \"gl_GlobalInvocationID\"\n"
2384
2385                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2386
2387                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2388
2389                 "%u32ptr    = OpTypePointer Function %u32\n"
2390                 "%uintfuint = OpTypeFunction %u32 %u32ptr\n"
2391                 "%unitf     = OpTypeFunction %u32\n"
2392
2393                 "%id        = OpVariable %uvec3ptr Input\n"
2394                 "%zero      = OpConstant %u32 0\n"
2395                 "%one       = OpConstant %u32 1\n"
2396                 "%two       = OpConstant %u32 2\n"
2397                 "%three     = OpConstant %u32 3\n"
2398                 "%four      = OpConstant %u32 4\n"
2399                 "%five      = OpConstant %u32 5\n"
2400                 "%hundred   = OpConstant %u32 100\n"
2401                 "%thousand  = OpConstant %u32 1000\n"
2402
2403                 + string(getComputeAsmInputOutputBuffer()) +
2404
2405                 // Main()
2406                 "%main   = OpFunction %void None %voidf\n"
2407                 "%main_entry  = OpLabel\n"
2408                 "%v_thousand  = OpVariable %u32ptr Function %thousand\n"
2409                 "%idval       = OpLoad %uvec3 %id\n"
2410                 "%x           = OpCompositeExtract %u32 %idval 0\n"
2411                 "%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
2412                 "%inval       = OpLoad %f32 %inloc\n"
2413                 "%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
2414                 "%ret_const5  = OpFunctionCall %u32 %func_const5\n"
2415                 "%ret_modulo4 = OpFunctionCall %u32 %func_modulo4 %v_thousand\n"
2416                 "%cmp_gt      = OpUGreaterThan %bool %ret_const5 %ret_modulo4\n"
2417                 "               OpSelectionMerge %if_end None\n"
2418                 "               OpBranchConditional %cmp_gt %if_true %if_false\n"
2419                 "%if_true     = OpLabel\n"
2420                 "%negate      = OpFNegate %f32 %inval\n"
2421                 "               OpStore %outloc %negate\n"
2422                 "               OpBranch %if_end\n"
2423                 "%if_false    = OpLabel\n"
2424                 "               OpUnreachable\n" // Unreachable else branch for if statement
2425                 "%if_end      = OpLabel\n"
2426                 "               OpReturn\n"
2427                 "               OpFunctionEnd\n"
2428
2429                 // not_called_function()
2430                 "%func_not_called_func  = OpFunction %void None %voidf\n"
2431                 "%not_called_func_entry = OpLabel\n"
2432                 "                         OpUnreachable\n" // Unreachable entry block in not called static function
2433                 "                         OpFunctionEnd\n"
2434
2435                 // modulo4()
2436                 "%func_modulo4  = OpFunction %u32 None %uintfuint\n"
2437                 "%valptr        = OpFunctionParameter %u32ptr\n"
2438                 "%modulo4_entry = OpLabel\n"
2439                 "%val           = OpLoad %u32 %valptr\n"
2440                 "%modulo        = OpUMod %u32 %val %four\n"
2441                 "                 OpSelectionMerge %switch_merge None\n"
2442                 "                 OpSwitch %modulo %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
2443                 "%case0         = OpLabel\n"
2444                 "                 OpReturnValue %three\n"
2445                 "%case1         = OpLabel\n"
2446                 "                 OpReturnValue %two\n"
2447                 "%case2         = OpLabel\n"
2448                 "                 OpReturnValue %one\n"
2449                 "%case3         = OpLabel\n"
2450                 "                 OpReturnValue %zero\n"
2451                 "%default       = OpLabel\n"
2452                 "                 OpUnreachable\n" // Unreachable default case for switch statement
2453                 "%switch_merge  = OpLabel\n"
2454                 "                 OpUnreachable\n" // Unreachable merge block for switch statement
2455                 "                 OpFunctionEnd\n"
2456
2457                 // const5()
2458                 "%func_const5  = OpFunction %u32 None %unitf\n"
2459                 "%const5_entry = OpLabel\n"
2460                 "                OpReturnValue %five\n"
2461                 "%unreachable  = OpLabel\n"
2462                 "                OpUnreachable\n" // Unreachable block in function
2463                 "                OpFunctionEnd\n";
2464         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
2465         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
2466         spec.numWorkGroups = IVec3(numElements, 1, 1);
2467
2468         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpUnreachable appearing at different places", spec));
2469
2470         return group.release();
2471 }
2472
2473 // Assembly code used for testing decoration group is based on GLSL source code:
2474 //
2475 // #version 430
2476 //
2477 // layout(std140, set = 0, binding = 0) readonly buffer Input0 {
2478 //   float elements[];
2479 // } input_data0;
2480 // layout(std140, set = 0, binding = 1) readonly buffer Input1 {
2481 //   float elements[];
2482 // } input_data1;
2483 // layout(std140, set = 0, binding = 2) readonly buffer Input2 {
2484 //   float elements[];
2485 // } input_data2;
2486 // layout(std140, set = 0, binding = 3) readonly buffer Input3 {
2487 //   float elements[];
2488 // } input_data3;
2489 // layout(std140, set = 0, binding = 4) readonly buffer Input4 {
2490 //   float elements[];
2491 // } input_data4;
2492 // layout(std140, set = 0, binding = 5) writeonly buffer Output {
2493 //   float elements[];
2494 // } output_data;
2495 //
2496 // void main() {
2497 //   uint x = gl_GlobalInvocationID.x;
2498 //   output_data.elements[x] = input_data0.elements[x] + input_data1.elements[x] + input_data2.elements[x] + input_data3.elements[x] + input_data4.elements[x];
2499 // }
2500 tcu::TestCaseGroup* createDecorationGroupGroup (tcu::TestContext& testCtx)
2501 {
2502         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "decoration_group", "Test the OpDecorationGroup & OpGroupDecorate instruction"));
2503         ComputeShaderSpec                               spec;
2504         de::Random                                              rnd                             (deStringHash(group->getName()));
2505         const int                                               numElements             = 100;
2506         vector<float>                                   inputFloats0    (numElements, 0);
2507         vector<float>                                   inputFloats1    (numElements, 0);
2508         vector<float>                                   inputFloats2    (numElements, 0);
2509         vector<float>                                   inputFloats3    (numElements, 0);
2510         vector<float>                                   inputFloats4    (numElements, 0);
2511         vector<float>                                   outputFloats    (numElements, 0);
2512
2513         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats0[0], numElements);
2514         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats1[0], numElements);
2515         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats2[0], numElements);
2516         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats3[0], numElements);
2517         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats4[0], numElements);
2518
2519         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2520         floorAll(inputFloats0);
2521         floorAll(inputFloats1);
2522         floorAll(inputFloats2);
2523         floorAll(inputFloats3);
2524         floorAll(inputFloats4);
2525
2526         for (size_t ndx = 0; ndx < numElements; ++ndx)
2527                 outputFloats[ndx] = inputFloats0[ndx] + inputFloats1[ndx] + inputFloats2[ndx] + inputFloats3[ndx] + inputFloats4[ndx];
2528
2529         spec.assembly =
2530                 string(getComputeAsmShaderPreamble()) +
2531
2532                 "OpSource GLSL 430\n"
2533                 "OpName %main \"main\"\n"
2534                 "OpName %id \"gl_GlobalInvocationID\"\n"
2535
2536                 // Not using group decoration on variable.
2537                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2538                 // Not using group decoration on type.
2539                 "OpDecorate %f32arr ArrayStride 4\n"
2540
2541                 "OpDecorate %groups BufferBlock\n"
2542                 "OpDecorate %groupm Offset 0\n"
2543                 "%groups = OpDecorationGroup\n"
2544                 "%groupm = OpDecorationGroup\n"
2545
2546                 // Group decoration on multiple structs.
2547                 "OpGroupDecorate %groups %outbuf %inbuf0 %inbuf1 %inbuf2 %inbuf3 %inbuf4\n"
2548                 // Group decoration on multiple struct members.
2549                 "OpGroupMemberDecorate %groupm %outbuf 0 %inbuf0 0 %inbuf1 0 %inbuf2 0 %inbuf3 0 %inbuf4 0\n"
2550
2551                 "OpDecorate %group1 DescriptorSet 0\n"
2552                 "OpDecorate %group3 DescriptorSet 0\n"
2553                 "OpDecorate %group3 NonWritable\n"
2554                 "OpDecorate %group3 Restrict\n"
2555                 "%group0 = OpDecorationGroup\n"
2556                 "%group1 = OpDecorationGroup\n"
2557                 "%group3 = OpDecorationGroup\n"
2558
2559                 // Applying the same decoration group multiple times.
2560                 "OpGroupDecorate %group1 %outdata\n"
2561                 "OpGroupDecorate %group1 %outdata\n"
2562                 "OpGroupDecorate %group1 %outdata\n"
2563                 "OpDecorate %outdata DescriptorSet 0\n"
2564                 "OpDecorate %outdata Binding 5\n"
2565                 // Applying decoration group containing nothing.
2566                 "OpGroupDecorate %group0 %indata0\n"
2567                 "OpDecorate %indata0 DescriptorSet 0\n"
2568                 "OpDecorate %indata0 Binding 0\n"
2569                 // Applying decoration group containing one decoration.
2570                 "OpGroupDecorate %group1 %indata1\n"
2571                 "OpDecorate %indata1 Binding 1\n"
2572                 // Applying decoration group containing multiple decorations.
2573                 "OpGroupDecorate %group3 %indata2 %indata3\n"
2574                 "OpDecorate %indata2 Binding 2\n"
2575                 "OpDecorate %indata3 Binding 3\n"
2576                 // Applying multiple decoration groups (with overlapping).
2577                 "OpGroupDecorate %group0 %indata4\n"
2578                 "OpGroupDecorate %group1 %indata4\n"
2579                 "OpGroupDecorate %group3 %indata4\n"
2580                 "OpDecorate %indata4 Binding 4\n"
2581
2582                 + string(getComputeAsmCommonTypes()) +
2583
2584                 "%id   = OpVariable %uvec3ptr Input\n"
2585                 "%zero = OpConstant %i32 0\n"
2586
2587                 "%outbuf    = OpTypeStruct %f32arr\n"
2588                 "%outbufptr = OpTypePointer Uniform %outbuf\n"
2589                 "%outdata   = OpVariable %outbufptr Uniform\n"
2590                 "%inbuf0    = OpTypeStruct %f32arr\n"
2591                 "%inbuf0ptr = OpTypePointer Uniform %inbuf0\n"
2592                 "%indata0   = OpVariable %inbuf0ptr Uniform\n"
2593                 "%inbuf1    = OpTypeStruct %f32arr\n"
2594                 "%inbuf1ptr = OpTypePointer Uniform %inbuf1\n"
2595                 "%indata1   = OpVariable %inbuf1ptr Uniform\n"
2596                 "%inbuf2    = OpTypeStruct %f32arr\n"
2597                 "%inbuf2ptr = OpTypePointer Uniform %inbuf2\n"
2598                 "%indata2   = OpVariable %inbuf2ptr Uniform\n"
2599                 "%inbuf3    = OpTypeStruct %f32arr\n"
2600                 "%inbuf3ptr = OpTypePointer Uniform %inbuf3\n"
2601                 "%indata3   = OpVariable %inbuf3ptr Uniform\n"
2602                 "%inbuf4    = OpTypeStruct %f32arr\n"
2603                 "%inbufptr  = OpTypePointer Uniform %inbuf4\n"
2604                 "%indata4   = OpVariable %inbufptr Uniform\n"
2605
2606                 "%main   = OpFunction %void None %voidf\n"
2607                 "%label  = OpLabel\n"
2608                 "%idval  = OpLoad %uvec3 %id\n"
2609                 "%x      = OpCompositeExtract %u32 %idval 0\n"
2610                 "%inloc0 = OpAccessChain %f32ptr %indata0 %zero %x\n"
2611                 "%inloc1 = OpAccessChain %f32ptr %indata1 %zero %x\n"
2612                 "%inloc2 = OpAccessChain %f32ptr %indata2 %zero %x\n"
2613                 "%inloc3 = OpAccessChain %f32ptr %indata3 %zero %x\n"
2614                 "%inloc4 = OpAccessChain %f32ptr %indata4 %zero %x\n"
2615                 "%outloc = OpAccessChain %f32ptr %outdata %zero %x\n"
2616                 "%inval0 = OpLoad %f32 %inloc0\n"
2617                 "%inval1 = OpLoad %f32 %inloc1\n"
2618                 "%inval2 = OpLoad %f32 %inloc2\n"
2619                 "%inval3 = OpLoad %f32 %inloc3\n"
2620                 "%inval4 = OpLoad %f32 %inloc4\n"
2621                 "%add0   = OpFAdd %f32 %inval0 %inval1\n"
2622                 "%add1   = OpFAdd %f32 %add0 %inval2\n"
2623                 "%add2   = OpFAdd %f32 %add1 %inval3\n"
2624                 "%add    = OpFAdd %f32 %add2 %inval4\n"
2625                 "          OpStore %outloc %add\n"
2626                 "          OpReturn\n"
2627                 "          OpFunctionEnd\n";
2628         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats0)));
2629         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
2630         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
2631         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
2632         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
2633         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2634         spec.numWorkGroups = IVec3(numElements, 1, 1);
2635
2636         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "decoration group cases", spec));
2637
2638         return group.release();
2639 }
2640
2641 struct SpecConstantTwoIntCase
2642 {
2643         const char*             caseName;
2644         const char*             scDefinition0;
2645         const char*             scDefinition1;
2646         const char*             scResultType;
2647         const char*             scOperation;
2648         deInt32                 scActualValue0;
2649         deInt32                 scActualValue1;
2650         const char*             resultOperation;
2651         vector<deInt32> expectedOutput;
2652         deInt32                 scActualValueLength;
2653
2654                                         SpecConstantTwoIntCase (const char* name,
2655                                                                                         const char* definition0,
2656                                                                                         const char* definition1,
2657                                                                                         const char* resultType,
2658                                                                                         const char* operation,
2659                                                                                         deInt32 value0,
2660                                                                                         deInt32 value1,
2661                                                                                         const char* resultOp,
2662                                                                                         const vector<deInt32>& output,
2663                                                                                         const deInt32   valueLength = sizeof(deInt32))
2664                                                 : caseName                              (name)
2665                                                 , scDefinition0                 (definition0)
2666                                                 , scDefinition1                 (definition1)
2667                                                 , scResultType                  (resultType)
2668                                                 , scOperation                   (operation)
2669                                                 , scActualValue0                (value0)
2670                                                 , scActualValue1                (value1)
2671                                                 , resultOperation               (resultOp)
2672                                                 , expectedOutput                (output)
2673                                                 , scActualValueLength   (valueLength)
2674                                                 {}
2675 };
2676
2677 tcu::TestCaseGroup* createSpecConstantGroup (tcu::TestContext& testCtx)
2678 {
2679         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
2680         vector<SpecConstantTwoIntCase>  cases;
2681         de::Random                                              rnd                             (deStringHash(group->getName()));
2682         const int                                               numElements             = 100;
2683         const deInt32                                   p1AsFloat16             = 0x3c00; // +1(fp16) == 0 01111 0000000000 == 0011 1100 0000 0000
2684         vector<deInt32>                                 inputInts               (numElements, 0);
2685         vector<deInt32>                                 outputInts1             (numElements, 0);
2686         vector<deInt32>                                 outputInts2             (numElements, 0);
2687         vector<deInt32>                                 outputInts3             (numElements, 0);
2688         vector<deInt32>                                 outputInts4             (numElements, 0);
2689         const StringTemplate                    shaderTemplate  (
2690                 "${CAPABILITIES:opt}"
2691                 + string(getComputeAsmShaderPreamble()) +
2692
2693                 "OpName %main           \"main\"\n"
2694                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2695
2696                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2697                 "OpDecorate %sc_0  SpecId 0\n"
2698                 "OpDecorate %sc_1  SpecId 1\n"
2699                 "OpDecorate %i32arr ArrayStride 4\n"
2700
2701                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2702
2703                 "${OPTYPE_DEFINITIONS:opt}"
2704                 "%buf     = OpTypeStruct %i32arr\n"
2705                 "%bufptr  = OpTypePointer Uniform %buf\n"
2706                 "%indata    = OpVariable %bufptr Uniform\n"
2707                 "%outdata   = OpVariable %bufptr Uniform\n"
2708
2709                 "%id        = OpVariable %uvec3ptr Input\n"
2710                 "%zero      = OpConstant %i32 0\n"
2711
2712                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
2713                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
2714                 "%sc_final  = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n"
2715
2716                 "%main      = OpFunction %void None %voidf\n"
2717                 "%label     = OpLabel\n"
2718                 "${TYPE_CONVERT:opt}"
2719                 "%idval     = OpLoad %uvec3 %id\n"
2720                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2721                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
2722                 "%inval     = OpLoad %i32 %inloc\n"
2723                 "%final     = ${GEN_RESULT}\n"
2724                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2725                 "             OpStore %outloc %final\n"
2726                 "             OpReturn\n"
2727                 "             OpFunctionEnd\n");
2728
2729         fillRandomScalars(rnd, -65536, 65536, &inputInts[0], numElements);
2730
2731         for (size_t ndx = 0; ndx < numElements; ++ndx)
2732         {
2733                 outputInts1[ndx] = inputInts[ndx] + 42;
2734                 outputInts2[ndx] = inputInts[ndx];
2735                 outputInts3[ndx] = inputInts[ndx] - 11200;
2736                 outputInts4[ndx] = inputInts[ndx] + 1;
2737         }
2738
2739         const char addScToInput[]               = "OpIAdd %i32 %inval %sc_final";
2740         const char addSc32ToInput[]             = "OpIAdd %i32 %inval %sc_final32";
2741         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_final %inval %zero";
2742         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_final %zero %inval";
2743
2744         cases.push_back(SpecConstantTwoIntCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                     62,             -20,    addScToInput,           outputInts1));
2745         cases.push_back(SpecConstantTwoIntCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                     100,    58,             addScToInput,           outputInts1));
2746         cases.push_back(SpecConstantTwoIntCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                     -2,             -21,    addScToInput,           outputInts1));
2747         cases.push_back(SpecConstantTwoIntCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                     -126,   -3,             addScToInput,           outputInts1));
2748         cases.push_back(SpecConstantTwoIntCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                     126,    3,              addScToInput,           outputInts1));
2749         cases.push_back(SpecConstantTwoIntCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
2750         cases.push_back(SpecConstantTwoIntCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
2751         cases.push_back(SpecConstantTwoIntCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                     342,    50,             addScToInput,           outputInts1));
2752         cases.push_back(SpecConstantTwoIntCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                     42,             63,             addScToInput,           outputInts1));
2753         cases.push_back(SpecConstantTwoIntCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                     34,             8,              addScToInput,           outputInts1));
2754         cases.push_back(SpecConstantTwoIntCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                     18,             56,             addScToInput,           outputInts1));
2755         cases.push_back(SpecConstantTwoIntCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
2756         cases.push_back(SpecConstantTwoIntCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
2757         cases.push_back(SpecConstantTwoIntCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                     21,             1,              addScToInput,           outputInts1));
2758         cases.push_back(SpecConstantTwoIntCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                     -20,    -10,    selectTrueUsingSc,      outputInts2));
2759         cases.push_back(SpecConstantTwoIntCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                     10,             20,             selectTrueUsingSc,      outputInts2));
2760         cases.push_back(SpecConstantTwoIntCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
2761         cases.push_back(SpecConstantTwoIntCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                     10,             5,              selectTrueUsingSc,      outputInts2));
2762         cases.push_back(SpecConstantTwoIntCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                     -10,    -10,    selectTrueUsingSc,      outputInts2));
2763         cases.push_back(SpecConstantTwoIntCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                     50,             100,    selectTrueUsingSc,      outputInts2));
2764         cases.push_back(SpecConstantTwoIntCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
2765         cases.push_back(SpecConstantTwoIntCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                     10,             10,             selectTrueUsingSc,      outputInts2));
2766         cases.push_back(SpecConstantTwoIntCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                     42,             24,             selectFalseUsingSc,     outputInts2));
2767         cases.push_back(SpecConstantTwoIntCase("inotequal",                             " %i32 0",              " %i32 0",              "%bool",        "INotEqual            %sc_0 %sc_1",                     42,             24,             selectTrueUsingSc,      outputInts2));
2768         cases.push_back(SpecConstantTwoIntCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
2769         cases.push_back(SpecConstantTwoIntCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
2770         cases.push_back(SpecConstantTwoIntCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
2771         cases.push_back(SpecConstantTwoIntCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
2772         cases.push_back(SpecConstantTwoIntCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                           -42,    0,              addScToInput,           outputInts1));
2773         cases.push_back(SpecConstantTwoIntCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                           -43,    0,              addScToInput,           outputInts1));
2774         cases.push_back(SpecConstantTwoIntCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                           1,              0,              selectFalseUsingSc,     outputInts2));
2775         cases.push_back(SpecConstantTwoIntCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %zero",       1,              42,             addScToInput,           outputInts1));
2776         cases.push_back(SpecConstantTwoIntCase("sconvert",                              " %i32 0",              " %i32 0",              "%i16",         "SConvert             %sc_0",                           -11200, 0,              addSc32ToInput,         outputInts3));
2777         // -969998336 stored as 32-bit two's complement is the binary representation of -11200 as IEEE-754 Float
2778         cases.push_back(SpecConstantTwoIntCase("fconvert",                              " %f32 0",              " %f32 0",              "%f64",         "FConvert             %sc_0",                           -969998336, 0,  addSc32ToInput,         outputInts3));
2779         cases.push_back(SpecConstantTwoIntCase("fconvert16",                    " %f16 0",              " %f16 0",              "%f32",         "FConvert             %sc_0",                           p1AsFloat16, 0, addSc32ToInput,         outputInts4, sizeof(deFloat16)));
2780
2781         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
2782         {
2783                 map<string, string>             specializations;
2784                 ComputeShaderSpec               spec;
2785
2786                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
2787                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
2788                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
2789                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
2790                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
2791
2792                 // Special SPIR-V code for SConvert-case
2793                 if (strcmp(cases[caseNdx].caseName, "sconvert") == 0)
2794                 {
2795                         spec.requestedVulkanFeatures.coreFeatures.shaderInt16   = VK_TRUE;
2796                         specializations["CAPABILITIES"]                                                 = "OpCapability Int16\n";                                                       // Adds 16-bit integer capability
2797                         specializations["OPTYPE_DEFINITIONS"]                                   = "%i16 = OpTypeInt 16 1\n";                                            // Adds 16-bit integer type
2798                         specializations["TYPE_CONVERT"]                                                 = "%sc_final32 = OpSConvert %i32 %sc_final\n";          // Converts 16-bit integer to 32-bit integer
2799                 }
2800
2801                 // Special SPIR-V code for FConvert-case
2802                 if (strcmp(cases[caseNdx].caseName, "fconvert") == 0)
2803                 {
2804                         spec.requestedVulkanFeatures.coreFeatures.shaderFloat64 = VK_TRUE;
2805                         specializations["CAPABILITIES"]                                                 = "OpCapability Float64\n";                                                     // Adds 64-bit float capability
2806                         specializations["OPTYPE_DEFINITIONS"]                                   = "%f64 = OpTypeFloat 64\n";                                            // Adds 64-bit float type
2807                         specializations["TYPE_CONVERT"]                                                 = "%sc_final32 = OpConvertFToS %i32 %sc_final\n";       // Converts 64-bit float to 32-bit integer
2808                 }
2809
2810                 // Special SPIR-V code for FConvert-case for 16-bit floats
2811                 if (strcmp(cases[caseNdx].caseName, "fconvert16") == 0)
2812                 {
2813                         spec.extensions.push_back("VK_KHR_shader_float16_int8");
2814                         spec.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
2815                         specializations["CAPABILITIES"]                 = "OpCapability Float16\n";                                                     // Adds 16-bit float capability
2816                         specializations["OPTYPE_DEFINITIONS"]   = "%f16 = OpTypeFloat 16\n";                                            // Adds 16-bit float type
2817                         specializations["TYPE_CONVERT"]                 = "%sc_final32 = OpConvertFToS %i32 %sc_final\n";       // Converts 16-bit float to 32-bit integer
2818                 }
2819
2820                 spec.assembly = shaderTemplate.specialize(specializations);
2821                 spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
2822                 spec.outputs.push_back(BufferSp(new Int32Buffer(cases[caseNdx].expectedOutput)));
2823                 spec.numWorkGroups = IVec3(numElements, 1, 1);
2824                 spec.specConstants.append(&cases[caseNdx].scActualValue0, cases[caseNdx].scActualValueLength);
2825                 spec.specConstants.append(&cases[caseNdx].scActualValue1, cases[caseNdx].scActualValueLength);
2826
2827                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].caseName, cases[caseNdx].caseName, spec));
2828         }
2829
2830         ComputeShaderSpec                               spec;
2831
2832         spec.assembly =
2833                 string(getComputeAsmShaderPreamble()) +
2834
2835                 "OpName %main           \"main\"\n"
2836                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2837
2838                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2839                 "OpDecorate %sc_0  SpecId 0\n"
2840                 "OpDecorate %sc_1  SpecId 1\n"
2841                 "OpDecorate %sc_2  SpecId 2\n"
2842                 "OpDecorate %i32arr ArrayStride 4\n"
2843
2844                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2845
2846                 "%ivec3       = OpTypeVector %i32 3\n"
2847                 "%buf         = OpTypeStruct %i32arr\n"
2848                 "%bufptr      = OpTypePointer Uniform %buf\n"
2849                 "%indata      = OpVariable %bufptr Uniform\n"
2850                 "%outdata     = OpVariable %bufptr Uniform\n"
2851
2852                 "%id          = OpVariable %uvec3ptr Input\n"
2853                 "%zero        = OpConstant %i32 0\n"
2854                 "%ivec3_0     = OpConstantComposite %ivec3 %zero %zero %zero\n"
2855                 "%vec3_undef  = OpUndef %ivec3\n"
2856
2857                 "%sc_0        = OpSpecConstant %i32 0\n"
2858                 "%sc_1        = OpSpecConstant %i32 0\n"
2859                 "%sc_2        = OpSpecConstant %i32 0\n"
2860                 "%sc_vec3_0   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_0        %ivec3_0     0\n"                                                 // (sc_0, 0, 0)
2861                 "%sc_vec3_1   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_1        %ivec3_0     1\n"                                                 // (0, sc_1, 0)
2862                 "%sc_vec3_2   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_2        %ivec3_0     2\n"                                                 // (0, 0, sc_2)
2863                 "%sc_vec3_0_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0   %vec3_undef  0          0xFFFFFFFF 2\n"   // (sc_0, ???,  0)
2864                 "%sc_vec3_1_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_1   %vec3_undef  0xFFFFFFFF 1          0\n"   // (???,  sc_1, 0)
2865                 "%sc_vec3_2_s = OpSpecConstantOp %ivec3 VectorShuffle    %vec3_undef  %sc_vec3_2   5          0xFFFFFFFF 5\n"   // (sc_2, ???,  sc_2)
2866                 "%sc_vec3_01  = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0_s %sc_vec3_1_s 1 0 4\n"                                             // (0,    sc_0, sc_1)
2867                 "%sc_vec3_012 = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_01  %sc_vec3_2_s 5 1 2\n"                                             // (sc_2, sc_0, sc_1)
2868                 "%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              0\n"                                                 // sc_2
2869                 "%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              1\n"                                                 // sc_0
2870                 "%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              2\n"                                                 // sc_1
2871                 "%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"                                                              // (sc_2 - sc_0)
2872                 "%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n"                                                              // (sc_2 - sc_0) * sc_1
2873
2874                 "%main      = OpFunction %void None %voidf\n"
2875                 "%label     = OpLabel\n"
2876                 "%idval     = OpLoad %uvec3 %id\n"
2877                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2878                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
2879                 "%inval     = OpLoad %i32 %inloc\n"
2880                 "%final     = OpIAdd %i32 %inval %sc_final\n"
2881                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2882                 "             OpStore %outloc %final\n"
2883                 "             OpReturn\n"
2884                 "             OpFunctionEnd\n";
2885         spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
2886         spec.outputs.push_back(BufferSp(new Int32Buffer(outputInts3)));
2887         spec.numWorkGroups = IVec3(numElements, 1, 1);
2888         spec.specConstants.append<deInt32>(123);
2889         spec.specConstants.append<deInt32>(56);
2890         spec.specConstants.append<deInt32>(-77);
2891
2892         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector_related", "VectorShuffle, CompositeExtract, & CompositeInsert", spec));
2893
2894         return group.release();
2895 }
2896
2897 void createOpPhiVartypeTests (de::MovePtr<tcu::TestCaseGroup>& group, tcu::TestContext& testCtx)
2898 {
2899         ComputeShaderSpec       specInt;
2900         ComputeShaderSpec       specFloat;
2901         ComputeShaderSpec       specFloat16;
2902         ComputeShaderSpec       specVec3;
2903         ComputeShaderSpec       specMat4;
2904         ComputeShaderSpec       specArray;
2905         ComputeShaderSpec       specStruct;
2906         de::Random                      rnd                             (deStringHash(group->getName()));
2907         const int                       numElements             = 100;
2908         vector<float>           inputFloats             (numElements, 0);
2909         vector<float>           outputFloats    (numElements, 0);
2910         vector<deFloat16>       inputFloats16   (numElements, 0);
2911         vector<deFloat16>       outputFloats16  (numElements, 0);
2912
2913         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
2914
2915         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2916         floorAll(inputFloats);
2917
2918         for (size_t ndx = 0; ndx < numElements; ++ndx)
2919         {
2920                 // Just check if the value is positive or not
2921                 outputFloats[ndx] = (inputFloats[ndx] > 0) ? 1.0f : -1.0f;
2922         }
2923
2924         for (size_t ndx = 0; ndx < numElements; ++ndx)
2925         {
2926                 inputFloats16[ndx] = tcu::Float16(inputFloats[ndx]).bits();
2927                 outputFloats16[ndx] = tcu::Float16(outputFloats[ndx]).bits();
2928         }
2929
2930         // All of the tests are of the form:
2931         //
2932         // testtype r
2933         //
2934         // if (inputdata > 0)
2935         //   r = 1
2936         // else
2937         //   r = -1
2938         //
2939         // return (float)r
2940
2941         specFloat.assembly =
2942                 string(getComputeAsmShaderPreamble()) +
2943
2944                 "OpSource GLSL 430\n"
2945                 "OpName %main \"main\"\n"
2946                 "OpName %id \"gl_GlobalInvocationID\"\n"
2947
2948                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2949
2950                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2951
2952                 "%id = OpVariable %uvec3ptr Input\n"
2953                 "%zero       = OpConstant %i32 0\n"
2954                 "%float_0    = OpConstant %f32 0.0\n"
2955                 "%float_1    = OpConstant %f32 1.0\n"
2956                 "%float_n1   = OpConstant %f32 -1.0\n"
2957
2958                 "%main     = OpFunction %void None %voidf\n"
2959                 "%entry    = OpLabel\n"
2960                 "%idval    = OpLoad %uvec3 %id\n"
2961                 "%x        = OpCompositeExtract %u32 %idval 0\n"
2962                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
2963                 "%inval    = OpLoad %f32 %inloc\n"
2964
2965                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
2966                 "            OpSelectionMerge %cm None\n"
2967                 "            OpBranchConditional %comp %tb %fb\n"
2968                 "%tb       = OpLabel\n"
2969                 "            OpBranch %cm\n"
2970                 "%fb       = OpLabel\n"
2971                 "            OpBranch %cm\n"
2972                 "%cm       = OpLabel\n"
2973                 "%res      = OpPhi %f32 %float_1 %tb %float_n1 %fb\n"
2974
2975                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
2976                 "            OpStore %outloc %res\n"
2977                 "            OpReturn\n"
2978
2979                 "            OpFunctionEnd\n";
2980         specFloat.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2981         specFloat.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2982         specFloat.numWorkGroups = IVec3(numElements, 1, 1);
2983
2984         specFloat16.assembly =
2985                 "OpCapability Shader\n"
2986                 "OpCapability StorageUniformBufferBlock16\n"
2987                 "OpExtension \"SPV_KHR_16bit_storage\"\n"
2988                 "OpMemoryModel Logical GLSL450\n"
2989                 "OpEntryPoint GLCompute %main \"main\" %id\n"
2990                 "OpExecutionMode %main LocalSize 1 1 1\n"
2991
2992                 "OpSource GLSL 430\n"
2993                 "OpName %main \"main\"\n"
2994                 "OpName %id \"gl_GlobalInvocationID\"\n"
2995
2996                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2997
2998                 "OpDecorate %buf BufferBlock\n"
2999                 "OpDecorate %indata DescriptorSet 0\n"
3000                 "OpDecorate %indata Binding 0\n"
3001                 "OpDecorate %outdata DescriptorSet 0\n"
3002                 "OpDecorate %outdata Binding 1\n"
3003                 "OpDecorate %f16arr ArrayStride 2\n"
3004                 "OpMemberDecorate %buf 0 Offset 0\n"
3005
3006                 "%f16      = OpTypeFloat 16\n"
3007                 "%f16ptr   = OpTypePointer Uniform %f16\n"
3008                 "%f16arr   = OpTypeRuntimeArray %f16\n"
3009
3010                 + string(getComputeAsmCommonTypes()) +
3011
3012                 "%buf      = OpTypeStruct %f16arr\n"
3013                 "%bufptr   = OpTypePointer Uniform %buf\n"
3014                 "%indata   = OpVariable %bufptr Uniform\n"
3015                 "%outdata  = OpVariable %bufptr Uniform\n"
3016
3017                 "%id       = OpVariable %uvec3ptr Input\n"
3018                 "%zero     = OpConstant %i32 0\n"
3019                 "%float_0  = OpConstant %f16 0.0\n"
3020                 "%float_1  = OpConstant %f16 1.0\n"
3021                 "%float_n1 = OpConstant %f16 -1.0\n"
3022
3023                 "%main     = OpFunction %void None %voidf\n"
3024                 "%entry    = OpLabel\n"
3025                 "%idval    = OpLoad %uvec3 %id\n"
3026                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3027                 "%inloc    = OpAccessChain %f16ptr %indata %zero %x\n"
3028                 "%inval    = OpLoad %f16 %inloc\n"
3029
3030                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3031                 "            OpSelectionMerge %cm None\n"
3032                 "            OpBranchConditional %comp %tb %fb\n"
3033                 "%tb       = OpLabel\n"
3034                 "            OpBranch %cm\n"
3035                 "%fb       = OpLabel\n"
3036                 "            OpBranch %cm\n"
3037                 "%cm       = OpLabel\n"
3038                 "%res      = OpPhi %f16 %float_1 %tb %float_n1 %fb\n"
3039
3040                 "%outloc   = OpAccessChain %f16ptr %outdata %zero %x\n"
3041                 "            OpStore %outloc %res\n"
3042                 "            OpReturn\n"
3043
3044                 "            OpFunctionEnd\n";
3045         specFloat16.inputs.push_back(BufferSp(new Float16Buffer(inputFloats16)));
3046         specFloat16.outputs.push_back(BufferSp(new Float16Buffer(outputFloats16)));
3047         specFloat16.numWorkGroups = IVec3(numElements, 1, 1);
3048         specFloat16.requestedVulkanFeatures.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
3049         specFloat16.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
3050
3051         specMat4.assembly =
3052                 string(getComputeAsmShaderPreamble()) +
3053
3054                 "OpSource GLSL 430\n"
3055                 "OpName %main \"main\"\n"
3056                 "OpName %id \"gl_GlobalInvocationID\"\n"
3057
3058                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3059
3060                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3061
3062                 "%id = OpVariable %uvec3ptr Input\n"
3063                 "%v4f32      = OpTypeVector %f32 4\n"
3064                 "%mat4v4f32  = OpTypeMatrix %v4f32 4\n"
3065                 "%zero       = OpConstant %i32 0\n"
3066                 "%float_0    = OpConstant %f32 0.0\n"
3067                 "%float_1    = OpConstant %f32 1.0\n"
3068                 "%float_n1   = OpConstant %f32 -1.0\n"
3069                 "%m11        = OpConstantComposite %v4f32 %float_1 %float_0 %float_0 %float_0\n"
3070                 "%m12        = OpConstantComposite %v4f32 %float_0 %float_1 %float_0 %float_0\n"
3071                 "%m13        = OpConstantComposite %v4f32 %float_0 %float_0 %float_1 %float_0\n"
3072                 "%m14        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_1\n"
3073                 "%m1         = OpConstantComposite %mat4v4f32 %m11 %m12 %m13 %m14\n"
3074                 "%m21        = OpConstantComposite %v4f32 %float_n1 %float_0 %float_0 %float_0\n"
3075                 "%m22        = OpConstantComposite %v4f32 %float_0 %float_n1 %float_0 %float_0\n"
3076                 "%m23        = OpConstantComposite %v4f32 %float_0 %float_0 %float_n1 %float_0\n"
3077                 "%m24        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_n1\n"
3078                 "%m2         = OpConstantComposite %mat4v4f32 %m21 %m22 %m23 %m24\n"
3079
3080                 "%main     = OpFunction %void None %voidf\n"
3081                 "%entry    = OpLabel\n"
3082                 "%idval    = OpLoad %uvec3 %id\n"
3083                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3084                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3085                 "%inval    = OpLoad %f32 %inloc\n"
3086
3087                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3088                 "            OpSelectionMerge %cm None\n"
3089                 "            OpBranchConditional %comp %tb %fb\n"
3090                 "%tb       = OpLabel\n"
3091                 "            OpBranch %cm\n"
3092                 "%fb       = OpLabel\n"
3093                 "            OpBranch %cm\n"
3094                 "%cm       = OpLabel\n"
3095                 "%mres     = OpPhi %mat4v4f32 %m1 %tb %m2 %fb\n"
3096                 "%res      = OpCompositeExtract %f32 %mres 2 2\n"
3097
3098                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3099                 "            OpStore %outloc %res\n"
3100                 "            OpReturn\n"
3101
3102                 "            OpFunctionEnd\n";
3103         specMat4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3104         specMat4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3105         specMat4.numWorkGroups = IVec3(numElements, 1, 1);
3106
3107         specVec3.assembly =
3108                 string(getComputeAsmShaderPreamble()) +
3109
3110                 "OpSource GLSL 430\n"
3111                 "OpName %main \"main\"\n"
3112                 "OpName %id \"gl_GlobalInvocationID\"\n"
3113
3114                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3115
3116                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3117
3118                 "%id = OpVariable %uvec3ptr Input\n"
3119                 "%zero       = OpConstant %i32 0\n"
3120                 "%float_0    = OpConstant %f32 0.0\n"
3121                 "%float_1    = OpConstant %f32 1.0\n"
3122                 "%float_n1   = OpConstant %f32 -1.0\n"
3123                 "%v1         = OpConstantComposite %fvec3 %float_1 %float_1 %float_1\n"
3124                 "%v2         = OpConstantComposite %fvec3 %float_n1 %float_n1 %float_n1\n"
3125
3126                 "%main     = OpFunction %void None %voidf\n"
3127                 "%entry    = OpLabel\n"
3128                 "%idval    = OpLoad %uvec3 %id\n"
3129                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3130                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3131                 "%inval    = OpLoad %f32 %inloc\n"
3132
3133                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3134                 "            OpSelectionMerge %cm None\n"
3135                 "            OpBranchConditional %comp %tb %fb\n"
3136                 "%tb       = OpLabel\n"
3137                 "            OpBranch %cm\n"
3138                 "%fb       = OpLabel\n"
3139                 "            OpBranch %cm\n"
3140                 "%cm       = OpLabel\n"
3141                 "%vres     = OpPhi %fvec3 %v1 %tb %v2 %fb\n"
3142                 "%res      = OpCompositeExtract %f32 %vres 2\n"
3143
3144                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3145                 "            OpStore %outloc %res\n"
3146                 "            OpReturn\n"
3147
3148                 "            OpFunctionEnd\n";
3149         specVec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3150         specVec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3151         specVec3.numWorkGroups = IVec3(numElements, 1, 1);
3152
3153         specInt.assembly =
3154                 string(getComputeAsmShaderPreamble()) +
3155
3156                 "OpSource GLSL 430\n"
3157                 "OpName %main \"main\"\n"
3158                 "OpName %id \"gl_GlobalInvocationID\"\n"
3159
3160                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3161
3162                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3163
3164                 "%id = OpVariable %uvec3ptr Input\n"
3165                 "%zero       = OpConstant %i32 0\n"
3166                 "%float_0    = OpConstant %f32 0.0\n"
3167                 "%i1         = OpConstant %i32 1\n"
3168                 "%i2         = OpConstant %i32 -1\n"
3169
3170                 "%main     = OpFunction %void None %voidf\n"
3171                 "%entry    = OpLabel\n"
3172                 "%idval    = OpLoad %uvec3 %id\n"
3173                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3174                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3175                 "%inval    = OpLoad %f32 %inloc\n"
3176
3177                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3178                 "            OpSelectionMerge %cm None\n"
3179                 "            OpBranchConditional %comp %tb %fb\n"
3180                 "%tb       = OpLabel\n"
3181                 "            OpBranch %cm\n"
3182                 "%fb       = OpLabel\n"
3183                 "            OpBranch %cm\n"
3184                 "%cm       = OpLabel\n"
3185                 "%ires     = OpPhi %i32 %i1 %tb %i2 %fb\n"
3186                 "%res      = OpConvertSToF %f32 %ires\n"
3187
3188                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3189                 "            OpStore %outloc %res\n"
3190                 "            OpReturn\n"
3191
3192                 "            OpFunctionEnd\n";
3193         specInt.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3194         specInt.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3195         specInt.numWorkGroups = IVec3(numElements, 1, 1);
3196
3197         specArray.assembly =
3198                 string(getComputeAsmShaderPreamble()) +
3199
3200                 "OpSource GLSL 430\n"
3201                 "OpName %main \"main\"\n"
3202                 "OpName %id \"gl_GlobalInvocationID\"\n"
3203
3204                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3205
3206                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3207
3208                 "%id = OpVariable %uvec3ptr Input\n"
3209                 "%zero       = OpConstant %i32 0\n"
3210                 "%u7         = OpConstant %u32 7\n"
3211                 "%float_0    = OpConstant %f32 0.0\n"
3212                 "%float_1    = OpConstant %f32 1.0\n"
3213                 "%float_n1   = OpConstant %f32 -1.0\n"
3214                 "%f32a7      = OpTypeArray %f32 %u7\n"
3215                 "%a1         = OpConstantComposite %f32a7 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1\n"
3216                 "%a2         = OpConstantComposite %f32a7 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1\n"
3217                 "%main     = OpFunction %void None %voidf\n"
3218                 "%entry    = OpLabel\n"
3219                 "%idval    = OpLoad %uvec3 %id\n"
3220                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3221                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3222                 "%inval    = OpLoad %f32 %inloc\n"
3223
3224                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3225                 "            OpSelectionMerge %cm None\n"
3226                 "            OpBranchConditional %comp %tb %fb\n"
3227                 "%tb       = OpLabel\n"
3228                 "            OpBranch %cm\n"
3229                 "%fb       = OpLabel\n"
3230                 "            OpBranch %cm\n"
3231                 "%cm       = OpLabel\n"
3232                 "%ares     = OpPhi %f32a7 %a1 %tb %a2 %fb\n"
3233                 "%res      = OpCompositeExtract %f32 %ares 5\n"
3234
3235                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3236                 "            OpStore %outloc %res\n"
3237                 "            OpReturn\n"
3238
3239                 "            OpFunctionEnd\n";
3240         specArray.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3241         specArray.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3242         specArray.numWorkGroups = IVec3(numElements, 1, 1);
3243
3244         specStruct.assembly =
3245                 string(getComputeAsmShaderPreamble()) +
3246
3247                 "OpSource GLSL 430\n"
3248                 "OpName %main \"main\"\n"
3249                 "OpName %id \"gl_GlobalInvocationID\"\n"
3250
3251                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3252
3253                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3254
3255                 "%id = OpVariable %uvec3ptr Input\n"
3256                 "%zero       = OpConstant %i32 0\n"
3257                 "%float_0    = OpConstant %f32 0.0\n"
3258                 "%float_1    = OpConstant %f32 1.0\n"
3259                 "%float_n1   = OpConstant %f32 -1.0\n"
3260
3261                 "%v2f32      = OpTypeVector %f32 2\n"
3262                 "%Data2      = OpTypeStruct %f32 %v2f32\n"
3263                 "%Data       = OpTypeStruct %Data2 %f32\n"
3264
3265                 "%in1a       = OpConstantComposite %v2f32 %float_1 %float_1\n"
3266                 "%in1b       = OpConstantComposite %Data2 %float_1 %in1a\n"
3267                 "%s1         = OpConstantComposite %Data %in1b %float_1\n"
3268                 "%in2a       = OpConstantComposite %v2f32 %float_n1 %float_n1\n"
3269                 "%in2b       = OpConstantComposite %Data2 %float_n1 %in2a\n"
3270                 "%s2         = OpConstantComposite %Data %in2b %float_n1\n"
3271
3272                 "%main     = OpFunction %void None %voidf\n"
3273                 "%entry    = OpLabel\n"
3274                 "%idval    = OpLoad %uvec3 %id\n"
3275                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3276                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3277                 "%inval    = OpLoad %f32 %inloc\n"
3278
3279                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3280                 "            OpSelectionMerge %cm None\n"
3281                 "            OpBranchConditional %comp %tb %fb\n"
3282                 "%tb       = OpLabel\n"
3283                 "            OpBranch %cm\n"
3284                 "%fb       = OpLabel\n"
3285                 "            OpBranch %cm\n"
3286                 "%cm       = OpLabel\n"
3287                 "%sres     = OpPhi %Data %s1 %tb %s2 %fb\n"
3288                 "%res      = OpCompositeExtract %f32 %sres 0 0\n"
3289
3290                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3291                 "            OpStore %outloc %res\n"
3292                 "            OpReturn\n"
3293
3294                 "            OpFunctionEnd\n";
3295         specStruct.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3296         specStruct.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3297         specStruct.numWorkGroups = IVec3(numElements, 1, 1);
3298
3299         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_int", "OpPhi with int variables", specInt));
3300         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_float", "OpPhi with float variables", specFloat));
3301         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_float16", "OpPhi with 16bit float variables", specFloat16));
3302         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_vec3", "OpPhi with vec3 variables", specVec3));
3303         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_mat4", "OpPhi with mat4 variables", specMat4));
3304         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_array", "OpPhi with array variables", specArray));
3305         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_struct", "OpPhi with struct variables", specStruct));
3306 }
3307
3308 string generateConstantDefinitions (int count)
3309 {
3310         std::ostringstream      r;
3311         for (int i = 0; i < count; i++)
3312                 r << "%cf" << (i * 10 + 5) << " = OpConstant %f32 " <<(i * 10 + 5) << ".0\n";
3313         r << "\n";
3314         return r.str();
3315 }
3316
3317 string generateSwitchCases (int count)
3318 {
3319         std::ostringstream      r;
3320         for (int i = 0; i < count; i++)
3321                 r << " " << i << " %case" << i;
3322         r << "\n";
3323         return r.str();
3324 }
3325
3326 string generateSwitchTargets (int count)
3327 {
3328         std::ostringstream      r;
3329         for (int i = 0; i < count; i++)
3330                 r << "%case" << i << " = OpLabel\n            OpBranch %phi\n";
3331         r << "\n";
3332         return r.str();
3333 }
3334
3335 string generateOpPhiParams (int count)
3336 {
3337         std::ostringstream      r;
3338         for (int i = 0; i < count; i++)
3339                 r << " %cf" << (i * 10 + 5) << " %case" << i;
3340         r << "\n";
3341         return r.str();
3342 }
3343
3344 string generateIntWidth (int value)
3345 {
3346         std::ostringstream      r;
3347         r << value;
3348         return r.str();
3349 }
3350
3351 // Expand input string by injecting "ABC" between the input
3352 // string characters. The acc/add/treshold parameters are used
3353 // to skip some of the injections to make the result less
3354 // uniform (and a lot shorter).
3355 string expandOpPhiCase5 (const string& s, int &acc, int add, int treshold)
3356 {
3357         std::ostringstream      res;
3358         const char*                     p = s.c_str();
3359
3360         while (*p)
3361         {
3362                 res << *p;
3363                 acc += add;
3364                 if (acc > treshold)
3365                 {
3366                         acc -= treshold;
3367                         res << "ABC";
3368                 }
3369                 p++;
3370         }
3371         return res.str();
3372 }
3373
3374 // Calculate expected result based on the code string
3375 float calcOpPhiCase5 (float val, const string& s)
3376 {
3377         const char*             p               = s.c_str();
3378         float                   x[8];
3379         bool                    b[8];
3380         const float             tv[8]   = { 0.5f, 1.5f, 3.5f, 7.5f, 15.5f, 31.5f, 63.5f, 127.5f };
3381         const float             v               = deFloatAbs(val);
3382         float                   res             = 0;
3383         int                             depth   = -1;
3384         int                             skip    = 0;
3385
3386         for (int i = 7; i >= 0; --i)
3387                 x[i] = std::fmod((float)v, (float)(2 << i));
3388         for (int i = 7; i >= 0; --i)
3389                 b[i] = x[i] > tv[i];
3390
3391         while (*p)
3392         {
3393                 if (*p == 'A')
3394                 {
3395                         depth++;
3396                         if (skip == 0 && b[depth])
3397                         {
3398                                 res++;
3399                         }
3400                         else
3401                                 skip++;
3402                 }
3403                 if (*p == 'B')
3404                 {
3405                         if (skip)
3406                                 skip--;
3407                         if (b[depth] || skip)
3408                                 skip++;
3409                 }
3410                 if (*p == 'C')
3411                 {
3412                         depth--;
3413                         if (skip)
3414                                 skip--;
3415                 }
3416                 p++;
3417         }
3418         return res;
3419 }
3420
3421 // In the code string, the letters represent the following:
3422 //
3423 // A:
3424 //     if (certain bit is set)
3425 //     {
3426 //       result++;
3427 //
3428 // B:
3429 //     } else {
3430 //
3431 // C:
3432 //     }
3433 //
3434 // examples:
3435 // AABCBC leads to if(){r++;if(){r++;}else{}}else{}
3436 // ABABCC leads to if(){r++;}else{if(){r++;}else{}}
3437 // ABCABC leads to if(){r++;}else{}if(){r++;}else{}
3438 //
3439 // Code generation gets a bit complicated due to the else-branches,
3440 // which do not generate new values. Thus, the generator needs to
3441 // keep track of the previous variable change seen by the else
3442 // branch.
3443 string generateOpPhiCase5 (const string& s)
3444 {
3445         std::stack<int>                         idStack;
3446         std::stack<std::string>         value;
3447         std::stack<std::string>         valueLabel;
3448         std::stack<std::string>         mergeLeft;
3449         std::stack<std::string>         mergeRight;
3450         std::ostringstream                      res;
3451         const char*                                     p                       = s.c_str();
3452         int                                                     depth           = -1;
3453         int                                                     currId          = 0;
3454         int                                                     iter            = 0;
3455
3456         idStack.push(-1);
3457         value.push("%f32_0");
3458         valueLabel.push("%f32_0 %entry");
3459
3460         while (*p)
3461         {
3462                 if (*p == 'A')
3463                 {
3464                         depth++;
3465                         currId = iter;
3466                         idStack.push(currId);
3467                         res << "\tOpSelectionMerge %m" << currId << " None\n";
3468                         res << "\tOpBranchConditional %b" << depth << " %t" << currId << " %f" << currId << "\n";
3469                         res << "%t" << currId << " = OpLabel\n";
3470                         res << "%rt" << currId << " = OpFAdd %f32 " << value.top() << " %f32_1\n";
3471                         std::ostringstream tag;
3472                         tag << "%rt" << currId;
3473                         value.push(tag.str());
3474                         tag << " %t" << currId;
3475                         valueLabel.push(tag.str());
3476                 }
3477
3478                 if (*p == 'B')
3479                 {
3480                         mergeLeft.push(valueLabel.top());
3481                         value.pop();
3482                         valueLabel.pop();
3483                         res << "\tOpBranch %m" << currId << "\n";
3484                         res << "%f" << currId << " = OpLabel\n";
3485                         std::ostringstream tag;
3486                         tag << value.top() << " %f" << currId;
3487                         valueLabel.pop();
3488                         valueLabel.push(tag.str());
3489                 }
3490
3491                 if (*p == 'C')
3492                 {
3493                         mergeRight.push(valueLabel.top());
3494                         res << "\tOpBranch %m" << currId << "\n";
3495                         res << "%m" << currId << " = OpLabel\n";
3496                         if (*(p + 1) == 0)
3497                                 res << "%res"; // last result goes to %res
3498                         else
3499                                 res << "%rm" << currId;
3500                         res << " = OpPhi %f32  " << mergeLeft.top() << "  " << mergeRight.top() << "\n";
3501                         std::ostringstream tag;
3502                         tag << "%rm" << currId;
3503                         value.pop();
3504                         value.push(tag.str());
3505                         tag << " %m" << currId;
3506                         valueLabel.pop();
3507                         valueLabel.push(tag.str());
3508                         mergeLeft.pop();
3509                         mergeRight.pop();
3510                         depth--;
3511                         idStack.pop();
3512                         currId = idStack.top();
3513                 }
3514                 p++;
3515                 iter++;
3516         }
3517         return res.str();
3518 }
3519
3520 tcu::TestCaseGroup* createOpPhiGroup (tcu::TestContext& testCtx)
3521 {
3522         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
3523         ComputeShaderSpec                               spec1;
3524         ComputeShaderSpec                               spec2;
3525         ComputeShaderSpec                               spec3;
3526         ComputeShaderSpec                               spec4;
3527         ComputeShaderSpec                               spec5;
3528         de::Random                                              rnd                             (deStringHash(group->getName()));
3529         const int                                               numElements             = 100;
3530         vector<float>                                   inputFloats             (numElements, 0);
3531         vector<float>                                   outputFloats1   (numElements, 0);
3532         vector<float>                                   outputFloats2   (numElements, 0);
3533         vector<float>                                   outputFloats3   (numElements, 0);
3534         vector<float>                                   outputFloats4   (numElements, 0);
3535         vector<float>                                   outputFloats5   (numElements, 0);
3536         std::string                                             codestring              = "ABC";
3537         const int                                               test4Width              = 1024;
3538
3539         // Build case 5 code string. Each iteration makes the hierarchy more complicated.
3540         // 9 iterations with (7, 24) parameters makes the hierarchy 8 deep with about 1500 lines of
3541         // shader code.
3542         for (int i = 0, acc = 0; i < 9; i++)
3543                 codestring = expandOpPhiCase5(codestring, acc, 7, 24);
3544
3545         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
3546
3547         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3548         floorAll(inputFloats);
3549
3550         for (size_t ndx = 0; ndx < numElements; ++ndx)
3551         {
3552                 switch (ndx % 3)
3553                 {
3554                         case 0:         outputFloats1[ndx] = inputFloats[ndx] + 5.5f;   break;
3555                         case 1:         outputFloats1[ndx] = inputFloats[ndx] + 20.5f;  break;
3556                         case 2:         outputFloats1[ndx] = inputFloats[ndx] + 1.75f;  break;
3557                         default:        break;
3558                 }
3559                 outputFloats2[ndx] = inputFloats[ndx] + 6.5f * 3;
3560                 outputFloats3[ndx] = 8.5f - inputFloats[ndx];
3561
3562                 int index4 = (int)deFloor(deAbs((float)ndx * inputFloats[ndx]));
3563                 outputFloats4[ndx] = (float)(index4 % test4Width) * 10.0f + 5.0f;
3564
3565                 outputFloats5[ndx] = calcOpPhiCase5(inputFloats[ndx], codestring);
3566         }
3567
3568         spec1.assembly =
3569                 string(getComputeAsmShaderPreamble()) +
3570
3571                 "OpSource GLSL 430\n"
3572                 "OpName %main \"main\"\n"
3573                 "OpName %id \"gl_GlobalInvocationID\"\n"
3574
3575                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3576
3577                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3578
3579                 "%id = OpVariable %uvec3ptr Input\n"
3580                 "%zero       = OpConstant %i32 0\n"
3581                 "%three      = OpConstant %u32 3\n"
3582                 "%constf5p5  = OpConstant %f32 5.5\n"
3583                 "%constf20p5 = OpConstant %f32 20.5\n"
3584                 "%constf1p75 = OpConstant %f32 1.75\n"
3585                 "%constf8p5  = OpConstant %f32 8.5\n"
3586                 "%constf6p5  = OpConstant %f32 6.5\n"
3587
3588                 "%main     = OpFunction %void None %voidf\n"
3589                 "%entry    = OpLabel\n"
3590                 "%idval    = OpLoad %uvec3 %id\n"
3591                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3592                 "%selector = OpUMod %u32 %x %three\n"
3593                 "            OpSelectionMerge %phi None\n"
3594                 "            OpSwitch %selector %default 0 %case0 1 %case1 2 %case2\n"
3595
3596                 // Case 1 before OpPhi.
3597                 "%case1    = OpLabel\n"
3598                 "            OpBranch %phi\n"
3599
3600                 "%default  = OpLabel\n"
3601                 "            OpUnreachable\n"
3602
3603                 "%phi      = OpLabel\n"
3604                 "%operand  = OpPhi %f32   %constf1p75 %case2   %constf20p5 %case1   %constf5p5 %case0\n" // not in the order of blocks
3605                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3606                 "%inval    = OpLoad %f32 %inloc\n"
3607                 "%add      = OpFAdd %f32 %inval %operand\n"
3608                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3609                 "            OpStore %outloc %add\n"
3610                 "            OpReturn\n"
3611
3612                 // Case 0 after OpPhi.
3613                 "%case0    = OpLabel\n"
3614                 "            OpBranch %phi\n"
3615
3616
3617                 // Case 2 after OpPhi.
3618                 "%case2    = OpLabel\n"
3619                 "            OpBranch %phi\n"
3620
3621                 "            OpFunctionEnd\n";
3622         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3623         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
3624         spec1.numWorkGroups = IVec3(numElements, 1, 1);
3625
3626         group->addChild(new SpvAsmComputeShaderCase(testCtx, "block", "out-of-order and unreachable blocks for OpPhi", spec1));
3627
3628         spec2.assembly =
3629                 string(getComputeAsmShaderPreamble()) +
3630
3631                 "OpName %main \"main\"\n"
3632                 "OpName %id \"gl_GlobalInvocationID\"\n"
3633
3634                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3635
3636                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3637
3638                 "%id         = OpVariable %uvec3ptr Input\n"
3639                 "%zero       = OpConstant %i32 0\n"
3640                 "%one        = OpConstant %i32 1\n"
3641                 "%three      = OpConstant %i32 3\n"
3642                 "%constf6p5  = OpConstant %f32 6.5\n"
3643
3644                 "%main       = OpFunction %void None %voidf\n"
3645                 "%entry      = OpLabel\n"
3646                 "%idval      = OpLoad %uvec3 %id\n"
3647                 "%x          = OpCompositeExtract %u32 %idval 0\n"
3648                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3649                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3650                 "%inval      = OpLoad %f32 %inloc\n"
3651                 "              OpBranch %phi\n"
3652
3653                 "%phi        = OpLabel\n"
3654                 "%step       = OpPhi %i32 %zero  %entry %step_next  %phi\n"
3655                 "%accum      = OpPhi %f32 %inval %entry %accum_next %phi\n"
3656                 "%step_next  = OpIAdd %i32 %step %one\n"
3657                 "%accum_next = OpFAdd %f32 %accum %constf6p5\n"
3658                 "%still_loop = OpSLessThan %bool %step %three\n"
3659                 "              OpLoopMerge %exit %phi None\n"
3660                 "              OpBranchConditional %still_loop %phi %exit\n"
3661
3662                 "%exit       = OpLabel\n"
3663                 "              OpStore %outloc %accum\n"
3664                 "              OpReturn\n"
3665                 "              OpFunctionEnd\n";
3666         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3667         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
3668         spec2.numWorkGroups = IVec3(numElements, 1, 1);
3669
3670         group->addChild(new SpvAsmComputeShaderCase(testCtx, "induction", "The usual way induction variables are handled in LLVM IR", spec2));
3671
3672         spec3.assembly =
3673                 string(getComputeAsmShaderPreamble()) +
3674
3675                 "OpName %main \"main\"\n"
3676                 "OpName %id \"gl_GlobalInvocationID\"\n"
3677
3678                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3679
3680                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3681
3682                 "%f32ptr_f   = OpTypePointer Function %f32\n"
3683                 "%id         = OpVariable %uvec3ptr Input\n"
3684                 "%true       = OpConstantTrue %bool\n"
3685                 "%false      = OpConstantFalse %bool\n"
3686                 "%zero       = OpConstant %i32 0\n"
3687                 "%constf8p5  = OpConstant %f32 8.5\n"
3688
3689                 "%main       = OpFunction %void None %voidf\n"
3690                 "%entry      = OpLabel\n"
3691                 "%b          = OpVariable %f32ptr_f Function %constf8p5\n"
3692                 "%idval      = OpLoad %uvec3 %id\n"
3693                 "%x          = OpCompositeExtract %u32 %idval 0\n"
3694                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3695                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3696                 "%a_init     = OpLoad %f32 %inloc\n"
3697                 "%b_init     = OpLoad %f32 %b\n"
3698                 "              OpBranch %phi\n"
3699
3700                 "%phi        = OpLabel\n"
3701                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
3702                 "%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
3703                 "%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
3704                 "              OpLoopMerge %exit %phi None\n"
3705                 "              OpBranchConditional %still_loop %phi %exit\n"
3706
3707                 "%exit       = OpLabel\n"
3708                 "%sub        = OpFSub %f32 %a_next %b_next\n"
3709                 "              OpStore %outloc %sub\n"
3710                 "              OpReturn\n"
3711                 "              OpFunctionEnd\n";
3712         spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3713         spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
3714         spec3.numWorkGroups = IVec3(numElements, 1, 1);
3715
3716         group->addChild(new SpvAsmComputeShaderCase(testCtx, "swap", "Swap the values of two variables using OpPhi", spec3));
3717
3718         spec4.assembly =
3719                 "OpCapability Shader\n"
3720                 "%ext = OpExtInstImport \"GLSL.std.450\"\n"
3721                 "OpMemoryModel Logical GLSL450\n"
3722                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3723                 "OpExecutionMode %main LocalSize 1 1 1\n"
3724
3725                 "OpSource GLSL 430\n"
3726                 "OpName %main \"main\"\n"
3727                 "OpName %id \"gl_GlobalInvocationID\"\n"
3728
3729                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3730
3731                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3732
3733                 "%id       = OpVariable %uvec3ptr Input\n"
3734                 "%zero     = OpConstant %i32 0\n"
3735                 "%cimod    = OpConstant %u32 " + generateIntWidth(test4Width) + "\n"
3736
3737                 + generateConstantDefinitions(test4Width) +
3738
3739                 "%main     = OpFunction %void None %voidf\n"
3740                 "%entry    = OpLabel\n"
3741                 "%idval    = OpLoad %uvec3 %id\n"
3742                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3743                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3744                 "%inval    = OpLoad %f32 %inloc\n"
3745                 "%xf       = OpConvertUToF %f32 %x\n"
3746                 "%xm       = OpFMul %f32 %xf %inval\n"
3747                 "%xa       = OpExtInst %f32 %ext FAbs %xm\n"
3748                 "%xi       = OpConvertFToU %u32 %xa\n"
3749                 "%selector = OpUMod %u32 %xi %cimod\n"
3750                 "            OpSelectionMerge %phi None\n"
3751                 "            OpSwitch %selector %default "
3752
3753                 + generateSwitchCases(test4Width) +
3754
3755                 "%default  = OpLabel\n"
3756                 "            OpUnreachable\n"
3757
3758                 + generateSwitchTargets(test4Width) +
3759
3760                 "%phi      = OpLabel\n"
3761                 "%result   = OpPhi %f32"
3762
3763                 + generateOpPhiParams(test4Width) +
3764
3765                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3766                 "            OpStore %outloc %result\n"
3767                 "            OpReturn\n"
3768
3769                 "            OpFunctionEnd\n";
3770         spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3771         spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
3772         spec4.numWorkGroups = IVec3(numElements, 1, 1);
3773
3774         group->addChild(new SpvAsmComputeShaderCase(testCtx, "wide", "OpPhi with a lot of parameters", spec4));
3775
3776         spec5.assembly =
3777                 "OpCapability Shader\n"
3778                 "%ext      = OpExtInstImport \"GLSL.std.450\"\n"
3779                 "OpMemoryModel Logical GLSL450\n"
3780                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3781                 "OpExecutionMode %main LocalSize 1 1 1\n"
3782                 "%code     = OpString \"" + codestring + "\"\n"
3783
3784                 "OpSource GLSL 430\n"
3785                 "OpName %main \"main\"\n"
3786                 "OpName %id \"gl_GlobalInvocationID\"\n"
3787
3788                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3789
3790                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3791
3792                 "%id       = OpVariable %uvec3ptr Input\n"
3793                 "%zero     = OpConstant %i32 0\n"
3794                 "%f32_0    = OpConstant %f32 0.0\n"
3795                 "%f32_0_5  = OpConstant %f32 0.5\n"
3796                 "%f32_1    = OpConstant %f32 1.0\n"
3797                 "%f32_1_5  = OpConstant %f32 1.5\n"
3798                 "%f32_2    = OpConstant %f32 2.0\n"
3799                 "%f32_3_5  = OpConstant %f32 3.5\n"
3800                 "%f32_4    = OpConstant %f32 4.0\n"
3801                 "%f32_7_5  = OpConstant %f32 7.5\n"
3802                 "%f32_8    = OpConstant %f32 8.0\n"
3803                 "%f32_15_5 = OpConstant %f32 15.5\n"
3804                 "%f32_16   = OpConstant %f32 16.0\n"
3805                 "%f32_31_5 = OpConstant %f32 31.5\n"
3806                 "%f32_32   = OpConstant %f32 32.0\n"
3807                 "%f32_63_5 = OpConstant %f32 63.5\n"
3808                 "%f32_64   = OpConstant %f32 64.0\n"
3809                 "%f32_127_5 = OpConstant %f32 127.5\n"
3810                 "%f32_128  = OpConstant %f32 128.0\n"
3811                 "%f32_256  = OpConstant %f32 256.0\n"
3812
3813                 "%main     = OpFunction %void None %voidf\n"
3814                 "%entry    = OpLabel\n"
3815                 "%idval    = OpLoad %uvec3 %id\n"
3816                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3817                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3818                 "%inval    = OpLoad %f32 %inloc\n"
3819
3820                 "%xabs     = OpExtInst %f32 %ext FAbs %inval\n"
3821                 "%x8       = OpFMod %f32 %xabs %f32_256\n"
3822                 "%x7       = OpFMod %f32 %xabs %f32_128\n"
3823                 "%x6       = OpFMod %f32 %xabs %f32_64\n"
3824                 "%x5       = OpFMod %f32 %xabs %f32_32\n"
3825                 "%x4       = OpFMod %f32 %xabs %f32_16\n"
3826                 "%x3       = OpFMod %f32 %xabs %f32_8\n"
3827                 "%x2       = OpFMod %f32 %xabs %f32_4\n"
3828                 "%x1       = OpFMod %f32 %xabs %f32_2\n"
3829
3830                 "%b7       = OpFOrdGreaterThanEqual %bool %x8 %f32_127_5\n"
3831                 "%b6       = OpFOrdGreaterThanEqual %bool %x7 %f32_63_5\n"
3832                 "%b5       = OpFOrdGreaterThanEqual %bool %x6 %f32_31_5\n"
3833                 "%b4       = OpFOrdGreaterThanEqual %bool %x5 %f32_15_5\n"
3834                 "%b3       = OpFOrdGreaterThanEqual %bool %x4 %f32_7_5\n"
3835                 "%b2       = OpFOrdGreaterThanEqual %bool %x3 %f32_3_5\n"
3836                 "%b1       = OpFOrdGreaterThanEqual %bool %x2 %f32_1_5\n"
3837                 "%b0       = OpFOrdGreaterThanEqual %bool %x1 %f32_0_5\n"
3838
3839                 + generateOpPhiCase5(codestring) +
3840
3841                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3842                 "            OpStore %outloc %res\n"
3843                 "            OpReturn\n"
3844
3845                 "            OpFunctionEnd\n";
3846         spec5.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3847         spec5.outputs.push_back(BufferSp(new Float32Buffer(outputFloats5)));
3848         spec5.numWorkGroups = IVec3(numElements, 1, 1);
3849
3850         group->addChild(new SpvAsmComputeShaderCase(testCtx, "nested", "Stress OpPhi with a lot of nesting", spec5));
3851
3852         createOpPhiVartypeTests(group, testCtx);
3853
3854         return group.release();
3855 }
3856
3857 // Assembly code used for testing block order is based on GLSL source code:
3858 //
3859 // #version 430
3860 //
3861 // layout(std140, set = 0, binding = 0) readonly buffer Input {
3862 //   float elements[];
3863 // } input_data;
3864 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
3865 //   float elements[];
3866 // } output_data;
3867 //
3868 // void main() {
3869 //   uint x = gl_GlobalInvocationID.x;
3870 //   output_data.elements[x] = input_data.elements[x];
3871 //   if (x > uint(50)) {
3872 //     switch (x % uint(3)) {
3873 //       case 0: output_data.elements[x] += 1.5f; break;
3874 //       case 1: output_data.elements[x] += 42.f; break;
3875 //       case 2: output_data.elements[x] -= 27.f; break;
3876 //       default: break;
3877 //     }
3878 //   } else {
3879 //     output_data.elements[x] = -input_data.elements[x];
3880 //   }
3881 // }
3882 tcu::TestCaseGroup* createBlockOrderGroup (tcu::TestContext& testCtx)
3883 {
3884         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "block_order", "Test block orders"));
3885         ComputeShaderSpec                               spec;
3886         de::Random                                              rnd                             (deStringHash(group->getName()));
3887         const int                                               numElements             = 100;
3888         vector<float>                                   inputFloats             (numElements, 0);
3889         vector<float>                                   outputFloats    (numElements, 0);
3890
3891         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
3892
3893         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3894         floorAll(inputFloats);
3895
3896         for (size_t ndx = 0; ndx <= 50; ++ndx)
3897                 outputFloats[ndx] = -inputFloats[ndx];
3898
3899         for (size_t ndx = 51; ndx < numElements; ++ndx)
3900         {
3901                 switch (ndx % 3)
3902                 {
3903                         case 0:         outputFloats[ndx] = inputFloats[ndx] + 1.5f; break;
3904                         case 1:         outputFloats[ndx] = inputFloats[ndx] + 42.f; break;
3905                         case 2:         outputFloats[ndx] = inputFloats[ndx] - 27.f; break;
3906                         default:        break;
3907                 }
3908         }
3909
3910         spec.assembly =
3911                 string(getComputeAsmShaderPreamble()) +
3912
3913                 "OpSource GLSL 430\n"
3914                 "OpName %main \"main\"\n"
3915                 "OpName %id \"gl_GlobalInvocationID\"\n"
3916
3917                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3918
3919                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
3920
3921                 "%u32ptr       = OpTypePointer Function %u32\n"
3922                 "%u32ptr_input = OpTypePointer Input %u32\n"
3923
3924                 + string(getComputeAsmInputOutputBuffer()) +
3925
3926                 "%id        = OpVariable %uvec3ptr Input\n"
3927                 "%zero      = OpConstant %i32 0\n"
3928                 "%const3    = OpConstant %u32 3\n"
3929                 "%const50   = OpConstant %u32 50\n"
3930                 "%constf1p5 = OpConstant %f32 1.5\n"
3931                 "%constf27  = OpConstant %f32 27.0\n"
3932                 "%constf42  = OpConstant %f32 42.0\n"
3933
3934                 "%main = OpFunction %void None %voidf\n"
3935
3936                 // entry block.
3937                 "%entry    = OpLabel\n"
3938
3939                 // Create a temporary variable to hold the value of gl_GlobalInvocationID.x.
3940                 "%xvar     = OpVariable %u32ptr Function\n"
3941                 "%xptr     = OpAccessChain %u32ptr_input %id %zero\n"
3942                 "%x        = OpLoad %u32 %xptr\n"
3943                 "            OpStore %xvar %x\n"
3944
3945                 "%cmp      = OpUGreaterThan %bool %x %const50\n"
3946                 "            OpSelectionMerge %if_merge None\n"
3947                 "            OpBranchConditional %cmp %if_true %if_false\n"
3948
3949                 // False branch for if-statement: placed in the middle of switch cases and before true branch.
3950                 "%if_false = OpLabel\n"
3951                 "%x_f      = OpLoad %u32 %xvar\n"
3952                 "%inloc_f  = OpAccessChain %f32ptr %indata %zero %x_f\n"
3953                 "%inval_f  = OpLoad %f32 %inloc_f\n"
3954                 "%negate   = OpFNegate %f32 %inval_f\n"
3955                 "%outloc_f = OpAccessChain %f32ptr %outdata %zero %x_f\n"
3956                 "            OpStore %outloc_f %negate\n"
3957                 "            OpBranch %if_merge\n"
3958
3959                 // Merge block for if-statement: placed in the middle of true and false branch.
3960                 "%if_merge = OpLabel\n"
3961                 "            OpReturn\n"
3962
3963                 // True branch for if-statement: placed in the middle of swtich cases and after the false branch.
3964                 "%if_true  = OpLabel\n"
3965                 "%xval_t   = OpLoad %u32 %xvar\n"
3966                 "%mod      = OpUMod %u32 %xval_t %const3\n"
3967                 "            OpSelectionMerge %switch_merge None\n"
3968                 "            OpSwitch %mod %default 0 %case0 1 %case1 2 %case2\n"
3969
3970                 // Merge block for switch-statement: placed before the case
3971                 // bodies.  But it must follow OpSwitch which dominates it.
3972                 "%switch_merge = OpLabel\n"
3973                 "                OpBranch %if_merge\n"
3974
3975                 // Case 1 for switch-statement: placed before case 0.
3976                 // It must follow the OpSwitch that dominates it.
3977                 "%case1    = OpLabel\n"
3978                 "%x_1      = OpLoad %u32 %xvar\n"
3979                 "%inloc_1  = OpAccessChain %f32ptr %indata %zero %x_1\n"
3980                 "%inval_1  = OpLoad %f32 %inloc_1\n"
3981                 "%addf42   = OpFAdd %f32 %inval_1 %constf42\n"
3982                 "%outloc_1 = OpAccessChain %f32ptr %outdata %zero %x_1\n"
3983                 "            OpStore %outloc_1 %addf42\n"
3984                 "            OpBranch %switch_merge\n"
3985
3986                 // Case 2 for switch-statement.
3987                 "%case2    = OpLabel\n"
3988                 "%x_2      = OpLoad %u32 %xvar\n"
3989                 "%inloc_2  = OpAccessChain %f32ptr %indata %zero %x_2\n"
3990                 "%inval_2  = OpLoad %f32 %inloc_2\n"
3991                 "%subf27   = OpFSub %f32 %inval_2 %constf27\n"
3992                 "%outloc_2 = OpAccessChain %f32ptr %outdata %zero %x_2\n"
3993                 "            OpStore %outloc_2 %subf27\n"
3994                 "            OpBranch %switch_merge\n"
3995
3996                 // Default case for switch-statement: placed in the middle of normal cases.
3997                 "%default = OpLabel\n"
3998                 "           OpBranch %switch_merge\n"
3999
4000                 // Case 0 for switch-statement: out of order.
4001                 "%case0    = OpLabel\n"
4002                 "%x_0      = OpLoad %u32 %xvar\n"
4003                 "%inloc_0  = OpAccessChain %f32ptr %indata %zero %x_0\n"
4004                 "%inval_0  = OpLoad %f32 %inloc_0\n"
4005                 "%addf1p5  = OpFAdd %f32 %inval_0 %constf1p5\n"
4006                 "%outloc_0 = OpAccessChain %f32ptr %outdata %zero %x_0\n"
4007                 "            OpStore %outloc_0 %addf1p5\n"
4008                 "            OpBranch %switch_merge\n"
4009
4010                 "            OpFunctionEnd\n";
4011         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4012         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
4013         spec.numWorkGroups = IVec3(numElements, 1, 1);
4014
4015         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "various out-of-order blocks", spec));
4016
4017         return group.release();
4018 }
4019
4020 tcu::TestCaseGroup* createMultipleShaderGroup (tcu::TestContext& testCtx)
4021 {
4022         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "multiple_shaders", "Test multiple shaders in the same module"));
4023         ComputeShaderSpec                               spec1;
4024         ComputeShaderSpec                               spec2;
4025         de::Random                                              rnd                             (deStringHash(group->getName()));
4026         const int                                               numElements             = 100;
4027         vector<float>                                   inputFloats             (numElements, 0);
4028         vector<float>                                   outputFloats1   (numElements, 0);
4029         vector<float>                                   outputFloats2   (numElements, 0);
4030         fillRandomScalars(rnd, -500.f, 500.f, &inputFloats[0], numElements);
4031
4032         for (size_t ndx = 0; ndx < numElements; ++ndx)
4033         {
4034                 outputFloats1[ndx] = inputFloats[ndx] + inputFloats[ndx];
4035                 outputFloats2[ndx] = -inputFloats[ndx];
4036         }
4037
4038         const string assembly(
4039                 "OpCapability Shader\n"
4040                 "OpMemoryModel Logical GLSL450\n"
4041                 "OpEntryPoint GLCompute %comp_main1 \"entrypoint1\" %id\n"
4042                 "OpEntryPoint GLCompute %comp_main2 \"entrypoint2\" %id\n"
4043                 // A module cannot have two OpEntryPoint instructions with the same Execution Model and the same Name string.
4044                 "OpEntryPoint Vertex    %vert_main  \"entrypoint2\" %vert_builtins %vertexIndex %instanceIndex\n"
4045                 "OpExecutionMode %comp_main1 LocalSize 1 1 1\n"
4046                 "OpExecutionMode %comp_main2 LocalSize 1 1 1\n"
4047
4048                 "OpName %comp_main1              \"entrypoint1\"\n"
4049                 "OpName %comp_main2              \"entrypoint2\"\n"
4050                 "OpName %vert_main               \"entrypoint2\"\n"
4051                 "OpName %id                      \"gl_GlobalInvocationID\"\n"
4052                 "OpName %vert_builtin_st         \"gl_PerVertex\"\n"
4053                 "OpName %vertexIndex             \"gl_VertexIndex\"\n"
4054                 "OpName %instanceIndex           \"gl_InstanceIndex\"\n"
4055                 "OpMemberName %vert_builtin_st 0 \"gl_Position\"\n"
4056                 "OpMemberName %vert_builtin_st 1 \"gl_PointSize\"\n"
4057                 "OpMemberName %vert_builtin_st 2 \"gl_ClipDistance\"\n"
4058
4059                 "OpDecorate %id                      BuiltIn GlobalInvocationId\n"
4060                 "OpDecorate %vertexIndex             BuiltIn VertexIndex\n"
4061                 "OpDecorate %instanceIndex           BuiltIn InstanceIndex\n"
4062                 "OpDecorate %vert_builtin_st         Block\n"
4063                 "OpMemberDecorate %vert_builtin_st 0 BuiltIn Position\n"
4064                 "OpMemberDecorate %vert_builtin_st 1 BuiltIn PointSize\n"
4065                 "OpMemberDecorate %vert_builtin_st 2 BuiltIn ClipDistance\n"
4066
4067                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4068
4069                 "%zero       = OpConstant %i32 0\n"
4070                 "%one        = OpConstant %u32 1\n"
4071                 "%c_f32_1    = OpConstant %f32 1\n"
4072
4073                 "%i32inputptr         = OpTypePointer Input %i32\n"
4074                 "%vec4                = OpTypeVector %f32 4\n"
4075                 "%vec4ptr             = OpTypePointer Output %vec4\n"
4076                 "%f32arr1             = OpTypeArray %f32 %one\n"
4077                 "%vert_builtin_st     = OpTypeStruct %vec4 %f32 %f32arr1\n"
4078                 "%vert_builtin_st_ptr = OpTypePointer Output %vert_builtin_st\n"
4079                 "%vert_builtins       = OpVariable %vert_builtin_st_ptr Output\n"
4080
4081                 "%id         = OpVariable %uvec3ptr Input\n"
4082                 "%vertexIndex = OpVariable %i32inputptr Input\n"
4083                 "%instanceIndex = OpVariable %i32inputptr Input\n"
4084                 "%c_vec4_1   = OpConstantComposite %vec4 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
4085
4086                 // gl_Position = vec4(1.);
4087                 "%vert_main  = OpFunction %void None %voidf\n"
4088                 "%vert_entry = OpLabel\n"
4089                 "%position   = OpAccessChain %vec4ptr %vert_builtins %zero\n"
4090                 "              OpStore %position %c_vec4_1\n"
4091                 "              OpReturn\n"
4092                 "              OpFunctionEnd\n"
4093
4094                 // Double inputs.
4095                 "%comp_main1  = OpFunction %void None %voidf\n"
4096                 "%comp1_entry = OpLabel\n"
4097                 "%idval1      = OpLoad %uvec3 %id\n"
4098                 "%x1          = OpCompositeExtract %u32 %idval1 0\n"
4099                 "%inloc1      = OpAccessChain %f32ptr %indata %zero %x1\n"
4100                 "%inval1      = OpLoad %f32 %inloc1\n"
4101                 "%add         = OpFAdd %f32 %inval1 %inval1\n"
4102                 "%outloc1     = OpAccessChain %f32ptr %outdata %zero %x1\n"
4103                 "               OpStore %outloc1 %add\n"
4104                 "               OpReturn\n"
4105                 "               OpFunctionEnd\n"
4106
4107                 // Negate inputs.
4108                 "%comp_main2  = OpFunction %void None %voidf\n"
4109                 "%comp2_entry = OpLabel\n"
4110                 "%idval2      = OpLoad %uvec3 %id\n"
4111                 "%x2          = OpCompositeExtract %u32 %idval2 0\n"
4112                 "%inloc2      = OpAccessChain %f32ptr %indata %zero %x2\n"
4113                 "%inval2      = OpLoad %f32 %inloc2\n"
4114                 "%neg         = OpFNegate %f32 %inval2\n"
4115                 "%outloc2     = OpAccessChain %f32ptr %outdata %zero %x2\n"
4116                 "               OpStore %outloc2 %neg\n"
4117                 "               OpReturn\n"
4118                 "               OpFunctionEnd\n");
4119
4120         spec1.assembly = assembly;
4121         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4122         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
4123         spec1.numWorkGroups = IVec3(numElements, 1, 1);
4124         spec1.entryPoint = "entrypoint1";
4125
4126         spec2.assembly = assembly;
4127         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4128         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
4129         spec2.numWorkGroups = IVec3(numElements, 1, 1);
4130         spec2.entryPoint = "entrypoint2";
4131
4132         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader1", "multiple shaders in the same module", spec1));
4133         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader2", "multiple shaders in the same module", spec2));
4134
4135         return group.release();
4136 }
4137
4138 inline std::string makeLongUTF8String (size_t num4ByteChars)
4139 {
4140         // An example of a longest valid UTF-8 character.  Be explicit about the
4141         // character type because Microsoft compilers can otherwise interpret the
4142         // character string as being over wide (16-bit) characters. Ideally, we
4143         // would just use a C++11 UTF-8 string literal, but we want to support older
4144         // Microsoft compilers.
4145         const std::basic_string<char> earthAfrica("\xF0\x9F\x8C\x8D");
4146         std::string longString;
4147         longString.reserve(num4ByteChars * 4);
4148         for (size_t count = 0; count < num4ByteChars; count++)
4149         {
4150                 longString += earthAfrica;
4151         }
4152         return longString;
4153 }
4154
4155 tcu::TestCaseGroup* createOpSourceGroup (tcu::TestContext& testCtx)
4156 {
4157         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsource", "Tests the OpSource & OpSourceContinued instruction"));
4158         vector<CaseParameter>                   cases;
4159         de::Random                                              rnd                             (deStringHash(group->getName()));
4160         const int                                               numElements             = 100;
4161         vector<float>                                   positiveFloats  (numElements, 0);
4162         vector<float>                                   negativeFloats  (numElements, 0);
4163         const StringTemplate                    shaderTemplate  (
4164                 "OpCapability Shader\n"
4165                 "OpMemoryModel Logical GLSL450\n"
4166
4167                 "OpEntryPoint GLCompute %main \"main\" %id\n"
4168                 "OpExecutionMode %main LocalSize 1 1 1\n"
4169
4170                 "${SOURCE}\n"
4171
4172                 "OpName %main           \"main\"\n"
4173                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4174
4175                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4176
4177                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4178
4179                 "%id        = OpVariable %uvec3ptr Input\n"
4180                 "%zero      = OpConstant %i32 0\n"
4181
4182                 "%main      = OpFunction %void None %voidf\n"
4183                 "%label     = OpLabel\n"
4184                 "%idval     = OpLoad %uvec3 %id\n"
4185                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4186                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4187                 "%inval     = OpLoad %f32 %inloc\n"
4188                 "%neg       = OpFNegate %f32 %inval\n"
4189                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4190                 "             OpStore %outloc %neg\n"
4191                 "             OpReturn\n"
4192                 "             OpFunctionEnd\n");
4193
4194         cases.push_back(CaseParameter("unknown_source",                                                 "OpSource Unknown 0"));
4195         cases.push_back(CaseParameter("wrong_source",                                                   "OpSource OpenCL_C 210"));
4196         cases.push_back(CaseParameter("normal_filename",                                                "%fname = OpString \"filename\"\n"
4197                                                                                                                                                         "OpSource GLSL 430 %fname"));
4198         cases.push_back(CaseParameter("empty_filename",                                                 "%fname = OpString \"\"\n"
4199                                                                                                                                                         "OpSource GLSL 430 %fname"));
4200         cases.push_back(CaseParameter("normal_source_code",                                             "%fname = OpString \"filename\"\n"
4201                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\""));
4202         cases.push_back(CaseParameter("empty_source_code",                                              "%fname = OpString \"filename\"\n"
4203                                                                                                                                                         "OpSource GLSL 430 %fname \"\""));
4204         cases.push_back(CaseParameter("long_source_code",                                               "%fname = OpString \"filename\"\n"
4205                                                                                                                                                         "OpSource GLSL 430 %fname \"" + makeLongUTF8String(65530) + "ccc\"")); // word count: 65535
4206         cases.push_back(CaseParameter("utf8_source_code",                                               "%fname = OpString \"filename\"\n"
4207                                                                                                                                                         "OpSource GLSL 430 %fname \"\xE2\x98\x82\xE2\x98\x85\"")); // umbrella & black star symbol
4208         cases.push_back(CaseParameter("normal_sourcecontinued",                                 "%fname = OpString \"filename\"\n"
4209                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvo\"\n"
4210                                                                                                                                                         "OpSourceContinued \"id main() {}\""));
4211         cases.push_back(CaseParameter("empty_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
4212                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4213                                                                                                                                                         "OpSourceContinued \"\""));
4214         cases.push_back(CaseParameter("long_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
4215                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4216                                                                                                                                                         "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\"")); // word count: 65535
4217         cases.push_back(CaseParameter("utf8_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
4218                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4219                                                                                                                                                         "OpSourceContinued \"\xE2\x98\x8E\xE2\x9A\x91\"")); // white telephone & black flag symbol
4220         cases.push_back(CaseParameter("multi_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
4221                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\n\"\n"
4222                                                                                                                                                         "OpSourceContinued \"void\"\n"
4223                                                                                                                                                         "OpSourceContinued \"main()\"\n"
4224                                                                                                                                                         "OpSourceContinued \"{}\""));
4225         cases.push_back(CaseParameter("empty_source_before_sourcecontinued",    "%fname = OpString \"filename\"\n"
4226                                                                                                                                                         "OpSource GLSL 430 %fname \"\"\n"
4227                                                                                                                                                         "OpSourceContinued \"#version 430\nvoid main() {}\""));
4228
4229         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4230
4231         for (size_t ndx = 0; ndx < numElements; ++ndx)
4232                 negativeFloats[ndx] = -positiveFloats[ndx];
4233
4234         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4235         {
4236                 map<string, string>             specializations;
4237                 ComputeShaderSpec               spec;
4238
4239                 specializations["SOURCE"] = cases[caseNdx].param;
4240                 spec.assembly = shaderTemplate.specialize(specializations);
4241                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4242                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4243                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4244
4245                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4246         }
4247
4248         return group.release();
4249 }
4250
4251 tcu::TestCaseGroup* createOpSourceExtensionGroup (tcu::TestContext& testCtx)
4252 {
4253         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsourceextension", "Tests the OpSource instruction"));
4254         vector<CaseParameter>                   cases;
4255         de::Random                                              rnd                             (deStringHash(group->getName()));
4256         const int                                               numElements             = 100;
4257         vector<float>                                   inputFloats             (numElements, 0);
4258         vector<float>                                   outputFloats    (numElements, 0);
4259         const StringTemplate                    shaderTemplate  (
4260                 string(getComputeAsmShaderPreamble()) +
4261
4262                 "OpSourceExtension \"${EXTENSION}\"\n"
4263
4264                 "OpName %main           \"main\"\n"
4265                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4266
4267                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4268
4269                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4270
4271                 "%id        = OpVariable %uvec3ptr Input\n"
4272                 "%zero      = OpConstant %i32 0\n"
4273
4274                 "%main      = OpFunction %void None %voidf\n"
4275                 "%label     = OpLabel\n"
4276                 "%idval     = OpLoad %uvec3 %id\n"
4277                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4278                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4279                 "%inval     = OpLoad %f32 %inloc\n"
4280                 "%neg       = OpFNegate %f32 %inval\n"
4281                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4282                 "             OpStore %outloc %neg\n"
4283                 "             OpReturn\n"
4284                 "             OpFunctionEnd\n");
4285
4286         cases.push_back(CaseParameter("empty_extension",        ""));
4287         cases.push_back(CaseParameter("real_extension",         "GL_ARB_texture_rectangle"));
4288         cases.push_back(CaseParameter("fake_extension",         "GL_ARB_im_the_ultimate_extension"));
4289         cases.push_back(CaseParameter("utf8_extension",         "GL_ARB_\xE2\x98\x82\xE2\x98\x85"));
4290         cases.push_back(CaseParameter("long_extension",         makeLongUTF8String(65533) + "ccc")); // word count: 65535
4291
4292         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
4293
4294         for (size_t ndx = 0; ndx < numElements; ++ndx)
4295                 outputFloats[ndx] = -inputFloats[ndx];
4296
4297         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4298         {
4299                 map<string, string>             specializations;
4300                 ComputeShaderSpec               spec;
4301
4302                 specializations["EXTENSION"] = cases[caseNdx].param;
4303                 spec.assembly = shaderTemplate.specialize(specializations);
4304                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4305                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
4306                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4307
4308                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4309         }
4310
4311         return group.release();
4312 }
4313
4314 // Checks that a compute shader can generate a constant null value of various types, without exercising a computation on it.
4315 tcu::TestCaseGroup* createOpConstantNullGroup (tcu::TestContext& testCtx)
4316 {
4317         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnull", "Tests the OpConstantNull instruction"));
4318         vector<CaseParameter>                   cases;
4319         de::Random                                              rnd                             (deStringHash(group->getName()));
4320         const int                                               numElements             = 100;
4321         vector<float>                                   positiveFloats  (numElements, 0);
4322         vector<float>                                   negativeFloats  (numElements, 0);
4323         const StringTemplate                    shaderTemplate  (
4324                 string(getComputeAsmShaderPreamble()) +
4325
4326                 "OpSource GLSL 430\n"
4327                 "OpName %main           \"main\"\n"
4328                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4329
4330                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4331
4332                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4333                 "%uvec2     = OpTypeVector %u32 2\n"
4334                 "%bvec3     = OpTypeVector %bool 3\n"
4335                 "%fvec4     = OpTypeVector %f32 4\n"
4336                 "%fmat33    = OpTypeMatrix %fvec3 3\n"
4337                 "%const100  = OpConstant %u32 100\n"
4338                 "%uarr100   = OpTypeArray %i32 %const100\n"
4339                 "%struct    = OpTypeStruct %f32 %i32 %u32\n"
4340                 "%pointer   = OpTypePointer Function %i32\n"
4341                 + string(getComputeAsmInputOutputBuffer()) +
4342
4343                 "%null      = OpConstantNull ${TYPE}\n"
4344
4345                 "%id        = OpVariable %uvec3ptr Input\n"
4346                 "%zero      = OpConstant %i32 0\n"
4347
4348                 "%main      = OpFunction %void None %voidf\n"
4349                 "%label     = OpLabel\n"
4350                 "%idval     = OpLoad %uvec3 %id\n"
4351                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4352                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4353                 "%inval     = OpLoad %f32 %inloc\n"
4354                 "%neg       = OpFNegate %f32 %inval\n"
4355                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4356                 "             OpStore %outloc %neg\n"
4357                 "             OpReturn\n"
4358                 "             OpFunctionEnd\n");
4359
4360         cases.push_back(CaseParameter("bool",                   "%bool"));
4361         cases.push_back(CaseParameter("sint32",                 "%i32"));
4362         cases.push_back(CaseParameter("uint32",                 "%u32"));
4363         cases.push_back(CaseParameter("float32",                "%f32"));
4364         cases.push_back(CaseParameter("vec4float32",    "%fvec4"));
4365         cases.push_back(CaseParameter("vec3bool",               "%bvec3"));
4366         cases.push_back(CaseParameter("vec2uint32",             "%uvec2"));
4367         cases.push_back(CaseParameter("matrix",                 "%fmat33"));
4368         cases.push_back(CaseParameter("array",                  "%uarr100"));
4369         cases.push_back(CaseParameter("struct",                 "%struct"));
4370         cases.push_back(CaseParameter("pointer",                "%pointer"));
4371
4372         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4373
4374         for (size_t ndx = 0; ndx < numElements; ++ndx)
4375                 negativeFloats[ndx] = -positiveFloats[ndx];
4376
4377         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4378         {
4379                 map<string, string>             specializations;
4380                 ComputeShaderSpec               spec;
4381
4382                 specializations["TYPE"] = cases[caseNdx].param;
4383                 spec.assembly = shaderTemplate.specialize(specializations);
4384                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4385                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4386                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4387
4388                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4389         }
4390
4391         return group.release();
4392 }
4393
4394 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
4395 tcu::TestCaseGroup* createOpConstantCompositeGroup (tcu::TestContext& testCtx)
4396 {
4397         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "Tests the OpConstantComposite instruction"));
4398         vector<CaseParameter>                   cases;
4399         de::Random                                              rnd                             (deStringHash(group->getName()));
4400         const int                                               numElements             = 100;
4401         vector<float>                                   positiveFloats  (numElements, 0);
4402         vector<float>                                   negativeFloats  (numElements, 0);
4403         const StringTemplate                    shaderTemplate  (
4404                 string(getComputeAsmShaderPreamble()) +
4405
4406                 "OpSource GLSL 430\n"
4407                 "OpName %main           \"main\"\n"
4408                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4409
4410                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4411
4412                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4413
4414                 "%id        = OpVariable %uvec3ptr Input\n"
4415                 "%zero      = OpConstant %i32 0\n"
4416
4417                 "${CONSTANT}\n"
4418
4419                 "%main      = OpFunction %void None %voidf\n"
4420                 "%label     = OpLabel\n"
4421                 "%idval     = OpLoad %uvec3 %id\n"
4422                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4423                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4424                 "%inval     = OpLoad %f32 %inloc\n"
4425                 "%neg       = OpFNegate %f32 %inval\n"
4426                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4427                 "             OpStore %outloc %neg\n"
4428                 "             OpReturn\n"
4429                 "             OpFunctionEnd\n");
4430
4431         cases.push_back(CaseParameter("vector",                 "%five = OpConstant %u32 5\n"
4432                                                                                                         "%const = OpConstantComposite %uvec3 %five %zero %five"));
4433         cases.push_back(CaseParameter("matrix",                 "%m3fvec3 = OpTypeMatrix %fvec3 3\n"
4434                                                                                                         "%ten = OpConstant %f32 10.\n"
4435                                                                                                         "%fzero = OpConstant %f32 0.\n"
4436                                                                                                         "%vec = OpConstantComposite %fvec3 %ten %fzero %ten\n"
4437                                                                                                         "%mat = OpConstantComposite %m3fvec3 %vec %vec %vec"));
4438         cases.push_back(CaseParameter("struct",                 "%m2vec3 = OpTypeMatrix %fvec3 2\n"
4439                                                                                                         "%struct = OpTypeStruct %i32 %f32 %fvec3 %m2vec3\n"
4440                                                                                                         "%fzero = OpConstant %f32 0.\n"
4441                                                                                                         "%one = OpConstant %f32 1.\n"
4442                                                                                                         "%point5 = OpConstant %f32 0.5\n"
4443                                                                                                         "%vec = OpConstantComposite %fvec3 %one %one %fzero\n"
4444                                                                                                         "%mat = OpConstantComposite %m2vec3 %vec %vec\n"
4445                                                                                                         "%const = OpConstantComposite %struct %zero %point5 %vec %mat"));
4446         cases.push_back(CaseParameter("nested_struct",  "%st1 = OpTypeStruct %u32 %f32\n"
4447                                                                                                         "%st2 = OpTypeStruct %i32 %i32\n"
4448                                                                                                         "%struct = OpTypeStruct %st1 %st2\n"
4449                                                                                                         "%point5 = OpConstant %f32 0.5\n"
4450                                                                                                         "%one = OpConstant %u32 1\n"
4451                                                                                                         "%ten = OpConstant %i32 10\n"
4452                                                                                                         "%st1val = OpConstantComposite %st1 %one %point5\n"
4453                                                                                                         "%st2val = OpConstantComposite %st2 %ten %ten\n"
4454                                                                                                         "%const = OpConstantComposite %struct %st1val %st2val"));
4455
4456         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4457
4458         for (size_t ndx = 0; ndx < numElements; ++ndx)
4459                 negativeFloats[ndx] = -positiveFloats[ndx];
4460
4461         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4462         {
4463                 map<string, string>             specializations;
4464                 ComputeShaderSpec               spec;
4465
4466                 specializations["CONSTANT"] = cases[caseNdx].param;
4467                 spec.assembly = shaderTemplate.specialize(specializations);
4468                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4469                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4470                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4471
4472                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4473         }
4474
4475         return group.release();
4476 }
4477
4478 // Creates a floating point number with the given exponent, and significand
4479 // bits set. It can only create normalized numbers. Only the least significant
4480 // 24 bits of the significand will be examined. The final bit of the
4481 // significand will also be ignored. This allows alignment to be written
4482 // similarly to C99 hex-floats.
4483 // For example if you wanted to write 0x1.7f34p-12 you would call
4484 // constructNormalizedFloat(-12, 0x7f3400)
4485 float constructNormalizedFloat (deInt32 exponent, deUint32 significand)
4486 {
4487         float f = 1.0f;
4488
4489         for (deInt32 idx = 0; idx < 23; ++idx)
4490         {
4491                 f += ((significand & 0x800000) == 0) ? 0.f : std::ldexp(1.0f, -(idx + 1));
4492                 significand <<= 1;
4493         }
4494
4495         return std::ldexp(f, exponent);
4496 }
4497
4498 // Compare instruction for the OpQuantizeF16 compute exact case.
4499 // Returns true if the output is what is expected from the test case.
4500 bool compareOpQuantizeF16ComputeExactCase (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
4501 {
4502         if (outputAllocs.size() != 1)
4503                 return false;
4504
4505         // Only size is needed because we cannot compare Nans.
4506         size_t byteSize = expectedOutputs[0].getByteSize();
4507
4508         const float*    outputAsFloat   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
4509
4510         if (byteSize != 4*sizeof(float)) {
4511                 return false;
4512         }
4513
4514         if (*outputAsFloat != constructNormalizedFloat(8, 0x304000) &&
4515                 *outputAsFloat != constructNormalizedFloat(8, 0x300000)) {
4516                 return false;
4517         }
4518         outputAsFloat++;
4519
4520         if (*outputAsFloat != -constructNormalizedFloat(-7, 0x600000) &&
4521                 *outputAsFloat != -constructNormalizedFloat(-7, 0x604000)) {
4522                 return false;
4523         }
4524         outputAsFloat++;
4525
4526         if (*outputAsFloat != constructNormalizedFloat(2, 0x01C000) &&
4527                 *outputAsFloat != constructNormalizedFloat(2, 0x020000)) {
4528                 return false;
4529         }
4530         outputAsFloat++;
4531
4532         if (*outputAsFloat != constructNormalizedFloat(1, 0xFFC000) &&
4533                 *outputAsFloat != constructNormalizedFloat(2, 0x000000)) {
4534                 return false;
4535         }
4536
4537         return true;
4538 }
4539
4540 // Checks that every output from a test-case is a float NaN.
4541 bool compareNan (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
4542 {
4543         if (outputAllocs.size() != 1)
4544                 return false;
4545
4546         // Only size is needed because we cannot compare Nans.
4547         size_t byteSize = expectedOutputs[0].getByteSize();
4548
4549         const float* const      output_as_float = static_cast<const float*>(outputAllocs[0]->getHostPtr());
4550
4551         for (size_t idx = 0; idx < byteSize / sizeof(float); ++idx)
4552         {
4553                 if (!deFloatIsNaN(output_as_float[idx]))
4554                 {
4555                         return false;
4556                 }
4557         }
4558
4559         return true;
4560 }
4561
4562 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
4563 tcu::TestCaseGroup* createOpQuantizeToF16Group (tcu::TestContext& testCtx)
4564 {
4565         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opquantize", "Tests the OpQuantizeToF16 instruction"));
4566
4567         const std::string shader (
4568                 string(getComputeAsmShaderPreamble()) +
4569
4570                 "OpSource GLSL 430\n"
4571                 "OpName %main           \"main\"\n"
4572                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4573
4574                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4575
4576                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4577
4578                 "%id        = OpVariable %uvec3ptr Input\n"
4579                 "%zero      = OpConstant %i32 0\n"
4580
4581                 "%main      = OpFunction %void None %voidf\n"
4582                 "%label     = OpLabel\n"
4583                 "%idval     = OpLoad %uvec3 %id\n"
4584                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4585                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4586                 "%inval     = OpLoad %f32 %inloc\n"
4587                 "%quant     = OpQuantizeToF16 %f32 %inval\n"
4588                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4589                 "             OpStore %outloc %quant\n"
4590                 "             OpReturn\n"
4591                 "             OpFunctionEnd\n");
4592
4593         {
4594                 ComputeShaderSpec       spec;
4595                 const deUint32          numElements             = 100;
4596                 vector<float>           infinities;
4597                 vector<float>           results;
4598
4599                 infinities.reserve(numElements);
4600                 results.reserve(numElements);
4601
4602                 for (size_t idx = 0; idx < numElements; ++idx)
4603                 {
4604                         switch(idx % 4)
4605                         {
4606                                 case 0:
4607                                         infinities.push_back(std::numeric_limits<float>::infinity());
4608                                         results.push_back(std::numeric_limits<float>::infinity());
4609                                         break;
4610                                 case 1:
4611                                         infinities.push_back(-std::numeric_limits<float>::infinity());
4612                                         results.push_back(-std::numeric_limits<float>::infinity());
4613                                         break;
4614                                 case 2:
4615                                         infinities.push_back(std::ldexp(1.0f, 16));
4616                                         results.push_back(std::numeric_limits<float>::infinity());
4617                                         break;
4618                                 case 3:
4619                                         infinities.push_back(std::ldexp(-1.0f, 32));
4620                                         results.push_back(-std::numeric_limits<float>::infinity());
4621                                         break;
4622                         }
4623                 }
4624
4625                 spec.assembly = shader;
4626                 spec.inputs.push_back(BufferSp(new Float32Buffer(infinities)));
4627                 spec.outputs.push_back(BufferSp(new Float32Buffer(results)));
4628                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4629
4630                 group->addChild(new SpvAsmComputeShaderCase(
4631                         testCtx, "infinities", "Check that infinities propagated and created", spec));
4632         }
4633
4634         {
4635                 ComputeShaderSpec       spec;
4636                 vector<float>           nans;
4637                 const deUint32          numElements             = 100;
4638
4639                 nans.reserve(numElements);
4640
4641                 for (size_t idx = 0; idx < numElements; ++idx)
4642                 {
4643                         if (idx % 2 == 0)
4644                         {
4645                                 nans.push_back(std::numeric_limits<float>::quiet_NaN());
4646                         }
4647                         else
4648                         {
4649                                 nans.push_back(-std::numeric_limits<float>::quiet_NaN());
4650                         }
4651                 }
4652
4653                 spec.assembly = shader;
4654                 spec.inputs.push_back(BufferSp(new Float32Buffer(nans)));
4655                 spec.outputs.push_back(BufferSp(new Float32Buffer(nans)));
4656                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4657                 spec.verifyIO = &compareNan;
4658
4659                 group->addChild(new SpvAsmComputeShaderCase(
4660                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
4661         }
4662
4663         {
4664                 ComputeShaderSpec       spec;
4665                 vector<float>           small;
4666                 vector<float>           zeros;
4667                 const deUint32          numElements             = 100;
4668
4669                 small.reserve(numElements);
4670                 zeros.reserve(numElements);
4671
4672                 for (size_t idx = 0; idx < numElements; ++idx)
4673                 {
4674                         switch(idx % 6)
4675                         {
4676                                 case 0:
4677                                         small.push_back(0.f);
4678                                         zeros.push_back(0.f);
4679                                         break;
4680                                 case 1:
4681                                         small.push_back(-0.f);
4682                                         zeros.push_back(-0.f);
4683                                         break;
4684                                 case 2:
4685                                         small.push_back(std::ldexp(1.0f, -16));
4686                                         zeros.push_back(0.f);
4687                                         break;
4688                                 case 3:
4689                                         small.push_back(std::ldexp(-1.0f, -32));
4690                                         zeros.push_back(-0.f);
4691                                         break;
4692                                 case 4:
4693                                         small.push_back(std::ldexp(1.0f, -127));
4694                                         zeros.push_back(0.f);
4695                                         break;
4696                                 case 5:
4697                                         small.push_back(-std::ldexp(1.0f, -128));
4698                                         zeros.push_back(-0.f);
4699                                         break;
4700                         }
4701                 }
4702
4703                 spec.assembly = shader;
4704                 spec.inputs.push_back(BufferSp(new Float32Buffer(small)));
4705                 spec.outputs.push_back(BufferSp(new Float32Buffer(zeros)));
4706                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4707
4708                 group->addChild(new SpvAsmComputeShaderCase(
4709                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
4710         }
4711
4712         {
4713                 ComputeShaderSpec       spec;
4714                 vector<float>           exact;
4715                 const deUint32          numElements             = 200;
4716
4717                 exact.reserve(numElements);
4718
4719                 for (size_t idx = 0; idx < numElements; ++idx)
4720                         exact.push_back(static_cast<float>(static_cast<int>(idx) - 100));
4721
4722                 spec.assembly = shader;
4723                 spec.inputs.push_back(BufferSp(new Float32Buffer(exact)));
4724                 spec.outputs.push_back(BufferSp(new Float32Buffer(exact)));
4725                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4726
4727                 group->addChild(new SpvAsmComputeShaderCase(
4728                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
4729         }
4730
4731         {
4732                 ComputeShaderSpec       spec;
4733                 vector<float>           inputs;
4734                 const deUint32          numElements             = 4;
4735
4736                 inputs.push_back(constructNormalizedFloat(8,    0x300300));
4737                 inputs.push_back(-constructNormalizedFloat(-7,  0x600800));
4738                 inputs.push_back(constructNormalizedFloat(2,    0x01E000));
4739                 inputs.push_back(constructNormalizedFloat(1,    0xFFE000));
4740
4741                 spec.assembly = shader;
4742                 spec.verifyIO = &compareOpQuantizeF16ComputeExactCase;
4743                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4744                 spec.outputs.push_back(BufferSp(new Float32Buffer(inputs)));
4745                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4746
4747                 group->addChild(new SpvAsmComputeShaderCase(
4748                         testCtx, "rounded", "Check that are rounded when needed", spec));
4749         }
4750
4751         return group.release();
4752 }
4753
4754 tcu::TestCaseGroup* createSpecConstantOpQuantizeToF16Group (tcu::TestContext& testCtx)
4755 {
4756         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opspecconstantop_opquantize", "Tests the OpQuantizeToF16 opcode for the OpSpecConstantOp instruction"));
4757
4758         const std::string shader (
4759                 string(getComputeAsmShaderPreamble()) +
4760
4761                 "OpName %main           \"main\"\n"
4762                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4763
4764                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4765
4766                 "OpDecorate %sc_0  SpecId 0\n"
4767                 "OpDecorate %sc_1  SpecId 1\n"
4768                 "OpDecorate %sc_2  SpecId 2\n"
4769                 "OpDecorate %sc_3  SpecId 3\n"
4770                 "OpDecorate %sc_4  SpecId 4\n"
4771                 "OpDecorate %sc_5  SpecId 5\n"
4772
4773                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4774
4775                 "%id        = OpVariable %uvec3ptr Input\n"
4776                 "%zero      = OpConstant %i32 0\n"
4777                 "%c_u32_6   = OpConstant %u32 6\n"
4778
4779                 "%sc_0      = OpSpecConstant %f32 0.\n"
4780                 "%sc_1      = OpSpecConstant %f32 0.\n"
4781                 "%sc_2      = OpSpecConstant %f32 0.\n"
4782                 "%sc_3      = OpSpecConstant %f32 0.\n"
4783                 "%sc_4      = OpSpecConstant %f32 0.\n"
4784                 "%sc_5      = OpSpecConstant %f32 0.\n"
4785
4786                 "%sc_0_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_0\n"
4787                 "%sc_1_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_1\n"
4788                 "%sc_2_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_2\n"
4789                 "%sc_3_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_3\n"
4790                 "%sc_4_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_4\n"
4791                 "%sc_5_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_5\n"
4792
4793                 "%main      = OpFunction %void None %voidf\n"
4794                 "%label     = OpLabel\n"
4795                 "%idval     = OpLoad %uvec3 %id\n"
4796                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4797                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4798                 "%selector  = OpUMod %u32 %x %c_u32_6\n"
4799                 "            OpSelectionMerge %exit None\n"
4800                 "            OpSwitch %selector %exit 0 %case0 1 %case1 2 %case2 3 %case3 4 %case4 5 %case5\n"
4801
4802                 "%case0     = OpLabel\n"
4803                 "             OpStore %outloc %sc_0_quant\n"
4804                 "             OpBranch %exit\n"
4805
4806                 "%case1     = OpLabel\n"
4807                 "             OpStore %outloc %sc_1_quant\n"
4808                 "             OpBranch %exit\n"
4809
4810                 "%case2     = OpLabel\n"
4811                 "             OpStore %outloc %sc_2_quant\n"
4812                 "             OpBranch %exit\n"
4813
4814                 "%case3     = OpLabel\n"
4815                 "             OpStore %outloc %sc_3_quant\n"
4816                 "             OpBranch %exit\n"
4817
4818                 "%case4     = OpLabel\n"
4819                 "             OpStore %outloc %sc_4_quant\n"
4820                 "             OpBranch %exit\n"
4821
4822                 "%case5     = OpLabel\n"
4823                 "             OpStore %outloc %sc_5_quant\n"
4824                 "             OpBranch %exit\n"
4825
4826                 "%exit      = OpLabel\n"
4827                 "             OpReturn\n"
4828
4829                 "             OpFunctionEnd\n");
4830
4831         {
4832                 ComputeShaderSpec       spec;
4833                 const deUint8           numCases        = 4;
4834                 vector<float>           inputs          (numCases, 0.f);
4835                 vector<float>           outputs;
4836
4837                 spec.assembly           = shader;
4838                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4839
4840                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::numeric_limits<float>::infinity()));
4841                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-std::numeric_limits<float>::infinity()));
4842                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, 16)));
4843                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(-1.0f, 32)));
4844
4845                 outputs.push_back(std::numeric_limits<float>::infinity());
4846                 outputs.push_back(-std::numeric_limits<float>::infinity());
4847                 outputs.push_back(std::numeric_limits<float>::infinity());
4848                 outputs.push_back(-std::numeric_limits<float>::infinity());
4849
4850                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4851                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4852
4853                 group->addChild(new SpvAsmComputeShaderCase(
4854                         testCtx, "infinities", "Check that infinities propagated and created", spec));
4855         }
4856
4857         {
4858                 ComputeShaderSpec       spec;
4859                 const deUint8           numCases        = 2;
4860                 vector<float>           inputs          (numCases, 0.f);
4861                 vector<float>           outputs;
4862
4863                 spec.assembly           = shader;
4864                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4865                 spec.verifyIO           = &compareNan;
4866
4867                 outputs.push_back(std::numeric_limits<float>::quiet_NaN());
4868                 outputs.push_back(-std::numeric_limits<float>::quiet_NaN());
4869
4870                 for (deUint8 idx = 0; idx < numCases; ++idx)
4871                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(outputs[idx]));
4872
4873                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4874                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4875
4876                 group->addChild(new SpvAsmComputeShaderCase(
4877                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
4878         }
4879
4880         {
4881                 ComputeShaderSpec       spec;
4882                 const deUint8           numCases        = 6;
4883                 vector<float>           inputs          (numCases, 0.f);
4884                 vector<float>           outputs;
4885
4886                 spec.assembly           = shader;
4887                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4888
4889                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(0.f));
4890                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-0.f));
4891                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, -16)));
4892                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(-1.0f, -32)));
4893                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, -127)));
4894                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-std::ldexp(1.0f, -128)));
4895
4896                 outputs.push_back(0.f);
4897                 outputs.push_back(-0.f);
4898                 outputs.push_back(0.f);
4899                 outputs.push_back(-0.f);
4900                 outputs.push_back(0.f);
4901                 outputs.push_back(-0.f);
4902
4903                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4904                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4905
4906                 group->addChild(new SpvAsmComputeShaderCase(
4907                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
4908         }
4909
4910         {
4911                 ComputeShaderSpec       spec;
4912                 const deUint8           numCases        = 6;
4913                 vector<float>           inputs          (numCases, 0.f);
4914                 vector<float>           outputs;
4915
4916                 spec.assembly           = shader;
4917                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4918
4919                 for (deUint8 idx = 0; idx < 6; ++idx)
4920                 {
4921                         const float f = static_cast<float>(idx * 10 - 30) / 4.f;
4922                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(f));
4923                         outputs.push_back(f);
4924                 }
4925
4926                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4927                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4928
4929                 group->addChild(new SpvAsmComputeShaderCase(
4930                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
4931         }
4932
4933         {
4934                 ComputeShaderSpec       spec;
4935                 const deUint8           numCases        = 4;
4936                 vector<float>           inputs          (numCases, 0.f);
4937                 vector<float>           outputs;
4938
4939                 spec.assembly           = shader;
4940                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4941                 spec.verifyIO           = &compareOpQuantizeF16ComputeExactCase;
4942
4943                 outputs.push_back(constructNormalizedFloat(8, 0x300300));
4944                 outputs.push_back(-constructNormalizedFloat(-7, 0x600800));
4945                 outputs.push_back(constructNormalizedFloat(2, 0x01E000));
4946                 outputs.push_back(constructNormalizedFloat(1, 0xFFE000));
4947
4948                 for (deUint8 idx = 0; idx < numCases; ++idx)
4949                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(outputs[idx]));
4950
4951                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4952                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4953
4954                 group->addChild(new SpvAsmComputeShaderCase(
4955                         testCtx, "rounded", "Check that are rounded when needed", spec));
4956         }
4957
4958         return group.release();
4959 }
4960
4961 // Checks that constant null/composite values can be used in computation.
4962 tcu::TestCaseGroup* createOpConstantUsageGroup (tcu::TestContext& testCtx)
4963 {
4964         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnullcomposite", "Spotcheck the OpConstantNull & OpConstantComposite instruction"));
4965         ComputeShaderSpec                               spec;
4966         de::Random                                              rnd                             (deStringHash(group->getName()));
4967         const int                                               numElements             = 100;
4968         vector<float>                                   positiveFloats  (numElements, 0);
4969         vector<float>                                   negativeFloats  (numElements, 0);
4970
4971         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4972
4973         for (size_t ndx = 0; ndx < numElements; ++ndx)
4974                 negativeFloats[ndx] = -positiveFloats[ndx];
4975
4976         spec.assembly =
4977                 "OpCapability Shader\n"
4978                 "%std450 = OpExtInstImport \"GLSL.std.450\"\n"
4979                 "OpMemoryModel Logical GLSL450\n"
4980                 "OpEntryPoint GLCompute %main \"main\" %id\n"
4981                 "OpExecutionMode %main LocalSize 1 1 1\n"
4982
4983                 "OpSource GLSL 430\n"
4984                 "OpName %main           \"main\"\n"
4985                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4986
4987                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4988
4989                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4990
4991                 "%fmat      = OpTypeMatrix %fvec3 3\n"
4992                 "%ten       = OpConstant %u32 10\n"
4993                 "%f32arr10  = OpTypeArray %f32 %ten\n"
4994                 "%fst       = OpTypeStruct %f32 %f32\n"
4995
4996                 + string(getComputeAsmInputOutputBuffer()) +
4997
4998                 "%id        = OpVariable %uvec3ptr Input\n"
4999                 "%zero      = OpConstant %i32 0\n"
5000
5001                 // Create a bunch of null values
5002                 "%unull     = OpConstantNull %u32\n"
5003                 "%fnull     = OpConstantNull %f32\n"
5004                 "%vnull     = OpConstantNull %fvec3\n"
5005                 "%mnull     = OpConstantNull %fmat\n"
5006                 "%anull     = OpConstantNull %f32arr10\n"
5007                 "%snull     = OpConstantComposite %fst %fnull %fnull\n"
5008
5009                 "%main      = OpFunction %void None %voidf\n"
5010                 "%label     = OpLabel\n"
5011                 "%idval     = OpLoad %uvec3 %id\n"
5012                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5013                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5014                 "%inval     = OpLoad %f32 %inloc\n"
5015                 "%neg       = OpFNegate %f32 %inval\n"
5016
5017                 // Get the abs() of (a certain element of) those null values
5018                 "%unull_cov = OpConvertUToF %f32 %unull\n"
5019                 "%unull_abs = OpExtInst %f32 %std450 FAbs %unull_cov\n"
5020                 "%fnull_abs = OpExtInst %f32 %std450 FAbs %fnull\n"
5021                 "%vnull_0   = OpCompositeExtract %f32 %vnull 0\n"
5022                 "%vnull_abs = OpExtInst %f32 %std450 FAbs %vnull_0\n"
5023                 "%mnull_12  = OpCompositeExtract %f32 %mnull 1 2\n"
5024                 "%mnull_abs = OpExtInst %f32 %std450 FAbs %mnull_12\n"
5025                 "%anull_3   = OpCompositeExtract %f32 %anull 3\n"
5026                 "%anull_abs = OpExtInst %f32 %std450 FAbs %anull_3\n"
5027                 "%snull_1   = OpCompositeExtract %f32 %snull 1\n"
5028                 "%snull_abs = OpExtInst %f32 %std450 FAbs %snull_1\n"
5029
5030                 // Add them all
5031                 "%add1      = OpFAdd %f32 %neg  %unull_abs\n"
5032                 "%add2      = OpFAdd %f32 %add1 %fnull_abs\n"
5033                 "%add3      = OpFAdd %f32 %add2 %vnull_abs\n"
5034                 "%add4      = OpFAdd %f32 %add3 %mnull_abs\n"
5035                 "%add5      = OpFAdd %f32 %add4 %anull_abs\n"
5036                 "%final     = OpFAdd %f32 %add5 %snull_abs\n"
5037
5038                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5039                 "             OpStore %outloc %final\n" // write to output
5040                 "             OpReturn\n"
5041                 "             OpFunctionEnd\n";
5042         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
5043         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
5044         spec.numWorkGroups = IVec3(numElements, 1, 1);
5045
5046         group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "Check that values constructed via OpConstantNull & OpConstantComposite can be used", spec));
5047
5048         return group.release();
5049 }
5050
5051 // Assembly code used for testing loop control is based on GLSL source code:
5052 // #version 430
5053 //
5054 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5055 //   float elements[];
5056 // } input_data;
5057 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5058 //   float elements[];
5059 // } output_data;
5060 //
5061 // void main() {
5062 //   uint x = gl_GlobalInvocationID.x;
5063 //   output_data.elements[x] = input_data.elements[x];
5064 //   for (uint i = 0; i < 4; ++i)
5065 //     output_data.elements[x] += 1.f;
5066 // }
5067 tcu::TestCaseGroup* createLoopControlGroup (tcu::TestContext& testCtx)
5068 {
5069         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "loop_control", "Tests loop control cases"));
5070         vector<CaseParameter>                   cases;
5071         de::Random                                              rnd                             (deStringHash(group->getName()));
5072         const int                                               numElements             = 100;
5073         vector<float>                                   inputFloats             (numElements, 0);
5074         vector<float>                                   outputFloats    (numElements, 0);
5075         const StringTemplate                    shaderTemplate  (
5076                 string(getComputeAsmShaderPreamble()) +
5077
5078                 "OpSource GLSL 430\n"
5079                 "OpName %main \"main\"\n"
5080                 "OpName %id \"gl_GlobalInvocationID\"\n"
5081
5082                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5083
5084                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5085
5086                 "%u32ptr      = OpTypePointer Function %u32\n"
5087
5088                 "%id          = OpVariable %uvec3ptr Input\n"
5089                 "%zero        = OpConstant %i32 0\n"
5090                 "%uzero       = OpConstant %u32 0\n"
5091                 "%one         = OpConstant %i32 1\n"
5092                 "%constf1     = OpConstant %f32 1.0\n"
5093                 "%four        = OpConstant %u32 4\n"
5094
5095                 "%main        = OpFunction %void None %voidf\n"
5096                 "%entry       = OpLabel\n"
5097                 "%i           = OpVariable %u32ptr Function\n"
5098                 "               OpStore %i %uzero\n"
5099
5100                 "%idval       = OpLoad %uvec3 %id\n"
5101                 "%x           = OpCompositeExtract %u32 %idval 0\n"
5102                 "%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
5103                 "%inval       = OpLoad %f32 %inloc\n"
5104                 "%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
5105                 "               OpStore %outloc %inval\n"
5106                 "               OpBranch %loop_entry\n"
5107
5108                 "%loop_entry  = OpLabel\n"
5109                 "%i_val       = OpLoad %u32 %i\n"
5110                 "%cmp_lt      = OpULessThan %bool %i_val %four\n"
5111                 "               OpLoopMerge %loop_merge %loop_body ${CONTROL}\n"
5112                 "               OpBranchConditional %cmp_lt %loop_body %loop_merge\n"
5113                 "%loop_body   = OpLabel\n"
5114                 "%outval      = OpLoad %f32 %outloc\n"
5115                 "%addf1       = OpFAdd %f32 %outval %constf1\n"
5116                 "               OpStore %outloc %addf1\n"
5117                 "%new_i       = OpIAdd %u32 %i_val %one\n"
5118                 "               OpStore %i %new_i\n"
5119                 "               OpBranch %loop_entry\n"
5120                 "%loop_merge  = OpLabel\n"
5121                 "               OpReturn\n"
5122                 "               OpFunctionEnd\n");
5123
5124         cases.push_back(CaseParameter("none",                           "None"));
5125         cases.push_back(CaseParameter("unroll",                         "Unroll"));
5126         cases.push_back(CaseParameter("dont_unroll",            "DontUnroll"));
5127         cases.push_back(CaseParameter("unroll_dont_unroll",     "Unroll|DontUnroll"));
5128
5129         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5130
5131         for (size_t ndx = 0; ndx < numElements; ++ndx)
5132                 outputFloats[ndx] = inputFloats[ndx] + 4.f;
5133
5134         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5135         {
5136                 map<string, string>             specializations;
5137                 ComputeShaderSpec               spec;
5138
5139                 specializations["CONTROL"] = cases[caseNdx].param;
5140                 spec.assembly = shaderTemplate.specialize(specializations);
5141                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5142                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5143                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5144
5145                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5146         }
5147
5148         group->addChild(new SpvAsmLoopControlDependencyLengthCase(testCtx, "dependency_length", "dependency_length"));
5149         group->addChild(new SpvAsmLoopControlDependencyInfiniteCase(testCtx, "dependency_infinite", "dependency_infinite"));
5150
5151         return group.release();
5152 }
5153
5154 // Assembly code used for testing selection control is based on GLSL source code:
5155 // #version 430
5156 //
5157 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5158 //   float elements[];
5159 // } input_data;
5160 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5161 //   float elements[];
5162 // } output_data;
5163 //
5164 // void main() {
5165 //   uint x = gl_GlobalInvocationID.x;
5166 //   float val = input_data.elements[x];
5167 //   if (val > 10.f)
5168 //     output_data.elements[x] = val + 1.f;
5169 //   else
5170 //     output_data.elements[x] = val - 1.f;
5171 // }
5172 tcu::TestCaseGroup* createSelectionControlGroup (tcu::TestContext& testCtx)
5173 {
5174         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "selection_control", "Tests selection control cases"));
5175         vector<CaseParameter>                   cases;
5176         de::Random                                              rnd                             (deStringHash(group->getName()));
5177         const int                                               numElements             = 100;
5178         vector<float>                                   inputFloats             (numElements, 0);
5179         vector<float>                                   outputFloats    (numElements, 0);
5180         const StringTemplate                    shaderTemplate  (
5181                 string(getComputeAsmShaderPreamble()) +
5182
5183                 "OpSource GLSL 430\n"
5184                 "OpName %main \"main\"\n"
5185                 "OpName %id \"gl_GlobalInvocationID\"\n"
5186
5187                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5188
5189                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5190
5191                 "%id       = OpVariable %uvec3ptr Input\n"
5192                 "%zero     = OpConstant %i32 0\n"
5193                 "%constf1  = OpConstant %f32 1.0\n"
5194                 "%constf10 = OpConstant %f32 10.0\n"
5195
5196                 "%main     = OpFunction %void None %voidf\n"
5197                 "%entry    = OpLabel\n"
5198                 "%idval    = OpLoad %uvec3 %id\n"
5199                 "%x        = OpCompositeExtract %u32 %idval 0\n"
5200                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
5201                 "%inval    = OpLoad %f32 %inloc\n"
5202                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
5203                 "%cmp_gt   = OpFOrdGreaterThan %bool %inval %constf10\n"
5204
5205                 "            OpSelectionMerge %if_end ${CONTROL}\n"
5206                 "            OpBranchConditional %cmp_gt %if_true %if_false\n"
5207                 "%if_true  = OpLabel\n"
5208                 "%addf1    = OpFAdd %f32 %inval %constf1\n"
5209                 "            OpStore %outloc %addf1\n"
5210                 "            OpBranch %if_end\n"
5211                 "%if_false = OpLabel\n"
5212                 "%subf1    = OpFSub %f32 %inval %constf1\n"
5213                 "            OpStore %outloc %subf1\n"
5214                 "            OpBranch %if_end\n"
5215                 "%if_end   = OpLabel\n"
5216                 "            OpReturn\n"
5217                 "            OpFunctionEnd\n");
5218
5219         cases.push_back(CaseParameter("none",                                   "None"));
5220         cases.push_back(CaseParameter("flatten",                                "Flatten"));
5221         cases.push_back(CaseParameter("dont_flatten",                   "DontFlatten"));
5222         cases.push_back(CaseParameter("flatten_dont_flatten",   "DontFlatten|Flatten"));
5223
5224         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5225
5226         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
5227         floorAll(inputFloats);
5228
5229         for (size_t ndx = 0; ndx < numElements; ++ndx)
5230                 outputFloats[ndx] = inputFloats[ndx] + (inputFloats[ndx] > 10.f ? 1.f : -1.f);
5231
5232         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5233         {
5234                 map<string, string>             specializations;
5235                 ComputeShaderSpec               spec;
5236
5237                 specializations["CONTROL"] = cases[caseNdx].param;
5238                 spec.assembly = shaderTemplate.specialize(specializations);
5239                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5240                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5241                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5242
5243                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5244         }
5245
5246         return group.release();
5247 }
5248
5249 void getOpNameAbuseCases (vector<CaseParameter> &abuseCases)
5250 {
5251         // Generate a long name.
5252         std::string longname;
5253         longname.resize(65535, 'k'); // max string literal, spir-v 2.17
5254
5255         // Some bad names, abusing utf-8 encoding. This may also cause problems
5256         // with the logs.
5257         // 1. Various illegal code points in utf-8
5258         std::string utf8illegal =
5259                 "Illegal bytes in UTF-8: "
5260                 "\xc0 \xc1 \xf5 \xf6 \xf7 \xf8 \xf9 \xfa \xfb \xfc \xfd \xfe \xff"
5261                 "illegal surrogates: \xed\xad\xbf \xed\xbe\x80";
5262
5263         // 2. Zero encoded as overlong, not exactly legal but often supported to differentiate from terminating zero
5264         std::string utf8nul = "UTF-8 encoded nul \xC0\x80 (should not end name)";
5265
5266         // 3. Some overlong encodings
5267         std::string utf8overlong =
5268                 "UTF-8 overlong \xF0\x82\x82\xAC \xfc\x83\xbf\xbf\xbf\xbf \xf8\x87\xbf\xbf\xbf "
5269                 "\xf0\x8f\xbf\xbf";
5270
5271         // 4. Internet "zalgo" meme "bleeding text"
5272         std::string utf8zalgo =
5273                 "\x56\xcc\xb5\xcc\x85\xcc\x94\xcc\x88\xcd\x8a\xcc\x91\xcc\x88\xcd\x91\xcc\x83\xcd\x82"
5274                 "\xcc\x83\xcd\x90\xcc\x8a\xcc\x92\xcc\x92\xcd\x8b\xcc\x94\xcd\x9d\xcc\x98\xcc\xab\xcc"
5275                 "\xae\xcc\xa9\xcc\xad\xcc\x97\xcc\xb0\x75\xcc\xb6\xcc\xbe\xcc\x80\xcc\x82\xcc\x84\xcd"
5276                 "\x84\xcc\x90\xcd\x86\xcc\x9a\xcd\x84\xcc\x9b\xcd\x86\xcd\x92\xcc\x9a\xcd\x99\xcd\x99"
5277                 "\xcc\xbb\xcc\x98\xcd\x8e\xcd\x88\xcd\x9a\xcc\xa6\xcc\x9c\xcc\xab\xcc\x99\xcd\x94\xcd"
5278                 "\x99\xcd\x95\xcc\xa5\xcc\xab\xcd\x89\x6c\xcc\xb8\xcc\x8e\xcc\x8b\xcc\x8b\xcc\x9a\xcc"
5279                 "\x8e\xcd\x9d\xcc\x80\xcc\xa1\xcc\xad\xcd\x9c\xcc\xba\xcc\x96\xcc\xb3\xcc\xa2\xcd\x8e"
5280                 "\xcc\xa2\xcd\x96\x6b\xcc\xb8\xcc\x84\xcd\x81\xcc\xbf\xcc\x8d\xcc\x89\xcc\x85\xcc\x92"
5281                 "\xcc\x84\xcc\x90\xcd\x81\xcc\x93\xcd\x90\xcd\x92\xcd\x9d\xcc\x84\xcd\x98\xcd\x9d\xcd"
5282                 "\xa0\xcd\x91\xcc\x94\xcc\xb9\xcd\x93\xcc\xa5\xcd\x87\xcc\xad\xcc\xa7\xcd\x96\xcd\x99"
5283                 "\xcc\x9d\xcc\xbc\xcd\x96\xcd\x93\xcc\x9d\xcc\x99\xcc\xa8\xcc\xb1\xcd\x85\xcc\xba\xcc"
5284                 "\xa7\x61\xcc\xb8\xcc\x8e\xcc\x81\xcd\x90\xcd\x84\xcd\x8c\xcc\x8c\xcc\x85\xcd\x86\xcc"
5285                 "\x84\xcd\x84\xcc\x90\xcc\x84\xcc\x8d\xcd\x99\xcd\x8d\xcc\xb0\xcc\xa3\xcc\xa6\xcd\x89"
5286                 "\xcd\x8d\xcd\x87\xcc\x98\xcd\x8d\xcc\xa4\xcd\x9a\xcd\x8e\xcc\xab\xcc\xb9\xcc\xac\xcc"
5287                 "\xa2\xcd\x87\xcc\xa0\xcc\xb3\xcd\x89\xcc\xb9\xcc\xa7\xcc\xa6\xcd\x89\xcd\x95\x6e\xcc"
5288                 "\xb8\xcd\x8a\xcc\x8a\xcd\x82\xcc\x9b\xcd\x81\xcd\x90\xcc\x85\xcc\x9b\xcd\x80\xcd\x91"
5289                 "\xcd\x9b\xcc\x81\xcd\x81\xcc\x9a\xcc\xb3\xcd\x9c\xcc\x9e\xcc\x9d\xcd\x99\xcc\xa2\xcd"
5290                 "\x93\xcd\x96\xcc\x97\xff";
5291
5292         // General name abuses
5293         abuseCases.push_back(CaseParameter("_has_very_long_name", longname));
5294         abuseCases.push_back(CaseParameter("_utf8_illegal", utf8illegal));
5295         abuseCases.push_back(CaseParameter("_utf8_nul", utf8nul));
5296         abuseCases.push_back(CaseParameter("_utf8_overlong", utf8overlong));
5297         abuseCases.push_back(CaseParameter("_utf8_zalgo", utf8zalgo));
5298
5299         // GL keywords
5300         abuseCases.push_back(CaseParameter("_is_gl_Position", "gl_Position"));
5301         abuseCases.push_back(CaseParameter("_is_gl_InstanceID", "gl_InstanceID"));
5302         abuseCases.push_back(CaseParameter("_is_gl_PrimitiveID", "gl_PrimitiveID"));
5303         abuseCases.push_back(CaseParameter("_is_gl_TessCoord", "gl_TessCoord"));
5304         abuseCases.push_back(CaseParameter("_is_gl_PerVertex", "gl_PerVertex"));
5305         abuseCases.push_back(CaseParameter("_is_gl_InvocationID", "gl_InvocationID"));
5306         abuseCases.push_back(CaseParameter("_is_gl_PointSize", "gl_PointSize"));
5307         abuseCases.push_back(CaseParameter("_is_gl_PointCoord", "gl_PointCoord"));
5308         abuseCases.push_back(CaseParameter("_is_gl_Layer", "gl_Layer"));
5309         abuseCases.push_back(CaseParameter("_is_gl_FragDepth", "gl_FragDepth"));
5310         abuseCases.push_back(CaseParameter("_is_gl_NumWorkGroups", "gl_NumWorkGroups"));
5311         abuseCases.push_back(CaseParameter("_is_gl_WorkGroupID", "gl_WorkGroupID"));
5312         abuseCases.push_back(CaseParameter("_is_gl_LocalInvocationID", "gl_LocalInvocationID"));
5313         abuseCases.push_back(CaseParameter("_is_gl_GlobalInvocationID", "gl_GlobalInvocationID"));
5314         abuseCases.push_back(CaseParameter("_is_gl_MaxVertexAttribs", "gl_MaxVertexAttribs"));
5315         abuseCases.push_back(CaseParameter("_is_gl_MaxViewports", "gl_MaxViewports"));
5316         abuseCases.push_back(CaseParameter("_is_gl_MaxComputeWorkGroupCount", "gl_MaxComputeWorkGroupCount"));
5317         abuseCases.push_back(CaseParameter("_is_mat3", "mat3"));
5318         abuseCases.push_back(CaseParameter("_is_volatile", "volatile"));
5319         abuseCases.push_back(CaseParameter("_is_inout", "inout"));
5320         abuseCases.push_back(CaseParameter("_is_isampler3d", "isampler3d"));
5321 }
5322
5323 tcu::TestCaseGroup* createOpNameGroup (tcu::TestContext& testCtx)
5324 {
5325         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opname", "Tests OpName cases"));
5326         de::MovePtr<tcu::TestCaseGroup> entryMainGroup  (new tcu::TestCaseGroup(testCtx, "entry_main", "OpName tests with entry main"));
5327         de::MovePtr<tcu::TestCaseGroup> entryNotGroup   (new tcu::TestCaseGroup(testCtx, "entry_rdc", "OpName tests with entry rdc"));
5328         de::MovePtr<tcu::TestCaseGroup> abuseGroup              (new tcu::TestCaseGroup(testCtx, "abuse", "OpName abuse tests"));
5329         vector<CaseParameter>                   cases;
5330         vector<CaseParameter>                   abuseCases;
5331         vector<string>                                  testFunc;
5332         de::Random                                              rnd                             (deStringHash(group->getName()));
5333         const int                                               numElements             = 128;
5334         vector<float>                                   inputFloats             (numElements, 0);
5335         vector<float>                                   outputFloats    (numElements, 0);
5336
5337         getOpNameAbuseCases(abuseCases);
5338
5339         fillRandomScalars(rnd, -100.0f, 100.0f, &inputFloats[0], numElements);
5340
5341         for(size_t ndx = 0; ndx < numElements; ++ndx)
5342                 outputFloats[ndx] = -inputFloats[ndx];
5343
5344         const string commonShaderHeader =
5345                 "OpCapability Shader\n"
5346                 "OpMemoryModel Logical GLSL450\n"
5347                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5348                 "OpExecutionMode %main LocalSize 1 1 1\n";
5349
5350         const string commonShaderFooter =
5351                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5352
5353                 + string(getComputeAsmInputOutputBufferTraits())
5354                 + string(getComputeAsmCommonTypes())
5355                 + string(getComputeAsmInputOutputBuffer()) +
5356
5357                 "%id        = OpVariable %uvec3ptr Input\n"
5358                 "%zero      = OpConstant %i32 0\n"
5359
5360                 "%func      = OpFunction %void None %voidf\n"
5361                 "%5         = OpLabel\n"
5362                 "             OpReturn\n"
5363                 "             OpFunctionEnd\n"
5364
5365                 "%main      = OpFunction %void None %voidf\n"
5366                 "%entry     = OpLabel\n"
5367                 "%7         = OpFunctionCall %void %func\n"
5368
5369                 "%idval     = OpLoad %uvec3 %id\n"
5370                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5371
5372                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5373                 "%inval     = OpLoad %f32 %inloc\n"
5374                 "%neg       = OpFNegate %f32 %inval\n"
5375                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5376                 "             OpStore %outloc %neg\n"
5377
5378                 "             OpReturn\n"
5379                 "             OpFunctionEnd\n";
5380
5381         const StringTemplate shaderTemplate (
5382                 "OpCapability Shader\n"
5383                 "OpMemoryModel Logical GLSL450\n"
5384                 "OpEntryPoint GLCompute %main \"${ENTRY}\" %id\n"
5385                 "OpExecutionMode %main LocalSize 1 1 1\n"
5386                 "OpName %${ID} \"${NAME}\"\n" +
5387                 commonShaderFooter);
5388
5389         const std::string multipleNames =
5390                 commonShaderHeader +
5391                 "OpName %main \"to_be\"\n"
5392                 "OpName %id   \"or_not\"\n"
5393                 "OpName %main \"to_be\"\n"
5394                 "OpName %main \"makes_no\"\n"
5395                 "OpName %func \"difference\"\n"
5396                 "OpName %5    \"to_me\"\n" +
5397                 commonShaderFooter;
5398
5399         {
5400                 ComputeShaderSpec       spec;
5401
5402                 spec.assembly           = multipleNames;
5403                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5404                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5405                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5406
5407                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "main_has_multiple_names", "multiple_names", spec));
5408         }
5409
5410         const std::string everythingNamed =
5411                 commonShaderHeader +
5412                 "OpName %main   \"name1\"\n"
5413                 "OpName %id     \"name2\"\n"
5414                 "OpName %zero   \"name3\"\n"
5415                 "OpName %entry  \"name4\"\n"
5416                 "OpName %func   \"name5\"\n"
5417                 "OpName %5      \"name6\"\n"
5418                 "OpName %7      \"name7\"\n"
5419                 "OpName %idval  \"name8\"\n"
5420                 "OpName %inloc  \"name9\"\n"
5421                 "OpName %inval  \"name10\"\n"
5422                 "OpName %neg    \"name11\"\n"
5423                 "OpName %outloc \"name12\"\n"+
5424                 commonShaderFooter;
5425         {
5426                 ComputeShaderSpec       spec;
5427
5428                 spec.assembly           = everythingNamed;
5429                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5430                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5431                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5432
5433                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named", "everything_named", spec));
5434         }
5435
5436         const std::string everythingNamedTheSame =
5437                 commonShaderHeader +
5438                 "OpName %main   \"the_same\"\n"
5439                 "OpName %id     \"the_same\"\n"
5440                 "OpName %zero   \"the_same\"\n"
5441                 "OpName %entry  \"the_same\"\n"
5442                 "OpName %func   \"the_same\"\n"
5443                 "OpName %5      \"the_same\"\n"
5444                 "OpName %7      \"the_same\"\n"
5445                 "OpName %idval  \"the_same\"\n"
5446                 "OpName %inloc  \"the_same\"\n"
5447                 "OpName %inval  \"the_same\"\n"
5448                 "OpName %neg    \"the_same\"\n"
5449                 "OpName %outloc \"the_same\"\n"+
5450                 commonShaderFooter;
5451         {
5452                 ComputeShaderSpec       spec;
5453
5454                 spec.assembly           = everythingNamedTheSame;
5455                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5456                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5457                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5458
5459                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named_the_same", "everything_named_the_same", spec));
5460         }
5461
5462         // main_is_...
5463         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5464         {
5465                 map<string, string>     specializations;
5466                 ComputeShaderSpec       spec;
5467
5468                 specializations["ENTRY"]        = "main";
5469                 specializations["ID"]           = "main";
5470                 specializations["NAME"]         = abuseCases[ndx].param;
5471                 spec.assembly                           = shaderTemplate.specialize(specializations);
5472                 spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5473                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5474                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5475
5476                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("main") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5477         }
5478
5479         // x_is_....
5480         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5481         {
5482                 map<string, string>     specializations;
5483                 ComputeShaderSpec       spec;
5484
5485                 specializations["ENTRY"]        = "main";
5486                 specializations["ID"]           = "x";
5487                 specializations["NAME"]         = abuseCases[ndx].param;
5488                 spec.assembly                           = shaderTemplate.specialize(specializations);
5489                 spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5490                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5491                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5492
5493                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("x") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5494         }
5495
5496         cases.push_back(CaseParameter("_is_main", "main"));
5497         cases.push_back(CaseParameter("_is_not_main", "not_main"));
5498         testFunc.push_back("main");
5499         testFunc.push_back("func");
5500
5501         for(size_t fNdx = 0; fNdx < testFunc.size(); ++fNdx)
5502         {
5503                 for(size_t ndx = 0; ndx < cases.size(); ++ndx)
5504                 {
5505                         map<string, string>     specializations;
5506                         ComputeShaderSpec       spec;
5507
5508                         specializations["ENTRY"]        = "main";
5509                         specializations["ID"]           = testFunc[fNdx];
5510                         specializations["NAME"]         = cases[ndx].param;
5511                         spec.assembly                           = shaderTemplate.specialize(specializations);
5512                         spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5513                         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5514                         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5515
5516                         entryMainGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (testFunc[fNdx] + cases[ndx].name).c_str(), cases[ndx].name, spec));
5517                 }
5518         }
5519
5520         cases.push_back(CaseParameter("_is_entry", "rdc"));
5521
5522         for(size_t fNdx = 0; fNdx < testFunc.size(); ++fNdx)
5523         {
5524                 for(size_t ndx = 0; ndx < cases.size(); ++ndx)
5525                 {
5526                         map<string, string>     specializations;
5527                         ComputeShaderSpec       spec;
5528
5529                         specializations["ENTRY"]        = "rdc";
5530                         specializations["ID"]           = testFunc[fNdx];
5531                         specializations["NAME"]         = cases[ndx].param;
5532                         spec.assembly                           = shaderTemplate.specialize(specializations);
5533                         spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5534                         spec.entryPoint                         = "rdc";
5535                         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5536                         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5537
5538                         entryNotGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (testFunc[fNdx] + cases[ndx].name).c_str(), cases[ndx].name, spec));
5539                 }
5540         }
5541
5542         group->addChild(entryMainGroup.release());
5543         group->addChild(entryNotGroup.release());
5544         group->addChild(abuseGroup.release());
5545
5546         return group.release();
5547 }
5548
5549 tcu::TestCaseGroup* createOpMemberNameGroup (tcu::TestContext& testCtx)
5550 {
5551         de::MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "opmembername", "Tests OpMemberName cases"));
5552         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "abuse", "OpMemberName abuse tests"));
5553         vector<CaseParameter>                   abuseCases;
5554         vector<string>                                  testFunc;
5555         de::Random                                              rnd(deStringHash(group->getName()));
5556         const int                                               numElements = 128;
5557         vector<float>                                   inputFloats(numElements, 0);
5558         vector<float>                                   outputFloats(numElements, 0);
5559
5560         getOpNameAbuseCases(abuseCases);
5561
5562         fillRandomScalars(rnd, -100.0f, 100.0f, &inputFloats[0], numElements);
5563
5564         for (size_t ndx = 0; ndx < numElements; ++ndx)
5565                 outputFloats[ndx] = -inputFloats[ndx];
5566
5567         const string commonShaderHeader =
5568                 "OpCapability Shader\n"
5569                 "OpMemoryModel Logical GLSL450\n"
5570                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5571                 "OpExecutionMode %main LocalSize 1 1 1\n";
5572
5573         const string commonShaderFooter =
5574                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5575
5576                 + string(getComputeAsmInputOutputBufferTraits())
5577                 + string(getComputeAsmCommonTypes())
5578                 + string(getComputeAsmInputOutputBuffer()) +
5579
5580                 "%u3str     = OpTypeStruct %u32 %u32 %u32\n"
5581
5582                 "%id        = OpVariable %uvec3ptr Input\n"
5583                 "%zero      = OpConstant %i32 0\n"
5584
5585                 "%main      = OpFunction %void None %voidf\n"
5586                 "%entry     = OpLabel\n"
5587
5588                 "%idval     = OpLoad %uvec3 %id\n"
5589                 "%x0        = OpCompositeExtract %u32 %idval 0\n"
5590
5591                 "%idstr     = OpCompositeConstruct %u3str %x0 %x0 %x0\n"
5592                 "%x         = OpCompositeExtract %u32 %idstr 0\n"
5593
5594                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5595                 "%inval     = OpLoad %f32 %inloc\n"
5596                 "%neg       = OpFNegate %f32 %inval\n"
5597                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5598                 "             OpStore %outloc %neg\n"
5599
5600                 "             OpReturn\n"
5601                 "             OpFunctionEnd\n";
5602
5603         const StringTemplate shaderTemplate(
5604                 commonShaderHeader +
5605                 "OpMemberName %u3str 0 \"${NAME}\"\n" +
5606                 commonShaderFooter);
5607
5608         const std::string multipleNames =
5609                 commonShaderHeader +
5610                 "OpMemberName %u3str 0 \"to_be\"\n"
5611                 "OpMemberName %u3str 1 \"or_not\"\n"
5612                 "OpMemberName %u3str 0 \"to_be\"\n"
5613                 "OpMemberName %u3str 2 \"makes_no\"\n"
5614                 "OpMemberName %u3str 0 \"difference\"\n"
5615                 "OpMemberName %u3str 0 \"to_me\"\n" +
5616                 commonShaderFooter;
5617         {
5618                 ComputeShaderSpec       spec;
5619
5620                 spec.assembly = multipleNames;
5621                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5622                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5623                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5624
5625                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "u3str_x_has_multiple_names", "multiple_names", spec));
5626         }
5627
5628         const std::string everythingNamedTheSame =
5629                 commonShaderHeader +
5630                 "OpMemberName %u3str 0 \"the_same\"\n"
5631                 "OpMemberName %u3str 1 \"the_same\"\n"
5632                 "OpMemberName %u3str 2 \"the_same\"\n" +
5633                 commonShaderFooter;
5634
5635         {
5636                 ComputeShaderSpec       spec;
5637
5638                 spec.assembly = everythingNamedTheSame;
5639                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5640                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5641                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5642
5643                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named_the_same", "everything_named_the_same", spec));
5644         }
5645
5646         // u3str_x_is_....
5647         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5648         {
5649                 map<string, string>     specializations;
5650                 ComputeShaderSpec       spec;
5651
5652                 specializations["NAME"] = abuseCases[ndx].param;
5653                 spec.assembly = shaderTemplate.specialize(specializations);
5654                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5655                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5656                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5657
5658                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("u3str_x") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5659         }
5660
5661         group->addChild(abuseGroup.release());
5662
5663         return group.release();
5664 }
5665
5666 // Assembly code used for testing function control is based on GLSL source code:
5667 //
5668 // #version 430
5669 //
5670 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5671 //   float elements[];
5672 // } input_data;
5673 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5674 //   float elements[];
5675 // } output_data;
5676 //
5677 // float const10() { return 10.f; }
5678 //
5679 // void main() {
5680 //   uint x = gl_GlobalInvocationID.x;
5681 //   output_data.elements[x] = input_data.elements[x] + const10();
5682 // }
5683 tcu::TestCaseGroup* createFunctionControlGroup (tcu::TestContext& testCtx)
5684 {
5685         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "function_control", "Tests function control cases"));
5686         vector<CaseParameter>                   cases;
5687         de::Random                                              rnd                             (deStringHash(group->getName()));
5688         const int                                               numElements             = 100;
5689         vector<float>                                   inputFloats             (numElements, 0);
5690         vector<float>                                   outputFloats    (numElements, 0);
5691         const StringTemplate                    shaderTemplate  (
5692                 string(getComputeAsmShaderPreamble()) +
5693
5694                 "OpSource GLSL 430\n"
5695                 "OpName %main \"main\"\n"
5696                 "OpName %func_const10 \"const10(\"\n"
5697                 "OpName %id \"gl_GlobalInvocationID\"\n"
5698
5699                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5700
5701                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5702
5703                 "%f32f = OpTypeFunction %f32\n"
5704                 "%id = OpVariable %uvec3ptr Input\n"
5705                 "%zero = OpConstant %i32 0\n"
5706                 "%constf10 = OpConstant %f32 10.0\n"
5707
5708                 "%main         = OpFunction %void None %voidf\n"
5709                 "%entry        = OpLabel\n"
5710                 "%idval        = OpLoad %uvec3 %id\n"
5711                 "%x            = OpCompositeExtract %u32 %idval 0\n"
5712                 "%inloc        = OpAccessChain %f32ptr %indata %zero %x\n"
5713                 "%inval        = OpLoad %f32 %inloc\n"
5714                 "%ret_10       = OpFunctionCall %f32 %func_const10\n"
5715                 "%fadd         = OpFAdd %f32 %inval %ret_10\n"
5716                 "%outloc       = OpAccessChain %f32ptr %outdata %zero %x\n"
5717                 "                OpStore %outloc %fadd\n"
5718                 "                OpReturn\n"
5719                 "                OpFunctionEnd\n"
5720
5721                 "%func_const10 = OpFunction %f32 ${CONTROL} %f32f\n"
5722                 "%label        = OpLabel\n"
5723                 "                OpReturnValue %constf10\n"
5724                 "                OpFunctionEnd\n");
5725
5726         cases.push_back(CaseParameter("none",                                           "None"));
5727         cases.push_back(CaseParameter("inline",                                         "Inline"));
5728         cases.push_back(CaseParameter("dont_inline",                            "DontInline"));
5729         cases.push_back(CaseParameter("pure",                                           "Pure"));
5730         cases.push_back(CaseParameter("const",                                          "Const"));
5731         cases.push_back(CaseParameter("inline_pure",                            "Inline|Pure"));
5732         cases.push_back(CaseParameter("const_dont_inline",                      "Const|DontInline"));
5733         cases.push_back(CaseParameter("inline_dont_inline",                     "Inline|DontInline"));
5734         cases.push_back(CaseParameter("pure_inline_dont_inline",        "Pure|Inline|DontInline"));
5735
5736         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5737
5738         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
5739         floorAll(inputFloats);
5740
5741         for (size_t ndx = 0; ndx < numElements; ++ndx)
5742                 outputFloats[ndx] = inputFloats[ndx] + 10.f;
5743
5744         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5745         {
5746                 map<string, string>             specializations;
5747                 ComputeShaderSpec               spec;
5748
5749                 specializations["CONTROL"] = cases[caseNdx].param;
5750                 spec.assembly = shaderTemplate.specialize(specializations);
5751                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5752                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5753                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5754
5755                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5756         }
5757
5758         return group.release();
5759 }
5760
5761 tcu::TestCaseGroup* createMemoryAccessGroup (tcu::TestContext& testCtx)
5762 {
5763         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "memory_access", "Tests memory access cases"));
5764         vector<CaseParameter>                   cases;
5765         de::Random                                              rnd                             (deStringHash(group->getName()));
5766         const int                                               numElements             = 100;
5767         vector<float>                                   inputFloats             (numElements, 0);
5768         vector<float>                                   outputFloats    (numElements, 0);
5769         const StringTemplate                    shaderTemplate  (
5770                 string(getComputeAsmShaderPreamble()) +
5771
5772                 "OpSource GLSL 430\n"
5773                 "OpName %main           \"main\"\n"
5774                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5775
5776                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5777
5778                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5779
5780                 "%f32ptr_f  = OpTypePointer Function %f32\n"
5781
5782                 "%id        = OpVariable %uvec3ptr Input\n"
5783                 "%zero      = OpConstant %i32 0\n"
5784                 "%four      = OpConstant %i32 4\n"
5785
5786                 "%main      = OpFunction %void None %voidf\n"
5787                 "%label     = OpLabel\n"
5788                 "%copy      = OpVariable %f32ptr_f Function\n"
5789                 "%idval     = OpLoad %uvec3 %id ${ACCESS}\n"
5790                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5791                 "%inloc     = OpAccessChain %f32ptr %indata  %zero %x\n"
5792                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5793                 "             OpCopyMemory %copy %inloc ${ACCESS}\n"
5794                 "%val1      = OpLoad %f32 %copy\n"
5795                 "%val2      = OpLoad %f32 %inloc\n"
5796                 "%add       = OpFAdd %f32 %val1 %val2\n"
5797                 "             OpStore %outloc %add ${ACCESS}\n"
5798                 "             OpReturn\n"
5799                 "             OpFunctionEnd\n");
5800
5801         cases.push_back(CaseParameter("null",                                   ""));
5802         cases.push_back(CaseParameter("none",                                   "None"));
5803         cases.push_back(CaseParameter("volatile",                               "Volatile"));
5804         cases.push_back(CaseParameter("aligned",                                "Aligned 4"));
5805         cases.push_back(CaseParameter("nontemporal",                    "Nontemporal"));
5806         cases.push_back(CaseParameter("aligned_nontemporal",    "Aligned|Nontemporal 4"));
5807         cases.push_back(CaseParameter("aligned_volatile",               "Volatile|Aligned 4"));
5808
5809         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5810
5811         for (size_t ndx = 0; ndx < numElements; ++ndx)
5812                 outputFloats[ndx] = inputFloats[ndx] + inputFloats[ndx];
5813
5814         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5815         {
5816                 map<string, string>             specializations;
5817                 ComputeShaderSpec               spec;
5818
5819                 specializations["ACCESS"] = cases[caseNdx].param;
5820                 spec.assembly = shaderTemplate.specialize(specializations);
5821                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5822                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5823                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5824
5825                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5826         }
5827
5828         return group.release();
5829 }
5830
5831 // Checks that we can get undefined values for various types, without exercising a computation with it.
5832 tcu::TestCaseGroup* createOpUndefGroup (tcu::TestContext& testCtx)
5833 {
5834         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opundef", "Tests the OpUndef instruction"));
5835         vector<CaseParameter>                   cases;
5836         de::Random                                              rnd                             (deStringHash(group->getName()));
5837         const int                                               numElements             = 100;
5838         vector<float>                                   positiveFloats  (numElements, 0);
5839         vector<float>                                   negativeFloats  (numElements, 0);
5840         const StringTemplate                    shaderTemplate  (
5841                 string(getComputeAsmShaderPreamble()) +
5842
5843                 "OpSource GLSL 430\n"
5844                 "OpName %main           \"main\"\n"
5845                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5846
5847                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5848
5849                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
5850                 "%uvec2     = OpTypeVector %u32 2\n"
5851                 "%fvec4     = OpTypeVector %f32 4\n"
5852                 "%fmat33    = OpTypeMatrix %fvec3 3\n"
5853                 "%image     = OpTypeImage %f32 2D 0 0 0 1 Unknown\n"
5854                 "%sampler   = OpTypeSampler\n"
5855                 "%simage    = OpTypeSampledImage %image\n"
5856                 "%const100  = OpConstant %u32 100\n"
5857                 "%uarr100   = OpTypeArray %i32 %const100\n"
5858                 "%struct    = OpTypeStruct %f32 %i32 %u32\n"
5859                 "%pointer   = OpTypePointer Function %i32\n"
5860                 + string(getComputeAsmInputOutputBuffer()) +
5861
5862                 "%id        = OpVariable %uvec3ptr Input\n"
5863                 "%zero      = OpConstant %i32 0\n"
5864
5865                 "%main      = OpFunction %void None %voidf\n"
5866                 "%label     = OpLabel\n"
5867
5868                 "%undef     = OpUndef ${TYPE}\n"
5869
5870                 "%idval     = OpLoad %uvec3 %id\n"
5871                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5872
5873                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5874                 "%inval     = OpLoad %f32 %inloc\n"
5875                 "%neg       = OpFNegate %f32 %inval\n"
5876                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5877                 "             OpStore %outloc %neg\n"
5878                 "             OpReturn\n"
5879                 "             OpFunctionEnd\n");
5880
5881         cases.push_back(CaseParameter("bool",                   "%bool"));
5882         cases.push_back(CaseParameter("sint32",                 "%i32"));
5883         cases.push_back(CaseParameter("uint32",                 "%u32"));
5884         cases.push_back(CaseParameter("float32",                "%f32"));
5885         cases.push_back(CaseParameter("vec4float32",    "%fvec4"));
5886         cases.push_back(CaseParameter("vec2uint32",             "%uvec2"));
5887         cases.push_back(CaseParameter("matrix",                 "%fmat33"));
5888         cases.push_back(CaseParameter("image",                  "%image"));
5889         cases.push_back(CaseParameter("sampler",                "%sampler"));
5890         cases.push_back(CaseParameter("sampledimage",   "%simage"));
5891         cases.push_back(CaseParameter("array",                  "%uarr100"));
5892         cases.push_back(CaseParameter("runtimearray",   "%f32arr"));
5893         cases.push_back(CaseParameter("struct",                 "%struct"));
5894         cases.push_back(CaseParameter("pointer",                "%pointer"));
5895
5896         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
5897
5898         for (size_t ndx = 0; ndx < numElements; ++ndx)
5899                 negativeFloats[ndx] = -positiveFloats[ndx];
5900
5901         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5902         {
5903                 map<string, string>             specializations;
5904                 ComputeShaderSpec               spec;
5905
5906                 specializations["TYPE"] = cases[caseNdx].param;
5907                 spec.assembly = shaderTemplate.specialize(specializations);
5908                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
5909                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
5910                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5911
5912                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5913         }
5914
5915                 return group.release();
5916 }
5917
5918 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
5919 tcu::TestCaseGroup* createFloat16OpConstantCompositeGroup (tcu::TestContext& testCtx)
5920 {
5921         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "Tests the OpConstantComposite instruction"));
5922         vector<CaseParameter>                   cases;
5923         de::Random                                              rnd                             (deStringHash(group->getName()));
5924         const int                                               numElements             = 100;
5925         vector<float>                                   positiveFloats  (numElements, 0);
5926         vector<float>                                   negativeFloats  (numElements, 0);
5927         const StringTemplate                    shaderTemplate  (
5928                 "OpCapability Shader\n"
5929                 "OpCapability Float16\n"
5930                 "OpMemoryModel Logical GLSL450\n"
5931                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5932                 "OpExecutionMode %main LocalSize 1 1 1\n"
5933                 "OpSource GLSL 430\n"
5934                 "OpName %main           \"main\"\n"
5935                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5936
5937                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5938
5939                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5940
5941                 "%id        = OpVariable %uvec3ptr Input\n"
5942                 "%zero      = OpConstant %i32 0\n"
5943                 "%f16       = OpTypeFloat 16\n"
5944                 "%c_f16_0   = OpConstant %f16 0.0\n"
5945                 "%c_f16_0_5 = OpConstant %f16 0.5\n"
5946                 "%c_f16_1   = OpConstant %f16 1.0\n"
5947                 "%v2f16     = OpTypeVector %f16 2\n"
5948                 "%v3f16     = OpTypeVector %f16 3\n"
5949                 "%v4f16     = OpTypeVector %f16 4\n"
5950
5951                 "${CONSTANT}\n"
5952
5953                 "%main      = OpFunction %void None %voidf\n"
5954                 "%label     = OpLabel\n"
5955                 "%idval     = OpLoad %uvec3 %id\n"
5956                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5957                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5958                 "%inval     = OpLoad %f32 %inloc\n"
5959                 "%neg       = OpFNegate %f32 %inval\n"
5960                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5961                 "             OpStore %outloc %neg\n"
5962                 "             OpReturn\n"
5963                 "             OpFunctionEnd\n");
5964
5965
5966         cases.push_back(CaseParameter("vector",                 "%const = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"));
5967         cases.push_back(CaseParameter("matrix",                 "%m3v3f16 = OpTypeMatrix %v3f16 3\n"
5968                                                                                                         "%vec = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"
5969                                                                                                         "%mat = OpConstantComposite %m3v3f16 %vec %vec %vec"));
5970         cases.push_back(CaseParameter("struct",                 "%m2v3f16 = OpTypeMatrix %v3f16 2\n"
5971                                                                                                         "%struct = OpTypeStruct %i32 %f16 %v3f16 %m2v3f16\n"
5972                                                                                                         "%vec = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"
5973                                                                                                         "%mat = OpConstantComposite %m2v3f16 %vec %vec\n"
5974                                                                                                         "%const = OpConstantComposite %struct %zero %c_f16_0_5 %vec %mat\n"));
5975         cases.push_back(CaseParameter("nested_struct",  "%st1 = OpTypeStruct %i32 %f16\n"
5976                                                                                                         "%st2 = OpTypeStruct %i32 %i32\n"
5977                                                                                                         "%struct = OpTypeStruct %st1 %st2\n"
5978                                                                                                         "%st1val = OpConstantComposite %st1 %zero %c_f16_0_5\n"
5979                                                                                                         "%st2val = OpConstantComposite %st2 %zero %zero\n"
5980                                                                                                         "%const = OpConstantComposite %struct %st1val %st2val"));
5981
5982         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
5983
5984         for (size_t ndx = 0; ndx < numElements; ++ndx)
5985                 negativeFloats[ndx] = -positiveFloats[ndx];
5986
5987         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5988         {
5989                 map<string, string>             specializations;
5990                 ComputeShaderSpec               spec;
5991
5992                 specializations["CONSTANT"] = cases[caseNdx].param;
5993                 spec.assembly = shaderTemplate.specialize(specializations);
5994                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
5995                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
5996                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5997
5998                 spec.extensions.push_back("VK_KHR_16bit_storage");
5999                 spec.extensions.push_back("VK_KHR_shader_float16_int8");
6000
6001                 spec.requestedVulkanFeatures.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
6002                 spec.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
6003
6004                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
6005         }
6006
6007         return group.release();
6008 }
6009
6010 const vector<deFloat16> squarize(const vector<deFloat16>& inData, const deUint32 argNo)
6011 {
6012         const size_t            inDataLength    = inData.size();
6013         vector<deFloat16>       result;
6014
6015         result.reserve(inDataLength * inDataLength);
6016
6017         if (argNo == 0)
6018         {
6019                 for (size_t numIdx = 0; numIdx < inDataLength; ++numIdx)
6020                         result.insert(result.end(), inData.begin(), inData.end());
6021         }
6022
6023         if (argNo == 1)
6024         {
6025                 for (size_t numIdx = 0; numIdx < inDataLength; ++numIdx)
6026                 {
6027                         const vector<deFloat16> tmp(inDataLength, inData[numIdx]);
6028
6029                         result.insert(result.end(), tmp.begin(), tmp.end());
6030                 }
6031         }
6032
6033         return result;
6034 }
6035
6036 const vector<deFloat16> squarizeVector(const vector<deFloat16>& inData, const deUint32 argNo)
6037 {
6038         vector<deFloat16>       vec;
6039         vector<deFloat16>       result;
6040
6041         // Create vectors. vec will contain each possible pair from inData
6042         {
6043                 const size_t    inDataLength    = inData.size();
6044
6045                 DE_ASSERT(inDataLength <= 64);
6046
6047                 vec.reserve(2 * inDataLength * inDataLength);
6048
6049                 for (size_t numIdxX = 0; numIdxX < inDataLength; ++numIdxX)
6050                 for (size_t numIdxY = 0; numIdxY < inDataLength; ++numIdxY)
6051                 {
6052                         vec.push_back(inData[numIdxX]);
6053                         vec.push_back(inData[numIdxY]);
6054                 }
6055         }
6056
6057         // Create vector pairs. result will contain each possible pair from vec
6058         {
6059                 const size_t    coordsPerVector = 2;
6060                 const size_t    vectorsCount    = vec.size() / coordsPerVector;
6061
6062                 result.reserve(coordsPerVector * vectorsCount * vectorsCount);
6063
6064                 if (argNo == 0)
6065                 {
6066                         for (size_t numIdxX = 0; numIdxX < vectorsCount; ++numIdxX)
6067                         for (size_t numIdxY = 0; numIdxY < vectorsCount; ++numIdxY)
6068                         {
6069                                 for (size_t coordNdx = 0; coordNdx < coordsPerVector; ++coordNdx)
6070                                         result.push_back(vec[coordsPerVector * numIdxY + coordNdx]);
6071                         }
6072                 }
6073
6074                 if (argNo == 1)
6075                 {
6076                         for (size_t numIdxX = 0; numIdxX < vectorsCount; ++numIdxX)
6077                         for (size_t numIdxY = 0; numIdxY < vectorsCount; ++numIdxY)
6078                         {
6079                                 for (size_t coordNdx = 0; coordNdx < coordsPerVector; ++coordNdx)
6080                                         result.push_back(vec[coordsPerVector * numIdxX + coordNdx]);
6081                         }
6082                 }
6083         }
6084
6085         return result;
6086 }
6087
6088 struct fp16isNan                        { bool operator()(const tcu::Float16 in1, const tcu::Float16)           { return in1.isNaN(); } };
6089 struct fp16isInf                        { bool operator()(const tcu::Float16 in1, const tcu::Float16)           { return in1.isInf(); } };
6090 struct fp16isEqual                      { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() == in2.asFloat(); } };
6091 struct fp16isUnequal            { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() != in2.asFloat(); } };
6092 struct fp16isLess                       { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() <  in2.asFloat(); } };
6093 struct fp16isGreater            { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() >  in2.asFloat(); } };
6094 struct fp16isLessOrEqual        { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() <= in2.asFloat(); } };
6095 struct fp16isGreaterOrEqual     { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() >= in2.asFloat(); } };
6096
6097 template <class TestedLogicalFunction, bool onlyTestFunc, bool unationModeAnd, bool nanSupported>
6098 bool compareFP16Logical (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
6099 {
6100         if (inputs.size() != 2 || outputAllocs.size() != 1)
6101                 return false;
6102
6103         vector<deUint8> input1Bytes;
6104         vector<deUint8> input2Bytes;
6105
6106         inputs[0].getBytes(input1Bytes);
6107         inputs[1].getBytes(input2Bytes);
6108
6109         const deUint32                  denormModesCount                        = 2;
6110         const deFloat16                 float16one                                      = tcu::Float16(1.0f).bits();
6111         const deFloat16                 float16zero                                     = tcu::Float16(0.0f).bits();
6112         const tcu::Float16              zero                                            = tcu::Float16::zero(1);
6113         const deFloat16* const  outputAsFP16                            = static_cast<deFloat16*>(outputAllocs[0]->getHostPtr());
6114         const deFloat16* const  input1AsFP16                            = reinterpret_cast<deFloat16* const>(&input1Bytes.front());
6115         const deFloat16* const  input2AsFP16                            = reinterpret_cast<deFloat16* const>(&input2Bytes.front());
6116         deUint32                                successfulRuns                          = denormModesCount;
6117         std::string                             results[denormModesCount];
6118         TestedLogicalFunction   testedLogicalFunction;
6119
6120         for (deUint32 denormMode = 0; denormMode < denormModesCount; denormMode++)
6121         {
6122                 const bool flushToZero = (denormMode == 1);
6123
6124                 for (size_t idx = 0; idx < input1Bytes.size() / sizeof(deFloat16); ++idx)
6125                 {
6126                         const tcu::Float16      f1pre                   = tcu::Float16(input1AsFP16[idx]);
6127                         const tcu::Float16      f2pre                   = tcu::Float16(input2AsFP16[idx]);
6128                         const tcu::Float16      f1                              = (flushToZero && f1pre.isDenorm()) ? zero : f1pre;
6129                         const tcu::Float16      f2                              = (flushToZero && f2pre.isDenorm()) ? zero : f2pre;
6130                         deFloat16                       expectedOutput  = float16zero;
6131
6132                         if (onlyTestFunc)
6133                         {
6134                                 if (testedLogicalFunction(f1, f2))
6135                                         expectedOutput = float16one;
6136                         }
6137                         else
6138                         {
6139                                 const bool      f1nan   = f1.isNaN();
6140                                 const bool      f2nan   = f2.isNaN();
6141
6142                                 // Skip NaN floats if not supported by implementation
6143                                 if (!nanSupported && (f1nan || f2nan))
6144                                         continue;
6145
6146                                 if (unationModeAnd)
6147                                 {
6148                                         const bool      ordered         = !f1nan && !f2nan;
6149
6150                                         if (ordered && testedLogicalFunction(f1, f2))
6151                                                 expectedOutput = float16one;
6152                                 }
6153                                 else
6154                                 {
6155                                         const bool      unordered       = f1nan || f2nan;
6156
6157                                         if (unordered || testedLogicalFunction(f1, f2))
6158                                                 expectedOutput = float16one;
6159                                 }
6160                         }
6161
6162                         if (outputAsFP16[idx] != expectedOutput)
6163                         {
6164                                 std::ostringstream str;
6165
6166                                 str << "ERROR: Sub-case #" << idx
6167                                         << " flushToZero:" << flushToZero
6168                                         << std::hex
6169                                         << " failed, inputs: 0x" << f1.bits()
6170                                         << ";0x" << f2.bits()
6171                                         << " output: 0x" << outputAsFP16[idx]
6172                                         << " expected output: 0x" << expectedOutput;
6173
6174                                 results[denormMode] = str.str();
6175
6176                                 successfulRuns--;
6177
6178                                 break;
6179                         }
6180                 }
6181         }
6182
6183         if (successfulRuns == 0)
6184                 for (deUint32 denormMode = 0; denormMode < denormModesCount; denormMode++)
6185                         log << TestLog::Message << results[denormMode] << TestLog::EndMessage;
6186
6187         return successfulRuns > 0;
6188 }
6189
6190 } // anonymous
6191
6192 tcu::TestCaseGroup* createOpSourceTests (tcu::TestContext& testCtx)
6193 {
6194         struct NameCodePair { string name, code; };
6195         RGBA                                                    defaultColors[4];
6196         de::MovePtr<tcu::TestCaseGroup> opSourceTests                   (new tcu::TestCaseGroup(testCtx, "opsource", "OpSource instruction"));
6197         const std::string                               opsourceGLSLWithFile    = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile ";
6198         map<string, string>                             fragments                               = passthruFragments();
6199         const NameCodePair                              tests[]                                 =
6200         {
6201                 {"unknown", "OpSource Unknown 321"},
6202                 {"essl", "OpSource ESSL 310"},
6203                 {"glsl", "OpSource GLSL 450"},
6204                 {"opencl_cpp", "OpSource OpenCL_CPP 120"},
6205                 {"opencl_c", "OpSource OpenCL_C 120"},
6206                 {"multiple", "OpSource GLSL 450\nOpSource GLSL 450"},
6207                 {"file", opsourceGLSLWithFile},
6208                 {"source", opsourceGLSLWithFile + "\"void main(){}\""},
6209                 // Longest possible source string: SPIR-V limits instructions to 65535
6210                 // words, of which the first 4 are opsourceGLSLWithFile; the rest will
6211                 // contain 65530 UTF8 characters (one word each) plus one last word
6212                 // containing 3 ASCII characters and \0.
6213                 {"longsource", opsourceGLSLWithFile + '"' + makeLongUTF8String(65530) + "ccc" + '"'}
6214         };
6215
6216         getDefaultColors(defaultColors);
6217         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
6218         {
6219                 fragments["debug"] = tests[testNdx].code;
6220                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
6221         }
6222
6223         return opSourceTests.release();
6224 }
6225
6226 tcu::TestCaseGroup* createOpSourceContinuedTests (tcu::TestContext& testCtx)
6227 {
6228         struct NameCodePair { string name, code; };
6229         RGBA                                                            defaultColors[4];
6230         de::MovePtr<tcu::TestCaseGroup>         opSourceTests           (new tcu::TestCaseGroup(testCtx, "opsourcecontinued", "OpSourceContinued instruction"));
6231         map<string, string>                                     fragments                       = passthruFragments();
6232         const std::string                                       opsource                        = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile \"void main(){}\"\n";
6233         const NameCodePair                                      tests[]                         =
6234         {
6235                 {"empty", opsource + "OpSourceContinued \"\""},
6236                 {"short", opsource + "OpSourceContinued \"abcde\""},
6237                 {"multiple", opsource + "OpSourceContinued \"abcde\"\nOpSourceContinued \"fghij\""},
6238                 // Longest possible source string: SPIR-V limits instructions to 65535
6239                 // words, of which the first one is OpSourceContinued/length; the rest
6240                 // will contain 65533 UTF8 characters (one word each) plus one last word
6241                 // containing 3 ASCII characters and \0.
6242                 {"long", opsource + "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\""}
6243         };
6244
6245         getDefaultColors(defaultColors);
6246         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
6247         {
6248                 fragments["debug"] = tests[testNdx].code;
6249                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
6250         }
6251
6252         return opSourceTests.release();
6253 }
6254 tcu::TestCaseGroup* createOpNoLineTests(tcu::TestContext& testCtx)
6255 {
6256         RGBA                                                             defaultColors[4];
6257         de::MovePtr<tcu::TestCaseGroup>          opLineTests             (new tcu::TestCaseGroup(testCtx, "opnoline", "OpNoLine instruction"));
6258         map<string, string>                                      fragments;
6259         getDefaultColors(defaultColors);
6260         fragments["debug"]                      =
6261                 "%name = OpString \"name\"\n";
6262
6263         fragments["pre_main"]   =
6264                 "OpNoLine\n"
6265                 "OpNoLine\n"
6266                 "OpLine %name 1 1\n"
6267                 "OpNoLine\n"
6268                 "OpLine %name 1 1\n"
6269                 "OpLine %name 1 1\n"
6270                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6271                 "OpNoLine\n"
6272                 "OpLine %name 1 1\n"
6273                 "OpNoLine\n"
6274                 "OpLine %name 1 1\n"
6275                 "OpLine %name 1 1\n"
6276                 "%second_param1 = OpFunctionParameter %v4f32\n"
6277                 "OpNoLine\n"
6278                 "OpNoLine\n"
6279                 "%label_secondfunction = OpLabel\n"
6280                 "OpNoLine\n"
6281                 "OpReturnValue %second_param1\n"
6282                 "OpFunctionEnd\n"
6283                 "OpNoLine\n"
6284                 "OpNoLine\n";
6285
6286         fragments["testfun"]            =
6287                 // A %test_code function that returns its argument unchanged.
6288                 "OpNoLine\n"
6289                 "OpNoLine\n"
6290                 "OpLine %name 1 1\n"
6291                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6292                 "OpNoLine\n"
6293                 "%param1 = OpFunctionParameter %v4f32\n"
6294                 "OpNoLine\n"
6295                 "OpNoLine\n"
6296                 "%label_testfun = OpLabel\n"
6297                 "OpNoLine\n"
6298                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6299                 "OpReturnValue %val1\n"
6300                 "OpFunctionEnd\n"
6301                 "OpLine %name 1 1\n"
6302                 "OpNoLine\n";
6303
6304         createTestsForAllStages("opnoline", defaultColors, defaultColors, fragments, opLineTests.get());
6305
6306         return opLineTests.release();
6307 }
6308
6309 tcu::TestCaseGroup* createOpModuleProcessedTests(tcu::TestContext& testCtx)
6310 {
6311         RGBA                                                            defaultColors[4];
6312         de::MovePtr<tcu::TestCaseGroup>         opModuleProcessedTests                  (new tcu::TestCaseGroup(testCtx, "opmoduleprocessed", "OpModuleProcessed instruction"));
6313         map<string, string>                                     fragments;
6314         std::vector<std::string>                        noExtensions;
6315         GraphicsResources                                       resources;
6316
6317         getDefaultColors(defaultColors);
6318         resources.verifyBinary = veryfiBinaryShader;
6319         resources.spirvVersion = SPIRV_VERSION_1_3;
6320
6321         fragments["moduleprocessed"]                                                    =
6322                 "OpModuleProcessed \"VULKAN CTS\"\n"
6323                 "OpModuleProcessed \"Negative values\"\n"
6324                 "OpModuleProcessed \"Date: 2017/09/21\"\n";
6325
6326         fragments["pre_main"]   =
6327                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6328                 "%second_param1 = OpFunctionParameter %v4f32\n"
6329                 "%label_secondfunction = OpLabel\n"
6330                 "OpReturnValue %second_param1\n"
6331                 "OpFunctionEnd\n";
6332
6333         fragments["testfun"]            =
6334                 // A %test_code function that returns its argument unchanged.
6335                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6336                 "%param1 = OpFunctionParameter %v4f32\n"
6337                 "%label_testfun = OpLabel\n"
6338                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6339                 "OpReturnValue %val1\n"
6340                 "OpFunctionEnd\n";
6341
6342         createTestsForAllStages ("opmoduleprocessed", defaultColors, defaultColors, fragments, resources, noExtensions, opModuleProcessedTests.get());
6343
6344         return opModuleProcessedTests.release();
6345 }
6346
6347
6348 tcu::TestCaseGroup* createOpLineTests(tcu::TestContext& testCtx)
6349 {
6350         RGBA                                                                                                    defaultColors[4];
6351         de::MovePtr<tcu::TestCaseGroup>                                                 opLineTests                     (new tcu::TestCaseGroup(testCtx, "opline", "OpLine instruction"));
6352         map<string, string>                                                                             fragments;
6353         std::vector<std::pair<std::string, std::string> >               problemStrings;
6354
6355         problemStrings.push_back(std::make_pair<std::string, std::string>("empty_name", ""));
6356         problemStrings.push_back(std::make_pair<std::string, std::string>("short_name", "short_name"));
6357         problemStrings.push_back(std::make_pair<std::string, std::string>("long_name", makeLongUTF8String(65530) + "ccc"));
6358         getDefaultColors(defaultColors);
6359
6360         fragments["debug"]                      =
6361                 "%other_name = OpString \"other_name\"\n";
6362
6363         fragments["pre_main"]   =
6364                 "OpLine %file_name 32 0\n"
6365                 "OpLine %file_name 32 32\n"
6366                 "OpLine %file_name 32 40\n"
6367                 "OpLine %other_name 32 40\n"
6368                 "OpLine %other_name 0 100\n"
6369                 "OpLine %other_name 0 4294967295\n"
6370                 "OpLine %other_name 4294967295 0\n"
6371                 "OpLine %other_name 32 40\n"
6372                 "OpLine %file_name 0 0\n"
6373                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6374                 "OpLine %file_name 1 0\n"
6375                 "%second_param1 = OpFunctionParameter %v4f32\n"
6376                 "OpLine %file_name 1 3\n"
6377                 "OpLine %file_name 1 2\n"
6378                 "%label_secondfunction = OpLabel\n"
6379                 "OpLine %file_name 0 2\n"
6380                 "OpReturnValue %second_param1\n"
6381                 "OpFunctionEnd\n"
6382                 "OpLine %file_name 0 2\n"
6383                 "OpLine %file_name 0 2\n";
6384
6385         fragments["testfun"]            =
6386                 // A %test_code function that returns its argument unchanged.
6387                 "OpLine %file_name 1 0\n"
6388                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6389                 "OpLine %file_name 16 330\n"
6390                 "%param1 = OpFunctionParameter %v4f32\n"
6391                 "OpLine %file_name 14 442\n"
6392                 "%label_testfun = OpLabel\n"
6393                 "OpLine %file_name 11 1024\n"
6394                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6395                 "OpLine %file_name 2 97\n"
6396                 "OpReturnValue %val1\n"
6397                 "OpFunctionEnd\n"
6398                 "OpLine %file_name 5 32\n";
6399
6400         for (size_t i = 0; i < problemStrings.size(); ++i)
6401         {
6402                 map<string, string> testFragments = fragments;
6403                 testFragments["debug"] += "%file_name = OpString \"" + problemStrings[i].second + "\"\n";
6404                 createTestsForAllStages(string("opline") + "_" + problemStrings[i].first, defaultColors, defaultColors, testFragments, opLineTests.get());
6405         }
6406
6407         return opLineTests.release();
6408 }
6409
6410 tcu::TestCaseGroup* createOpConstantNullTests(tcu::TestContext& testCtx)
6411 {
6412         de::MovePtr<tcu::TestCaseGroup> opConstantNullTests             (new tcu::TestCaseGroup(testCtx, "opconstantnull", "OpConstantNull instruction"));
6413         RGBA                                                    colors[4];
6414
6415
6416         const char                                              functionStart[] =
6417                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6418                 "%param1 = OpFunctionParameter %v4f32\n"
6419                 "%lbl    = OpLabel\n";
6420
6421         const char                                              functionEnd[]   =
6422                 "OpReturnValue %transformed_param\n"
6423                 "OpFunctionEnd\n";
6424
6425         struct NameConstantsCode
6426         {
6427                 string name;
6428                 string constants;
6429                 string code;
6430         };
6431
6432         NameConstantsCode tests[] =
6433         {
6434                 {
6435                         "vec4",
6436                         "%cnull = OpConstantNull %v4f32\n",
6437                         "%transformed_param = OpFAdd %v4f32 %param1 %cnull\n"
6438                 },
6439                 {
6440                         "float",
6441                         "%cnull = OpConstantNull %f32\n",
6442                         "%vp = OpVariable %fp_v4f32 Function\n"
6443                         "%v  = OpLoad %v4f32 %vp\n"
6444                         "%v0 = OpVectorInsertDynamic %v4f32 %v %cnull %c_i32_0\n"
6445                         "%v1 = OpVectorInsertDynamic %v4f32 %v0 %cnull %c_i32_1\n"
6446                         "%v2 = OpVectorInsertDynamic %v4f32 %v1 %cnull %c_i32_2\n"
6447                         "%v3 = OpVectorInsertDynamic %v4f32 %v2 %cnull %c_i32_3\n"
6448                         "%transformed_param = OpFAdd %v4f32 %param1 %v3\n"
6449                 },
6450                 {
6451                         "bool",
6452                         "%cnull             = OpConstantNull %bool\n",
6453                         "%v                 = OpVariable %fp_v4f32 Function\n"
6454                         "                     OpStore %v %param1\n"
6455                         "                     OpSelectionMerge %false_label None\n"
6456                         "                     OpBranchConditional %cnull %true_label %false_label\n"
6457                         "%true_label        = OpLabel\n"
6458                         "                     OpStore %v %c_v4f32_0_5_0_5_0_5_0_5\n"
6459                         "                     OpBranch %false_label\n"
6460                         "%false_label       = OpLabel\n"
6461                         "%transformed_param = OpLoad %v4f32 %v\n"
6462                 },
6463                 {
6464                         "i32",
6465                         "%cnull             = OpConstantNull %i32\n",
6466                         "%v                 = OpVariable %fp_v4f32 Function %c_v4f32_0_5_0_5_0_5_0_5\n"
6467                         "%b                 = OpIEqual %bool %cnull %c_i32_0\n"
6468                         "                     OpSelectionMerge %false_label None\n"
6469                         "                     OpBranchConditional %b %true_label %false_label\n"
6470                         "%true_label        = OpLabel\n"
6471                         "                     OpStore %v %param1\n"
6472                         "                     OpBranch %false_label\n"
6473                         "%false_label       = OpLabel\n"
6474                         "%transformed_param = OpLoad %v4f32 %v\n"
6475                 },
6476                 {
6477                         "struct",
6478                         "%stype             = OpTypeStruct %f32 %v4f32\n"
6479                         "%fp_stype          = OpTypePointer Function %stype\n"
6480                         "%cnull             = OpConstantNull %stype\n",
6481                         "%v                 = OpVariable %fp_stype Function %cnull\n"
6482                         "%f                 = OpAccessChain %fp_v4f32 %v %c_i32_1\n"
6483                         "%f_val             = OpLoad %v4f32 %f\n"
6484                         "%transformed_param = OpFAdd %v4f32 %param1 %f_val\n"
6485                 },
6486                 {
6487                         "array",
6488                         "%a4_v4f32          = OpTypeArray %v4f32 %c_u32_4\n"
6489                         "%fp_a4_v4f32       = OpTypePointer Function %a4_v4f32\n"
6490                         "%cnull             = OpConstantNull %a4_v4f32\n",
6491                         "%v                 = OpVariable %fp_a4_v4f32 Function %cnull\n"
6492                         "%f                 = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
6493                         "%f1                = OpAccessChain %fp_v4f32 %v %c_u32_1\n"
6494                         "%f2                = OpAccessChain %fp_v4f32 %v %c_u32_2\n"
6495                         "%f3                = OpAccessChain %fp_v4f32 %v %c_u32_3\n"
6496                         "%f_val             = OpLoad %v4f32 %f\n"
6497                         "%f1_val            = OpLoad %v4f32 %f1\n"
6498                         "%f2_val            = OpLoad %v4f32 %f2\n"
6499                         "%f3_val            = OpLoad %v4f32 %f3\n"
6500                         "%t0                = OpFAdd %v4f32 %param1 %f_val\n"
6501                         "%t1                = OpFAdd %v4f32 %t0 %f1_val\n"
6502                         "%t2                = OpFAdd %v4f32 %t1 %f2_val\n"
6503                         "%transformed_param = OpFAdd %v4f32 %t2 %f3_val\n"
6504                 },
6505                 {
6506                         "matrix",
6507                         "%mat4x4_f32        = OpTypeMatrix %v4f32 4\n"
6508                         "%cnull             = OpConstantNull %mat4x4_f32\n",
6509                         // Our null matrix * any vector should result in a zero vector.
6510                         "%v                 = OpVectorTimesMatrix %v4f32 %param1 %cnull\n"
6511                         "%transformed_param = OpFAdd %v4f32 %param1 %v\n"
6512                 }
6513         };
6514
6515         getHalfColorsFullAlpha(colors);
6516
6517         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
6518         {
6519                 map<string, string> fragments;
6520                 fragments["pre_main"] = tests[testNdx].constants;
6521                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
6522                 createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, opConstantNullTests.get());
6523         }
6524         return opConstantNullTests.release();
6525 }
6526 tcu::TestCaseGroup* createOpConstantCompositeTests(tcu::TestContext& testCtx)
6527 {
6528         de::MovePtr<tcu::TestCaseGroup> opConstantCompositeTests                (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "OpConstantComposite instruction"));
6529         RGBA                                                    inputColors[4];
6530         RGBA                                                    outputColors[4];
6531
6532
6533         const char                                              functionStart[]  =
6534                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6535                 "%param1 = OpFunctionParameter %v4f32\n"
6536                 "%lbl    = OpLabel\n";
6537
6538         const char                                              functionEnd[]           =
6539                 "OpReturnValue %transformed_param\n"
6540                 "OpFunctionEnd\n";
6541
6542         struct NameConstantsCode
6543         {
6544                 string name;
6545                 string constants;
6546                 string code;
6547         };
6548
6549         NameConstantsCode tests[] =
6550         {
6551                 {
6552                         "vec4",
6553
6554                         "%cval              = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0\n",
6555                         "%transformed_param = OpFAdd %v4f32 %param1 %cval\n"
6556                 },
6557                 {
6558                         "struct",
6559
6560                         "%stype             = OpTypeStruct %v4f32 %f32\n"
6561                         "%fp_stype          = OpTypePointer Function %stype\n"
6562                         "%f32_n_1           = OpConstant %f32 -1.0\n"
6563                         "%f32_1_5           = OpConstant %f32 !0x3fc00000\n" // +1.5
6564                         "%cvec              = OpConstantComposite %v4f32 %f32_1_5 %f32_1_5 %f32_1_5 %c_f32_1\n"
6565                         "%cval              = OpConstantComposite %stype %cvec %f32_n_1\n",
6566
6567                         "%v                 = OpVariable %fp_stype Function %cval\n"
6568                         "%vec_ptr           = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
6569                         "%f32_ptr           = OpAccessChain %fp_f32 %v %c_u32_1\n"
6570                         "%vec_val           = OpLoad %v4f32 %vec_ptr\n"
6571                         "%f32_val           = OpLoad %f32 %f32_ptr\n"
6572                         "%tmp1              = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_1 %f32_val\n" // vec4(-1)
6573                         "%tmp2              = OpFAdd %v4f32 %tmp1 %param1\n" // param1 + vec4(-1)
6574                         "%transformed_param = OpFAdd %v4f32 %tmp2 %vec_val\n" // param1 + vec4(-1) + vec4(1.5, 1.5, 1.5, 1.0)
6575                 },
6576                 {
6577                         // [1|0|0|0.5] [x] = x + 0.5
6578                         // [0|1|0|0.5] [y] = y + 0.5
6579                         // [0|0|1|0.5] [z] = z + 0.5
6580                         // [0|0|0|1  ] [1] = 1
6581                         "matrix",
6582
6583                         "%mat4x4_f32          = OpTypeMatrix %v4f32 4\n"
6584                         "%v4f32_1_0_0_0       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_0 %c_f32_0 %c_f32_0\n"
6585                         "%v4f32_0_1_0_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_1 %c_f32_0 %c_f32_0\n"
6586                         "%v4f32_0_0_1_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_1 %c_f32_0\n"
6587                         "%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"
6588                         "%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",
6589
6590                         "%transformed_param   = OpMatrixTimesVector %v4f32 %cval %param1\n"
6591                 },
6592                 {
6593                         "array",
6594
6595                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
6596                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
6597                         "%f32_n_1             = OpConstant %f32 -1.0\n"
6598                         "%f32_1_5             = OpConstant %f32 !0x3fc00000\n" // +1.5
6599                         "%carr                = OpConstantComposite %a4f32 %c_f32_0 %f32_n_1 %f32_1_5 %c_f32_0\n",
6600
6601                         "%v                   = OpVariable %fp_a4f32 Function %carr\n"
6602                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_0\n"
6603                         "%f1                  = OpAccessChain %fp_f32 %v %c_u32_1\n"
6604                         "%f2                  = OpAccessChain %fp_f32 %v %c_u32_2\n"
6605                         "%f3                  = OpAccessChain %fp_f32 %v %c_u32_3\n"
6606                         "%f_val               = OpLoad %f32 %f\n"
6607                         "%f1_val              = OpLoad %f32 %f1\n"
6608                         "%f2_val              = OpLoad %f32 %f2\n"
6609                         "%f3_val              = OpLoad %f32 %f3\n"
6610                         "%ftot1               = OpFAdd %f32 %f_val %f1_val\n"
6611                         "%ftot2               = OpFAdd %f32 %ftot1 %f2_val\n"
6612                         "%ftot3               = OpFAdd %f32 %ftot2 %f3_val\n"  // 0 - 1 + 1.5 + 0
6613                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %ftot3\n"
6614                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
6615                 },
6616                 {
6617                         //
6618                         // [
6619                         //   {
6620                         //      0.0,
6621                         //      [ 1.0, 1.0, 1.0, 1.0]
6622                         //   },
6623                         //   {
6624                         //      1.0,
6625                         //      [ 0.0, 0.5, 0.0, 0.0]
6626                         //   }, //     ^^^
6627                         //   {
6628                         //      0.0,
6629                         //      [ 1.0, 1.0, 1.0, 1.0]
6630                         //   }
6631                         // ]
6632                         "array_of_struct_of_array",
6633
6634                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
6635                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
6636                         "%stype               = OpTypeStruct %f32 %a4f32\n"
6637                         "%a3stype             = OpTypeArray %stype %c_u32_3\n"
6638                         "%fp_a3stype          = OpTypePointer Function %a3stype\n"
6639                         "%ca4f32_0            = OpConstantComposite %a4f32 %c_f32_0 %c_f32_0_5 %c_f32_0 %c_f32_0\n"
6640                         "%ca4f32_1            = OpConstantComposite %a4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
6641                         "%cstype1             = OpConstantComposite %stype %c_f32_0 %ca4f32_1\n"
6642                         "%cstype2             = OpConstantComposite %stype %c_f32_1 %ca4f32_0\n"
6643                         "%carr                = OpConstantComposite %a3stype %cstype1 %cstype2 %cstype1",
6644
6645                         "%v                   = OpVariable %fp_a3stype Function %carr\n"
6646                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_1 %c_u32_1 %c_u32_1\n"
6647                         "%f_l                 = OpLoad %f32 %f\n"
6648                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %f_l\n"
6649                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
6650                 }
6651         };
6652
6653         getHalfColorsFullAlpha(inputColors);
6654         outputColors[0] = RGBA(255, 255, 255, 255);
6655         outputColors[1] = RGBA(255, 127, 127, 255);
6656         outputColors[2] = RGBA(127, 255, 127, 255);
6657         outputColors[3] = RGBA(127, 127, 255, 255);
6658
6659         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
6660         {
6661                 map<string, string> fragments;
6662                 fragments["pre_main"] = tests[testNdx].constants;
6663                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
6664                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, opConstantCompositeTests.get());
6665         }
6666         return opConstantCompositeTests.release();
6667 }
6668
6669 tcu::TestCaseGroup* createSelectionBlockOrderTests(tcu::TestContext& testCtx)
6670 {
6671         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "selection_block_order", "Out-of-order blocks for selection"));
6672         RGBA                                                    inputColors[4];
6673         RGBA                                                    outputColors[4];
6674         map<string, string>                             fragments;
6675
6676         // vec4 test_code(vec4 param) {
6677         //   vec4 result = param;
6678         //   for (int i = 0; i < 4; ++i) {
6679         //     if (i == 0) result[i] = 0.;
6680         //     else        result[i] = 1. - result[i];
6681         //   }
6682         //   return result;
6683         // }
6684         const char                                              function[]                      =
6685                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6686                 "%param1    = OpFunctionParameter %v4f32\n"
6687                 "%lbl       = OpLabel\n"
6688                 "%iptr      = OpVariable %fp_i32 Function\n"
6689                 "%result    = OpVariable %fp_v4f32 Function\n"
6690                 "             OpStore %iptr %c_i32_0\n"
6691                 "             OpStore %result %param1\n"
6692                 "             OpBranch %loop\n"
6693
6694                 // Loop entry block.
6695                 "%loop      = OpLabel\n"
6696                 "%ival      = OpLoad %i32 %iptr\n"
6697                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6698                 "             OpLoopMerge %exit %if_entry None\n"
6699                 "             OpBranchConditional %lt_4 %if_entry %exit\n"
6700
6701                 // Merge block for loop.
6702                 "%exit      = OpLabel\n"
6703                 "%ret       = OpLoad %v4f32 %result\n"
6704                 "             OpReturnValue %ret\n"
6705
6706                 // If-statement entry block.
6707                 "%if_entry  = OpLabel\n"
6708                 "%loc       = OpAccessChain %fp_f32 %result %ival\n"
6709                 "%eq_0      = OpIEqual %bool %ival %c_i32_0\n"
6710                 "             OpSelectionMerge %if_exit None\n"
6711                 "             OpBranchConditional %eq_0 %if_true %if_false\n"
6712
6713                 // False branch for if-statement.
6714                 "%if_false  = OpLabel\n"
6715                 "%val       = OpLoad %f32 %loc\n"
6716                 "%sub       = OpFSub %f32 %c_f32_1 %val\n"
6717                 "             OpStore %loc %sub\n"
6718                 "             OpBranch %if_exit\n"
6719
6720                 // Merge block for if-statement.
6721                 "%if_exit   = OpLabel\n"
6722                 "%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
6723                 "             OpStore %iptr %ival_next\n"
6724                 "             OpBranch %loop\n"
6725
6726                 // True branch for if-statement.
6727                 "%if_true   = OpLabel\n"
6728                 "             OpStore %loc %c_f32_0\n"
6729                 "             OpBranch %if_exit\n"
6730
6731                 "             OpFunctionEnd\n";
6732
6733         fragments["testfun"]    = function;
6734
6735         inputColors[0]                  = RGBA(127, 127, 127, 0);
6736         inputColors[1]                  = RGBA(127, 0,   0,   0);
6737         inputColors[2]                  = RGBA(0,   127, 0,   0);
6738         inputColors[3]                  = RGBA(0,   0,   127, 0);
6739
6740         outputColors[0]                 = RGBA(0, 128, 128, 255);
6741         outputColors[1]                 = RGBA(0, 255, 255, 255);
6742         outputColors[2]                 = RGBA(0, 128, 255, 255);
6743         outputColors[3]                 = RGBA(0, 255, 128, 255);
6744
6745         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
6746
6747         return group.release();
6748 }
6749
6750 tcu::TestCaseGroup* createSwitchBlockOrderTests(tcu::TestContext& testCtx)
6751 {
6752         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "switch_block_order", "Out-of-order blocks for switch"));
6753         RGBA                                                    inputColors[4];
6754         RGBA                                                    outputColors[4];
6755         map<string, string>                             fragments;
6756
6757         const char                                              typesAndConstants[]     =
6758                 "%c_f32_p2  = OpConstant %f32 0.2\n"
6759                 "%c_f32_p4  = OpConstant %f32 0.4\n"
6760                 "%c_f32_p6  = OpConstant %f32 0.6\n"
6761                 "%c_f32_p8  = OpConstant %f32 0.8\n";
6762
6763         // vec4 test_code(vec4 param) {
6764         //   vec4 result = param;
6765         //   for (int i = 0; i < 4; ++i) {
6766         //     switch (i) {
6767         //       case 0: result[i] += .2; break;
6768         //       case 1: result[i] += .6; break;
6769         //       case 2: result[i] += .4; break;
6770         //       case 3: result[i] += .8; break;
6771         //       default: break; // unreachable
6772         //     }
6773         //   }
6774         //   return result;
6775         // }
6776         const char                                              function[]                      =
6777                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6778                 "%param1    = OpFunctionParameter %v4f32\n"
6779                 "%lbl       = OpLabel\n"
6780                 "%iptr      = OpVariable %fp_i32 Function\n"
6781                 "%result    = OpVariable %fp_v4f32 Function\n"
6782                 "             OpStore %iptr %c_i32_0\n"
6783                 "             OpStore %result %param1\n"
6784                 "             OpBranch %loop\n"
6785
6786                 // Loop entry block.
6787                 "%loop      = OpLabel\n"
6788                 "%ival      = OpLoad %i32 %iptr\n"
6789                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6790                 "             OpLoopMerge %exit %switch_exit None\n"
6791                 "             OpBranchConditional %lt_4 %switch_entry %exit\n"
6792
6793                 // Merge block for loop.
6794                 "%exit      = OpLabel\n"
6795                 "%ret       = OpLoad %v4f32 %result\n"
6796                 "             OpReturnValue %ret\n"
6797
6798                 // Switch-statement entry block.
6799                 "%switch_entry   = OpLabel\n"
6800                 "%loc            = OpAccessChain %fp_f32 %result %ival\n"
6801                 "%val            = OpLoad %f32 %loc\n"
6802                 "                  OpSelectionMerge %switch_exit None\n"
6803                 "                  OpSwitch %ival %switch_default 0 %case0 1 %case1 2 %case2 3 %case3\n"
6804
6805                 "%case2          = OpLabel\n"
6806                 "%addp4          = OpFAdd %f32 %val %c_f32_p4\n"
6807                 "                  OpStore %loc %addp4\n"
6808                 "                  OpBranch %switch_exit\n"
6809
6810                 "%switch_default = OpLabel\n"
6811                 "                  OpUnreachable\n"
6812
6813                 "%case3          = OpLabel\n"
6814                 "%addp8          = OpFAdd %f32 %val %c_f32_p8\n"
6815                 "                  OpStore %loc %addp8\n"
6816                 "                  OpBranch %switch_exit\n"
6817
6818                 "%case0          = OpLabel\n"
6819                 "%addp2          = OpFAdd %f32 %val %c_f32_p2\n"
6820                 "                  OpStore %loc %addp2\n"
6821                 "                  OpBranch %switch_exit\n"
6822
6823                 // Merge block for switch-statement.
6824                 "%switch_exit    = OpLabel\n"
6825                 "%ival_next      = OpIAdd %i32 %ival %c_i32_1\n"
6826                 "                  OpStore %iptr %ival_next\n"
6827                 "                  OpBranch %loop\n"
6828
6829                 "%case1          = OpLabel\n"
6830                 "%addp6          = OpFAdd %f32 %val %c_f32_p6\n"
6831                 "                  OpStore %loc %addp6\n"
6832                 "                  OpBranch %switch_exit\n"
6833
6834                 "                  OpFunctionEnd\n";
6835
6836         fragments["pre_main"]   = typesAndConstants;
6837         fragments["testfun"]    = function;
6838
6839         inputColors[0]                  = RGBA(127, 27,  127, 51);
6840         inputColors[1]                  = RGBA(127, 0,   0,   51);
6841         inputColors[2]                  = RGBA(0,   27,  0,   51);
6842         inputColors[3]                  = RGBA(0,   0,   127, 51);
6843
6844         outputColors[0]                 = RGBA(178, 180, 229, 255);
6845         outputColors[1]                 = RGBA(178, 153, 102, 255);
6846         outputColors[2]                 = RGBA(51,  180, 102, 255);
6847         outputColors[3]                 = RGBA(51,  153, 229, 255);
6848
6849         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
6850
6851         return group.release();
6852 }
6853
6854 tcu::TestCaseGroup* createDecorationGroupTests(tcu::TestContext& testCtx)
6855 {
6856         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "decoration_group", "Decoration group tests"));
6857         RGBA                                                    inputColors[4];
6858         RGBA                                                    outputColors[4];
6859         map<string, string>                             fragments;
6860
6861         const char                                              decorations[]           =
6862                 "OpDecorate %array_group         ArrayStride 4\n"
6863                 "OpDecorate %struct_member_group Offset 0\n"
6864                 "%array_group         = OpDecorationGroup\n"
6865                 "%struct_member_group = OpDecorationGroup\n"
6866
6867                 "OpDecorate %group1 RelaxedPrecision\n"
6868                 "OpDecorate %group3 RelaxedPrecision\n"
6869                 "OpDecorate %group3 Invariant\n"
6870                 "OpDecorate %group3 Restrict\n"
6871                 "%group0 = OpDecorationGroup\n"
6872                 "%group1 = OpDecorationGroup\n"
6873                 "%group3 = OpDecorationGroup\n";
6874
6875         const char                                              typesAndConstants[]     =
6876                 "%a3f32     = OpTypeArray %f32 %c_u32_3\n"
6877                 "%struct1   = OpTypeStruct %a3f32\n"
6878                 "%struct2   = OpTypeStruct %a3f32\n"
6879                 "%fp_struct1 = OpTypePointer Function %struct1\n"
6880                 "%fp_struct2 = OpTypePointer Function %struct2\n"
6881                 "%c_f32_2    = OpConstant %f32 2.\n"
6882                 "%c_f32_n2   = OpConstant %f32 -2.\n"
6883
6884                 "%c_a3f32_1 = OpConstantComposite %a3f32 %c_f32_1 %c_f32_2 %c_f32_1\n"
6885                 "%c_a3f32_2 = OpConstantComposite %a3f32 %c_f32_n1 %c_f32_n2 %c_f32_n1\n"
6886                 "%c_struct1 = OpConstantComposite %struct1 %c_a3f32_1\n"
6887                 "%c_struct2 = OpConstantComposite %struct2 %c_a3f32_2\n";
6888
6889         const char                                              function[]                      =
6890                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6891                 "%param     = OpFunctionParameter %v4f32\n"
6892                 "%entry     = OpLabel\n"
6893                 "%result    = OpVariable %fp_v4f32 Function\n"
6894                 "%v_struct1 = OpVariable %fp_struct1 Function\n"
6895                 "%v_struct2 = OpVariable %fp_struct2 Function\n"
6896                 "             OpStore %result %param\n"
6897                 "             OpStore %v_struct1 %c_struct1\n"
6898                 "             OpStore %v_struct2 %c_struct2\n"
6899                 "%ptr1      = OpAccessChain %fp_f32 %v_struct1 %c_i32_0 %c_i32_2\n"
6900                 "%val1      = OpLoad %f32 %ptr1\n"
6901                 "%ptr2      = OpAccessChain %fp_f32 %v_struct2 %c_i32_0 %c_i32_2\n"
6902                 "%val2      = OpLoad %f32 %ptr2\n"
6903                 "%addvalues = OpFAdd %f32 %val1 %val2\n"
6904                 "%ptr       = OpAccessChain %fp_f32 %result %c_i32_1\n"
6905                 "%val       = OpLoad %f32 %ptr\n"
6906                 "%addresult = OpFAdd %f32 %addvalues %val\n"
6907                 "             OpStore %ptr %addresult\n"
6908                 "%ret       = OpLoad %v4f32 %result\n"
6909                 "             OpReturnValue %ret\n"
6910                 "             OpFunctionEnd\n";
6911
6912         struct CaseNameDecoration
6913         {
6914                 string name;
6915                 string decoration;
6916         };
6917
6918         CaseNameDecoration tests[] =
6919         {
6920                 {
6921                         "same_decoration_group_on_multiple_types",
6922                         "OpGroupMemberDecorate %struct_member_group %struct1 0 %struct2 0\n"
6923                 },
6924                 {
6925                         "empty_decoration_group",
6926                         "OpGroupDecorate %group0      %a3f32\n"
6927                         "OpGroupDecorate %group0      %result\n"
6928                 },
6929                 {
6930                         "one_element_decoration_group",
6931                         "OpGroupDecorate %array_group %a3f32\n"
6932                 },
6933                 {
6934                         "multiple_elements_decoration_group",
6935                         "OpGroupDecorate %group3      %v_struct1\n"
6936                 },
6937                 {
6938                         "multiple_decoration_groups_on_same_variable",
6939                         "OpGroupDecorate %group0      %v_struct2\n"
6940                         "OpGroupDecorate %group1      %v_struct2\n"
6941                         "OpGroupDecorate %group3      %v_struct2\n"
6942                 },
6943                 {
6944                         "same_decoration_group_multiple_times",
6945                         "OpGroupDecorate %group1      %addvalues\n"
6946                         "OpGroupDecorate %group1      %addvalues\n"
6947                         "OpGroupDecorate %group1      %addvalues\n"
6948                 },
6949
6950         };
6951
6952         getHalfColorsFullAlpha(inputColors);
6953         getHalfColorsFullAlpha(outputColors);
6954
6955         for (size_t idx = 0; idx < (sizeof(tests) / sizeof(tests[0])); ++idx)
6956         {
6957                 fragments["decoration"] = decorations + tests[idx].decoration;
6958                 fragments["pre_main"]   = typesAndConstants;
6959                 fragments["testfun"]    = function;
6960
6961                 createTestsForAllStages(tests[idx].name, inputColors, outputColors, fragments, group.get());
6962         }
6963
6964         return group.release();
6965 }
6966
6967 struct SpecConstantTwoIntGraphicsCase
6968 {
6969         const char*             caseName;
6970         const char*             scDefinition0;
6971         const char*             scDefinition1;
6972         const char*             scResultType;
6973         const char*             scOperation;
6974         deInt32                 scActualValue0;
6975         deInt32                 scActualValue1;
6976         const char*             resultOperation;
6977         RGBA                    expectedColors[4];
6978         deInt32                 scActualValueLength;
6979
6980                                         SpecConstantTwoIntGraphicsCase (const char*             name,
6981                                                                                                         const char*             definition0,
6982                                                                                                         const char*             definition1,
6983                                                                                                         const char*             resultType,
6984                                                                                                         const char*             operation,
6985                                                                                                         const deInt32   value0,
6986                                                                                                         const deInt32   value1,
6987                                                                                                         const char*             resultOp,
6988                                                                                                         const RGBA              (&output)[4],
6989                                                                                                         const deInt32   valueLength = sizeof(deInt32))
6990                                                 : caseName                              (name)
6991                                                 , scDefinition0                 (definition0)
6992                                                 , scDefinition1                 (definition1)
6993                                                 , scResultType                  (resultType)
6994                                                 , scOperation                   (operation)
6995                                                 , scActualValue0                (value0)
6996                                                 , scActualValue1                (value1)
6997                                                 , resultOperation               (resultOp)
6998                                                 , scActualValueLength   (valueLength)
6999         {
7000                 expectedColors[0] = output[0];
7001                 expectedColors[1] = output[1];
7002                 expectedColors[2] = output[2];
7003                 expectedColors[3] = output[3];
7004         }
7005 };
7006
7007 tcu::TestCaseGroup* createSpecConstantTests (tcu::TestContext& testCtx)
7008 {
7009         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
7010         vector<SpecConstantTwoIntGraphicsCase>  cases;
7011         RGBA                                                    inputColors[4];
7012         RGBA                                                    outputColors0[4];
7013         RGBA                                                    outputColors1[4];
7014         RGBA                                                    outputColors2[4];
7015
7016         const deInt32                                   m1AsFloat16                     = 0xbc00; // -1(fp16) == 1 01111 0000000000 == 1011 1100 0000 0000
7017
7018         const char      decorations1[]                  =
7019                 "OpDecorate %sc_0  SpecId 0\n"
7020                 "OpDecorate %sc_1  SpecId 1\n";
7021
7022         const char      typesAndConstants1[]    =
7023                 "${OPTYPE_DEFINITIONS:opt}"
7024                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
7025                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
7026                 "%sc_op     = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n";
7027
7028         const char      function1[]                             =
7029                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7030                 "%param     = OpFunctionParameter %v4f32\n"
7031                 "%label     = OpLabel\n"
7032                 "%result    = OpVariable %fp_v4f32 Function\n"
7033                 "${TYPE_CONVERT:opt}"
7034                 "             OpStore %result %param\n"
7035                 "%gen       = ${GEN_RESULT}\n"
7036                 "%index     = OpIAdd %i32 %gen %c_i32_1\n"
7037                 "%loc       = OpAccessChain %fp_f32 %result %index\n"
7038                 "%val       = OpLoad %f32 %loc\n"
7039                 "%add       = OpFAdd %f32 %val %c_f32_0_5\n"
7040                 "             OpStore %loc %add\n"
7041                 "%ret       = OpLoad %v4f32 %result\n"
7042                 "             OpReturnValue %ret\n"
7043                 "             OpFunctionEnd\n";
7044
7045         inputColors[0] = RGBA(127, 127, 127, 255);
7046         inputColors[1] = RGBA(127, 0,   0,   255);
7047         inputColors[2] = RGBA(0,   127, 0,   255);
7048         inputColors[3] = RGBA(0,   0,   127, 255);
7049
7050         // Derived from inputColors[x] by adding 128 to inputColors[x][0].
7051         outputColors0[0] = RGBA(255, 127, 127, 255);
7052         outputColors0[1] = RGBA(255, 0,   0,   255);
7053         outputColors0[2] = RGBA(128, 127, 0,   255);
7054         outputColors0[3] = RGBA(128, 0,   127, 255);
7055
7056         // Derived from inputColors[x] by adding 128 to inputColors[x][1].
7057         outputColors1[0] = RGBA(127, 255, 127, 255);
7058         outputColors1[1] = RGBA(127, 128, 0,   255);
7059         outputColors1[2] = RGBA(0,   255, 0,   255);
7060         outputColors1[3] = RGBA(0,   128, 127, 255);
7061
7062         // Derived from inputColors[x] by adding 128 to inputColors[x][2].
7063         outputColors2[0] = RGBA(127, 127, 255, 255);
7064         outputColors2[1] = RGBA(127, 0,   128, 255);
7065         outputColors2[2] = RGBA(0,   127, 128, 255);
7066         outputColors2[3] = RGBA(0,   0,   255, 255);
7067
7068         const char addZeroToSc[]                = "OpIAdd %i32 %c_i32_0 %sc_op";
7069         const char addZeroToSc32[]              = "OpIAdd %i32 %c_i32_0 %sc_op32";
7070         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_op %c_i32_1 %c_i32_0";
7071         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_op %c_i32_0 %c_i32_1";
7072
7073         cases.push_back(SpecConstantTwoIntGraphicsCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                             19,             -20,    addZeroToSc,            outputColors0));
7074         cases.push_back(SpecConstantTwoIntGraphicsCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                             19,             20,             addZeroToSc,            outputColors0));
7075         cases.push_back(SpecConstantTwoIntGraphicsCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                             -1,             -1,             addZeroToSc,            outputColors2));
7076         cases.push_back(SpecConstantTwoIntGraphicsCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                             -126,   126,    addZeroToSc,            outputColors0));
7077         cases.push_back(SpecConstantTwoIntGraphicsCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                             126,    126,    addZeroToSc,            outputColors2));
7078         cases.push_back(SpecConstantTwoIntGraphicsCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
7079         cases.push_back(SpecConstantTwoIntGraphicsCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
7080         cases.push_back(SpecConstantTwoIntGraphicsCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                             1001,   500,    addZeroToSc,            outputColors2));
7081         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                             0x33,   0x0d,   addZeroToSc,            outputColors2));
7082         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                             0,              1,              addZeroToSc,            outputColors2));
7083         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                             0x2e,   0x2f,   addZeroToSc,            outputColors2));
7084         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                             2,              1,              addZeroToSc,            outputColors2));
7085         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                             -4,             2,              addZeroToSc,            outputColors0));
7086         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                             1,              0,              addZeroToSc,            outputColors2));
7087         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                             -20,    -10,    selectTrueUsingSc,      outputColors2));
7088         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                             10,             20,             selectTrueUsingSc,      outputColors2));
7089         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
7090         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                             10,             5,              selectTrueUsingSc,      outputColors2));
7091         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                             -10,    -10,    selectTrueUsingSc,      outputColors2));
7092         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                             50,             100,    selectTrueUsingSc,      outputColors2));
7093         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
7094         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                             10,             10,             selectTrueUsingSc,      outputColors2));
7095         cases.push_back(SpecConstantTwoIntGraphicsCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                             42,             24,             selectFalseUsingSc,     outputColors2));
7096         cases.push_back(SpecConstantTwoIntGraphicsCase("inotequal",                             " %i32 0",              " %i32 0",              "%bool",        "INotEqual            %sc_0 %sc_1",                             42,             24,             selectTrueUsingSc,      outputColors2));
7097         cases.push_back(SpecConstantTwoIntGraphicsCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
7098         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
7099         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
7100         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
7101         cases.push_back(SpecConstantTwoIntGraphicsCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                                   -1,             0,              addZeroToSc,            outputColors2));
7102         cases.push_back(SpecConstantTwoIntGraphicsCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                                   -2,             0,              addZeroToSc,            outputColors2));
7103         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                                   1,              0,              selectFalseUsingSc,     outputColors2));
7104         cases.push_back(SpecConstantTwoIntGraphicsCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %c_i32_0",    1,              1,              addZeroToSc,            outputColors2));
7105         cases.push_back(SpecConstantTwoIntGraphicsCase("sconvert",                              " %i32 0",              " %i32 0",              "%i16",         "SConvert             %sc_0",                                   -1,             0,              addZeroToSc32,          outputColors0));
7106         // -1082130432 stored as 32-bit two's complement is the binary representation of -1 as IEEE-754 Float
7107         cases.push_back(SpecConstantTwoIntGraphicsCase("fconvert",                              " %f32 0",              " %f32 0",              "%f64",         "FConvert             %sc_0",                                   -1082130432, 0, addZeroToSc32,          outputColors0));
7108         cases.push_back(SpecConstantTwoIntGraphicsCase("fconvert16",                    " %f16 0",              " %f16 0",              "%f32",         "FConvert             %sc_0",                                   m1AsFloat16, 0, addZeroToSc32,          outputColors0, sizeof(deFloat16)));
7109         // \todo[2015-12-1 antiagainst] OpQuantizeToF16
7110
7111         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
7112         {
7113                 map<string, string>                     specializations;
7114                 map<string, string>                     fragments;
7115                 SpecConstants                           specConstants;
7116                 PushConstants                           noPushConstants;
7117                 GraphicsResources                       noResources;
7118                 GraphicsInterfaces                      noInterfaces;
7119                 vector<string>                          extensions;
7120                 VulkanFeatures                          requiredFeatures;
7121
7122                 // Special SPIR-V code for SConvert-case
7123                 if (strcmp(cases[caseNdx].caseName, "sconvert") == 0)
7124                 {
7125                         requiredFeatures.coreFeatures.shaderInt16 = VK_TRUE;
7126                         fragments["capability"]                                 = "OpCapability Int16\n";                                       // Adds 16-bit integer capability
7127                         specializations["OPTYPE_DEFINITIONS"]   = "%i16 = OpTypeInt 16 1\n";                            // Adds 16-bit integer type
7128                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpSConvert %i32 %sc_op\n";        // Converts 16-bit integer to 32-bit integer
7129                 }
7130
7131                 // Special SPIR-V code for FConvert-case
7132                 if (strcmp(cases[caseNdx].caseName, "fconvert") == 0)
7133                 {
7134                         requiredFeatures.coreFeatures.shaderFloat64 = VK_TRUE;
7135                         fragments["capability"]                                 = "OpCapability Float64\n";                                     // Adds 64-bit float capability
7136                         specializations["OPTYPE_DEFINITIONS"]   = "%f64 = OpTypeFloat 64\n";                            // Adds 64-bit float type
7137                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpConvertFToS %i32 %sc_op\n";     // Converts 64-bit float to 32-bit integer
7138                 }
7139
7140                 // Special SPIR-V code for FConvert-case for 16-bit floats
7141                 if (strcmp(cases[caseNdx].caseName, "fconvert16") == 0)
7142                 {
7143                         extensions.push_back("VK_KHR_shader_float16_int8");
7144                         requiredFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
7145                         fragments["capability"]                                 = "OpCapability Float16\n";                                     // Adds 16-bit float capability
7146                         specializations["OPTYPE_DEFINITIONS"]   = "%f16 = OpTypeFloat 16\n";                            // Adds 16-bit float type
7147                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpConvertFToS %i32 %sc_op\n";     // Converts 16-bit float to 32-bit integer
7148                 }
7149
7150                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
7151                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
7152                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
7153                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
7154                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
7155
7156                 fragments["decoration"]                         = tcu::StringTemplate(decorations1).specialize(specializations);
7157                 fragments["pre_main"]                           = tcu::StringTemplate(typesAndConstants1).specialize(specializations);
7158                 fragments["testfun"]                            = tcu::StringTemplate(function1).specialize(specializations);
7159
7160                 specConstants.append(&cases[caseNdx].scActualValue0, cases[caseNdx].scActualValueLength);
7161                 specConstants.append(&cases[caseNdx].scActualValue1, cases[caseNdx].scActualValueLength);
7162
7163                 createTestsForAllStages(
7164                         cases[caseNdx].caseName, inputColors, cases[caseNdx].expectedColors, fragments, specConstants,
7165                         noPushConstants, noResources, noInterfaces, extensions, requiredFeatures, group.get());
7166         }
7167
7168         const char      decorations2[]                  =
7169                 "OpDecorate %sc_0  SpecId 0\n"
7170                 "OpDecorate %sc_1  SpecId 1\n"
7171                 "OpDecorate %sc_2  SpecId 2\n";
7172
7173         const char      typesAndConstants2[]    =
7174                 "%vec3_0      = OpConstantComposite %v3i32 %c_i32_0 %c_i32_0 %c_i32_0\n"
7175                 "%vec3_undef  = OpUndef %v3i32\n"
7176
7177                 "%sc_0        = OpSpecConstant %i32 0\n"
7178                 "%sc_1        = OpSpecConstant %i32 0\n"
7179                 "%sc_2        = OpSpecConstant %i32 0\n"
7180                 "%sc_vec3_0   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_0        %vec3_0      0\n"                                                 // (sc_0, 0,    0)
7181                 "%sc_vec3_1   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_1        %vec3_0      1\n"                                                 // (0,    sc_1, 0)
7182                 "%sc_vec3_2   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_2        %vec3_0      2\n"                                                 // (0,    0,    sc_2)
7183                 "%sc_vec3_0_s = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_0   %vec3_undef  0          0xFFFFFFFF 2\n"   // (sc_0, ???,  0)
7184                 "%sc_vec3_1_s = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_1   %vec3_undef  0xFFFFFFFF 1          0\n"   // (???,  sc_1, 0)
7185                 "%sc_vec3_2_s = OpSpecConstantOp %v3i32 VectorShuffle    %vec3_undef  %sc_vec3_2   5          0xFFFFFFFF 5\n"   // (sc_2, ???,  sc_2)
7186                 "%sc_vec3_01  = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_0_s %sc_vec3_1_s 1 0 4\n"                                             // (0,    sc_0, sc_1)
7187                 "%sc_vec3_012 = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_01  %sc_vec3_2_s 5 1 2\n"                                             // (sc_2, sc_0, sc_1)
7188                 "%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              0\n"                                                 // sc_2
7189                 "%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              1\n"                                                 // sc_0
7190                 "%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              2\n"                                                 // sc_1
7191                 "%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"                                                              // (sc_2 - sc_0)
7192                 "%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n";                                                             // (sc_2 - sc_0) * sc_1
7193
7194         const char      function2[]                             =
7195                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7196                 "%param     = OpFunctionParameter %v4f32\n"
7197                 "%label     = OpLabel\n"
7198                 "%result    = OpVariable %fp_v4f32 Function\n"
7199                 "             OpStore %result %param\n"
7200                 "%loc       = OpAccessChain %fp_f32 %result %sc_final\n"
7201                 "%val       = OpLoad %f32 %loc\n"
7202                 "%add       = OpFAdd %f32 %val %c_f32_0_5\n"
7203                 "             OpStore %loc %add\n"
7204                 "%ret       = OpLoad %v4f32 %result\n"
7205                 "             OpReturnValue %ret\n"
7206                 "             OpFunctionEnd\n";
7207
7208         map<string, string>     fragments;
7209         SpecConstants           specConstants;
7210
7211         fragments["decoration"] = decorations2;
7212         fragments["pre_main"]   = typesAndConstants2;
7213         fragments["testfun"]    = function2;
7214
7215         specConstants.append<deInt32>(56789);
7216         specConstants.append<deInt32>(-2);
7217         specConstants.append<deInt32>(56788);
7218
7219         createTestsForAllStages("vector_related", inputColors, outputColors2, fragments, specConstants, group.get());
7220
7221         return group.release();
7222 }
7223
7224 tcu::TestCaseGroup* createOpPhiTests(tcu::TestContext& testCtx)
7225 {
7226         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
7227         RGBA                                                    inputColors[4];
7228         RGBA                                                    outputColors1[4];
7229         RGBA                                                    outputColors2[4];
7230         RGBA                                                    outputColors3[4];
7231         RGBA                                                    outputColors4[4];
7232         map<string, string>                             fragments1;
7233         map<string, string>                             fragments2;
7234         map<string, string>                             fragments3;
7235         map<string, string>                             fragments4;
7236         std::vector<std::string>                extensions4;
7237         GraphicsResources                               resources4;
7238         VulkanFeatures                                  vulkanFeatures4;
7239
7240         const char      typesAndConstants1[]    =
7241                 "%c_f32_p2  = OpConstant %f32 0.2\n"
7242                 "%c_f32_p4  = OpConstant %f32 0.4\n"
7243                 "%c_f32_p5  = OpConstant %f32 0.5\n"
7244                 "%c_f32_p8  = OpConstant %f32 0.8\n";
7245
7246         // vec4 test_code(vec4 param) {
7247         //   vec4 result = param;
7248         //   for (int i = 0; i < 4; ++i) {
7249         //     float operand;
7250         //     switch (i) {
7251         //       case 0: operand = .2; break;
7252         //       case 1: operand = .5; break;
7253         //       case 2: operand = .4; break;
7254         //       case 3: operand = .0; break;
7255         //       default: break; // unreachable
7256         //     }
7257         //     result[i] += operand;
7258         //   }
7259         //   return result;
7260         // }
7261         const char      function1[]                             =
7262                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7263                 "%param1    = OpFunctionParameter %v4f32\n"
7264                 "%lbl       = OpLabel\n"
7265                 "%iptr      = OpVariable %fp_i32 Function\n"
7266                 "%result    = OpVariable %fp_v4f32 Function\n"
7267                 "             OpStore %iptr %c_i32_0\n"
7268                 "             OpStore %result %param1\n"
7269                 "             OpBranch %loop\n"
7270
7271                 "%loop      = OpLabel\n"
7272                 "%ival      = OpLoad %i32 %iptr\n"
7273                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
7274                 "             OpLoopMerge %exit %phi None\n"
7275                 "             OpBranchConditional %lt_4 %entry %exit\n"
7276
7277                 "%entry     = OpLabel\n"
7278                 "%loc       = OpAccessChain %fp_f32 %result %ival\n"
7279                 "%val       = OpLoad %f32 %loc\n"
7280                 "             OpSelectionMerge %phi None\n"
7281                 "             OpSwitch %ival %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
7282
7283                 "%case0     = OpLabel\n"
7284                 "             OpBranch %phi\n"
7285                 "%case1     = OpLabel\n"
7286                 "             OpBranch %phi\n"
7287                 "%case2     = OpLabel\n"
7288                 "             OpBranch %phi\n"
7289                 "%case3     = OpLabel\n"
7290                 "             OpBranch %phi\n"
7291
7292                 "%default   = OpLabel\n"
7293                 "             OpUnreachable\n"
7294
7295                 "%phi       = OpLabel\n"
7296                 "%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
7297                 "%add       = OpFAdd %f32 %val %operand\n"
7298                 "             OpStore %loc %add\n"
7299                 "%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
7300                 "             OpStore %iptr %ival_next\n"
7301                 "             OpBranch %loop\n"
7302
7303                 "%exit      = OpLabel\n"
7304                 "%ret       = OpLoad %v4f32 %result\n"
7305                 "             OpReturnValue %ret\n"
7306
7307                 "             OpFunctionEnd\n";
7308
7309         fragments1["pre_main"]  = typesAndConstants1;
7310         fragments1["testfun"]   = function1;
7311
7312         getHalfColorsFullAlpha(inputColors);
7313
7314         outputColors1[0]                = RGBA(178, 255, 229, 255);
7315         outputColors1[1]                = RGBA(178, 127, 102, 255);
7316         outputColors1[2]                = RGBA(51,  255, 102, 255);
7317         outputColors1[3]                = RGBA(51,  127, 229, 255);
7318
7319         createTestsForAllStages("out_of_order", inputColors, outputColors1, fragments1, group.get());
7320
7321         const char      typesAndConstants2[]    =
7322                 "%c_f32_p2  = OpConstant %f32 0.2\n";
7323
7324         // Add .4 to the second element of the given parameter.
7325         const char      function2[]                             =
7326                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7327                 "%param     = OpFunctionParameter %v4f32\n"
7328                 "%entry     = OpLabel\n"
7329                 "%result    = OpVariable %fp_v4f32 Function\n"
7330                 "             OpStore %result %param\n"
7331                 "%loc       = OpAccessChain %fp_f32 %result %c_i32_1\n"
7332                 "%val       = OpLoad %f32 %loc\n"
7333                 "             OpBranch %phi\n"
7334
7335                 "%phi        = OpLabel\n"
7336                 "%step       = OpPhi %i32 %c_i32_0  %entry %step_next  %phi\n"
7337                 "%accum      = OpPhi %f32 %val      %entry %accum_next %phi\n"
7338                 "%step_next  = OpIAdd %i32 %step  %c_i32_1\n"
7339                 "%accum_next = OpFAdd %f32 %accum %c_f32_p2\n"
7340                 "%still_loop = OpSLessThan %bool %step %c_i32_2\n"
7341                 "              OpLoopMerge %exit %phi None\n"
7342                 "              OpBranchConditional %still_loop %phi %exit\n"
7343
7344                 "%exit       = OpLabel\n"
7345                 "              OpStore %loc %accum\n"
7346                 "%ret        = OpLoad %v4f32 %result\n"
7347                 "              OpReturnValue %ret\n"
7348
7349                 "              OpFunctionEnd\n";
7350
7351         fragments2["pre_main"]  = typesAndConstants2;
7352         fragments2["testfun"]   = function2;
7353
7354         outputColors2[0]                        = RGBA(127, 229, 127, 255);
7355         outputColors2[1]                        = RGBA(127, 102, 0,   255);
7356         outputColors2[2]                        = RGBA(0,   229, 0,   255);
7357         outputColors2[3]                        = RGBA(0,   102, 127, 255);
7358
7359         createTestsForAllStages("induction", inputColors, outputColors2, fragments2, group.get());
7360
7361         const char      typesAndConstants3[]    =
7362                 "%true      = OpConstantTrue %bool\n"
7363                 "%false     = OpConstantFalse %bool\n"
7364                 "%c_f32_p2  = OpConstant %f32 0.2\n";
7365
7366         // Swap the second and the third element of the given parameter.
7367         const char      function3[]                             =
7368                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7369                 "%param     = OpFunctionParameter %v4f32\n"
7370                 "%entry     = OpLabel\n"
7371                 "%result    = OpVariable %fp_v4f32 Function\n"
7372                 "             OpStore %result %param\n"
7373                 "%a_loc     = OpAccessChain %fp_f32 %result %c_i32_1\n"
7374                 "%a_init    = OpLoad %f32 %a_loc\n"
7375                 "%b_loc     = OpAccessChain %fp_f32 %result %c_i32_2\n"
7376                 "%b_init    = OpLoad %f32 %b_loc\n"
7377                 "             OpBranch %phi\n"
7378
7379                 "%phi        = OpLabel\n"
7380                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
7381                 "%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
7382                 "%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
7383                 "              OpLoopMerge %exit %phi None\n"
7384                 "              OpBranchConditional %still_loop %phi %exit\n"
7385
7386                 "%exit       = OpLabel\n"
7387                 "              OpStore %a_loc %a_next\n"
7388                 "              OpStore %b_loc %b_next\n"
7389                 "%ret        = OpLoad %v4f32 %result\n"
7390                 "              OpReturnValue %ret\n"
7391
7392                 "              OpFunctionEnd\n";
7393
7394         fragments3["pre_main"]  = typesAndConstants3;
7395         fragments3["testfun"]   = function3;
7396
7397         outputColors3[0]                        = RGBA(127, 127, 127, 255);
7398         outputColors3[1]                        = RGBA(127, 0,   0,   255);
7399         outputColors3[2]                        = RGBA(0,   0,   127, 255);
7400         outputColors3[3]                        = RGBA(0,   127, 0,   255);
7401
7402         createTestsForAllStages("swap", inputColors, outputColors3, fragments3, group.get());
7403
7404         const char      typesAndConstants4[]    =
7405                 "%f16        = OpTypeFloat 16\n"
7406                 "%v4f16      = OpTypeVector %f16 4\n"
7407                 "%fp_f16     = OpTypePointer Function %f16\n"
7408                 "%fp_v4f16   = OpTypePointer Function %v4f16\n"
7409                 "%true       = OpConstantTrue %bool\n"
7410                 "%false      = OpConstantFalse %bool\n"
7411                 "%c_f32_p2   = OpConstant %f32 0.2\n";
7412
7413         // Swap the second and the third element of the given parameter.
7414         const char      function4[]                             =
7415                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7416                 "%param      = OpFunctionParameter %v4f32\n"
7417                 "%entry      = OpLabel\n"
7418                 "%result     = OpVariable %fp_v4f16 Function\n"
7419                 "%param16    = OpFConvert %v4f16 %param\n"
7420                 "              OpStore %result %param16\n"
7421                 "%a_loc      = OpAccessChain %fp_f16 %result %c_i32_1\n"
7422                 "%a_init     = OpLoad %f16 %a_loc\n"
7423                 "%b_loc      = OpAccessChain %fp_f16 %result %c_i32_2\n"
7424                 "%b_init     = OpLoad %f16 %b_loc\n"
7425                 "              OpBranch %phi\n"
7426
7427                 "%phi        = OpLabel\n"
7428                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
7429                 "%a_next     = OpPhi %f16  %a_init %entry %b_next %phi\n"
7430                 "%b_next     = OpPhi %f16  %b_init %entry %a_next %phi\n"
7431                 "              OpLoopMerge %exit %phi None\n"
7432                 "              OpBranchConditional %still_loop %phi %exit\n"
7433
7434                 "%exit       = OpLabel\n"
7435                 "              OpStore %a_loc %a_next\n"
7436                 "              OpStore %b_loc %b_next\n"
7437                 "%ret16      = OpLoad %v4f16 %result\n"
7438                 "%ret        = OpFConvert %v4f32 %ret16\n"
7439                 "              OpReturnValue %ret\n"
7440
7441                 "              OpFunctionEnd\n";
7442
7443         fragments4["pre_main"]          = typesAndConstants4;
7444         fragments4["testfun"]           = function4;
7445         fragments4["capability"]        = "OpCapability StorageUniformBufferBlock16\n";
7446         fragments4["extension"]         = "OpExtension \"SPV_KHR_16bit_storage\"";
7447
7448         extensions4.push_back("VK_KHR_16bit_storage");
7449         extensions4.push_back("VK_KHR_shader_float16_int8");
7450
7451         vulkanFeatures4.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
7452         vulkanFeatures4.extFloat16Int8  = EXTFLOAT16INT8FEATURES_FLOAT16;
7453
7454         outputColors4[0]                        = RGBA(127, 127, 127, 255);
7455         outputColors4[1]                        = RGBA(127, 0,   0,   255);
7456         outputColors4[2]                        = RGBA(0,   0,   127, 255);
7457         outputColors4[3]                        = RGBA(0,   127, 0,   255);
7458
7459         createTestsForAllStages("swap16", inputColors, outputColors4, fragments4, resources4, extensions4, group.get(), vulkanFeatures4);
7460
7461         return group.release();
7462 }
7463
7464 tcu::TestCaseGroup* createNoContractionTests(tcu::TestContext& testCtx)
7465 {
7466         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
7467         RGBA                                                    inputColors[4];
7468         RGBA                                                    outputColors[4];
7469
7470         // With NoContraction, (1 + 2^-23) * (1 - 2^-23) - 1 should be conducted as a multiplication and an addition separately.
7471         // For the multiplication, the result is 1 - 2^-46, which is out of the precision range for 32-bit float. (32-bit float
7472         // only have 23-bit fraction.) So it will be rounded to 1. Or 0x1.fffffc. Then the final result is 0 or -0x1p-24.
7473         // On the contrary, the result will be 2^-46, which is a normalized number perfectly representable as 32-bit float.
7474         const char                                              constantsAndTypes[]      =
7475                 "%c_vec4_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_0 %c_f32_1\n"
7476                 "%c_vec4_1       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
7477                 "%c_f32_1pl2_23  = OpConstant %f32 0x1.000002p+0\n" // 1 + 2^-23
7478                 "%c_f32_1mi2_23  = OpConstant %f32 0x1.fffffcp-1\n" // 1 - 2^-23
7479                 "%c_f32_n1pn24   = OpConstant %f32 -0x1p-24\n";
7480
7481         const char                                              function[]       =
7482                 "%test_code      = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7483                 "%param          = OpFunctionParameter %v4f32\n"
7484                 "%label          = OpLabel\n"
7485                 "%var1           = OpVariable %fp_f32 Function %c_f32_1pl2_23\n"
7486                 "%var2           = OpVariable %fp_f32 Function\n"
7487                 "%red            = OpCompositeExtract %f32 %param 0\n"
7488                 "%plus_red       = OpFAdd %f32 %c_f32_1mi2_23 %red\n"
7489                 "                  OpStore %var2 %plus_red\n"
7490                 "%val1           = OpLoad %f32 %var1\n"
7491                 "%val2           = OpLoad %f32 %var2\n"
7492                 "%mul            = OpFMul %f32 %val1 %val2\n"
7493                 "%add            = OpFAdd %f32 %mul %c_f32_n1\n"
7494                 "%is0            = OpFOrdEqual %bool %add %c_f32_0\n"
7495                 "%isn1n24         = OpFOrdEqual %bool %add %c_f32_n1pn24\n"
7496                 "%success        = OpLogicalOr %bool %is0 %isn1n24\n"
7497                 "%v4success      = OpCompositeConstruct %v4bool %success %success %success %success\n"
7498                 "%ret            = OpSelect %v4f32 %v4success %c_vec4_0 %c_vec4_1\n"
7499                 "                  OpReturnValue %ret\n"
7500                 "                  OpFunctionEnd\n";
7501
7502         struct CaseNameDecoration
7503         {
7504                 string name;
7505                 string decoration;
7506         };
7507
7508
7509         CaseNameDecoration tests[] = {
7510                 {"multiplication",      "OpDecorate %mul NoContraction"},
7511                 {"addition",            "OpDecorate %add NoContraction"},
7512                 {"both",                        "OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"},
7513         };
7514
7515         getHalfColorsFullAlpha(inputColors);
7516
7517         for (deUint8 idx = 0; idx < 4; ++idx)
7518         {
7519                 inputColors[idx].setRed(0);
7520                 outputColors[idx] = RGBA(0, 0, 0, 255);
7521         }
7522
7523         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(CaseNameDecoration); ++testNdx)
7524         {
7525                 map<string, string> fragments;
7526
7527                 fragments["decoration"] = tests[testNdx].decoration;
7528                 fragments["pre_main"] = constantsAndTypes;
7529                 fragments["testfun"] = function;
7530
7531                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, group.get());
7532         }
7533
7534         return group.release();
7535 }
7536
7537 tcu::TestCaseGroup* createMemoryAccessTests(tcu::TestContext& testCtx)
7538 {
7539         de::MovePtr<tcu::TestCaseGroup> memoryAccessTests (new tcu::TestCaseGroup(testCtx, "opmemoryaccess", "Memory Semantics"));
7540         RGBA                                                    colors[4];
7541
7542         const char                                              constantsAndTypes[]      =
7543                 "%c_a2f32_1         = OpConstantComposite %a2f32 %c_f32_1 %c_f32_1\n"
7544                 "%fp_a2f32          = OpTypePointer Function %a2f32\n"
7545                 "%stype             = OpTypeStruct  %v4f32 %a2f32 %f32\n"
7546                 "%fp_stype          = OpTypePointer Function %stype\n";
7547
7548         const char                                              function[]       =
7549                 "%test_code         = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7550                 "%param1            = OpFunctionParameter %v4f32\n"
7551                 "%lbl               = OpLabel\n"
7552                 "%v1                = OpVariable %fp_v4f32 Function\n"
7553                 "%v2                = OpVariable %fp_a2f32 Function\n"
7554                 "%v3                = OpVariable %fp_f32 Function\n"
7555                 "%v                 = OpVariable %fp_stype Function\n"
7556                 "%vv                = OpVariable %fp_stype Function\n"
7557                 "%vvv               = OpVariable %fp_f32 Function\n"
7558
7559                 "                     OpStore %v1 %c_v4f32_1_1_1_1\n"
7560                 "                     OpStore %v2 %c_a2f32_1\n"
7561                 "                     OpStore %v3 %c_f32_1\n"
7562
7563                 "%p_v4f32          = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
7564                 "%p_a2f32          = OpAccessChain %fp_a2f32 %v %c_u32_1\n"
7565                 "%p_f32            = OpAccessChain %fp_f32 %v %c_u32_2\n"
7566                 "%v1_v             = OpLoad %v4f32 %v1 ${access_type}\n"
7567                 "%v2_v             = OpLoad %a2f32 %v2 ${access_type}\n"
7568                 "%v3_v             = OpLoad %f32 %v3 ${access_type}\n"
7569
7570                 "                    OpStore %p_v4f32 %v1_v ${access_type}\n"
7571                 "                    OpStore %p_a2f32 %v2_v ${access_type}\n"
7572                 "                    OpStore %p_f32 %v3_v ${access_type}\n"
7573
7574                 "                    OpCopyMemory %vv %v ${access_type}\n"
7575                 "                    OpCopyMemory %vvv %p_f32 ${access_type}\n"
7576
7577                 "%p_f32_2          = OpAccessChain %fp_f32 %vv %c_u32_2\n"
7578                 "%v_f32_2          = OpLoad %f32 %p_f32_2\n"
7579                 "%v_f32_3          = OpLoad %f32 %vvv\n"
7580
7581                 "%ret1             = OpVectorTimesScalar %v4f32 %param1 %v_f32_2\n"
7582                 "%ret2             = OpVectorTimesScalar %v4f32 %ret1 %v_f32_3\n"
7583                 "                    OpReturnValue %ret2\n"
7584                 "                    OpFunctionEnd\n";
7585
7586         struct NameMemoryAccess
7587         {
7588                 string name;
7589                 string accessType;
7590         };
7591
7592
7593         NameMemoryAccess tests[] =
7594         {
7595                 { "none", "" },
7596                 { "volatile", "Volatile" },
7597                 { "aligned",  "Aligned 1" },
7598                 { "volatile_aligned",  "Volatile|Aligned 1" },
7599                 { "nontemporal_aligned",  "Nontemporal|Aligned 1" },
7600                 { "volatile_nontemporal",  "Volatile|Nontemporal" },
7601                 { "volatile_nontermporal_aligned",  "Volatile|Nontemporal|Aligned 1" },
7602         };
7603
7604         getHalfColorsFullAlpha(colors);
7605
7606         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameMemoryAccess); ++testNdx)
7607         {
7608                 map<string, string> fragments;
7609                 map<string, string> memoryAccess;
7610                 memoryAccess["access_type"] = tests[testNdx].accessType;
7611
7612                 fragments["pre_main"] = constantsAndTypes;
7613                 fragments["testfun"] = tcu::StringTemplate(function).specialize(memoryAccess);
7614                 createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, memoryAccessTests.get());
7615         }
7616         return memoryAccessTests.release();
7617 }
7618 tcu::TestCaseGroup* createOpUndefTests(tcu::TestContext& testCtx)
7619 {
7620         de::MovePtr<tcu::TestCaseGroup>         opUndefTests             (new tcu::TestCaseGroup(testCtx, "opundef", "Test OpUndef"));
7621         RGBA                                                            defaultColors[4];
7622         map<string, string>                                     fragments;
7623         getDefaultColors(defaultColors);
7624
7625         // First, simple cases that don't do anything with the OpUndef result.
7626         struct NameCodePair { string name, decl, type; };
7627         const NameCodePair tests[] =
7628         {
7629                 {"bool", "", "%bool"},
7630                 {"vec2uint32", "", "%v2u32"},
7631                 {"image", "%type = OpTypeImage %f32 2D 0 0 0 1 Unknown", "%type"},
7632                 {"sampler", "%type = OpTypeSampler", "%type"},
7633                 {"sampledimage", "%img = OpTypeImage %f32 2D 0 0 0 1 Unknown\n" "%type = OpTypeSampledImage %img", "%type"},
7634                 {"pointer", "", "%fp_i32"},
7635                 {"runtimearray", "%type = OpTypeRuntimeArray %f32", "%type"},
7636                 {"array", "%c_u32_100 = OpConstant %u32 100\n" "%type = OpTypeArray %i32 %c_u32_100", "%type"},
7637                 {"struct", "%type = OpTypeStruct %f32 %i32 %u32", "%type"}};
7638         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
7639         {
7640                 fragments["undef_type"] = tests[testNdx].type;
7641                 fragments["testfun"] = StringTemplate(
7642                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7643                         "%param1 = OpFunctionParameter %v4f32\n"
7644                         "%label_testfun = OpLabel\n"
7645                         "%undef = OpUndef ${undef_type}\n"
7646                         "OpReturnValue %param1\n"
7647                         "OpFunctionEnd\n").specialize(fragments);
7648                 fragments["pre_main"] = tests[testNdx].decl;
7649                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opUndefTests.get());
7650         }
7651         fragments.clear();
7652
7653         fragments["testfun"] =
7654                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7655                 "%param1 = OpFunctionParameter %v4f32\n"
7656                 "%label_testfun = OpLabel\n"
7657                 "%undef = OpUndef %f32\n"
7658                 "%zero = OpFMul %f32 %undef %c_f32_0\n"
7659                 "%is_nan = OpIsNan %bool %zero\n" //OpUndef may result in NaN which may turn %zero into Nan.
7660                 "%actually_zero = OpSelect %f32 %is_nan %c_f32_0 %zero\n"
7661                 "%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7662                 "%b = OpFAdd %f32 %a %actually_zero\n"
7663                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %b %c_i32_0\n"
7664                 "OpReturnValue %ret\n"
7665                 "OpFunctionEnd\n";
7666
7667         createTestsForAllStages("float32", defaultColors, defaultColors, fragments, opUndefTests.get());
7668
7669         fragments["testfun"] =
7670                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7671                 "%param1 = OpFunctionParameter %v4f32\n"
7672                 "%label_testfun = OpLabel\n"
7673                 "%undef = OpUndef %i32\n"
7674                 "%zero = OpIMul %i32 %undef %c_i32_0\n"
7675                 "%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
7676                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
7677                 "OpReturnValue %ret\n"
7678                 "OpFunctionEnd\n";
7679
7680         createTestsForAllStages("sint32", defaultColors, defaultColors, fragments, opUndefTests.get());
7681
7682         fragments["testfun"] =
7683                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7684                 "%param1 = OpFunctionParameter %v4f32\n"
7685                 "%label_testfun = OpLabel\n"
7686                 "%undef = OpUndef %u32\n"
7687                 "%zero = OpIMul %u32 %undef %c_i32_0\n"
7688                 "%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
7689                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
7690                 "OpReturnValue %ret\n"
7691                 "OpFunctionEnd\n";
7692
7693         createTestsForAllStages("uint32", defaultColors, defaultColors, fragments, opUndefTests.get());
7694
7695         fragments["testfun"] =
7696                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7697                 "%param1 = OpFunctionParameter %v4f32\n"
7698                 "%label_testfun = OpLabel\n"
7699                 "%undef = OpUndef %v4f32\n"
7700                 "%vzero = OpVectorTimesScalar %v4f32 %undef %c_f32_0\n"
7701                 "%zero_0 = OpVectorExtractDynamic %f32 %vzero %c_i32_0\n"
7702                 "%zero_1 = OpVectorExtractDynamic %f32 %vzero %c_i32_1\n"
7703                 "%zero_2 = OpVectorExtractDynamic %f32 %vzero %c_i32_2\n"
7704                 "%zero_3 = OpVectorExtractDynamic %f32 %vzero %c_i32_3\n"
7705                 "%is_nan_0 = OpIsNan %bool %zero_0\n"
7706                 "%is_nan_1 = OpIsNan %bool %zero_1\n"
7707                 "%is_nan_2 = OpIsNan %bool %zero_2\n"
7708                 "%is_nan_3 = OpIsNan %bool %zero_3\n"
7709                 "%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
7710                 "%actually_zero_1 = OpSelect %f32 %is_nan_1 %c_f32_0 %zero_1\n"
7711                 "%actually_zero_2 = OpSelect %f32 %is_nan_2 %c_f32_0 %zero_2\n"
7712                 "%actually_zero_3 = OpSelect %f32 %is_nan_3 %c_f32_0 %zero_3\n"
7713                 "%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7714                 "%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
7715                 "%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
7716                 "%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
7717                 "%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
7718                 "%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
7719                 "%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
7720                 "%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
7721                 "%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
7722                 "%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
7723                 "%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
7724                 "%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
7725                 "OpReturnValue %ret\n"
7726                 "OpFunctionEnd\n";
7727
7728         createTestsForAllStages("vec4float32", defaultColors, defaultColors, fragments, opUndefTests.get());
7729
7730         fragments["pre_main"] =
7731                 "%m2x2f32 = OpTypeMatrix %v2f32 2\n";
7732         fragments["testfun"] =
7733                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7734                 "%param1 = OpFunctionParameter %v4f32\n"
7735                 "%label_testfun = OpLabel\n"
7736                 "%undef = OpUndef %m2x2f32\n"
7737                 "%mzero = OpMatrixTimesScalar %m2x2f32 %undef %c_f32_0\n"
7738                 "%zero_0 = OpCompositeExtract %f32 %mzero 0 0\n"
7739                 "%zero_1 = OpCompositeExtract %f32 %mzero 0 1\n"
7740                 "%zero_2 = OpCompositeExtract %f32 %mzero 1 0\n"
7741                 "%zero_3 = OpCompositeExtract %f32 %mzero 1 1\n"
7742                 "%is_nan_0 = OpIsNan %bool %zero_0\n"
7743                 "%is_nan_1 = OpIsNan %bool %zero_1\n"
7744                 "%is_nan_2 = OpIsNan %bool %zero_2\n"
7745                 "%is_nan_3 = OpIsNan %bool %zero_3\n"
7746                 "%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
7747                 "%actually_zero_1 = OpSelect %f32 %is_nan_1 %c_f32_0 %zero_1\n"
7748                 "%actually_zero_2 = OpSelect %f32 %is_nan_2 %c_f32_0 %zero_2\n"
7749                 "%actually_zero_3 = OpSelect %f32 %is_nan_3 %c_f32_0 %zero_3\n"
7750                 "%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7751                 "%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
7752                 "%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
7753                 "%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
7754                 "%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
7755                 "%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
7756                 "%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
7757                 "%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
7758                 "%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
7759                 "%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
7760                 "%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
7761                 "%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
7762                 "OpReturnValue %ret\n"
7763                 "OpFunctionEnd\n";
7764
7765         createTestsForAllStages("matrix", defaultColors, defaultColors, fragments, opUndefTests.get());
7766
7767         return opUndefTests.release();
7768 }
7769
7770 void createOpQuantizeSingleOptionTests(tcu::TestCaseGroup* testCtx)
7771 {
7772         const RGBA              inputColors[4]          =
7773         {
7774                 RGBA(0,         0,              0,              255),
7775                 RGBA(0,         0,              255,    255),
7776                 RGBA(0,         255,    0,              255),
7777                 RGBA(0,         255,    255,    255)
7778         };
7779
7780         const RGBA              expectedColors[4]       =
7781         {
7782                 RGBA(255,        0,              0,              255),
7783                 RGBA(255,        0,              0,              255),
7784                 RGBA(255,        0,              0,              255),
7785                 RGBA(255,        0,              0,              255)
7786         };
7787
7788         const struct SingleFP16Possibility
7789         {
7790                 const char* name;
7791                 const char* constant;  // Value to assign to %test_constant.
7792                 float           valueAsFloat;
7793                 const char* condition; // Must assign to %cond an expression that evaluates to true after %c = OpQuantizeToF16(%test_constant + 0).
7794         }                               tests[]                         =
7795         {
7796                 {
7797                         "negative",
7798                         "-0x1.3p1\n",
7799                         -constructNormalizedFloat(1, 0x300000),
7800                         "%cond = OpFOrdEqual %bool %c %test_constant\n"
7801                 }, // -19
7802                 {
7803                         "positive",
7804                         "0x1.0p7\n",
7805                         constructNormalizedFloat(7, 0x000000),
7806                         "%cond = OpFOrdEqual %bool %c %test_constant\n"
7807                 },  // +128
7808                 // SPIR-V requires that OpQuantizeToF16 flushes
7809                 // any numbers that would end up denormalized in F16 to zero.
7810                 {
7811                         "denorm",
7812                         "0x0.0006p-126\n",
7813                         std::ldexp(1.5f, -140),
7814                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7815                 },  // denorm
7816                 {
7817                         "negative_denorm",
7818                         "-0x0.0006p-126\n",
7819                         -std::ldexp(1.5f, -140),
7820                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7821                 }, // -denorm
7822                 {
7823                         "too_small",
7824                         "0x1.0p-16\n",
7825                         std::ldexp(1.0f, -16),
7826                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7827                 },     // too small positive
7828                 {
7829                         "negative_too_small",
7830                         "-0x1.0p-32\n",
7831                         -std::ldexp(1.0f, -32),
7832                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7833                 },      // too small negative
7834                 {
7835                         "negative_inf",
7836                         "-0x1.0p128\n",
7837                         -std::ldexp(1.0f, 128),
7838
7839                         "%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
7840                         "%inf = OpIsInf %bool %c\n"
7841                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7842                 },     // -inf to -inf
7843                 {
7844                         "inf",
7845                         "0x1.0p128\n",
7846                         std::ldexp(1.0f, 128),
7847
7848                         "%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
7849                         "%inf = OpIsInf %bool %c\n"
7850                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7851                 },     // +inf to +inf
7852                 {
7853                         "round_to_negative_inf",
7854                         "-0x1.0p32\n",
7855                         -std::ldexp(1.0f, 32),
7856
7857                         "%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
7858                         "%inf = OpIsInf %bool %c\n"
7859                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7860                 },     // round to -inf
7861                 {
7862                         "round_to_inf",
7863                         "0x1.0p16\n",
7864                         std::ldexp(1.0f, 16),
7865
7866                         "%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
7867                         "%inf = OpIsInf %bool %c\n"
7868                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7869                 },     // round to +inf
7870                 {
7871                         "nan",
7872                         "0x1.1p128\n",
7873                         std::numeric_limits<float>::quiet_NaN(),
7874
7875                         // Test for any NaN value, as NaNs are not preserved
7876                         "%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
7877                         "%cond = OpIsNan %bool %direct_quant\n"
7878                 }, // nan
7879                 {
7880                         "negative_nan",
7881                         "-0x1.0001p128\n",
7882                         std::numeric_limits<float>::quiet_NaN(),
7883
7884                         // Test for any NaN value, as NaNs are not preserved
7885                         "%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
7886                         "%cond = OpIsNan %bool %direct_quant\n"
7887                 } // -nan
7888         };
7889         const char*             constants                       =
7890                 "%test_constant = OpConstant %f32 ";  // The value will be test.constant.
7891
7892         StringTemplate  function                        (
7893                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7894                 "%param1        = OpFunctionParameter %v4f32\n"
7895                 "%label_testfun = OpLabel\n"
7896                 "%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7897                 "%b             = OpFAdd %f32 %test_constant %a\n"
7898                 "%c             = OpQuantizeToF16 %f32 %b\n"
7899                 "${condition}\n"
7900                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
7901                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
7902                 "                 OpReturnValue %retval\n"
7903                 "OpFunctionEnd\n"
7904         );
7905
7906         const char*             specDecorations         = "OpDecorate %test_constant SpecId 0\n";
7907         const char*             specConstants           =
7908                         "%test_constant = OpSpecConstant %f32 0.\n"
7909                         "%c             = OpSpecConstantOp %f32 QuantizeToF16 %test_constant\n";
7910
7911         StringTemplate  specConstantFunction(
7912                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7913                 "%param1        = OpFunctionParameter %v4f32\n"
7914                 "%label_testfun = OpLabel\n"
7915                 "${condition}\n"
7916                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
7917                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
7918                 "                 OpReturnValue %retval\n"
7919                 "OpFunctionEnd\n"
7920         );
7921
7922         for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
7923         {
7924                 map<string, string>                                                             codeSpecialization;
7925                 map<string, string>                                                             fragments;
7926                 codeSpecialization["condition"]                                 = tests[idx].condition;
7927                 fragments["testfun"]                                                    = function.specialize(codeSpecialization);
7928                 fragments["pre_main"]                                                   = string(constants) + tests[idx].constant + "\n";
7929                 createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
7930         }
7931
7932         for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
7933         {
7934                 map<string, string>                                                             codeSpecialization;
7935                 map<string, string>                                                             fragments;
7936                 SpecConstants                                                                   passConstants;
7937
7938                 codeSpecialization["condition"]                                 = tests[idx].condition;
7939                 fragments["testfun"]                                                    = specConstantFunction.specialize(codeSpecialization);
7940                 fragments["decoration"]                                                 = specDecorations;
7941                 fragments["pre_main"]                                                   = specConstants;
7942
7943                 passConstants.append<float>(tests[idx].valueAsFloat);
7944
7945                 createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
7946         }
7947 }
7948
7949 void createOpQuantizeTwoPossibilityTests(tcu::TestCaseGroup* testCtx)
7950 {
7951         RGBA inputColors[4] =  {
7952                 RGBA(0,         0,              0,              255),
7953                 RGBA(0,         0,              255,    255),
7954                 RGBA(0,         255,    0,              255),
7955                 RGBA(0,         255,    255,    255)
7956         };
7957
7958         RGBA expectedColors[4] =
7959         {
7960                 RGBA(255,        0,              0,              255),
7961                 RGBA(255,        0,              0,              255),
7962                 RGBA(255,        0,              0,              255),
7963                 RGBA(255,        0,              0,              255)
7964         };
7965
7966         struct DualFP16Possibility
7967         {
7968                 const char* name;
7969                 const char* input;
7970                 float           inputAsFloat;
7971                 const char* possibleOutput1;
7972                 const char* possibleOutput2;
7973         } tests[] = {
7974                 {
7975                         "positive_round_up_or_round_down",
7976                         "0x1.3003p8",
7977                         constructNormalizedFloat(8, 0x300300),
7978                         "0x1.304p8",
7979                         "0x1.3p8"
7980                 },
7981                 {
7982                         "negative_round_up_or_round_down",
7983                         "-0x1.6008p-7",
7984                         -constructNormalizedFloat(-7, 0x600800),
7985                         "-0x1.6p-7",
7986                         "-0x1.604p-7"
7987                 },
7988                 {
7989                         "carry_bit",
7990                         "0x1.01ep2",
7991                         constructNormalizedFloat(2, 0x01e000),
7992                         "0x1.01cp2",
7993                         "0x1.02p2"
7994                 },
7995                 {
7996                         "carry_to_exponent",
7997                         "0x1.ffep1",
7998                         constructNormalizedFloat(1, 0xffe000),
7999                         "0x1.ffcp1",
8000                         "0x1.0p2"
8001                 },
8002         };
8003         StringTemplate constants (
8004                 "%input_const = OpConstant %f32 ${input}\n"
8005                 "%possible_solution1 = OpConstant %f32 ${output1}\n"
8006                 "%possible_solution2 = OpConstant %f32 ${output2}\n"
8007                 );
8008
8009         StringTemplate specConstants (
8010                 "%input_const = OpSpecConstant %f32 0.\n"
8011                 "%possible_solution1 = OpConstant %f32 ${output1}\n"
8012                 "%possible_solution2 = OpConstant %f32 ${output2}\n"
8013         );
8014
8015         const char* specDecorations = "OpDecorate %input_const  SpecId 0\n";
8016
8017         const char* function  =
8018                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8019                 "%param1        = OpFunctionParameter %v4f32\n"
8020                 "%label_testfun = OpLabel\n"
8021                 "%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8022                 // For the purposes of this test we assume that 0.f will always get
8023                 // faithfully passed through the pipeline stages.
8024                 "%b             = OpFAdd %f32 %input_const %a\n"
8025                 "%c             = OpQuantizeToF16 %f32 %b\n"
8026                 "%eq_1          = OpFOrdEqual %bool %c %possible_solution1\n"
8027                 "%eq_2          = OpFOrdEqual %bool %c %possible_solution2\n"
8028                 "%cond          = OpLogicalOr %bool %eq_1 %eq_2\n"
8029                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
8030                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1"
8031                 "                 OpReturnValue %retval\n"
8032                 "OpFunctionEnd\n";
8033
8034         for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
8035                 map<string, string>                                                                     fragments;
8036                 map<string, string>                                                                     constantSpecialization;
8037
8038                 constantSpecialization["input"]                                         = tests[idx].input;
8039                 constantSpecialization["output1"]                                       = tests[idx].possibleOutput1;
8040                 constantSpecialization["output2"]                                       = tests[idx].possibleOutput2;
8041                 fragments["testfun"]                                                            = function;
8042                 fragments["pre_main"]                                                           = constants.specialize(constantSpecialization);
8043                 createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
8044         }
8045
8046         for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
8047                 map<string, string>                                                                     fragments;
8048                 map<string, string>                                                                     constantSpecialization;
8049                 SpecConstants                                                                           passConstants;
8050
8051                 constantSpecialization["output1"]                                       = tests[idx].possibleOutput1;
8052                 constantSpecialization["output2"]                                       = tests[idx].possibleOutput2;
8053                 fragments["testfun"]                                                            = function;
8054                 fragments["decoration"]                                                         = specDecorations;
8055                 fragments["pre_main"]                                                           = specConstants.specialize(constantSpecialization);
8056
8057                 passConstants.append<float>(tests[idx].inputAsFloat);
8058
8059                 createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
8060         }
8061 }
8062
8063 tcu::TestCaseGroup* createOpQuantizeTests(tcu::TestContext& testCtx)
8064 {
8065         de::MovePtr<tcu::TestCaseGroup> opQuantizeTests (new tcu::TestCaseGroup(testCtx, "opquantize", "Test OpQuantizeToF16"));
8066         createOpQuantizeSingleOptionTests(opQuantizeTests.get());
8067         createOpQuantizeTwoPossibilityTests(opQuantizeTests.get());
8068         return opQuantizeTests.release();
8069 }
8070
8071 struct ShaderPermutation
8072 {
8073         deUint8 vertexPermutation;
8074         deUint8 geometryPermutation;
8075         deUint8 tesscPermutation;
8076         deUint8 tessePermutation;
8077         deUint8 fragmentPermutation;
8078 };
8079
8080 ShaderPermutation getShaderPermutation(deUint8 inputValue)
8081 {
8082         ShaderPermutation       permutation =
8083         {
8084                 static_cast<deUint8>(inputValue & 0x10? 1u: 0u),
8085                 static_cast<deUint8>(inputValue & 0x08? 1u: 0u),
8086                 static_cast<deUint8>(inputValue & 0x04? 1u: 0u),
8087                 static_cast<deUint8>(inputValue & 0x02? 1u: 0u),
8088                 static_cast<deUint8>(inputValue & 0x01? 1u: 0u)
8089         };
8090         return permutation;
8091 }
8092
8093 tcu::TestCaseGroup* createModuleTests(tcu::TestContext& testCtx)
8094 {
8095         RGBA                                                            defaultColors[4];
8096         RGBA                                                            invertedColors[4];
8097         de::MovePtr<tcu::TestCaseGroup>         moduleTests                     (new tcu::TestCaseGroup(testCtx, "module", "Multiple entry points into shaders"));
8098
8099         getDefaultColors(defaultColors);
8100         getInvertedDefaultColors(invertedColors);
8101
8102         // Combined module tests
8103         {
8104                 // Shader stages: vertex and fragment
8105                 {
8106                         const ShaderElement combinedPipeline[]  =
8107                         {
8108                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8109                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8110                         };
8111
8112                         addFunctionCaseWithPrograms<InstanceContext>(
8113                                 moduleTests.get(), "same_module", "", createCombinedModule, runAndVerifyDefaultPipeline,
8114                                 createInstanceContext(combinedPipeline, map<string, string>()));
8115                 }
8116
8117                 // Shader stages: vertex, geometry and fragment
8118                 {
8119                         const ShaderElement combinedPipeline[]  =
8120                         {
8121                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8122                                 ShaderElement("module", "main", VK_SHADER_STAGE_GEOMETRY_BIT),
8123                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8124                         };
8125
8126                         addFunctionCaseWithPrograms<InstanceContext>(
8127                                 moduleTests.get(), "same_module_geom", "", createCombinedModule, runAndVerifyDefaultPipeline,
8128                                 createInstanceContext(combinedPipeline, map<string, string>()));
8129                 }
8130
8131                 // Shader stages: vertex, tessellation control, tessellation evaluation and fragment
8132                 {
8133                         const ShaderElement combinedPipeline[]  =
8134                         {
8135                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8136                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8137                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8138                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8139                         };
8140
8141                         addFunctionCaseWithPrograms<InstanceContext>(
8142                                 moduleTests.get(), "same_module_tessc_tesse", "", createCombinedModule, runAndVerifyDefaultPipeline,
8143                                 createInstanceContext(combinedPipeline, map<string, string>()));
8144                 }
8145
8146                 // Shader stages: vertex, tessellation control, tessellation evaluation, geometry and fragment
8147                 {
8148                         const ShaderElement combinedPipeline[]  =
8149                         {
8150                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8151                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8152                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8153                                 ShaderElement("module", "main", VK_SHADER_STAGE_GEOMETRY_BIT),
8154                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8155                         };
8156
8157                         addFunctionCaseWithPrograms<InstanceContext>(
8158                                 moduleTests.get(), "same_module_tessc_tesse_geom", "", createCombinedModule, runAndVerifyDefaultPipeline,
8159                                 createInstanceContext(combinedPipeline, map<string, string>()));
8160                 }
8161         }
8162
8163         const char* numbers[] =
8164         {
8165                 "1", "2"
8166         };
8167
8168         for (deInt8 idx = 0; idx < 32; ++idx)
8169         {
8170                 ShaderPermutation                       permutation             = getShaderPermutation(idx);
8171                 string                                          name                    = string("vert") + numbers[permutation.vertexPermutation] + "_geom" + numbers[permutation.geometryPermutation] + "_tessc" + numbers[permutation.tesscPermutation] + "_tesse" + numbers[permutation.tessePermutation] + "_frag" + numbers[permutation.fragmentPermutation];
8172                 const ShaderElement                     pipeline[]              =
8173                 {
8174                         ShaderElement("vert",   string("vert") +        numbers[permutation.vertexPermutation],         VK_SHADER_STAGE_VERTEX_BIT),
8175                         ShaderElement("geom",   string("geom") +        numbers[permutation.geometryPermutation],       VK_SHADER_STAGE_GEOMETRY_BIT),
8176                         ShaderElement("tessc",  string("tessc") +       numbers[permutation.tesscPermutation],          VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8177                         ShaderElement("tesse",  string("tesse") +       numbers[permutation.tessePermutation],          VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8178                         ShaderElement("frag",   string("frag") +        numbers[permutation.fragmentPermutation],       VK_SHADER_STAGE_FRAGMENT_BIT)
8179                 };
8180
8181                 // If there are an even number of swaps, then it should be no-op.
8182                 // If there are an odd number, the color should be flipped.
8183                 if ((permutation.vertexPermutation + permutation.geometryPermutation + permutation.tesscPermutation + permutation.tessePermutation + permutation.fragmentPermutation) % 2 == 0)
8184                 {
8185                         addFunctionCaseWithPrograms<InstanceContext>(
8186                                         moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline,
8187                                         createInstanceContext(pipeline, defaultColors, defaultColors, map<string, string>()));
8188                 }
8189                 else
8190                 {
8191                         addFunctionCaseWithPrograms<InstanceContext>(
8192                                         moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline,
8193                                         createInstanceContext(pipeline, defaultColors, invertedColors, map<string, string>()));
8194                 }
8195         }
8196         return moduleTests.release();
8197 }
8198
8199 tcu::TestCaseGroup* createLoopTests(tcu::TestContext& testCtx)
8200 {
8201         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "loop", "Looping control flow"));
8202         RGBA defaultColors[4];
8203         getDefaultColors(defaultColors);
8204         map<string, string> fragments;
8205         fragments["pre_main"] =
8206                 "%c_f32_5 = OpConstant %f32 5.\n";
8207
8208         // A loop with a single block. The Continue Target is the loop block
8209         // itself. In SPIR-V terms, the "loop construct" contains no blocks at all
8210         // -- the "continue construct" forms the entire loop.
8211         fragments["testfun"] =
8212                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8213                 "%param1 = OpFunctionParameter %v4f32\n"
8214
8215                 "%entry = OpLabel\n"
8216                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8217                 "OpBranch %loop\n"
8218
8219                 ";adds and subtracts 1.0 to %val in alternate iterations\n"
8220                 "%loop = OpLabel\n"
8221                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
8222                 "%delta = OpPhi %f32 %c_f32_1 %entry %minus_delta %loop\n"
8223                 "%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
8224                 "%val = OpFAdd %f32 %val1 %delta\n"
8225                 "%minus_delta = OpFSub %f32 %c_f32_0 %delta\n"
8226                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8227                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8228                 "OpLoopMerge %exit %loop None\n"
8229                 "OpBranchConditional %again %loop %exit\n"
8230
8231                 "%exit = OpLabel\n"
8232                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8233                 "OpReturnValue %result\n"
8234
8235                 "OpFunctionEnd\n";
8236
8237         createTestsForAllStages("single_block", defaultColors, defaultColors, fragments, testGroup.get());
8238
8239         // Body comprised of multiple basic blocks.
8240         const StringTemplate multiBlock(
8241                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8242                 "%param1 = OpFunctionParameter %v4f32\n"
8243
8244                 "%entry = OpLabel\n"
8245                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8246                 "OpBranch %loop\n"
8247
8248                 ";adds and subtracts 1.0 to %val in alternate iterations\n"
8249                 "%loop = OpLabel\n"
8250                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %gather\n"
8251                 "%delta = OpPhi %f32 %c_f32_1 %entry %delta_next %gather\n"
8252                 "%val1 = OpPhi %f32 %val0 %entry %val %gather\n"
8253                 // There are several possibilities for the Continue Target below.  Each
8254                 // will be specialized into a separate test case.
8255                 "OpLoopMerge %exit ${continue_target} None\n"
8256                 "OpBranch %if\n"
8257
8258                 "%if = OpLabel\n"
8259                 ";delta_next = (delta > 0) ? -1 : 1;\n"
8260                 "%gt0 = OpFOrdGreaterThan %bool %delta %c_f32_0\n"
8261                 "OpSelectionMerge %gather DontFlatten\n"
8262                 "OpBranchConditional %gt0 %even %odd ;tells us if %count is even or odd\n"
8263
8264                 "%odd = OpLabel\n"
8265                 "OpBranch %gather\n"
8266
8267                 "%even = OpLabel\n"
8268                 "OpBranch %gather\n"
8269
8270                 "%gather = OpLabel\n"
8271                 "%delta_next = OpPhi %f32 %c_f32_n1 %even %c_f32_1 %odd\n"
8272                 "%val = OpFAdd %f32 %val1 %delta\n"
8273                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8274                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8275                 "OpBranchConditional %again %loop %exit\n"
8276
8277                 "%exit = OpLabel\n"
8278                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8279                 "OpReturnValue %result\n"
8280
8281                 "OpFunctionEnd\n");
8282
8283         map<string, string> continue_target;
8284
8285         // The Continue Target is the loop block itself.
8286         continue_target["continue_target"] = "%loop";
8287         fragments["testfun"] = multiBlock.specialize(continue_target);
8288         createTestsForAllStages("multi_block_continue_construct", defaultColors, defaultColors, fragments, testGroup.get());
8289
8290         // The Continue Target is at the end of the loop.
8291         continue_target["continue_target"] = "%gather";
8292         fragments["testfun"] = multiBlock.specialize(continue_target);
8293         createTestsForAllStages("multi_block_loop_construct", defaultColors, defaultColors, fragments, testGroup.get());
8294
8295         // A loop with continue statement.
8296         fragments["testfun"] =
8297                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8298                 "%param1 = OpFunctionParameter %v4f32\n"
8299
8300                 "%entry = OpLabel\n"
8301                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8302                 "OpBranch %loop\n"
8303
8304                 ";adds 4, 3, and 1 to %val0 (skips 2)\n"
8305                 "%loop = OpLabel\n"
8306                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8307                 "%val1 = OpPhi %f32 %val0 %entry %val %continue\n"
8308                 "OpLoopMerge %exit %continue None\n"
8309                 "OpBranch %if\n"
8310
8311                 "%if = OpLabel\n"
8312                 ";skip if %count==2\n"
8313                 "%eq2 = OpIEqual %bool %count %c_i32_2\n"
8314                 "OpSelectionMerge %continue DontFlatten\n"
8315                 "OpBranchConditional %eq2 %continue %body\n"
8316
8317                 "%body = OpLabel\n"
8318                 "%fcount = OpConvertSToF %f32 %count\n"
8319                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8320                 "OpBranch %continue\n"
8321
8322                 "%continue = OpLabel\n"
8323                 "%val = OpPhi %f32 %val2 %body %val1 %if\n"
8324                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8325                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8326                 "OpBranchConditional %again %loop %exit\n"
8327
8328                 "%exit = OpLabel\n"
8329                 "%same = OpFSub %f32 %val %c_f32_8\n"
8330                 "%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8331                 "OpReturnValue %result\n"
8332                 "OpFunctionEnd\n";
8333         createTestsForAllStages("continue", defaultColors, defaultColors, fragments, testGroup.get());
8334
8335         // A loop with break.
8336         fragments["testfun"] =
8337                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8338                 "%param1 = OpFunctionParameter %v4f32\n"
8339
8340                 "%entry = OpLabel\n"
8341                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8342                 "%dot = OpDot %f32 %param1 %param1\n"
8343                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8344                 "%zero = OpConvertFToU %u32 %div\n"
8345                 "%two = OpIAdd %i32 %zero %c_i32_2\n"
8346                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8347                 "OpBranch %loop\n"
8348
8349                 ";adds 4 and 3 to %val0 (exits early)\n"
8350                 "%loop = OpLabel\n"
8351                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8352                 "%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
8353                 "OpLoopMerge %exit %continue None\n"
8354                 "OpBranch %if\n"
8355
8356                 "%if = OpLabel\n"
8357                 ";end loop if %count==%two\n"
8358                 "%above2 = OpSGreaterThan %bool %count %two\n"
8359                 "OpSelectionMerge %continue DontFlatten\n"
8360                 "OpBranchConditional %above2 %body %exit\n"
8361
8362                 "%body = OpLabel\n"
8363                 "%fcount = OpConvertSToF %f32 %count\n"
8364                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8365                 "OpBranch %continue\n"
8366
8367                 "%continue = OpLabel\n"
8368                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8369                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8370                 "OpBranchConditional %again %loop %exit\n"
8371
8372                 "%exit = OpLabel\n"
8373                 "%val_post = OpPhi %f32 %val2 %continue %val1 %if\n"
8374                 "%same = OpFSub %f32 %val_post %c_f32_7\n"
8375                 "%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8376                 "OpReturnValue %result\n"
8377                 "OpFunctionEnd\n";
8378         createTestsForAllStages("break", defaultColors, defaultColors, fragments, testGroup.get());
8379
8380         // A loop with return.
8381         fragments["testfun"] =
8382                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8383                 "%param1 = OpFunctionParameter %v4f32\n"
8384
8385                 "%entry = OpLabel\n"
8386                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8387                 "%dot = OpDot %f32 %param1 %param1\n"
8388                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8389                 "%zero = OpConvertFToU %u32 %div\n"
8390                 "%two = OpIAdd %i32 %zero %c_i32_2\n"
8391                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8392                 "OpBranch %loop\n"
8393
8394                 ";returns early without modifying %param1\n"
8395                 "%loop = OpLabel\n"
8396                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8397                 "%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
8398                 "OpLoopMerge %exit %continue None\n"
8399                 "OpBranch %if\n"
8400
8401                 "%if = OpLabel\n"
8402                 ";return if %count==%two\n"
8403                 "%above2 = OpSGreaterThan %bool %count %two\n"
8404                 "OpSelectionMerge %continue DontFlatten\n"
8405                 "OpBranchConditional %above2 %body %early_exit\n"
8406
8407                 "%early_exit = OpLabel\n"
8408                 "OpReturnValue %param1\n"
8409
8410                 "%body = OpLabel\n"
8411                 "%fcount = OpConvertSToF %f32 %count\n"
8412                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8413                 "OpBranch %continue\n"
8414
8415                 "%continue = OpLabel\n"
8416                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8417                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8418                 "OpBranchConditional %again %loop %exit\n"
8419
8420                 "%exit = OpLabel\n"
8421                 ";should never get here, so return an incorrect result\n"
8422                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val2 %c_i32_0\n"
8423                 "OpReturnValue %result\n"
8424                 "OpFunctionEnd\n";
8425         createTestsForAllStages("return", defaultColors, defaultColors, fragments, testGroup.get());
8426
8427         // Continue inside a switch block to break to enclosing loop's merge block.
8428         // Matches roughly the following GLSL code:
8429         // for (; keep_going; keep_going = false)
8430         // {
8431         //     switch (int(param1.x))
8432         //     {
8433         //         case 0: continue;
8434         //         case 1: continue;
8435         //         default: continue;
8436         //     }
8437         //     dead code: modify return value to invalid result.
8438         // }
8439         fragments["pre_main"] =
8440                 "%fp_bool = OpTypePointer Function %bool\n"
8441                 "%true = OpConstantTrue %bool\n"
8442                 "%false = OpConstantFalse %bool\n";
8443
8444         fragments["testfun"] =
8445                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8446                 "%param1 = OpFunctionParameter %v4f32\n"
8447
8448                 "%entry = OpLabel\n"
8449                 "%keep_going = OpVariable %fp_bool Function\n"
8450                 "%val_ptr = OpVariable %fp_f32 Function\n"
8451                 "%param1_x = OpCompositeExtract %f32 %param1 0\n"
8452                 "OpStore %keep_going %true\n"
8453                 "OpBranch %forloop_begin\n"
8454
8455                 "%forloop_begin = OpLabel\n"
8456                 "OpLoopMerge %forloop_merge %forloop_continue None\n"
8457                 "OpBranch %forloop\n"
8458
8459                 "%forloop = OpLabel\n"
8460                 "%for_condition = OpLoad %bool %keep_going\n"
8461                 "OpBranchConditional %for_condition %forloop_body %forloop_merge\n"
8462
8463                 "%forloop_body = OpLabel\n"
8464                 "OpStore %val_ptr %param1_x\n"
8465                 "%param1_x_int = OpConvertFToS %i32 %param1_x\n"
8466
8467                 "OpSelectionMerge %switch_merge None\n"
8468                 "OpSwitch %param1_x_int %default 0 %case_0 1 %case_1\n"
8469                 "%case_0 = OpLabel\n"
8470                 "OpBranch %forloop_continue\n"
8471                 "%case_1 = OpLabel\n"
8472                 "OpBranch %forloop_continue\n"
8473                 "%default = OpLabel\n"
8474                 "OpBranch %forloop_continue\n"
8475                 "%switch_merge = OpLabel\n"
8476                 ";should never get here, so change the return value to invalid result\n"
8477                 "OpStore %val_ptr %c_f32_1\n"
8478                 "OpBranch %forloop_continue\n"
8479
8480                 "%forloop_continue = OpLabel\n"
8481                 "OpStore %keep_going %false\n"
8482                 "OpBranch %forloop_begin\n"
8483                 "%forloop_merge = OpLabel\n"
8484
8485                 "%val = OpLoad %f32 %val_ptr\n"
8486                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8487                 "OpReturnValue %result\n"
8488                 "OpFunctionEnd\n";
8489         createTestsForAllStages("switch_continue", defaultColors, defaultColors, fragments, testGroup.get());
8490
8491         return testGroup.release();
8492 }
8493
8494 // A collection of tests putting OpControlBarrier in places GLSL forbids but SPIR-V allows.
8495 tcu::TestCaseGroup* createBarrierTests(tcu::TestContext& testCtx)
8496 {
8497         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "barrier", "OpControlBarrier"));
8498         map<string, string> fragments;
8499
8500         // A barrier inside a function body.
8501         fragments["pre_main"] =
8502                 "%Workgroup = OpConstant %i32 2\n"
8503                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n";
8504         fragments["testfun"] =
8505                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8506                 "%param1 = OpFunctionParameter %v4f32\n"
8507                 "%label_testfun = OpLabel\n"
8508                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8509                 "OpReturnValue %param1\n"
8510                 "OpFunctionEnd\n";
8511         addTessCtrlTest(testGroup.get(), "in_function", fragments);
8512
8513         // Common setup code for the following tests.
8514         fragments["pre_main"] =
8515                 "%Workgroup = OpConstant %i32 2\n"
8516                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n"
8517                 "%c_f32_5 = OpConstant %f32 5.\n";
8518         const string setupPercentZero =  // Begins %test_code function with code that sets %zero to 0u but cannot be optimized away.
8519                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8520                 "%param1 = OpFunctionParameter %v4f32\n"
8521                 "%entry = OpLabel\n"
8522                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8523                 "%dot = OpDot %f32 %param1 %param1\n"
8524                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8525                 "%zero = OpConvertFToU %u32 %div\n";
8526
8527         // Barriers inside OpSwitch branches.
8528         fragments["testfun"] =
8529                 setupPercentZero +
8530                 "OpSelectionMerge %switch_exit None\n"
8531                 "OpSwitch %zero %switch_default 0 %case0 1 %case1 ;should always go to %case0\n"
8532
8533                 "%case1 = OpLabel\n"
8534                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8535                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8536                 "%wrong_branch_alert1 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8537                 "OpBranch %switch_exit\n"
8538
8539                 "%switch_default = OpLabel\n"
8540                 "%wrong_branch_alert2 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8541                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8542                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8543                 "OpBranch %switch_exit\n"
8544
8545                 "%case0 = OpLabel\n"
8546                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8547                 "OpBranch %switch_exit\n"
8548
8549                 "%switch_exit = OpLabel\n"
8550                 "%ret = OpPhi %v4f32 %param1 %case0 %wrong_branch_alert1 %case1 %wrong_branch_alert2 %switch_default\n"
8551                 "OpReturnValue %ret\n"
8552                 "OpFunctionEnd\n";
8553         addTessCtrlTest(testGroup.get(), "in_switch", fragments);
8554
8555         // Barriers inside if-then-else.
8556         fragments["testfun"] =
8557                 setupPercentZero +
8558                 "%eq0 = OpIEqual %bool %zero %c_u32_0\n"
8559                 "OpSelectionMerge %exit DontFlatten\n"
8560                 "OpBranchConditional %eq0 %then %else\n"
8561
8562                 "%else = OpLabel\n"
8563                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8564                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8565                 "%wrong_branch_alert = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8566                 "OpBranch %exit\n"
8567
8568                 "%then = OpLabel\n"
8569                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8570                 "OpBranch %exit\n"
8571                 "%exit = OpLabel\n"
8572                 "%ret = OpPhi %v4f32 %param1 %then %wrong_branch_alert %else\n"
8573                 "OpReturnValue %ret\n"
8574                 "OpFunctionEnd\n";
8575         addTessCtrlTest(testGroup.get(), "in_if", fragments);
8576
8577         // A barrier after control-flow reconvergence, tempting the compiler to attempt something like this:
8578         // http://lists.llvm.org/pipermail/llvm-dev/2009-October/026317.html.
8579         fragments["testfun"] =
8580                 setupPercentZero +
8581                 "%thread_id = OpLoad %i32 %BP_gl_InvocationID\n"
8582                 "%thread0 = OpIEqual %bool %thread_id %c_i32_0\n"
8583                 "OpSelectionMerge %exit DontFlatten\n"
8584                 "OpBranchConditional %thread0 %then %else\n"
8585
8586                 "%else = OpLabel\n"
8587                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8588                 "OpBranch %exit\n"
8589
8590                 "%then = OpLabel\n"
8591                 "%val1 = OpVectorExtractDynamic %f32 %param1 %zero\n"
8592                 "OpBranch %exit\n"
8593
8594                 "%exit = OpLabel\n"
8595                 "%val = OpPhi %f32 %val0 %else %val1 %then\n"
8596                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8597                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %val %zero\n"
8598                 "OpReturnValue %ret\n"
8599                 "OpFunctionEnd\n";
8600         addTessCtrlTest(testGroup.get(), "after_divergent_if", fragments);
8601
8602         // A barrier inside a loop.
8603         fragments["pre_main"] =
8604                 "%Workgroup = OpConstant %i32 2\n"
8605                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n"
8606                 "%c_f32_10 = OpConstant %f32 10.\n";
8607         fragments["testfun"] =
8608                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8609                 "%param1 = OpFunctionParameter %v4f32\n"
8610                 "%entry = OpLabel\n"
8611                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8612                 "OpBranch %loop\n"
8613
8614                 ";adds 4, 3, 2, and 1 to %val0\n"
8615                 "%loop = OpLabel\n"
8616                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
8617                 "%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
8618                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8619                 "%fcount = OpConvertSToF %f32 %count\n"
8620                 "%val = OpFAdd %f32 %val1 %fcount\n"
8621                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8622                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8623                 "OpLoopMerge %exit %loop None\n"
8624                 "OpBranchConditional %again %loop %exit\n"
8625
8626                 "%exit = OpLabel\n"
8627                 "%same = OpFSub %f32 %val %c_f32_10\n"
8628                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8629                 "OpReturnValue %ret\n"
8630                 "OpFunctionEnd\n";
8631         addTessCtrlTest(testGroup.get(), "in_loop", fragments);
8632
8633         return testGroup.release();
8634 }
8635
8636 // Test for the OpFRem instruction.
8637 tcu::TestCaseGroup* createFRemTests(tcu::TestContext& testCtx)
8638 {
8639         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "frem", "OpFRem"));
8640         map<string, string>                                     fragments;
8641         RGBA                                                            inputColors[4];
8642         RGBA                                                            outputColors[4];
8643
8644         fragments["pre_main"]                            =
8645                 "%c_f32_3 = OpConstant %f32 3.0\n"
8646                 "%c_f32_n3 = OpConstant %f32 -3.0\n"
8647                 "%c_f32_4 = OpConstant %f32 4.0\n"
8648                 "%c_f32_p75 = OpConstant %f32 0.75\n"
8649                 "%c_v4f32_p75_p75_p75_p75 = OpConstantComposite %v4f32 %c_f32_p75 %c_f32_p75 %c_f32_p75 %c_f32_p75 \n"
8650                 "%c_v4f32_4_4_4_4 = OpConstantComposite %v4f32 %c_f32_4 %c_f32_4 %c_f32_4 %c_f32_4\n"
8651                 "%c_v4f32_3_n3_3_n3 = OpConstantComposite %v4f32 %c_f32_3 %c_f32_n3 %c_f32_3 %c_f32_n3\n";
8652
8653         // The test does the following.
8654         // vec4 result = (param1 * 8.0) - 4.0;
8655         // return (frem(result.x,3) + 0.75, frem(result.y, -3) + 0.75, 0, 1)
8656         fragments["testfun"]                             =
8657                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8658                 "%param1 = OpFunctionParameter %v4f32\n"
8659                 "%label_testfun = OpLabel\n"
8660                 "%v_times_8 = OpVectorTimesScalar %v4f32 %param1 %c_f32_8\n"
8661                 "%minus_4 = OpFSub %v4f32 %v_times_8 %c_v4f32_4_4_4_4\n"
8662                 "%frem = OpFRem %v4f32 %minus_4 %c_v4f32_3_n3_3_n3\n"
8663                 "%added = OpFAdd %v4f32 %frem %c_v4f32_p75_p75_p75_p75\n"
8664                 "%xyz_1 = OpVectorInsertDynamic %v4f32 %added %c_f32_1 %c_i32_3\n"
8665                 "%xy_0_1 = OpVectorInsertDynamic %v4f32 %xyz_1 %c_f32_0 %c_i32_2\n"
8666                 "OpReturnValue %xy_0_1\n"
8667                 "OpFunctionEnd\n";
8668
8669
8670         inputColors[0]          = RGBA(16,      16,             0, 255);
8671         inputColors[1]          = RGBA(232, 232,        0, 255);
8672         inputColors[2]          = RGBA(232, 16,         0, 255);
8673         inputColors[3]          = RGBA(16,      232,    0, 255);
8674
8675         outputColors[0]         = RGBA(64,      64,             0, 255);
8676         outputColors[1]         = RGBA(255, 255,        0, 255);
8677         outputColors[2]         = RGBA(255, 64,         0, 255);
8678         outputColors[3]         = RGBA(64,      255,    0, 255);
8679
8680         createTestsForAllStages("frem", inputColors, outputColors, fragments, testGroup.get());
8681         return testGroup.release();
8682 }
8683
8684 // Test for the OpSRem instruction.
8685 tcu::TestCaseGroup* createOpSRemGraphicsTests(tcu::TestContext& testCtx, qpTestResult negFailResult)
8686 {
8687         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "srem", "OpSRem"));
8688         map<string, string>                                     fragments;
8689
8690         fragments["pre_main"]                            =
8691                 "%c_f32_255 = OpConstant %f32 255.0\n"
8692                 "%c_i32_128 = OpConstant %i32 128\n"
8693                 "%c_i32_255 = OpConstant %i32 255\n"
8694                 "%c_v4f32_255 = OpConstantComposite %v4f32 %c_f32_255 %c_f32_255 %c_f32_255 %c_f32_255 \n"
8695                 "%c_v4f32_0_5 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 \n"
8696                 "%c_v4i32_128 = OpConstantComposite %v4i32 %c_i32_128 %c_i32_128 %c_i32_128 %c_i32_128 \n";
8697
8698         // The test does the following.
8699         // ivec4 ints = int(param1 * 255.0 + 0.5) - 128;
8700         // ivec4 result = ivec4(srem(ints.x, ints.y), srem(ints.y, ints.z), srem(ints.z, ints.x), 255);
8701         // return float(result + 128) / 255.0;
8702         fragments["testfun"]                             =
8703                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8704                 "%param1 = OpFunctionParameter %v4f32\n"
8705                 "%label_testfun = OpLabel\n"
8706                 "%div255 = OpFMul %v4f32 %param1 %c_v4f32_255\n"
8707                 "%add0_5 = OpFAdd %v4f32 %div255 %c_v4f32_0_5\n"
8708                 "%uints_in = OpConvertFToS %v4i32 %add0_5\n"
8709                 "%ints_in = OpISub %v4i32 %uints_in %c_v4i32_128\n"
8710                 "%x_in = OpCompositeExtract %i32 %ints_in 0\n"
8711                 "%y_in = OpCompositeExtract %i32 %ints_in 1\n"
8712                 "%z_in = OpCompositeExtract %i32 %ints_in 2\n"
8713                 "%x_out = OpSRem %i32 %x_in %y_in\n"
8714                 "%y_out = OpSRem %i32 %y_in %z_in\n"
8715                 "%z_out = OpSRem %i32 %z_in %x_in\n"
8716                 "%ints_out = OpCompositeConstruct %v4i32 %x_out %y_out %z_out %c_i32_255\n"
8717                 "%ints_offset = OpIAdd %v4i32 %ints_out %c_v4i32_128\n"
8718                 "%f_ints_offset = OpConvertSToF %v4f32 %ints_offset\n"
8719                 "%float_out = OpFDiv %v4f32 %f_ints_offset %c_v4f32_255\n"
8720                 "OpReturnValue %float_out\n"
8721                 "OpFunctionEnd\n";
8722
8723         const struct CaseParams
8724         {
8725                 const char*             name;
8726                 const char*             failMessageTemplate;    // customized status message
8727                 qpTestResult    failResult;                             // override status on failure
8728                 int                             operands[4][3];                 // four (x, y, z) vectors of operands
8729                 int                             results[4][3];                  // four (x, y, z) vectors of results
8730         } cases[] =
8731         {
8732                 {
8733                         "positive",
8734                         "${reason}",
8735                         QP_TEST_RESULT_FAIL,
8736                         { { 5, 12, 17 }, { 5, 5, 7 }, { 75, 8, 81 }, { 25, 60, 100 } },                 // operands
8737                         { { 5, 12,  2 }, { 0, 5, 2 }, {  3, 8,  6 }, { 25, 60,   0 } },                 // results
8738                 },
8739                 {
8740                         "all",
8741                         "Inconsistent results, but within specification: ${reason}",
8742                         negFailResult,                                                                                                                  // negative operands, not required by the spec
8743                         { { 5, 12, -17 }, { -5, -5, 7 }, { 75, 8, -81 }, { 25, -60, 100 } },    // operands
8744                         { { 5, 12,  -2 }, {  0, -5, 2 }, {  3, 8,  -6 }, { 25, -60,   0 } },    // results
8745                 },
8746         };
8747         // If either operand is negative the result is undefined. Some implementations may still return correct values.
8748
8749         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
8750         {
8751                 const CaseParams&       params                  = cases[caseNdx];
8752                 RGBA                            inputColors[4];
8753                 RGBA                            outputColors[4];
8754
8755                 for (int i = 0; i < 4; ++i)
8756                 {
8757                         inputColors [i] = RGBA(params.operands[i][0] + 128, params.operands[i][1] + 128, params.operands[i][2] + 128, 255);
8758                         outputColors[i] = RGBA(params.results [i][0] + 128, params.results [i][1] + 128, params.results [i][2] + 128, 255);
8759                 }
8760
8761                 createTestsForAllStages(params.name, inputColors, outputColors, fragments, testGroup.get(), params.failResult, params.failMessageTemplate);
8762         }
8763
8764         return testGroup.release();
8765 }
8766
8767 // Test for the OpSMod instruction.
8768 tcu::TestCaseGroup* createOpSModGraphicsTests(tcu::TestContext& testCtx, qpTestResult negFailResult)
8769 {
8770         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "smod", "OpSMod"));
8771         map<string, string>                                     fragments;
8772
8773         fragments["pre_main"]                            =
8774                 "%c_f32_255 = OpConstant %f32 255.0\n"
8775                 "%c_i32_128 = OpConstant %i32 128\n"
8776                 "%c_i32_255 = OpConstant %i32 255\n"
8777                 "%c_v4f32_255 = OpConstantComposite %v4f32 %c_f32_255 %c_f32_255 %c_f32_255 %c_f32_255 \n"
8778                 "%c_v4f32_0_5 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 \n"
8779                 "%c_v4i32_128 = OpConstantComposite %v4i32 %c_i32_128 %c_i32_128 %c_i32_128 %c_i32_128 \n";
8780
8781         // The test does the following.
8782         // ivec4 ints = int(param1 * 255.0 + 0.5) - 128;
8783         // ivec4 result = ivec4(smod(ints.x, ints.y), smod(ints.y, ints.z), smod(ints.z, ints.x), 255);
8784         // return float(result + 128) / 255.0;
8785         fragments["testfun"]                             =
8786                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8787                 "%param1 = OpFunctionParameter %v4f32\n"
8788                 "%label_testfun = OpLabel\n"
8789                 "%div255 = OpFMul %v4f32 %param1 %c_v4f32_255\n"
8790                 "%add0_5 = OpFAdd %v4f32 %div255 %c_v4f32_0_5\n"
8791                 "%uints_in = OpConvertFToS %v4i32 %add0_5\n"
8792                 "%ints_in = OpISub %v4i32 %uints_in %c_v4i32_128\n"
8793                 "%x_in = OpCompositeExtract %i32 %ints_in 0\n"
8794                 "%y_in = OpCompositeExtract %i32 %ints_in 1\n"
8795                 "%z_in = OpCompositeExtract %i32 %ints_in 2\n"
8796                 "%x_out = OpSMod %i32 %x_in %y_in\n"
8797                 "%y_out = OpSMod %i32 %y_in %z_in\n"
8798                 "%z_out = OpSMod %i32 %z_in %x_in\n"
8799                 "%ints_out = OpCompositeConstruct %v4i32 %x_out %y_out %z_out %c_i32_255\n"
8800                 "%ints_offset = OpIAdd %v4i32 %ints_out %c_v4i32_128\n"
8801                 "%f_ints_offset = OpConvertSToF %v4f32 %ints_offset\n"
8802                 "%float_out = OpFDiv %v4f32 %f_ints_offset %c_v4f32_255\n"
8803                 "OpReturnValue %float_out\n"
8804                 "OpFunctionEnd\n";
8805
8806         const struct CaseParams
8807         {
8808                 const char*             name;
8809                 const char*             failMessageTemplate;    // customized status message
8810                 qpTestResult    failResult;                             // override status on failure
8811                 int                             operands[4][3];                 // four (x, y, z) vectors of operands
8812                 int                             results[4][3];                  // four (x, y, z) vectors of results
8813         } cases[] =
8814         {
8815                 {
8816                         "positive",
8817                         "${reason}",
8818                         QP_TEST_RESULT_FAIL,
8819                         { { 5, 12, 17 }, { 5, 5, 7 }, { 75, 8, 81 }, { 25, 60, 100 } },                         // operands
8820                         { { 5, 12,  2 }, { 0, 5, 2 }, {  3, 8,  6 }, { 25, 60,   0 } },                         // results
8821                 },
8822                 {
8823                         "all",
8824                         "Inconsistent results, but within specification: ${reason}",
8825                         negFailResult,                                                                                                                          // negative operands, not required by the spec
8826                         { { 5, 12, -17 }, { -5, -5,  7 }, { 75,   8, -81 }, {  25, -60, 100 } },        // operands
8827                         { { 5, -5,   3 }, {  0,  2, -3 }, {  3, -73,  69 }, { -35,  40,   0 } },        // results
8828                 },
8829         };
8830         // If either operand is negative the result is undefined. Some implementations may still return correct values.
8831
8832         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
8833         {
8834                 const CaseParams&       params                  = cases[caseNdx];
8835                 RGBA                            inputColors[4];
8836                 RGBA                            outputColors[4];
8837
8838                 for (int i = 0; i < 4; ++i)
8839                 {
8840                         inputColors [i] = RGBA(params.operands[i][0] + 128, params.operands[i][1] + 128, params.operands[i][2] + 128, 255);
8841                         outputColors[i] = RGBA(params.results [i][0] + 128, params.results [i][1] + 128, params.results [i][2] + 128, 255);
8842                 }
8843
8844                 createTestsForAllStages(params.name, inputColors, outputColors, fragments, testGroup.get(), params.failResult, params.failMessageTemplate);
8845         }
8846         return testGroup.release();
8847 }
8848
8849 enum ConversionDataType
8850 {
8851         DATA_TYPE_SIGNED_8,
8852         DATA_TYPE_SIGNED_16,
8853         DATA_TYPE_SIGNED_32,
8854         DATA_TYPE_SIGNED_64,
8855         DATA_TYPE_UNSIGNED_8,
8856         DATA_TYPE_UNSIGNED_16,
8857         DATA_TYPE_UNSIGNED_32,
8858         DATA_TYPE_UNSIGNED_64,
8859         DATA_TYPE_FLOAT_16,
8860         DATA_TYPE_FLOAT_32,
8861         DATA_TYPE_FLOAT_64,
8862         DATA_TYPE_VEC2_SIGNED_16,
8863         DATA_TYPE_VEC2_SIGNED_32
8864 };
8865
8866 const string getBitWidthStr (ConversionDataType type)
8867 {
8868         switch (type)
8869         {
8870                 case DATA_TYPE_SIGNED_8:
8871                 case DATA_TYPE_UNSIGNED_8:
8872                         return "8";
8873
8874                 case DATA_TYPE_SIGNED_16:
8875                 case DATA_TYPE_UNSIGNED_16:
8876                 case DATA_TYPE_FLOAT_16:
8877                         return "16";
8878
8879                 case DATA_TYPE_SIGNED_32:
8880                 case DATA_TYPE_UNSIGNED_32:
8881                 case DATA_TYPE_FLOAT_32:
8882                 case DATA_TYPE_VEC2_SIGNED_16:
8883                         return "32";
8884
8885                 case DATA_TYPE_SIGNED_64:
8886                 case DATA_TYPE_UNSIGNED_64:
8887                 case DATA_TYPE_FLOAT_64:
8888                 case DATA_TYPE_VEC2_SIGNED_32:
8889                         return "64";
8890
8891                 default:
8892                         DE_ASSERT(false);
8893         }
8894         return "";
8895 }
8896
8897 const string getByteWidthStr (ConversionDataType type)
8898 {
8899         switch (type)
8900         {
8901                 case DATA_TYPE_SIGNED_8:
8902                 case DATA_TYPE_UNSIGNED_8:
8903                         return "1";
8904
8905                 case DATA_TYPE_SIGNED_16:
8906                 case DATA_TYPE_UNSIGNED_16:
8907                 case DATA_TYPE_FLOAT_16:
8908                         return "2";
8909
8910                 case DATA_TYPE_SIGNED_32:
8911                 case DATA_TYPE_UNSIGNED_32:
8912                 case DATA_TYPE_FLOAT_32:
8913                 case DATA_TYPE_VEC2_SIGNED_16:
8914                         return "4";
8915
8916                 case DATA_TYPE_SIGNED_64:
8917                 case DATA_TYPE_UNSIGNED_64:
8918                 case DATA_TYPE_FLOAT_64:
8919                 case DATA_TYPE_VEC2_SIGNED_32:
8920                         return "8";
8921
8922                 default:
8923                         DE_ASSERT(false);
8924         }
8925         return "";
8926 }
8927
8928 bool isSigned (ConversionDataType type)
8929 {
8930         switch (type)
8931         {
8932                 case DATA_TYPE_SIGNED_8:
8933                 case DATA_TYPE_SIGNED_16:
8934                 case DATA_TYPE_SIGNED_32:
8935                 case DATA_TYPE_SIGNED_64:
8936                 case DATA_TYPE_FLOAT_16:
8937                 case DATA_TYPE_FLOAT_32:
8938                 case DATA_TYPE_FLOAT_64:
8939                 case DATA_TYPE_VEC2_SIGNED_16:
8940                 case DATA_TYPE_VEC2_SIGNED_32:
8941                         return true;
8942
8943                 case DATA_TYPE_UNSIGNED_8:
8944                 case DATA_TYPE_UNSIGNED_16:
8945                 case DATA_TYPE_UNSIGNED_32:
8946                 case DATA_TYPE_UNSIGNED_64:
8947                         return false;
8948
8949                 default:
8950                         DE_ASSERT(false);
8951         }
8952         return false;
8953 }
8954
8955 bool isInt (ConversionDataType type)
8956 {
8957         switch (type)
8958         {
8959                 case DATA_TYPE_SIGNED_8:
8960                 case DATA_TYPE_SIGNED_16:
8961                 case DATA_TYPE_SIGNED_32:
8962                 case DATA_TYPE_SIGNED_64:
8963                 case DATA_TYPE_UNSIGNED_8:
8964                 case DATA_TYPE_UNSIGNED_16:
8965                 case DATA_TYPE_UNSIGNED_32:
8966                 case DATA_TYPE_UNSIGNED_64:
8967                         return true;
8968
8969                 case DATA_TYPE_FLOAT_16:
8970                 case DATA_TYPE_FLOAT_32:
8971                 case DATA_TYPE_FLOAT_64:
8972                 case DATA_TYPE_VEC2_SIGNED_16:
8973                 case DATA_TYPE_VEC2_SIGNED_32:
8974                         return false;
8975
8976                 default:
8977                         DE_ASSERT(false);
8978         }
8979         return false;
8980 }
8981
8982 bool isFloat (ConversionDataType type)
8983 {
8984         switch (type)
8985         {
8986                 case DATA_TYPE_SIGNED_8:
8987                 case DATA_TYPE_SIGNED_16:
8988                 case DATA_TYPE_SIGNED_32:
8989                 case DATA_TYPE_SIGNED_64:
8990                 case DATA_TYPE_UNSIGNED_8:
8991                 case DATA_TYPE_UNSIGNED_16:
8992                 case DATA_TYPE_UNSIGNED_32:
8993                 case DATA_TYPE_UNSIGNED_64:
8994                 case DATA_TYPE_VEC2_SIGNED_16:
8995                 case DATA_TYPE_VEC2_SIGNED_32:
8996                         return false;
8997
8998                 case DATA_TYPE_FLOAT_16:
8999                 case DATA_TYPE_FLOAT_32:
9000                 case DATA_TYPE_FLOAT_64:
9001                         return true;
9002
9003                 default:
9004                         DE_ASSERT(false);
9005         }
9006         return false;
9007 }
9008
9009 const string getTypeName (ConversionDataType type)
9010 {
9011         string prefix = isSigned(type) ? "" : "u";
9012
9013         if              (isInt(type))                                           return prefix + "int"   + getBitWidthStr(type);
9014         else if (isFloat(type))                                         return prefix + "float" + getBitWidthStr(type);
9015         else if (type == DATA_TYPE_VEC2_SIGNED_16)      return "i16vec2";
9016         else if (type == DATA_TYPE_VEC2_SIGNED_32)      return "i32vec2";
9017         else                                                                            DE_ASSERT(false);
9018
9019         return "";
9020 }
9021
9022 const string getTestName (ConversionDataType from, ConversionDataType to, const char* suffix)
9023 {
9024         const string fullSuffix(suffix == DE_NULL ? "" : string("_") + string(suffix));
9025
9026         return getTypeName(from) + "_to_" + getTypeName(to) + fullSuffix;
9027 }
9028
9029 const string getAsmTypeName (ConversionDataType type)
9030 {
9031         string prefix;
9032
9033         if              (isInt(type))                                           prefix = isSigned(type) ? "i" : "u";
9034         else if (isFloat(type))                                         prefix = "f";
9035         else if (type == DATA_TYPE_VEC2_SIGNED_16)      return "i16vec2";
9036         else if (type == DATA_TYPE_VEC2_SIGNED_32)      return "v2i32";
9037         else                                                                            DE_ASSERT(false);
9038
9039         return prefix + getBitWidthStr(type);
9040 }
9041
9042 template<typename T>
9043 BufferSp getSpecializedBuffer (deInt64 number)
9044 {
9045         return BufferSp(new Buffer<T>(vector<T>(1, (T)number)));
9046 }
9047
9048 BufferSp getBuffer (ConversionDataType type, deInt64 number)
9049 {
9050         switch (type)
9051         {
9052                 case DATA_TYPE_SIGNED_8:                return getSpecializedBuffer<deInt8>(number);
9053                 case DATA_TYPE_SIGNED_16:               return getSpecializedBuffer<deInt16>(number);
9054                 case DATA_TYPE_SIGNED_32:               return getSpecializedBuffer<deInt32>(number);
9055                 case DATA_TYPE_SIGNED_64:               return getSpecializedBuffer<deInt64>(number);
9056                 case DATA_TYPE_UNSIGNED_8:              return getSpecializedBuffer<deUint8>(number);
9057                 case DATA_TYPE_UNSIGNED_16:             return getSpecializedBuffer<deUint16>(number);
9058                 case DATA_TYPE_UNSIGNED_32:             return getSpecializedBuffer<deUint32>(number);
9059                 case DATA_TYPE_UNSIGNED_64:             return getSpecializedBuffer<deUint64>(number);
9060                 case DATA_TYPE_FLOAT_16:                return getSpecializedBuffer<deUint16>(number);
9061                 case DATA_TYPE_FLOAT_32:                return getSpecializedBuffer<deUint32>(number);
9062                 case DATA_TYPE_FLOAT_64:                return getSpecializedBuffer<deUint64>(number);
9063                 case DATA_TYPE_VEC2_SIGNED_16:  return getSpecializedBuffer<deUint32>(number);
9064                 case DATA_TYPE_VEC2_SIGNED_32:  return getSpecializedBuffer<deUint64>(number);
9065
9066                 default:                                                TCU_THROW(InternalError, "Unimplemented type passed");
9067         }
9068 }
9069
9070 bool usesInt8 (ConversionDataType from, ConversionDataType to)
9071 {
9072         return (from == DATA_TYPE_SIGNED_8 || to == DATA_TYPE_SIGNED_8 ||
9073                         from == DATA_TYPE_UNSIGNED_8 || to == DATA_TYPE_UNSIGNED_8);
9074 }
9075
9076 bool usesInt16 (ConversionDataType from, ConversionDataType to)
9077 {
9078         return (from == DATA_TYPE_SIGNED_16 || to == DATA_TYPE_SIGNED_16 ||
9079                         from == DATA_TYPE_UNSIGNED_16 || to == DATA_TYPE_UNSIGNED_16 ||
9080                         from == DATA_TYPE_VEC2_SIGNED_16 || to == DATA_TYPE_VEC2_SIGNED_16);
9081 }
9082
9083 bool usesInt32 (ConversionDataType from, ConversionDataType to)
9084 {
9085         return (from == DATA_TYPE_SIGNED_32 || to == DATA_TYPE_SIGNED_32 ||
9086                         from == DATA_TYPE_UNSIGNED_32 || to == DATA_TYPE_UNSIGNED_32 ||
9087                         from == DATA_TYPE_VEC2_SIGNED_32|| to == DATA_TYPE_VEC2_SIGNED_32);
9088 }
9089
9090 bool usesInt64 (ConversionDataType from, ConversionDataType to)
9091 {
9092         return (from == DATA_TYPE_SIGNED_64 || to == DATA_TYPE_SIGNED_64 ||
9093                         from == DATA_TYPE_UNSIGNED_64 || to == DATA_TYPE_UNSIGNED_64);
9094 }
9095
9096 bool usesFloat16 (ConversionDataType from, ConversionDataType to)
9097 {
9098         return (from == DATA_TYPE_FLOAT_16 || to == DATA_TYPE_FLOAT_16);
9099 }
9100
9101 bool usesFloat32 (ConversionDataType from, ConversionDataType to)
9102 {
9103         return (from == DATA_TYPE_FLOAT_32 || to == DATA_TYPE_FLOAT_32);
9104 }
9105
9106 bool usesFloat64 (ConversionDataType from, ConversionDataType to)
9107 {
9108         return (from == DATA_TYPE_FLOAT_64 || to == DATA_TYPE_FLOAT_64);
9109 }
9110
9111 void getVulkanFeaturesAndExtensions (ConversionDataType from, ConversionDataType to, VulkanFeatures& vulkanFeatures, vector<string>& extensions)
9112 {
9113         if (usesInt16(from, to) && !usesInt32(from, to))
9114                 vulkanFeatures.coreFeatures.shaderInt16 = DE_TRUE;
9115
9116         if (usesInt64(from, to))
9117                 vulkanFeatures.coreFeatures.shaderInt64 = DE_TRUE;
9118
9119         if (usesFloat64(from, to))
9120                 vulkanFeatures.coreFeatures.shaderFloat64 = DE_TRUE;
9121
9122         if (usesInt16(from, to) || usesFloat16(from, to))
9123         {
9124                 extensions.push_back("VK_KHR_16bit_storage");
9125                 vulkanFeatures.ext16BitStorage |= EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
9126         }
9127
9128         if (usesFloat16(from, to) || usesInt8(from, to))
9129         {
9130                 extensions.push_back("VK_KHR_shader_float16_int8");
9131
9132                 if (usesFloat16(from, to))
9133                 {
9134                         vulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_FLOAT16;
9135                 }
9136
9137                 if (usesInt8(from, to))
9138                 {
9139                         vulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_INT8;
9140
9141                         extensions.push_back("VK_KHR_8bit_storage");
9142                         vulkanFeatures.ext8BitStorage |= EXT8BITSTORAGEFEATURES_STORAGE_BUFFER;
9143                 }
9144         }
9145 }
9146
9147 struct ConvertCase
9148 {
9149         ConvertCase (const string& instruction, ConversionDataType from, ConversionDataType to, deInt64 number, bool separateOutput = false, deInt64 outputNumber = 0, const char* suffix = DE_NULL)
9150         : m_fromType            (from)
9151         , m_toType                      (to)
9152         , m_name                        (getTestName(from, to, suffix))
9153         , m_inputBuffer         (getBuffer(from, number))
9154         {
9155                 string caps;
9156                 string decl;
9157                 string exts;
9158
9159                 m_asmTypes["inputType"]         = getAsmTypeName(from);
9160                 m_asmTypes["outputType"]        = getAsmTypeName(to);
9161
9162                 if (separateOutput)
9163                         m_outputBuffer = getBuffer(to, outputNumber);
9164                 else
9165                         m_outputBuffer = getBuffer(to, number);
9166
9167                 if (usesInt8(from, to))
9168                 {
9169                         bool requiresInt8Capability = true;
9170                         if (instruction == "OpUConvert" || instruction == "OpSConvert")
9171                         {
9172                                 // Conversions between 8 and 32 bit are provided by SPV_KHR_8bit_storage. The rest requires explicit Int8
9173                                 if (usesInt32(from, to))
9174                                         requiresInt8Capability = false;
9175                         }
9176
9177                         caps += "OpCapability StorageBuffer8BitAccess\n";
9178                         if (requiresInt8Capability)
9179                                 caps += "OpCapability Int8\n";
9180
9181                         decl += "%i8         = OpTypeInt 8 1\n"
9182                                         "%u8         = OpTypeInt 8 0\n";
9183                         exts += "OpExtension \"SPV_KHR_8bit_storage\"\n";
9184                 }
9185
9186                 if (usesInt16(from, to))
9187                 {
9188                         bool requiresInt16Capability = true;
9189
9190                         if (instruction == "OpUConvert" || instruction == "OpSConvert" || instruction == "OpFConvert")
9191                         {
9192                                 // Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Int16
9193                                 if (usesInt32(from, to) || usesFloat32(from, to))
9194                                         requiresInt16Capability = false;
9195                         }
9196
9197                         decl += "%i16        = OpTypeInt 16 1\n"
9198                                         "%u16        = OpTypeInt 16 0\n"
9199                                         "%i16vec2    = OpTypeVector %i16 2\n";
9200
9201                         // Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Int16
9202                         if (requiresInt16Capability)
9203                                 caps += "OpCapability Int16\n";
9204                 }
9205
9206                 if (usesFloat16(from, to))
9207                 {
9208                         decl += "%f16        = OpTypeFloat 16\n";
9209
9210                         // Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Float16
9211                         if (!(usesInt32(from, to) || usesFloat32(from, to)))
9212                                 caps += "OpCapability Float16\n";
9213                 }
9214
9215                 if (usesInt16(from, to) || usesFloat16(from, to))
9216                 {
9217                         caps += "OpCapability StorageUniformBufferBlock16\n";
9218                         exts += "OpExtension \"SPV_KHR_16bit_storage\"\n";
9219                 }
9220
9221                 if (usesInt64(from, to))
9222                 {
9223                         caps += "OpCapability Int64\n";
9224                         decl += "%i64        = OpTypeInt 64 1\n"
9225                                         "%u64        = OpTypeInt 64 0\n";
9226                 }
9227
9228                 if (usesFloat64(from, to))
9229                 {
9230                         caps += "OpCapability Float64\n";
9231                         decl += "%f64        = OpTypeFloat 64\n";
9232                 }
9233
9234                 m_asmTypes["datatype_capabilities"]             = caps;
9235                 m_asmTypes["datatype_additional_decl"]  = decl;
9236                 m_asmTypes["datatype_extensions"]               = exts;
9237         }
9238
9239         ConversionDataType              m_fromType;
9240         ConversionDataType              m_toType;
9241         string                                  m_name;
9242         map<string, string>             m_asmTypes;
9243         BufferSp                                m_inputBuffer;
9244         BufferSp                                m_outputBuffer;
9245 };
9246
9247 const string getConvertCaseShaderStr (const string& instruction, const ConvertCase& convertCase)
9248 {
9249         map<string, string> params = convertCase.m_asmTypes;
9250
9251         params["instruction"]   = instruction;
9252         params["inDecorator"]   = getByteWidthStr(convertCase.m_fromType);
9253         params["outDecorator"]  = getByteWidthStr(convertCase.m_toType);
9254
9255         const StringTemplate shader (
9256                 "OpCapability Shader\n"
9257                 "${datatype_capabilities}"
9258                 "${datatype_extensions:opt}"
9259                 "OpMemoryModel Logical GLSL450\n"
9260                 "OpEntryPoint GLCompute %main \"main\"\n"
9261                 "OpExecutionMode %main LocalSize 1 1 1\n"
9262                 "OpSource GLSL 430\n"
9263                 "OpName %main           \"main\"\n"
9264                 // Decorators
9265                 "OpDecorate %indata DescriptorSet 0\n"
9266                 "OpDecorate %indata Binding 0\n"
9267                 "OpDecorate %outdata DescriptorSet 0\n"
9268                 "OpDecorate %outdata Binding 1\n"
9269                 "OpDecorate %in_buf BufferBlock\n"
9270                 "OpDecorate %out_buf BufferBlock\n"
9271                 "OpMemberDecorate %in_buf 0 Offset 0\n"
9272                 "OpMemberDecorate %out_buf 0 Offset 0\n"
9273                 // Base types
9274                 "%void       = OpTypeVoid\n"
9275                 "%voidf      = OpTypeFunction %void\n"
9276                 "%u32        = OpTypeInt 32 0\n"
9277                 "%i32        = OpTypeInt 32 1\n"
9278                 "%f32        = OpTypeFloat 32\n"
9279                 "%v2i32      = OpTypeVector %i32 2\n"
9280                 "${datatype_additional_decl}"
9281                 "%uvec3      = OpTypeVector %u32 3\n"
9282                 // Derived types
9283                 "%in_ptr     = OpTypePointer Uniform %${inputType}\n"
9284                 "%out_ptr    = OpTypePointer Uniform %${outputType}\n"
9285                 "%in_buf     = OpTypeStruct %${inputType}\n"
9286                 "%out_buf    = OpTypeStruct %${outputType}\n"
9287                 "%in_bufptr  = OpTypePointer Uniform %in_buf\n"
9288                 "%out_bufptr = OpTypePointer Uniform %out_buf\n"
9289                 "%indata     = OpVariable %in_bufptr Uniform\n"
9290                 "%outdata    = OpVariable %out_bufptr Uniform\n"
9291                 // Constants
9292                 "%zero       = OpConstant %i32 0\n"
9293                 // Main function
9294                 "%main       = OpFunction %void None %voidf\n"
9295                 "%label      = OpLabel\n"
9296                 "%inloc      = OpAccessChain %in_ptr %indata %zero\n"
9297                 "%outloc     = OpAccessChain %out_ptr %outdata %zero\n"
9298                 "%inval      = OpLoad %${inputType} %inloc\n"
9299                 "%conv       = ${instruction} %${outputType} %inval\n"
9300                 "              OpStore %outloc %conv\n"
9301                 "              OpReturn\n"
9302                 "              OpFunctionEnd\n"
9303         );
9304
9305         return shader.specialize(params);
9306 }
9307
9308 void createConvertCases (vector<ConvertCase>& testCases, const string& instruction)
9309 {
9310         if (instruction == "OpUConvert")
9311         {
9312                 // Convert unsigned int to unsigned int
9313                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_16,          42));
9314                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_32,          73));
9315                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_64,          121));
9316
9317                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_8,           33));
9318                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_32,          60653));
9319                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_64,          17991));
9320
9321                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_64,          904256275));
9322                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_16,          6275));
9323                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_8,           17));
9324
9325                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_32,          701256243));
9326                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_16,          4741));
9327                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_8,           65));
9328         }
9329         else if (instruction == "OpSConvert")
9330         {
9331                 // Sign extension int->int
9332                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_16,            -30));
9333                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_32,            55));
9334                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_64,            -3));
9335                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_32,            14669));
9336                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_64,            -3341));
9337                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_64,            973610259));
9338
9339                 // Truncate for int->int
9340                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_8,                     81));
9341                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_8,                     -93));
9342                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_8,                     3182748172687672ll,                                     true,   56));
9343                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_16,            12382));
9344                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_32,            -972812359));
9345                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_16,            -1067742499291926803ll,                         true,   -4371));
9346
9347                 // Sign extension for int->uint
9348                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_16,          56));
9349                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_32,          -47,                                                            true,   4294967249u));
9350                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_64,          -5,                                                                     true,   18446744073709551611ull));
9351                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_32,          14669));
9352                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_64,          -3341,                                                          true,   18446744073709548275ull));
9353                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_64,          973610259));
9354
9355                 // Truncate for int->uint
9356                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_8,           -25711,                                                         true,   145));
9357                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_8,           103));
9358                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_8,           -1067742499291926803ll,                         true,   61165));
9359                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_16,          12382));
9360                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_32,          -972812359,                                                     true,   3322154937u));
9361                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_16,          -1067742499291926803ll,                         true,   61165));
9362
9363                 // Sign extension for uint->int
9364                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_16,            71));
9365                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_32,            201,                                                            true,   -55));
9366                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_64,            188,                                                            true,   -68));
9367                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_32,            14669));
9368                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_64,            62195,                                                          true,   -3341));
9369                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_64,            973610259));
9370
9371                 // Truncate for uint->int
9372                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_8,                     67));
9373                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_8,                     133,                                                            true,   -123));
9374                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_8,                     836927654193256494ull,                          true,   46));
9375                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_16,            12382));
9376                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_32,            18446744072736739257ull,                        true,   -972812359));
9377                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_16,            17379001574417624813ull,                        true,   -4371));
9378
9379                 // Convert i16vec2 to i32vec2 and vice versa
9380                 // Unsigned values are used here to represent negative signed values and to allow defined shifting behaviour.
9381                 // The actual signed value -32123 is used here as uint16 value 33413 and uint32 value 4294935173
9382                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_VEC2_SIGNED_16,       DATA_TYPE_VEC2_SIGNED_32,       (33413u << 16)                  | 27593,        true,   (4294935173ull << 32)   | 27593));
9383                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_VEC2_SIGNED_32,       DATA_TYPE_VEC2_SIGNED_16,       (4294935173ull << 32)   | 27593,        true,   (33413u << 16)                  | 27593));
9384         }
9385         else if (instruction == "OpFConvert")
9386         {
9387                 // All hexadecimal values below represent 1234.0 as 16/32/64-bit IEEE 754 float
9388                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_FLOAT_64,                     0x449a4000,                                                     true,   0x4093480000000000));
9389                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_FLOAT_32,                     0x4093480000000000,                                     true,   0x449a4000));
9390
9391                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_FLOAT_16,                     0x449a4000,                                                     true,   0x64D2));
9392                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_FLOAT_32,                     0x64D2,                                                         true,   0x449a4000));
9393
9394                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_FLOAT_64,                     0x64D2,                                                         true,   0x4093480000000000));
9395                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_FLOAT_16,                     0x4093480000000000,                                     true,   0x64D2));
9396         }
9397         else if (instruction == "OpConvertFToU")
9398         {
9399                 // Normal numbers from uint8 range
9400                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x5020,                                                         true,   33,                                                                     "33"));
9401                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x42280000,                                                     true,   42,                                                                     "42"));
9402                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x4067800000000000ull,                          true,   188,                                                            "188"));
9403
9404                 // Maximum uint8 value
9405                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x5BF8,                                                         true,   255,                                                            "max"));
9406                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x437F0000,                                                     true,   255,                                                            "max"));
9407                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x406FE00000000000ull,                          true,   255,                                                            "max"));
9408
9409                 // +0
9410                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x0000,                                                         true,   0,                                                                      "p0"));
9411                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x00000000,                                                     true,   0,                                                                      "p0"));
9412                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x0000000000000000ull,                          true,   0,                                                                      "p0"));
9413
9414                 // -0
9415                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x8000,                                                         true,   0,                                                                      "m0"));
9416                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x80000000,                                                     true,   0,                                                                      "m0"));
9417                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x8000000000000000ull,                          true,   0,                                                                      "m0"));
9418
9419                 // All hexadecimal values below represent 1234.0 as 16/32/64-bit IEEE 754 float
9420                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x64D2,                                                         true,   1234,                                                           "1234"));
9421                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x64D2,                                                         true,   1234,                                                           "1234"));
9422                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x64D2,                                                         true,   1234,                                                           "1234"));
9423
9424                 // 0x7BFF = 0111 1011 1111 1111 = 0 11110 1111111111 = 65504
9425                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x7BFF,                                                         true,   65504,                                                          "max"));
9426                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x7BFF,                                                         true,   65504,                                                          "max"));
9427                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x7BFF,                                                         true,   65504,                                                          "max"));
9428
9429                 // +0
9430                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x0000,                                                         true,   0,                                                                      "p0"));
9431                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x0000,                                                         true,   0,                                                                      "p0"));
9432                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x0000,                                                         true,   0,                                                                      "p0"));
9433
9434                 // -0
9435                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x8000,                                                         true,   0,                                                                      "m0"));
9436                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x8000,                                                         true,   0,                                                                      "m0"));
9437                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x8000,                                                         true,   0,                                                                      "m0"));
9438
9439                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_16,          0x449a4000,                                                     true,   1234));
9440                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_32,          0x449a4000,                                                     true,   1234));
9441                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_64,          0x449a4000,                                                     true,   1234));
9442                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_16,          0x4093480000000000,                                     true,   1234));
9443                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_32,          0x4093480000000000,                                     true,   1234));
9444                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_64,          0x4093480000000000,                                     true,   1234));
9445         }
9446         else if (instruction == "OpConvertUToF")
9447         {
9448                 // Normal numbers from uint8 range
9449                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_16,                     116,                                                            true,   0x5740,                                                         "116"));
9450                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_32,                     232,                                                            true,   0x43680000,                                                     "232"));
9451                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_64,                     164,                                                            true,   0x4064800000000000ull,                          "164"));
9452
9453                 // Maximum uint8 value
9454                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_16,                     255,                                                            true,   0x5BF8,                                                         "max"));
9455                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_32,                     255,                                                            true,   0x437F0000,                                                     "max"));
9456                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_64,                     255,                                                            true,   0x406FE00000000000ull,                          "max"));
9457
9458                 // All hexadecimal values below represent 1234.0 as 32/64-bit IEEE 754 float
9459                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9460                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9461                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9462
9463                 // 0x7BFF = 0111 1011 1111 1111 = 0 11110 1111111111 = 65504
9464                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9465                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9466                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9467
9468                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9469                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9470                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9471                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9472                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9473                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9474         }
9475         else if (instruction == "OpConvertFToS")
9476         {
9477                 // Normal numbers from int8 range
9478                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0xC980,                                                         true,   -11,                                                            "m11"));
9479                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0xC2140000,                                                     true,   -37,                                                            "m37"));
9480                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0xC050800000000000ull,                          true,   -66,                                                            "m66"));
9481
9482                 // Minimum int8 value
9483                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0xD800,                                                         true,   -128,                                                           "min"));
9484                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0xC3000000,                                                     true,   -128,                                                           "min"));
9485                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0xC060000000000000ull,                          true,   -128,                                                           "min"));
9486
9487                 // Maximum int8 value
9488                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x57F0,                                                         true,   127,                                                            "max"));
9489                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x42FE0000,                                                     true,   127,                                                            "max"));
9490                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x405FC00000000000ull,                          true,   127,                                                            "max"));
9491
9492                 // +0
9493                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x0000,                                                         true,   0,                                                                      "p0"));
9494                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x00000000,                                                     true,   0,                                                                      "p0"));
9495                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x0000000000000000ull,                          true,   0,                                                                      "p0"));
9496
9497                 // -0
9498                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x8000,                                                         true,   0,                                                                      "m0"));
9499                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x80000000,                                                     true,   0,                                                                      "m0"));
9500                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x8000000000000000ull,                          true,   0,                                                                      "m0"));
9501
9502                 // All hexadecimal values below represent -1234.0 as 32/64-bit IEEE 754 float
9503                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9504                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9505                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9506
9507                 // 0xF800 = 1111 1000 0000 0000 = 1 11110 0000000000 = -32768
9508                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0xF800,                                                         true,   -32768,                                                         "min"));
9509                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0xF800,                                                         true,   -32768,                                                         "min"));
9510                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0xF800,                                                         true,   -32768,                                                         "min"));
9511
9512                 // 0x77FF = 0111 0111 1111 1111 = 0 11101 1111111111 = 32752
9513                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x77FF,                                                         true,   32752,                                                          "max"));
9514                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x77FF,                                                         true,   32752,                                                          "max"));
9515                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x77FF,                                                         true,   32752,                                                          "max"));
9516
9517                 // +0
9518                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x0000,                                                         true,   0,                                                                      "p0"));
9519                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x0000,                                                         true,   0,                                                                      "p0"));
9520                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x0000,                                                         true,   0,                                                                      "p0"));
9521
9522                 // -0
9523                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x8000,                                                         true,   0,                                                                      "m0"));
9524                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x8000,                                                         true,   0,                                                                      "m0"));
9525                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x8000,                                                         true,   0,                                                                      "m0"));
9526
9527                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0xc49a4000,                                                     true,   -1234));
9528                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_32,            0xc49a4000,                                                     true,   -1234));
9529                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_64,            0xc49a4000,                                                     true,   -1234));
9530                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_16,            0xc093480000000000,                                     true,   -1234));
9531                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_32,            0xc093480000000000,                                     true,   -1234));
9532                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_64,            0xc093480000000000,                                     true,   -1234));
9533                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0x453b9000,                                                     true,    3001,                                                          "p3001"));
9534                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0xc53b9000,                                                     true,   -3001,                                                          "m3001"));
9535         }
9536         else if (instruction == "OpConvertSToF")
9537         {
9538                 // Normal numbers from int8 range
9539                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     -12,                                                            true,   0xCA00,                                                         "m21"));
9540                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     -21,                                                            true,   0xC1A80000,                                                     "m21"));
9541                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     -99,                                                            true,   0xC058C00000000000ull,                          "m99"));
9542
9543                 // Minimum int8 value
9544                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     -128,                                                           true,   0xD800,                                                         "min"));
9545                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     -128,                                                           true,   0xC3000000,                                                     "min"));
9546                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     -128,                                                           true,   0xC060000000000000ull,                          "min"));
9547
9548                 // Maximum int8 value
9549                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     127,                                                            true,   0x57F0,                                                         "max"));
9550                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     127,                                                            true,   0x42FE0000,                                                     "max"));
9551                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     127,                                                            true,   0x405FC00000000000ull,                          "max"));
9552
9553                 // All hexadecimal values below represent 1234.0 as 32/64-bit IEEE 754 float
9554                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9555                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9556                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9557
9558                 // 0xF800 = 1111 1000 0000 0000 = 1 11110 0000000000 = -32768
9559                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9560                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9561                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9562
9563                 // 0x77FF = 0111 0111 1111 1111 = 0 11101 1111111111 = 32752
9564                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9565                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9566                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9567
9568                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9569                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9570                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9571                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9572                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9573                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9574         }
9575         else
9576                 DE_FATAL("Unknown instruction");
9577 }
9578
9579 const map<string, string> getConvertCaseFragments (string instruction, const ConvertCase& convertCase)
9580 {
9581         map<string, string> params = convertCase.m_asmTypes;
9582         map<string, string> fragments;
9583
9584         params["instruction"] = instruction;
9585         params["inDecorator"] = getByteWidthStr(convertCase.m_fromType);
9586
9587         const StringTemplate decoration (
9588                 "      OpDecorate %SSBOi DescriptorSet 0\n"
9589                 "      OpDecorate %SSBOo DescriptorSet 0\n"
9590                 "      OpDecorate %SSBOi Binding 0\n"
9591                 "      OpDecorate %SSBOo Binding 1\n"
9592                 "      OpDecorate %s_SSBOi Block\n"
9593                 "      OpDecorate %s_SSBOo Block\n"
9594                 "OpMemberDecorate %s_SSBOi 0 Offset 0\n"
9595                 "OpMemberDecorate %s_SSBOo 0 Offset 0\n");
9596
9597         const StringTemplate pre_main (
9598                 "${datatype_additional_decl:opt}"
9599                 "    %ptr_in = OpTypePointer StorageBuffer %${inputType}\n"
9600                 "   %ptr_out = OpTypePointer StorageBuffer %${outputType}\n"
9601                 "   %s_SSBOi = OpTypeStruct %${inputType}\n"
9602                 "   %s_SSBOo = OpTypeStruct %${outputType}\n"
9603                 " %ptr_SSBOi = OpTypePointer StorageBuffer %s_SSBOi\n"
9604                 " %ptr_SSBOo = OpTypePointer StorageBuffer %s_SSBOo\n"
9605                 "     %SSBOi = OpVariable %ptr_SSBOi StorageBuffer\n"
9606                 "     %SSBOo = OpVariable %ptr_SSBOo StorageBuffer\n");
9607
9608         const StringTemplate testfun (
9609                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9610                 "%param     = OpFunctionParameter %v4f32\n"
9611                 "%label     = OpLabel\n"
9612                 "%iLoc      = OpAccessChain %ptr_in %SSBOi %c_u32_0\n"
9613                 "%oLoc      = OpAccessChain %ptr_out %SSBOo %c_u32_0\n"
9614                 "%valIn     = OpLoad %${inputType} %iLoc\n"
9615                 "%valOut    = ${instruction} %${outputType} %valIn\n"
9616                 "             OpStore %oLoc %valOut\n"
9617                 "             OpReturnValue %param\n"
9618                 "             OpFunctionEnd\n");
9619
9620         params["datatype_extensions"] =
9621                 params["datatype_extensions"] +
9622                 "OpExtension \"SPV_KHR_storage_buffer_storage_class\"\n";
9623
9624         fragments["capability"] = params["datatype_capabilities"];
9625         fragments["extension"]  = params["datatype_extensions"];
9626         fragments["decoration"] = decoration.specialize(params);
9627         fragments["pre_main"]   = pre_main.specialize(params);
9628         fragments["testfun"]    = testfun.specialize(params);
9629
9630         return fragments;
9631 }
9632
9633 // Test for OpSConvert, OpUConvert, OpFConvert and OpConvert* in compute shaders
9634 tcu::TestCaseGroup* createConvertComputeTests (tcu::TestContext& testCtx, const string& instruction, const string& name)
9635 {
9636         de::MovePtr<tcu::TestCaseGroup>         group(new tcu::TestCaseGroup(testCtx, name.c_str(), instruction.c_str()));
9637         vector<ConvertCase>                                     testCases;
9638         createConvertCases(testCases, instruction);
9639
9640         for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
9641         {
9642                 ComputeShaderSpec spec;
9643                 spec.assembly                   = getConvertCaseShaderStr(instruction, *test);
9644                 spec.numWorkGroups              = IVec3(1, 1, 1);
9645                 spec.inputs.push_back   (test->m_inputBuffer);
9646                 spec.outputs.push_back  (test->m_outputBuffer);
9647
9648                 getVulkanFeaturesAndExtensions(test->m_fromType, test->m_toType, spec.requestedVulkanFeatures, spec.extensions);
9649
9650                 group->addChild(new SpvAsmComputeShaderCase(testCtx, test->m_name.c_str(), "", spec));
9651         }
9652         return group.release();
9653 }
9654
9655 // Test for OpSConvert, OpUConvert, OpFConvert and OpConvert* in graphics shaders
9656 tcu::TestCaseGroup* createConvertGraphicsTests (tcu::TestContext& testCtx, const string& instruction, const string& name)
9657 {
9658         de::MovePtr<tcu::TestCaseGroup>         group(new tcu::TestCaseGroup(testCtx, name.c_str(), instruction.c_str()));
9659         vector<ConvertCase>                                     testCases;
9660         createConvertCases(testCases, instruction);
9661
9662         for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
9663         {
9664                 map<string, string>     fragments               = getConvertCaseFragments(instruction, *test);
9665                 VulkanFeatures          vulkanFeatures;
9666                 GraphicsResources       resources;
9667                 vector<string>          extensions;
9668                 SpecConstants           noSpecConstants;
9669                 PushConstants           noPushConstants;
9670                 GraphicsInterfaces      noInterfaces;
9671                 tcu::RGBA                       defaultColors[4];
9672
9673                 getDefaultColors                        (defaultColors);
9674                 resources.inputs.push_back      (Resource(test->m_inputBuffer, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9675                 resources.outputs.push_back     (Resource(test->m_outputBuffer, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9676                 extensions.push_back            ("VK_KHR_storage_buffer_storage_class");
9677
9678                 getVulkanFeaturesAndExtensions(test->m_fromType, test->m_toType, vulkanFeatures, extensions);
9679
9680                 createTestsForAllStages(
9681                         test->m_name, defaultColors, defaultColors, fragments, noSpecConstants,
9682                         noPushConstants, resources, noInterfaces, extensions, vulkanFeatures, group.get());
9683         }
9684         return group.release();
9685 }
9686
9687 // Constant-Creation Instructions: OpConstant, OpConstantComposite
9688 tcu::TestCaseGroup* createOpConstantFloat16Tests(tcu::TestContext& testCtx)
9689 {
9690         de::MovePtr<tcu::TestCaseGroup> opConstantCompositeTests                (new tcu::TestCaseGroup(testCtx, "opconstant", "OpConstant and OpConstantComposite instruction"));
9691         RGBA                                                    inputColors[4];
9692         RGBA                                                    outputColors[4];
9693         vector<string>                                  extensions;
9694         GraphicsResources                               resources;
9695         VulkanFeatures                                  features;
9696
9697         const char                                              functionStart[]  =
9698                 "%test_code             = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9699                 "%param1                = OpFunctionParameter %v4f32\n"
9700                 "%lbl                   = OpLabel\n";
9701
9702         const char                                              functionEnd[]           =
9703                 "%transformed_param_32  = OpFConvert %v4f32 %transformed_param\n"
9704                 "                         OpReturnValue %transformed_param_32\n"
9705                 "                         OpFunctionEnd\n";
9706
9707         struct NameConstantsCode
9708         {
9709                 string name;
9710                 string constants;
9711                 string code;
9712         };
9713
9714 #define FLOAT_16_COMMON_TYPES_AND_CONSTS \
9715                         "%f16                  = OpTypeFloat 16\n"                                                 \
9716                         "%c_f16_0              = OpConstant %f16 0.0\n"                                            \
9717                         "%c_f16_0_5            = OpConstant %f16 0.5\n"                                            \
9718                         "%c_f16_1              = OpConstant %f16 1.0\n"                                            \
9719                         "%v4f16                = OpTypeVector %f16 4\n"                                            \
9720                         "%fp_f16               = OpTypePointer Function %f16\n"                                    \
9721                         "%fp_v4f16             = OpTypePointer Function %v4f16\n"                                  \
9722                         "%c_v4f16_1_1_1_1      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_1\n" \
9723                         "%a4f16                = OpTypeArray %f16 %c_u32_4\n"                                      \
9724
9725         NameConstantsCode                               tests[] =
9726         {
9727                 {
9728                         "vec4",
9729
9730                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9731                         "%cval                 = OpConstantComposite %v4f16 %c_f16_0_5 %c_f16_0_5 %c_f16_0_5 %c_f16_0\n",
9732                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9733                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %cval\n"
9734                 },
9735                 {
9736                         "struct",
9737
9738                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9739                         "%stype                = OpTypeStruct %v4f16 %f16\n"
9740                         "%fp_stype             = OpTypePointer Function %stype\n"
9741                         "%f16_n_1              = OpConstant %f16 -1.0\n"
9742                         "%f16_1_5              = OpConstant %f16 !0x3e00\n" // +1.5
9743                         "%cvec                 = OpConstantComposite %v4f16 %f16_1_5 %f16_1_5 %f16_1_5 %c_f16_1\n"
9744                         "%cval                 = OpConstantComposite %stype %cvec %f16_n_1\n",
9745
9746                         "%v                    = OpVariable %fp_stype Function %cval\n"
9747                         "%vec_ptr              = OpAccessChain %fp_v4f16 %v %c_u32_0\n"
9748                         "%f16_ptr              = OpAccessChain %fp_f16 %v %c_u32_1\n"
9749                         "%vec_val              = OpLoad %v4f16 %vec_ptr\n"
9750                         "%f16_val              = OpLoad %f16 %f16_ptr\n"
9751                         "%tmp1                 = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_1 %f16_val\n" // vec4(-1)
9752                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9753                         "%tmp2                 = OpFAdd %v4f16 %tmp1 %param1_16\n" // param1 + vec4(-1)
9754                         "%transformed_param    = OpFAdd %v4f16 %tmp2 %vec_val\n" // param1 + vec4(-1) + vec4(1.5, 1.5, 1.5, 1.0)
9755                 },
9756                 {
9757                         // [1|0|0|0.5] [x] = x + 0.5
9758                         // [0|1|0|0.5] [y] = y + 0.5
9759                         // [0|0|1|0.5] [z] = z + 0.5
9760                         // [0|0|0|1  ] [1] = 1
9761                         "matrix",
9762
9763                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9764                         "%mat4x4_f16           = OpTypeMatrix %v4f16 4\n"
9765                         "%v4f16_1_0_0_0        = OpConstantComposite %v4f16 %c_f16_1 %c_f16_0 %c_f16_0 %c_f16_0\n"
9766                         "%v4f16_0_1_0_0        = OpConstantComposite %v4f16 %c_f16_0 %c_f16_1 %c_f16_0 %c_f16_0\n"
9767                         "%v4f16_0_0_1_0        = OpConstantComposite %v4f16 %c_f16_0 %c_f16_0 %c_f16_1 %c_f16_0\n"
9768                         "%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"
9769                         "%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",
9770
9771                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9772                         "%transformed_param    = OpMatrixTimesVector %v4f16 %cval %param1_16\n"
9773                 },
9774                 {
9775                         "array",
9776
9777                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9778                         "%c_v4f16_1_1_1_0      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_0\n"
9779                         "%fp_a4f16             = OpTypePointer Function %a4f16\n"
9780                         "%f16_n_1              = OpConstant %f16 -1.0\n"
9781                         "%f16_1_5              = OpConstant %f16 !0x3e00\n" // +1.5
9782                         "%carr                 = OpConstantComposite %a4f16 %c_f16_0 %f16_n_1 %f16_1_5 %c_f16_0\n",
9783
9784                         "%v                    = OpVariable %fp_a4f16 Function %carr\n"
9785                         "%f                    = OpAccessChain %fp_f16 %v %c_u32_0\n"
9786                         "%f1                   = OpAccessChain %fp_f16 %v %c_u32_1\n"
9787                         "%f2                   = OpAccessChain %fp_f16 %v %c_u32_2\n"
9788                         "%f3                   = OpAccessChain %fp_f16 %v %c_u32_3\n"
9789                         "%f_val                = OpLoad %f16 %f\n"
9790                         "%f1_val               = OpLoad %f16 %f1\n"
9791                         "%f2_val               = OpLoad %f16 %f2\n"
9792                         "%f3_val               = OpLoad %f16 %f3\n"
9793                         "%ftot1                = OpFAdd %f16 %f_val %f1_val\n"
9794                         "%ftot2                = OpFAdd %f16 %ftot1 %f2_val\n"
9795                         "%ftot3                = OpFAdd %f16 %ftot2 %f3_val\n"  // 0 - 1 + 1.5 + 0
9796                         "%add_vec              = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_0 %ftot3\n"
9797                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9798                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %add_vec\n"
9799                 },
9800                 {
9801                         //
9802                         // [
9803                         //   {
9804                         //      0.0,
9805                         //      [ 1.0, 1.0, 1.0, 1.0]
9806                         //   },
9807                         //   {
9808                         //      1.0,
9809                         //      [ 0.0, 0.5, 0.0, 0.0]
9810                         //   }, //     ^^^
9811                         //   {
9812                         //      0.0,
9813                         //      [ 1.0, 1.0, 1.0, 1.0]
9814                         //   }
9815                         // ]
9816                         "array_of_struct_of_array",
9817
9818                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9819                         "%c_v4f16_1_1_1_0      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_0\n"
9820                         "%fp_a4f16             = OpTypePointer Function %a4f16\n"
9821                         "%stype                = OpTypeStruct %f16 %a4f16\n"
9822                         "%a3stype              = OpTypeArray %stype %c_u32_3\n"
9823                         "%fp_a3stype           = OpTypePointer Function %a3stype\n"
9824                         "%ca4f16_0             = OpConstantComposite %a4f16 %c_f16_0 %c_f16_0_5 %c_f16_0 %c_f16_0\n"
9825                         "%ca4f16_1             = OpConstantComposite %a4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_1\n"
9826                         "%cstype1              = OpConstantComposite %stype %c_f16_0 %ca4f16_1\n"
9827                         "%cstype2              = OpConstantComposite %stype %c_f16_1 %ca4f16_0\n"
9828                         "%carr                 = OpConstantComposite %a3stype %cstype1 %cstype2 %cstype1",
9829
9830                         "%v                    = OpVariable %fp_a3stype Function %carr\n"
9831                         "%f                    = OpAccessChain %fp_f16 %v %c_u32_1 %c_u32_1 %c_u32_1\n"
9832                         "%f_l                  = OpLoad %f16 %f\n"
9833                         "%add_vec              = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_0 %f_l\n"
9834                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9835                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %add_vec\n"
9836                 }
9837         };
9838
9839         getHalfColorsFullAlpha(inputColors);
9840         outputColors[0] = RGBA(255, 255, 255, 255);
9841         outputColors[1] = RGBA(255, 127, 127, 255);
9842         outputColors[2] = RGBA(127, 255, 127, 255);
9843         outputColors[3] = RGBA(127, 127, 255, 255);
9844
9845         extensions.push_back("VK_KHR_16bit_storage");
9846         extensions.push_back("VK_KHR_shader_float16_int8");
9847         features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
9848
9849         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
9850         {
9851                 map<string, string> fragments;
9852
9853                 fragments["extension"]  = "OpExtension \"SPV_KHR_16bit_storage\"";
9854                 fragments["capability"] = "OpCapability Float16\n";
9855                 fragments["pre_main"]   = tests[testNdx].constants;
9856                 fragments["testfun"]    = string(functionStart) + tests[testNdx].code + functionEnd;
9857
9858                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, resources, extensions, opConstantCompositeTests.get(), features);
9859         }
9860         return opConstantCompositeTests.release();
9861 }
9862
9863 template<typename T>
9864 void finalizeTestsCreation (T&                                                  specResource,
9865                                                         const map<string, string>&      fragments,
9866                                                         tcu::TestContext&                       testCtx,
9867                                                         tcu::TestCaseGroup&                     testGroup,
9868                                                         const std::string&                      testName,
9869                                                         const VulkanFeatures&           vulkanFeatures,
9870                                                         const vector<string>&           extensions,
9871                                                         const IVec3&                            numWorkGroups);
9872
9873 template<>
9874 void finalizeTestsCreation (GraphicsResources&                  specResource,
9875                                                         const map<string, string>&      fragments,
9876                                                         tcu::TestContext&                       ,
9877                                                         tcu::TestCaseGroup&                     testGroup,
9878                                                         const std::string&                      testName,
9879                                                         const VulkanFeatures&           vulkanFeatures,
9880                                                         const vector<string>&           extensions,
9881                                                         const IVec3&                            )
9882 {
9883         RGBA defaultColors[4];
9884         getDefaultColors(defaultColors);
9885
9886         createTestsForAllStages(testName, defaultColors, defaultColors, fragments, specResource, extensions, &testGroup, vulkanFeatures);
9887 }
9888
9889 template<>
9890 void finalizeTestsCreation (ComputeShaderSpec&                  specResource,
9891                                                         const map<string, string>&      fragments,
9892                                                         tcu::TestContext&                       testCtx,
9893                                                         tcu::TestCaseGroup&                     testGroup,
9894                                                         const std::string&                      testName,
9895                                                         const VulkanFeatures&           vulkanFeatures,
9896                                                         const vector<string>&           extensions,
9897                                                         const IVec3&                            numWorkGroups)
9898 {
9899         specResource.numWorkGroups = numWorkGroups;
9900         specResource.requestedVulkanFeatures = vulkanFeatures;
9901         specResource.extensions = extensions;
9902
9903         specResource.assembly = makeComputeShaderAssembly(fragments);
9904
9905         testGroup.addChild(new SpvAsmComputeShaderCase(testCtx, testName.c_str(), "", specResource));
9906 }
9907
9908 template<class SpecResource>
9909 tcu::TestCaseGroup* createFloat16LogicalSet (tcu::TestContext& testCtx, const bool nanSupported)
9910 {
9911         const string                                            nan                                     = nanSupported ? "_nan" : "";
9912         const string                                            groupName                       = "logical" + nan;
9913         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Float 16 logical tests"));
9914
9915         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
9916         const string                                            spvCapabilities         = string("OpCapability StorageUniformBufferBlock16\n") + (nanSupported ? "OpCapability SignedZeroInfNanPreserve\n" : "");
9917         const string                                            spvExtensions           = string("OpExtension \"SPV_KHR_16bit_storage\"\n") + (nanSupported ? "OpExtension \"SPV_KHR_float_controls\"\n" : "");
9918         const string                                            spvExecutionMode        = nanSupported ? "OpExecutionMode %BP_main SignedZeroInfNanPreserve 16\n" : "";
9919         const deUint32                                          numDataPoints           = 16;
9920         const vector<deFloat16>                         float16Data                     = getFloat16s(rnd, numDataPoints);
9921         const vector<deFloat16>                         float16Data1            = squarize(float16Data, 0);
9922         const vector<deFloat16>                         float16Data2            = squarize(float16Data, 1);
9923         const vector<deFloat16>                         float16DataVec1         = squarizeVector(float16Data, 0);
9924         const vector<deFloat16>                         float16DataVec2         = squarizeVector(float16Data, 1);
9925         const vector<deFloat16>                         float16OutDummy         (float16Data1.size(), 0);
9926         const vector<deFloat16>                         float16OutVecDummy      (float16DataVec1.size(), 0);
9927
9928         struct TestOp
9929         {
9930                 const char*             opCode;
9931                 VerifyIOFunc    verifyFuncNan;
9932                 VerifyIOFunc    verifyFuncNonNan;
9933                 const deUint32  argCount;
9934         };
9935
9936         const TestOp    testOps[]       =
9937         {
9938                 { "OpIsNan"                                             ,       compareFP16Logical<fp16isNan,                           true,  false, true>,    compareFP16Logical<fp16isNan,                           true,  false, false>,   1       },
9939                 { "OpIsInf"                                             ,       compareFP16Logical<fp16isInf,                           true,  false, true>,    compareFP16Logical<fp16isInf,                           true,  false, false>,   1       },
9940                 { "OpFOrdEqual"                                 ,       compareFP16Logical<fp16isEqual,                         false, true,  true>,    compareFP16Logical<fp16isEqual,                         false, true,  false>,   2       },
9941                 { "OpFUnordEqual"                               ,       compareFP16Logical<fp16isEqual,                         false, false, true>,    compareFP16Logical<fp16isEqual,                         false, false, false>,   2       },
9942                 { "OpFOrdNotEqual"                              ,       compareFP16Logical<fp16isUnequal,                       false, true,  true>,    compareFP16Logical<fp16isUnequal,                       false, true,  false>,   2       },
9943                 { "OpFUnordNotEqual"                    ,       compareFP16Logical<fp16isUnequal,                       false, false, true>,    compareFP16Logical<fp16isUnequal,                       false, false, false>,   2       },
9944                 { "OpFOrdLessThan"                              ,       compareFP16Logical<fp16isLess,                          false, true,  true>,    compareFP16Logical<fp16isLess,                          false, true,  false>,   2       },
9945                 { "OpFUnordLessThan"                    ,       compareFP16Logical<fp16isLess,                          false, false, true>,    compareFP16Logical<fp16isLess,                          false, false, false>,   2       },
9946                 { "OpFOrdGreaterThan"                   ,       compareFP16Logical<fp16isGreater,                       false, true,  true>,    compareFP16Logical<fp16isGreater,                       false, true,  false>,   2       },
9947                 { "OpFUnordGreaterThan"                 ,       compareFP16Logical<fp16isGreater,                       false, false, true>,    compareFP16Logical<fp16isGreater,                       false, false, false>,   2       },
9948                 { "OpFOrdLessThanEqual"                 ,       compareFP16Logical<fp16isLessOrEqual,           false, true,  true>,    compareFP16Logical<fp16isLessOrEqual,           false, true,  false>,   2       },
9949                 { "OpFUnordLessThanEqual"               ,       compareFP16Logical<fp16isLessOrEqual,           false, false, true>,    compareFP16Logical<fp16isLessOrEqual,           false, false, false>,   2       },
9950                 { "OpFOrdGreaterThanEqual"              ,       compareFP16Logical<fp16isGreaterOrEqual,        false, true,  true>,    compareFP16Logical<fp16isGreaterOrEqual,        false, true,  false>,   2       },
9951                 { "OpFUnordGreaterThanEqual"    ,       compareFP16Logical<fp16isGreaterOrEqual,        false, false, true>,    compareFP16Logical<fp16isGreaterOrEqual,        false, false, false>,   2       },
9952         };
9953
9954         { // scalar cases
9955                 const StringTemplate preMain
9956                 (
9957                         "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
9958                         "      %f16 = OpTypeFloat 16\n"
9959                         "  %c_f16_0 = OpConstant %f16 0.0\n"
9960                         "  %c_f16_1 = OpConstant %f16 1.0\n"
9961                         "   %up_f16 = OpTypePointer Uniform %f16\n"
9962                         "   %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
9963                         "   %SSBO16 = OpTypeStruct %ra_f16\n"
9964                         "%up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
9965                         "%ssbo_src0 = OpVariable %up_SSBO16 Uniform\n"
9966                         "%ssbo_src1 = OpVariable %up_SSBO16 Uniform\n"
9967                         " %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
9968                 );
9969
9970                 const StringTemplate decoration
9971                 (
9972                         "OpDecorate %ra_f16 ArrayStride 2\n"
9973                         "OpMemberDecorate %SSBO16 0 Offset 0\n"
9974                         "OpDecorate %SSBO16 BufferBlock\n"
9975                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
9976                         "OpDecorate %ssbo_src0 Binding 0\n"
9977                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
9978                         "OpDecorate %ssbo_src1 Binding 1\n"
9979                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
9980                         "OpDecorate %ssbo_dst Binding 2\n"
9981                 );
9982
9983                 const StringTemplate testFun
9984                 (
9985                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9986                         "    %param = OpFunctionParameter %v4f32\n"
9987
9988                         "    %entry = OpLabel\n"
9989                         "        %i = OpVariable %fp_i32 Function\n"
9990                         "             OpStore %i %c_i32_0\n"
9991                         "             OpBranch %loop\n"
9992
9993                         "     %loop = OpLabel\n"
9994                         "    %i_cmp = OpLoad %i32 %i\n"
9995                         "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
9996                         "             OpLoopMerge %merge %next None\n"
9997                         "             OpBranchConditional %lt %write %merge\n"
9998
9999                         "    %write = OpLabel\n"
10000                         "      %ndx = OpLoad %i32 %i\n"
10001
10002                         "     %src0 = OpAccessChain %up_f16 %ssbo_src0 %c_i32_0 %ndx\n"
10003                         " %val_src0 = OpLoad %f16 %src0\n"
10004
10005                         "${op_arg1_calc}"
10006
10007                         " %val_bdst = ${op_code} %bool %val_src0 ${op_arg1}\n"
10008                         "  %val_dst = OpSelect %f16 %val_bdst %c_f16_1 %c_f16_0\n"
10009                         "      %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
10010                         "             OpStore %dst %val_dst\n"
10011                         "             OpBranch %next\n"
10012
10013                         "     %next = OpLabel\n"
10014                         "    %i_cur = OpLoad %i32 %i\n"
10015                         "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10016                         "             OpStore %i %i_new\n"
10017                         "             OpBranch %loop\n"
10018
10019                         "    %merge = OpLabel\n"
10020                         "             OpReturnValue %param\n"
10021
10022                         "             OpFunctionEnd\n"
10023                 );
10024
10025                 const StringTemplate arg1Calc
10026                 (
10027                         "     %src1 = OpAccessChain %up_f16 %ssbo_src1 %c_i32_0 %ndx\n"
10028                         " %val_src1 = OpLoad %f16 %src1\n"
10029                 );
10030
10031                 for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10032                 {
10033                         const size_t            iterations              = float16Data1.size();
10034                         const TestOp&           testOp                  = testOps[testOpsIdx];
10035                         const string            testName                = de::toLower(string(testOp.opCode)) + "_scalar";
10036                         SpecResource            specResource;
10037                         map<string, string>     specs;
10038                         VulkanFeatures          features;
10039                         map<string, string>     fragments;
10040                         vector<string>          extensions;
10041
10042                         specs["num_data_points"]        = de::toString(iterations);
10043                         specs["op_code"]                        = testOp.opCode;
10044                         specs["op_arg1"]                        = (testOp.argCount == 1) ? "" : "%val_src1";
10045                         specs["op_arg1_calc"]           = (testOp.argCount == 1) ? "" : arg1Calc.specialize(specs);
10046
10047                         fragments["extension"]          = spvExtensions;
10048                         fragments["capability"]         = spvCapabilities;
10049                         fragments["execution_mode"]     = spvExecutionMode;
10050                         fragments["decoration"]         = decoration.specialize(specs);
10051                         fragments["pre_main"]           = preMain.specialize(specs);
10052                         fragments["testfun"]            = testFun.specialize(specs);
10053
10054                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Data1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10055                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Data2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10056                         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10057                         specResource.verifyIO = nanSupported ? testOp.verifyFuncNan : testOp.verifyFuncNonNan;
10058
10059                         extensions.push_back("VK_KHR_16bit_storage");
10060                         extensions.push_back("VK_KHR_shader_float16_int8");
10061
10062                         if (nanSupported)
10063                         {
10064                                 extensions.push_back("VK_KHR_shader_float_controls");
10065
10066                                 features.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat16 = DE_TRUE;
10067                         }
10068
10069                         features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10070                         features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10071
10072                         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10073                 }
10074         }
10075         { // vector cases
10076                 const StringTemplate preMain
10077                 (
10078                         "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10079                         "     %v2bool = OpTypeVector %bool 2\n"
10080                         "        %f16 = OpTypeFloat 16\n"
10081                         "    %c_f16_0 = OpConstant %f16 0.0\n"
10082                         "    %c_f16_1 = OpConstant %f16 1.0\n"
10083                         "      %v2f16 = OpTypeVector %f16 2\n"
10084                         "%c_v2f16_0_0 = OpConstantComposite %v2f16 %c_f16_0 %c_f16_0\n"
10085                         "%c_v2f16_1_1 = OpConstantComposite %v2f16 %c_f16_1 %c_f16_1\n"
10086                         "   %up_v2f16 = OpTypePointer Uniform %v2f16\n"
10087                         "   %ra_v2f16 = OpTypeArray %v2f16 %c_i32_ndp\n"
10088                         "     %SSBO16 = OpTypeStruct %ra_v2f16\n"
10089                         "  %up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10090                         "  %ssbo_src0 = OpVariable %up_SSBO16 Uniform\n"
10091                         "  %ssbo_src1 = OpVariable %up_SSBO16 Uniform\n"
10092                         "   %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10093                 );
10094
10095                 const StringTemplate decoration
10096                 (
10097                         "OpDecorate %ra_v2f16 ArrayStride 4\n"
10098                         "OpMemberDecorate %SSBO16 0 Offset 0\n"
10099                         "OpDecorate %SSBO16 BufferBlock\n"
10100                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
10101                         "OpDecorate %ssbo_src0 Binding 0\n"
10102                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
10103                         "OpDecorate %ssbo_src1 Binding 1\n"
10104                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
10105                         "OpDecorate %ssbo_dst Binding 2\n"
10106                 );
10107
10108                 const StringTemplate testFun
10109                 (
10110                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10111                         "    %param = OpFunctionParameter %v4f32\n"
10112
10113                         "    %entry = OpLabel\n"
10114                         "        %i = OpVariable %fp_i32 Function\n"
10115                         "             OpStore %i %c_i32_0\n"
10116                         "             OpBranch %loop\n"
10117
10118                         "     %loop = OpLabel\n"
10119                         "    %i_cmp = OpLoad %i32 %i\n"
10120                         "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10121                         "             OpLoopMerge %merge %next None\n"
10122                         "             OpBranchConditional %lt %write %merge\n"
10123
10124                         "    %write = OpLabel\n"
10125                         "      %ndx = OpLoad %i32 %i\n"
10126
10127                         "     %src0 = OpAccessChain %up_v2f16 %ssbo_src0 %c_i32_0 %ndx\n"
10128                         " %val_src0 = OpLoad %v2f16 %src0\n"
10129
10130                         "${op_arg1_calc}"
10131
10132                         " %val_bdst = ${op_code} %v2bool %val_src0 ${op_arg1}\n"
10133                         "  %val_dst = OpSelect %v2f16 %val_bdst %c_v2f16_1_1 %c_v2f16_0_0\n"
10134                         "      %dst = OpAccessChain %up_v2f16 %ssbo_dst %c_i32_0 %ndx\n"
10135                         "             OpStore %dst %val_dst\n"
10136                         "             OpBranch %next\n"
10137
10138                         "     %next = OpLabel\n"
10139                         "    %i_cur = OpLoad %i32 %i\n"
10140                         "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10141                         "             OpStore %i %i_new\n"
10142                         "             OpBranch %loop\n"
10143
10144                         "    %merge = OpLabel\n"
10145                         "             OpReturnValue %param\n"
10146
10147                         "             OpFunctionEnd\n"
10148                 );
10149
10150                 const StringTemplate arg1Calc
10151                 (
10152                         "     %src1 = OpAccessChain %up_v2f16 %ssbo_src1 %c_i32_0 %ndx\n"
10153                         " %val_src1 = OpLoad %v2f16 %src1\n"
10154                 );
10155
10156                 for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10157                 {
10158                         const deUint32          itemsPerVec     = 2;
10159                         const size_t            iterations      = float16DataVec1.size() / itemsPerVec;
10160                         const TestOp&           testOp          = testOps[testOpsIdx];
10161                         const string            testName        = de::toLower(string(testOp.opCode)) + "_vector";
10162                         SpecResource            specResource;
10163                         map<string, string>     specs;
10164                         vector<string>          extensions;
10165                         VulkanFeatures          features;
10166                         map<string, string>     fragments;
10167
10168                         specs["num_data_points"]        = de::toString(iterations);
10169                         specs["op_code"]                        = testOp.opCode;
10170                         specs["op_arg1"]                        = (testOp.argCount == 1) ? "" : "%val_src1";
10171                         specs["op_arg1_calc"]           = (testOp.argCount == 1) ? "" : arg1Calc.specialize(specs);
10172
10173                         fragments["extension"]          = spvExtensions;
10174                         fragments["capability"]         = spvCapabilities;
10175                         fragments["execution_mode"]     = spvExecutionMode;
10176                         fragments["decoration"]         = decoration.specialize(specs);
10177                         fragments["pre_main"]           = preMain.specialize(specs);
10178                         fragments["testfun"]            = testFun.specialize(specs);
10179
10180                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16DataVec1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10181                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16DataVec2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10182                         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutVecDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10183                         specResource.verifyIO = nanSupported ? testOp.verifyFuncNan : testOp.verifyFuncNonNan;
10184
10185                         extensions.push_back("VK_KHR_16bit_storage");
10186                         extensions.push_back("VK_KHR_shader_float16_int8");
10187
10188                         if (nanSupported)
10189                         {
10190                                 extensions.push_back("VK_KHR_shader_float_controls");
10191
10192                                 features.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat16 = DE_TRUE;
10193                         }
10194
10195                         features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10196                         features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10197
10198                         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10199                 }
10200         }
10201
10202         return testGroup.release();
10203 }
10204
10205 bool compareFP16FunctionSetFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10206 {
10207         if (inputs.size() != 1 || outputAllocs.size() != 1)
10208                 return false;
10209
10210         vector<deUint8> input1Bytes;
10211
10212         inputs[0].getBytes(input1Bytes);
10213
10214         const deUint16* const   input1AsFP16    = (const deUint16*)&input1Bytes[0];
10215         const deUint16* const   outputAsFP16    = (const deUint16*)outputAllocs[0]->getHostPtr();
10216         std::string                             error;
10217
10218         for (size_t idx = 0; idx < input1Bytes.size() / sizeof(deUint16); ++idx)
10219         {
10220                 if (!compare16BitFloat(input1AsFP16[idx], outputAsFP16[idx], error))
10221                 {
10222                         log << TestLog::Message << error << TestLog::EndMessage;
10223
10224                         return false;
10225                 }
10226         }
10227
10228         return true;
10229 }
10230
10231 template<class SpecResource>
10232 tcu::TestCaseGroup* createFloat16FuncSet (tcu::TestContext& testCtx)
10233 {
10234         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "function", "Float 16 function call related tests"));
10235
10236         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10237         const StringTemplate                            capabilities            ("OpCapability ${cap}\n");
10238         const deUint32                                          numDataPoints           = 256;
10239         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
10240         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
10241         map<string, string>                                     fragments;
10242
10243         struct TestType
10244         {
10245                 const deUint32  typeComponents;
10246                 const char*             typeName;
10247                 const char*             typeDecls;
10248         };
10249
10250         const TestType  testTypes[]     =
10251         {
10252                 {
10253                         1,
10254                         "f16",
10255                         ""
10256                 },
10257                 {
10258                         2,
10259                         "v2f16",
10260                         "      %v2f16 = OpTypeVector %f16 2\n"
10261                         "  %c_v2f16_0 = OpConstantComposite %v2f16 %c_f16_0 %c_f16_0\n"
10262                 },
10263                 {
10264                         4,
10265                         "v4f16",
10266                         "      %v4f16 = OpTypeVector %f16 4\n"
10267                         "  %c_v4f16_0 = OpConstantComposite %v4f16 %c_f16_0 %c_f16_0 %c_f16_0 %c_f16_0\n"
10268                 },
10269         };
10270
10271         const StringTemplate preMain
10272         (
10273                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10274                 "     %v2bool = OpTypeVector %bool 2\n"
10275                 "        %f16 = OpTypeFloat 16\n"
10276                 "    %c_f16_0 = OpConstant %f16 0.0\n"
10277
10278                 "${type_decls}"
10279
10280                 "  %${tt}_fun = OpTypeFunction %${tt} %${tt}\n"
10281                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
10282                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10283                 "     %SSBO16 = OpTypeStruct %ra_${tt}\n"
10284                 "  %up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10285                 "   %ssbo_src = OpVariable %up_SSBO16 Uniform\n"
10286                 "   %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10287         );
10288
10289         const StringTemplate decoration
10290         (
10291                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10292                 "OpMemberDecorate %SSBO16 0 Offset 0\n"
10293                 "OpDecorate %SSBO16 BufferBlock\n"
10294                 "OpDecorate %ssbo_src DescriptorSet 0\n"
10295                 "OpDecorate %ssbo_src Binding 0\n"
10296                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
10297                 "OpDecorate %ssbo_dst Binding 1\n"
10298         );
10299
10300         const StringTemplate testFun
10301         (
10302                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10303                 "    %param = OpFunctionParameter %v4f32\n"
10304                 "    %entry = OpLabel\n"
10305
10306                 "        %i = OpVariable %fp_i32 Function\n"
10307                 "             OpStore %i %c_i32_0\n"
10308                 "             OpBranch %loop\n"
10309
10310                 "     %loop = OpLabel\n"
10311                 "    %i_cmp = OpLoad %i32 %i\n"
10312                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10313                 "             OpLoopMerge %merge %next None\n"
10314                 "             OpBranchConditional %lt %write %merge\n"
10315
10316                 "    %write = OpLabel\n"
10317                 "      %ndx = OpLoad %i32 %i\n"
10318
10319                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10320                 "  %val_src = OpLoad %${tt} %src\n"
10321
10322                 "  %val_dst = OpFunctionCall %${tt} %pass_fun %val_src\n"
10323                 "      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
10324                 "             OpStore %dst %val_dst\n"
10325                 "             OpBranch %next\n"
10326
10327                 "     %next = OpLabel\n"
10328                 "    %i_cur = OpLoad %i32 %i\n"
10329                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10330                 "             OpStore %i %i_new\n"
10331                 "             OpBranch %loop\n"
10332
10333                 "    %merge = OpLabel\n"
10334                 "             OpReturnValue %param\n"
10335
10336                 "             OpFunctionEnd\n"
10337
10338                 " %pass_fun = OpFunction %${tt} None %${tt}_fun\n"
10339                 "   %param0 = OpFunctionParameter %${tt}\n"
10340                 " %entry_pf = OpLabel\n"
10341                 "     %res0 = OpFAdd %${tt} %param0 %c_${tt}_0\n"
10342                 "             OpReturnValue %res0\n"
10343                 "             OpFunctionEnd\n"
10344         );
10345
10346         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
10347         {
10348                 const TestType&         testType                = testTypes[testTypeIdx];
10349                 const string            testName                = testType.typeName;
10350                 const deUint32          itemsPerType    = testType.typeComponents;
10351                 const size_t            iterations              = float16InputData.size() / itemsPerType;
10352                 const size_t            typeStride              = itemsPerType * sizeof(deFloat16);
10353                 SpecResource            specResource;
10354                 map<string, string>     specs;
10355                 VulkanFeatures          features;
10356                 vector<string>          extensions;
10357
10358                 specs["cap"]                            = "StorageUniformBufferBlock16";
10359                 specs["num_data_points"]        = de::toString(iterations);
10360                 specs["tt"]                                     = testType.typeName;
10361                 specs["tt_stride"]                      = de::toString(typeStride);
10362                 specs["type_decls"]                     = testType.typeDecls;
10363
10364                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
10365                 fragments["capability"]         = capabilities.specialize(specs);
10366                 fragments["decoration"]         = decoration.specialize(specs);
10367                 fragments["pre_main"]           = preMain.specialize(specs);
10368                 fragments["testfun"]            = testFun.specialize(specs);
10369
10370                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10371                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10372                 specResource.verifyIO = compareFP16FunctionSetFunc;
10373
10374                 extensions.push_back("VK_KHR_16bit_storage");
10375                 extensions.push_back("VK_KHR_shader_float16_int8");
10376
10377                 features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10378                 features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10379
10380                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10381         }
10382
10383         return testGroup.release();
10384 }
10385
10386 struct getV_    { deUint32 inline operator()(deUint32 v) const  { return v;        } getV_(){} };
10387 struct getV0    { deUint32 inline operator()(deUint32 v) const  { return v & (~1); } getV0(){} };
10388 struct getV1    { deUint32 inline operator()(deUint32 v) const  { return v | ( 1); } getV1(){} };
10389
10390 template<deUint32 R, deUint32 N>
10391 inline static deUint32 getOffset(deUint32 x, deUint32 y, deUint32 n)
10392 {
10393         return N * ((R * y) + x) + n;
10394 }
10395
10396 template<deUint32 R, deUint32 N, class X0, class X1, class Y0, class Y1>
10397 struct getFDelta
10398 {
10399         float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10400         {
10401                 DE_STATIC_ASSERT(R%2 == 0);
10402                 DE_ASSERT(flavor == 0);
10403                 DE_UNREF(flavor);
10404
10405                 const X0                        x0;
10406                 const X1                        x1;
10407                 const Y0                        y0;
10408                 const Y1                        y1;
10409                 const deFloat16         v0      = data[getOffset<R, N>(x0(x), y0(y), n)];
10410                 const deFloat16         v1      = data[getOffset<R, N>(x1(x), y1(y), n)];
10411                 const tcu::Float16      f0      = tcu::Float16(v0);
10412                 const tcu::Float16      f1      = tcu::Float16(v1);
10413                 const float                     d0      = f0.asFloat();
10414                 const float                     d1      = f1.asFloat();
10415                 const float                     d       = d1 - d0;
10416
10417                 return d;
10418         }
10419
10420         getFDelta(){}
10421 };
10422
10423 template<deUint32 F, class Class0, class Class1>
10424 struct getFOneOf
10425 {
10426         float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10427         {
10428                 DE_ASSERT(flavor < F);
10429
10430                 if (flavor == 0)
10431                 {
10432                         Class0 c;
10433
10434                         return c(data, x, y, n, flavor);
10435                 }
10436                 else
10437                 {
10438                         Class1 c;
10439
10440                         return c(data, x, y, n, flavor - 1);
10441                 }
10442         }
10443
10444         getFOneOf(){}
10445 };
10446
10447 template<class FineX0, class FineX1, class FineY0, class FineY1>
10448 struct calcWidthOf4
10449 {
10450         float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10451         {
10452                 DE_ASSERT(flavor < 4);
10453
10454                 const deUint32                                          flavorX = (flavor & 1) == 0 ? 0 : 1;
10455                 const deUint32                                          flavorY = (flavor & 2) == 0 ? 0 : 1;
10456                 const getFOneOf<2, FineX0, FineX1>      cx;
10457                 const getFOneOf<2, FineY0, FineY1>      cy;
10458                 float                                                           v               = 0;
10459
10460                 v += fabsf(cx(data, x, y, n, flavorX));
10461                 v += fabsf(cy(data, x, y, n, flavorY));
10462
10463                 return v;
10464         }
10465
10466         calcWidthOf4(){}
10467 };
10468
10469 template<deUint32 R, deUint32 N, class Derivative>
10470 bool compareDerivativeWithFlavor (const deFloat16* inputAsFP16, const deFloat16* outputAsFP16, deUint32 flavor, std::string& error)
10471 {
10472         const deUint32          numDataPointsByAxis     = R;
10473         const Derivative        derivativeFunc;
10474
10475         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10476         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10477         for (deUint32 n = 0; n < N; ++n)
10478         {
10479                 const float             expectedFloat   = derivativeFunc(inputAsFP16, x, y, n, flavor);
10480                 deFloat16               expected                = deFloat32To16Round(expectedFloat, DE_ROUNDINGMODE_TO_NEAREST_EVEN);
10481                 const deFloat16 output                  = outputAsFP16[getOffset<R, N>(x, y, n)];
10482
10483                 bool                    reportError             = !compare16BitFloat(expected, output, error);
10484
10485                 if (reportError)
10486                 {
10487                         expected        = deFloat32To16Round(expectedFloat, DE_ROUNDINGMODE_TO_ZERO);
10488                         reportError     = !compare16BitFloat(expected, output, error);
10489                 }
10490
10491                 if (reportError)
10492                 {
10493                         error = "subcase at " + de::toString(x) + "," + de::toString(y) + "," + de::toString(n) + ": " + error;
10494
10495                         return false;
10496                 }
10497         }
10498
10499         return true;
10500 }
10501
10502 template<deUint32 R, deUint32 N, deUint32 FLAVOUR_COUNT, class Derivative>
10503 bool compareDerivative (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10504 {
10505         if (inputs.size() != 1 || outputAllocs.size() != 1)
10506                 return false;
10507
10508         deUint32                        successfulRuns                  = FLAVOUR_COUNT;
10509         std::string                     results[FLAVOUR_COUNT];
10510         vector<deUint8>         inputBytes;
10511
10512         inputs[0].getBytes(inputBytes);
10513
10514         const deFloat16*        inputAsFP16             = reinterpret_cast<deFloat16* const>(&inputBytes.front());
10515         const deFloat16*        outputAsFP16    = static_cast<deFloat16*>(outputAllocs[0]->getHostPtr());
10516
10517         DE_ASSERT(inputBytes.size() ==  R * R * N * sizeof(deFloat16));
10518
10519         for (deUint32 flavor = 0; flavor < FLAVOUR_COUNT; ++flavor)
10520                 if (compareDerivativeWithFlavor<R, N, Derivative> (inputAsFP16, outputAsFP16, flavor, results[flavor]))
10521                 {
10522                         break;
10523                 }
10524                 else
10525                 {
10526                         successfulRuns--;
10527                 }
10528
10529         if (successfulRuns == 0)
10530                 for (deUint32 flavor = 0; flavor < FLAVOUR_COUNT; flavor++)
10531                         log << TestLog::Message << "At flavor #" << flavor << " " << results[flavor] << TestLog::EndMessage;
10532
10533         return successfulRuns > 0;
10534 }
10535
10536 template<deUint32 R, deUint32 N>
10537 tcu::TestCaseGroup* createDerivativeTests (tcu::TestContext& testCtx)
10538 {
10539         typedef getFDelta<R, N, getV0, getV1, getV_, getV_> getFDxFine;
10540         typedef getFDelta<R, N, getV_, getV_, getV0, getV1> getFDyFine;
10541
10542         typedef getFDelta<R, N, getV0, getV1, getV0, getV0> getFdxCoarse0;
10543         typedef getFDelta<R, N, getV0, getV1, getV1, getV1> getFdxCoarse1;
10544         typedef getFDelta<R, N, getV0, getV0, getV0, getV1> getFdyCoarse0;
10545         typedef getFDelta<R, N, getV1, getV1, getV0, getV1> getFdyCoarse1;
10546         typedef getFOneOf<2, getFdxCoarse0, getFdxCoarse1> getFDxCoarse;
10547         typedef getFOneOf<2, getFdyCoarse0, getFdyCoarse1> getFDyCoarse;
10548
10549         typedef calcWidthOf4<getFDxFine, getFDxFine, getFDyFine, getFDyFine> getFWidthFine;
10550         typedef calcWidthOf4<getFdxCoarse0, getFdxCoarse1, getFdyCoarse0, getFdyCoarse1> getFWidthCoarse;
10551
10552         typedef getFOneOf<3, getFDxFine, getFDxCoarse> getFDx;
10553         typedef getFOneOf<3, getFDyFine, getFDyCoarse> getFDy;
10554         typedef getFOneOf<5, getFWidthFine, getFWidthCoarse> getFWidth;
10555
10556         const std::string                                       testGroupName           (std::string("derivative_") + de::toString(N));
10557         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Derivative instruction tests"));
10558
10559         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10560         const deUint32                                          numDataPointsByAxis     = R;
10561         const deUint32                                          numDataPoints           = N * numDataPointsByAxis * numDataPointsByAxis;
10562         vector<deFloat16>                                       float16InputX;
10563         vector<deFloat16>                                       float16InputY;
10564         vector<deFloat16>                                       float16InputW;
10565         vector<deFloat16>                                       float16OutputDummy      (numDataPoints, 0);
10566         RGBA                                                            defaultColors[4];
10567
10568         getDefaultColors(defaultColors);
10569
10570         float16InputX.reserve(numDataPoints);
10571         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10572         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10573         for (deUint32 n = 0; n < N; ++n)
10574         {
10575                 const float arg = static_cast<float>(2 * DE_PI) * static_cast<float>(x * (n + 1)) / static_cast<float>(1 * numDataPointsByAxis);
10576
10577                 if (y%2 == 0)
10578                         float16InputX.push_back(tcu::Float16(sin(arg)).bits());
10579                 else
10580                         float16InputX.push_back(tcu::Float16(cos(arg)).bits());
10581         }
10582
10583         float16InputY.reserve(numDataPoints);
10584         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10585         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10586         for (deUint32 n = 0; n < N; ++n)
10587         {
10588                 const float arg = static_cast<float>(2 * DE_PI) * static_cast<float>(y * (n + 1)) / static_cast<float>(1 * numDataPointsByAxis);
10589
10590                 if (x%2 == 0)
10591                         float16InputY.push_back(tcu::Float16(sin(arg)).bits());
10592                 else
10593                         float16InputY.push_back(tcu::Float16(cos(arg)).bits());
10594         }
10595
10596         const deFloat16 testNumbers[]   =
10597         {
10598                 tcu::Float16( 2.0  ).bits(),
10599                 tcu::Float16( 4.0  ).bits(),
10600                 tcu::Float16( 8.0  ).bits(),
10601                 tcu::Float16( 16.0 ).bits(),
10602                 tcu::Float16( 32.0 ).bits(),
10603                 tcu::Float16( 64.0 ).bits(),
10604                 tcu::Float16( 128.0).bits(),
10605                 tcu::Float16( 256.0).bits(),
10606                 tcu::Float16( 512.0).bits(),
10607                 tcu::Float16(-2.0  ).bits(),
10608                 tcu::Float16(-4.0  ).bits(),
10609                 tcu::Float16(-8.0  ).bits(),
10610                 tcu::Float16(-16.0 ).bits(),
10611                 tcu::Float16(-32.0 ).bits(),
10612                 tcu::Float16(-64.0 ).bits(),
10613                 tcu::Float16(-128.0).bits(),
10614                 tcu::Float16(-256.0).bits(),
10615                 tcu::Float16(-512.0).bits(),
10616         };
10617
10618         float16InputW.reserve(numDataPoints);
10619         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10620         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10621         for (deUint32 n = 0; n < N; ++n)
10622                 float16InputW.push_back(testNumbers[rnd.getInt(0, DE_LENGTH_OF_ARRAY(testNumbers) - 1)]);
10623
10624         struct TestOp
10625         {
10626                 const char*                     opCode;
10627                 vector<deFloat16>&      inputData;
10628                 VerifyIOFunc            verifyFunc;
10629         };
10630
10631         const TestOp    testOps[]       =
10632         {
10633                 { "OpDPdxFine"          ,       float16InputX   ,       compareDerivative<R, N, 1, getFDxFine           >       },
10634                 { "OpDPdyFine"          ,       float16InputY   ,       compareDerivative<R, N, 1, getFDyFine           >       },
10635                 { "OpFwidthFine"        ,       float16InputW   ,       compareDerivative<R, N, 1, getFWidthFine        >       },
10636                 { "OpDPdxCoarse"        ,       float16InputX   ,       compareDerivative<R, N, 3, getFDx                       >       },
10637                 { "OpDPdyCoarse"        ,       float16InputY   ,       compareDerivative<R, N, 3, getFDy                       >       },
10638                 { "OpFwidthCoarse"      ,       float16InputW   ,       compareDerivative<R, N, 5, getFWidth            >       },
10639                 { "OpDPdx"                      ,       float16InputX   ,       compareDerivative<R, N, 3, getFDx                       >       },
10640                 { "OpDPdy"                      ,       float16InputY   ,       compareDerivative<R, N, 3, getFDy                       >       },
10641                 { "OpFwidth"            ,       float16InputW   ,       compareDerivative<R, N, 5, getFWidth            >       },
10642         };
10643
10644         struct TestType
10645         {
10646                 const deUint32  typeComponents;
10647                 const char*             typeName;
10648                 const char*             typeDecls;
10649         };
10650
10651         const TestType  testTypes[]     =
10652         {
10653                 {
10654                         1,
10655                         "f16",
10656                         ""
10657                 },
10658                 {
10659                         2,
10660                         "v2f16",
10661                         "      %v2f16 = OpTypeVector %f16 2\n"
10662                 },
10663                 {
10664                         4,
10665                         "v4f16",
10666                         "      %v4f16 = OpTypeVector %f16 4\n"
10667                 },
10668         };
10669
10670         const deUint32  testTypeNdx     = (N == 1) ? 0
10671                                                                 : (N == 2) ? 1
10672                                                                 : (N == 4) ? 2
10673                                                                 : DE_LENGTH_OF_ARRAY(testTypes);
10674         const TestType& testType        =       testTypes[testTypeNdx];
10675
10676         DE_ASSERT(testTypeNdx < DE_LENGTH_OF_ARRAY(testTypes));
10677         DE_ASSERT(testType.typeComponents == N);
10678
10679         const StringTemplate preMain
10680         (
10681                 "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10682                 " %c_u32_xw = OpConstant %u32 ${items_by_x}\n"
10683                 "      %f16 = OpTypeFloat 16\n"
10684                 "${type_decls}"
10685                 " %up_${tt} = OpTypePointer Uniform %${tt}\n"
10686                 " %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10687                 "   %SSBO16 = OpTypeStruct %ra_${tt}\n"
10688                 "%up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10689                 " %ssbo_src = OpVariable %up_SSBO16 Uniform\n"
10690                 " %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10691         );
10692
10693         const StringTemplate decoration
10694         (
10695                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10696                 "OpMemberDecorate %SSBO16 0 Offset 0\n"
10697                 "OpDecorate %SSBO16 BufferBlock\n"
10698                 "OpDecorate %ssbo_src DescriptorSet 0\n"
10699                 "OpDecorate %ssbo_src Binding 0\n"
10700                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
10701                 "OpDecorate %ssbo_dst Binding 1\n"
10702         );
10703
10704         const StringTemplate testFun
10705         (
10706                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10707                 "    %param = OpFunctionParameter %v4f32\n"
10708                 "    %entry = OpLabel\n"
10709
10710                 "  %loc_x_c = OpAccessChain %ip_f32 %BP_gl_FragCoord %c_i32_0\n"
10711                 "  %loc_y_c = OpAccessChain %ip_f32 %BP_gl_FragCoord %c_i32_1\n"
10712                 "      %x_c = OpLoad %f32 %loc_x_c\n"
10713                 "      %y_c = OpLoad %f32 %loc_y_c\n"
10714                 "    %x_idx = OpConvertFToU %u32 %x_c\n"
10715                 "    %y_idx = OpConvertFToU %u32 %y_c\n"
10716                 "    %ndx_y = OpIMul %u32 %y_idx %c_u32_xw\n"
10717                 "      %ndx = OpIAdd %u32 %ndx_y %x_idx\n"
10718
10719                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10720                 "  %val_src = OpLoad %${tt} %src\n"
10721                 "  %val_dst = ${op_code} %${tt} %val_src\n"
10722                 "      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
10723                 "             OpStore %dst %val_dst\n"
10724                 "             OpBranch %merge\n"
10725
10726                 "    %merge = OpLabel\n"
10727                 "             OpReturnValue %param\n"
10728
10729                 "             OpFunctionEnd\n"
10730         );
10731
10732         for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10733         {
10734                 const TestOp&           testOp                  = testOps[testOpsIdx];
10735                 const string            testName                = de::toLower(string(testOp.opCode));
10736                 const size_t            typeStride              = N * sizeof(deFloat16);
10737                 GraphicsResources       specResource;
10738                 map<string, string>     specs;
10739                 VulkanFeatures          features;
10740                 vector<string>          extensions;
10741                 map<string, string>     fragments;
10742                 SpecConstants           noSpecConstants;
10743                 PushConstants           noPushConstants;
10744                 GraphicsInterfaces      noInterfaces;
10745
10746                 specs["op_code"]                        = testOp.opCode;
10747                 specs["num_data_points"]        = de::toString(testOp.inputData.size() / N);
10748                 specs["items_by_x"]                     = de::toString(numDataPointsByAxis);
10749                 specs["tt"]                                     = testType.typeName;
10750                 specs["tt_stride"]                      = de::toString(typeStride);
10751                 specs["type_decls"]                     = testType.typeDecls;
10752
10753                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
10754                 fragments["capability"]         = "OpCapability DerivativeControl\nOpCapability StorageUniformBufferBlock16\n";
10755                 fragments["decoration"]         = decoration.specialize(specs);
10756                 fragments["pre_main"]           = preMain.specialize(specs);
10757                 fragments["testfun"]            = testFun.specialize(specs);
10758
10759                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(testOp.inputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10760                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10761                 specResource.verifyIO = testOp.verifyFunc;
10762
10763                 extensions.push_back("VK_KHR_16bit_storage");
10764                 extensions.push_back("VK_KHR_shader_float16_int8");
10765
10766                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
10767                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10768
10769                 createTestForStage(VK_SHADER_STAGE_FRAGMENT_BIT, testName.c_str(), defaultColors, defaultColors, fragments, noSpecConstants,
10770                                                         noPushConstants, specResource, noInterfaces, extensions, features, testGroup.get(), QP_TEST_RESULT_FAIL, string(), true);
10771         }
10772
10773         return testGroup.release();
10774 }
10775
10776 bool compareFP16VectorExtractFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10777 {
10778         if (inputs.size() != 2 || outputAllocs.size() != 1)
10779                 return false;
10780
10781         vector<deUint8> input1Bytes;
10782         vector<deUint8> input2Bytes;
10783
10784         inputs[0].getBytes(input1Bytes);
10785         inputs[1].getBytes(input2Bytes);
10786
10787         DE_ASSERT(input1Bytes.size() > 0);
10788         DE_ASSERT(input2Bytes.size() > 0);
10789         DE_ASSERT(input2Bytes.size() % sizeof(deUint32) == 0);
10790
10791         const size_t                    iterations              = input2Bytes.size() / sizeof(deUint32);
10792         const size_t                    components              = input1Bytes.size() / (sizeof(deFloat16) * iterations);
10793         const deFloat16* const  input1AsFP16    = (const deFloat16*)&input1Bytes[0];
10794         const deUint32* const   inputIndices    = (const deUint32*)&input2Bytes[0];
10795         const deFloat16* const  outputAsFP16    = (const deFloat16*)outputAllocs[0]->getHostPtr();
10796         std::string                             error;
10797
10798         DE_ASSERT(components == 2 || components == 4);
10799         DE_ASSERT(input1Bytes.size() == iterations * components * sizeof(deFloat16));
10800
10801         for (size_t idx = 0; idx < iterations; ++idx)
10802         {
10803                 const deUint32  componentNdx    = inputIndices[idx];
10804
10805                 DE_ASSERT(componentNdx < components);
10806
10807                 const deFloat16 expected                = input1AsFP16[components * idx + componentNdx];
10808
10809                 if (!compare16BitFloat(expected, outputAsFP16[idx], error))
10810                 {
10811                         log << TestLog::Message << "At " << idx << error << TestLog::EndMessage;
10812
10813                         return false;
10814                 }
10815         }
10816
10817         return true;
10818 }
10819
10820 template<class SpecResource>
10821 tcu::TestCaseGroup* createFloat16VectorExtractSet (tcu::TestContext& testCtx)
10822 {
10823         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorextractdynamic", "OpVectorExtractDynamic tests"));
10824
10825         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10826         const deUint32                                          numDataPoints           = 256;
10827         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
10828         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
10829
10830         struct TestType
10831         {
10832                 const deUint32  typeComponents;
10833                 const size_t    typeStride;
10834                 const char*             typeName;
10835                 const char*             typeDecls;
10836         };
10837
10838         const TestType  testTypes[]     =
10839         {
10840                 {
10841                         2,
10842                         2 * sizeof(deFloat16),
10843                         "v2f16",
10844                         "      %v2f16 = OpTypeVector %f16 2\n"
10845                 },
10846                 {
10847                         3,
10848                         4 * sizeof(deFloat16),
10849                         "v3f16",
10850                         "      %v3f16 = OpTypeVector %f16 3\n"
10851                 },
10852                 {
10853                         4,
10854                         4 * sizeof(deFloat16),
10855                         "v4f16",
10856                         "      %v4f16 = OpTypeVector %f16 4\n"
10857                 },
10858         };
10859
10860         const StringTemplate preMain
10861         (
10862                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10863                 "        %f16 = OpTypeFloat 16\n"
10864
10865                 "${type_decl}"
10866
10867                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
10868                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10869                 "   %SSBO_SRC = OpTypeStruct %ra_${tt}\n"
10870                 "%up_SSBO_SRC = OpTypePointer Uniform %SSBO_SRC\n"
10871
10872                 "     %up_u32 = OpTypePointer Uniform %u32\n"
10873                 "     %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
10874                 "   %SSBO_IDX = OpTypeStruct %ra_u32\n"
10875                 "%up_SSBO_IDX = OpTypePointer Uniform %SSBO_IDX\n"
10876
10877                 "     %up_f16 = OpTypePointer Uniform %f16\n"
10878                 "     %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
10879                 "   %SSBO_DST = OpTypeStruct %ra_f16\n"
10880                 "%up_SSBO_DST = OpTypePointer Uniform %SSBO_DST\n"
10881
10882                 "   %ssbo_src = OpVariable %up_SSBO_SRC Uniform\n"
10883                 "   %ssbo_idx = OpVariable %up_SSBO_IDX Uniform\n"
10884                 "   %ssbo_dst = OpVariable %up_SSBO_DST Uniform\n"
10885         );
10886
10887         const StringTemplate decoration
10888         (
10889                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10890                 "OpMemberDecorate %SSBO_SRC 0 Offset 0\n"
10891                 "OpDecorate %SSBO_SRC BufferBlock\n"
10892                 "OpDecorate %ssbo_src DescriptorSet 0\n"
10893                 "OpDecorate %ssbo_src Binding 0\n"
10894
10895                 "OpDecorate %ra_u32 ArrayStride 4\n"
10896                 "OpMemberDecorate %SSBO_IDX 0 Offset 0\n"
10897                 "OpDecorate %SSBO_IDX BufferBlock\n"
10898                 "OpDecorate %ssbo_idx DescriptorSet 0\n"
10899                 "OpDecorate %ssbo_idx Binding 1\n"
10900
10901                 "OpDecorate %ra_f16 ArrayStride 2\n"
10902                 "OpMemberDecorate %SSBO_DST 0 Offset 0\n"
10903                 "OpDecorate %SSBO_DST BufferBlock\n"
10904                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
10905                 "OpDecorate %ssbo_dst Binding 2\n"
10906         );
10907
10908         const StringTemplate testFun
10909         (
10910                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10911                 "    %param = OpFunctionParameter %v4f32\n"
10912                 "    %entry = OpLabel\n"
10913
10914                 "        %i = OpVariable %fp_i32 Function\n"
10915                 "             OpStore %i %c_i32_0\n"
10916
10917                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
10918                 "             OpSelectionMerge %end_if None\n"
10919                 "             OpBranchConditional %will_run %run_test %end_if\n"
10920
10921                 " %run_test = OpLabel\n"
10922                 "             OpBranch %loop\n"
10923
10924                 "     %loop = OpLabel\n"
10925                 "    %i_cmp = OpLoad %i32 %i\n"
10926                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10927                 "             OpLoopMerge %merge %next None\n"
10928                 "             OpBranchConditional %lt %write %merge\n"
10929
10930                 "    %write = OpLabel\n"
10931                 "      %ndx = OpLoad %i32 %i\n"
10932
10933                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10934                 "  %val_src = OpLoad %${tt} %src\n"
10935
10936                 "  %src_idx = OpAccessChain %up_u32 %ssbo_idx %c_i32_0 %ndx\n"
10937                 "  %val_idx = OpLoad %u32 %src_idx\n"
10938
10939                 "  %val_dst = OpVectorExtractDynamic %f16 %val_src %val_idx\n"
10940                 "      %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
10941
10942                 "             OpStore %dst %val_dst\n"
10943                 "             OpBranch %next\n"
10944
10945                 "     %next = OpLabel\n"
10946                 "    %i_cur = OpLoad %i32 %i\n"
10947                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10948                 "             OpStore %i %i_new\n"
10949                 "             OpBranch %loop\n"
10950
10951                 "    %merge = OpLabel\n"
10952                 "             OpBranch %end_if\n"
10953                 "   %end_if = OpLabel\n"
10954                 "             OpReturnValue %param\n"
10955
10956                 "             OpFunctionEnd\n"
10957         );
10958
10959         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
10960         {
10961                 const TestType&         testType                = testTypes[testTypeIdx];
10962                 const string            testName                = testType.typeName;
10963                 const size_t            itemsPerType    = testType.typeStride / sizeof(deFloat16);
10964                 const size_t            iterations              = float16InputData.size() / itemsPerType;
10965                 SpecResource            specResource;
10966                 map<string, string>     specs;
10967                 VulkanFeatures          features;
10968                 vector<deUint32>        inputDataNdx;
10969                 map<string, string>     fragments;
10970                 vector<string>          extensions;
10971
10972                 for (deUint32 ndx = 0; ndx < iterations; ++ndx)
10973                         inputDataNdx.push_back(rnd.getUint32() % testType.typeComponents);
10974
10975                 specs["num_data_points"]        = de::toString(iterations);
10976                 specs["tt"]                                     = testType.typeName;
10977                 specs["tt_stride"]                      = de::toString(testType.typeStride);
10978                 specs["type_decl"]                      = testType.typeDecls;
10979
10980                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
10981                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
10982                 fragments["decoration"]         = decoration.specialize(specs);
10983                 fragments["pre_main"]           = preMain.specialize(specs);
10984                 fragments["testfun"]            = testFun.specialize(specs);
10985
10986                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10987                 specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inputDataNdx)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10988                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10989                 specResource.verifyIO = compareFP16VectorExtractFunc;
10990
10991                 extensions.push_back("VK_KHR_16bit_storage");
10992                 extensions.push_back("VK_KHR_shader_float16_int8");
10993
10994                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
10995                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10996
10997                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10998         }
10999
11000         return testGroup.release();
11001 }
11002
11003 template<deUint32 COMPONENTS_COUNT, deUint32 REPLACEMENT>
11004 bool compareFP16VectorInsertFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11005 {
11006         if (inputs.size() != 2 || outputAllocs.size() != 1)
11007                 return false;
11008
11009         vector<deUint8> input1Bytes;
11010         vector<deUint8> input2Bytes;
11011
11012         inputs[0].getBytes(input1Bytes);
11013         inputs[1].getBytes(input2Bytes);
11014
11015         DE_ASSERT(input1Bytes.size() > 0);
11016         DE_ASSERT(input2Bytes.size() > 0);
11017         DE_ASSERT(input2Bytes.size() % sizeof(deUint32) == 0);
11018
11019         const size_t                    iterations                      = input2Bytes.size() / sizeof(deUint32);
11020         const size_t                    componentsStride        = input1Bytes.size() / (sizeof(deFloat16) * iterations);
11021         const deFloat16* const  input1AsFP16            = (const deFloat16*)&input1Bytes[0];
11022         const deUint32* const   inputIndices            = (const deUint32*)&input2Bytes[0];
11023         const deFloat16* const  outputAsFP16            = (const deFloat16*)outputAllocs[0]->getHostPtr();
11024         const deFloat16                 magic                           = tcu::Float16(float(REPLACEMENT)).bits();
11025         std::string                             error;
11026
11027         DE_ASSERT(componentsStride == 2 || componentsStride == 4);
11028         DE_ASSERT(input1Bytes.size() == iterations * componentsStride * sizeof(deFloat16));
11029
11030         for (size_t idx = 0; idx < iterations; ++idx)
11031         {
11032                 const deFloat16*        inputVec                = &input1AsFP16[componentsStride * idx];
11033                 const deFloat16*        outputVec               = &outputAsFP16[componentsStride * idx];
11034                 const deUint32          replacedCompNdx = inputIndices[idx];
11035
11036                 DE_ASSERT(replacedCompNdx < COMPONENTS_COUNT);
11037
11038                 for (size_t compNdx = 0; compNdx < COMPONENTS_COUNT; ++compNdx)
11039                 {
11040                         const deFloat16 expected        = (compNdx == replacedCompNdx) ? magic : inputVec[compNdx];
11041
11042                         if (!compare16BitFloat(expected, outputVec[compNdx], error))
11043                         {
11044                                 log << TestLog::Message << "At " << idx << "[" << compNdx << "]: " << error << TestLog::EndMessage;
11045
11046                                 return false;
11047                         }
11048                 }
11049         }
11050
11051         return true;
11052 }
11053
11054 template<class SpecResource>
11055 tcu::TestCaseGroup* createFloat16VectorInsertSet (tcu::TestContext& testCtx)
11056 {
11057         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorinsertdynamic", "OpVectorInsertDynamic tests"));
11058
11059         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
11060         const deUint32                                          replacement                     = 42;
11061         const deUint32                                          numDataPoints           = 256;
11062         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
11063         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
11064
11065         struct TestType
11066         {
11067                 const deUint32  typeComponents;
11068                 const size_t    typeStride;
11069                 const char*             typeName;
11070                 const char*             typeDecls;
11071                 VerifyIOFunc    verifyIOFunc;
11072         };
11073
11074         const TestType  testTypes[]     =
11075         {
11076                 {
11077                         2,
11078                         2 * sizeof(deFloat16),
11079                         "v2f16",
11080                         "      %v2f16 = OpTypeVector %f16 2\n",
11081                         compareFP16VectorInsertFunc<2, replacement>
11082                 },
11083                 {
11084                         3,
11085                         4 * sizeof(deFloat16),
11086                         "v3f16",
11087                         "      %v3f16 = OpTypeVector %f16 3\n",
11088                         compareFP16VectorInsertFunc<3, replacement>
11089                 },
11090                 {
11091                         4,
11092                         4 * sizeof(deFloat16),
11093                         "v4f16",
11094                         "      %v4f16 = OpTypeVector %f16 4\n",
11095                         compareFP16VectorInsertFunc<4, replacement>
11096                 },
11097         };
11098
11099         const StringTemplate preMain
11100         (
11101                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
11102                 "        %f16 = OpTypeFloat 16\n"
11103                 "  %c_f16_ins = OpConstant %f16 ${replacement}\n"
11104
11105                 "${type_decl}"
11106
11107                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
11108                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
11109                 "   %SSBO_SRC = OpTypeStruct %ra_${tt}\n"
11110                 "%up_SSBO_SRC = OpTypePointer Uniform %SSBO_SRC\n"
11111
11112                 "     %up_u32 = OpTypePointer Uniform %u32\n"
11113                 "     %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
11114                 "   %SSBO_IDX = OpTypeStruct %ra_u32\n"
11115                 "%up_SSBO_IDX = OpTypePointer Uniform %SSBO_IDX\n"
11116
11117                 "   %SSBO_DST = OpTypeStruct %ra_${tt}\n"
11118                 "%up_SSBO_DST = OpTypePointer Uniform %SSBO_DST\n"
11119
11120                 "   %ssbo_src = OpVariable %up_SSBO_SRC Uniform\n"
11121                 "   %ssbo_idx = OpVariable %up_SSBO_IDX Uniform\n"
11122                 "   %ssbo_dst = OpVariable %up_SSBO_DST Uniform\n"
11123         );
11124
11125         const StringTemplate decoration
11126         (
11127                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
11128                 "OpMemberDecorate %SSBO_SRC 0 Offset 0\n"
11129                 "OpDecorate %SSBO_SRC BufferBlock\n"
11130                 "OpDecorate %ssbo_src DescriptorSet 0\n"
11131                 "OpDecorate %ssbo_src Binding 0\n"
11132
11133                 "OpDecorate %ra_u32 ArrayStride 4\n"
11134                 "OpMemberDecorate %SSBO_IDX 0 Offset 0\n"
11135                 "OpDecorate %SSBO_IDX BufferBlock\n"
11136                 "OpDecorate %ssbo_idx DescriptorSet 0\n"
11137                 "OpDecorate %ssbo_idx Binding 1\n"
11138
11139                 "OpMemberDecorate %SSBO_DST 0 Offset 0\n"
11140                 "OpDecorate %SSBO_DST BufferBlock\n"
11141                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11142                 "OpDecorate %ssbo_dst Binding 2\n"
11143         );
11144
11145         const StringTemplate testFun
11146         (
11147                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11148                 "    %param = OpFunctionParameter %v4f32\n"
11149                 "    %entry = OpLabel\n"
11150
11151                 "        %i = OpVariable %fp_i32 Function\n"
11152                 "             OpStore %i %c_i32_0\n"
11153
11154                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11155                 "             OpSelectionMerge %end_if None\n"
11156                 "             OpBranchConditional %will_run %run_test %end_if\n"
11157
11158                 " %run_test = OpLabel\n"
11159                 "             OpBranch %loop\n"
11160
11161                 "     %loop = OpLabel\n"
11162                 "    %i_cmp = OpLoad %i32 %i\n"
11163                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11164                 "             OpLoopMerge %merge %next None\n"
11165                 "             OpBranchConditional %lt %write %merge\n"
11166
11167                 "    %write = OpLabel\n"
11168                 "      %ndx = OpLoad %i32 %i\n"
11169
11170                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
11171                 "  %val_src = OpLoad %${tt} %src\n"
11172
11173                 "  %src_idx = OpAccessChain %up_u32 %ssbo_idx %c_i32_0 %ndx\n"
11174                 "  %val_idx = OpLoad %u32 %src_idx\n"
11175
11176                 "  %val_dst = OpVectorInsertDynamic %${tt} %val_src %c_f16_ins %val_idx\n"
11177                 "      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
11178
11179                 "             OpStore %dst %val_dst\n"
11180                 "             OpBranch %next\n"
11181
11182                 "     %next = OpLabel\n"
11183                 "    %i_cur = OpLoad %i32 %i\n"
11184                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11185                 "             OpStore %i %i_new\n"
11186                 "             OpBranch %loop\n"
11187
11188                 "    %merge = OpLabel\n"
11189                 "             OpBranch %end_if\n"
11190                 "   %end_if = OpLabel\n"
11191                 "             OpReturnValue %param\n"
11192
11193                 "             OpFunctionEnd\n"
11194         );
11195
11196         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
11197         {
11198                 const TestType&         testType                = testTypes[testTypeIdx];
11199                 const string            testName                = testType.typeName;
11200                 const size_t            itemsPerType    = testType.typeStride / sizeof(deFloat16);
11201                 const size_t            iterations              = float16InputData.size() / itemsPerType;
11202                 SpecResource            specResource;
11203                 map<string, string>     specs;
11204                 VulkanFeatures          features;
11205                 vector<deUint32>        inputDataNdx;
11206                 map<string, string>     fragments;
11207                 vector<string>          extensions;
11208
11209                 for (deUint32 ndx = 0; ndx < iterations; ++ndx)
11210                         inputDataNdx.push_back(rnd.getUint32() % testType.typeComponents);
11211
11212                 specs["num_data_points"]        = de::toString(iterations);
11213                 specs["tt"]                                     = testType.typeName;
11214                 specs["tt_stride"]                      = de::toString(testType.typeStride);
11215                 specs["type_decl"]                      = testType.typeDecls;
11216                 specs["replacement"]            = de::toString(replacement);
11217
11218                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11219                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
11220                 fragments["decoration"]         = decoration.specialize(specs);
11221                 fragments["pre_main"]           = preMain.specialize(specs);
11222                 fragments["testfun"]            = testFun.specialize(specs);
11223
11224                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11225                 specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inputDataNdx)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11226                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11227                 specResource.verifyIO = testType.verifyIOFunc;
11228
11229                 extensions.push_back("VK_KHR_16bit_storage");
11230                 extensions.push_back("VK_KHR_shader_float16_int8");
11231
11232                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11233                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11234
11235                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11236         }
11237
11238         return testGroup.release();
11239 }
11240
11241 inline deFloat16 getShuffledComponent (const size_t iteration, const size_t componentNdx, const deFloat16* input1Vec, const deFloat16* input2Vec, size_t vec1Len, size_t vec2Len, bool& validate)
11242 {
11243         const size_t    compNdxCount    = (vec1Len + vec2Len + 1);
11244         const size_t    compNdxLimited  = iteration % (compNdxCount * compNdxCount);
11245         size_t                  comp;
11246
11247         switch (componentNdx)
11248         {
11249                 case 0: comp = compNdxLimited / compNdxCount; break;
11250                 case 1: comp = compNdxLimited % compNdxCount; break;
11251                 case 2: comp = 0; break;
11252                 case 3: comp = 1; break;
11253                 default: TCU_THROW(InternalError, "Impossible");
11254         }
11255
11256         if (comp >= vec1Len + vec2Len)
11257         {
11258                 validate = false;
11259                 return 0;
11260         }
11261         else
11262         {
11263                 validate = true;
11264                 return (comp < vec1Len) ? input1Vec[comp] : input2Vec[comp - vec1Len];
11265         }
11266 }
11267
11268 template<deUint32 DST_COMPONENTS_COUNT, deUint32 SRC0_COMPONENTS_COUNT, deUint32 SRC1_COMPONENTS_COUNT>
11269 bool compareFP16VectorShuffleFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11270 {
11271         DE_STATIC_ASSERT(DST_COMPONENTS_COUNT == 2 || DST_COMPONENTS_COUNT == 3 || DST_COMPONENTS_COUNT == 4);
11272         DE_STATIC_ASSERT(SRC0_COMPONENTS_COUNT == 2 || SRC0_COMPONENTS_COUNT == 3 || SRC0_COMPONENTS_COUNT == 4);
11273         DE_STATIC_ASSERT(SRC1_COMPONENTS_COUNT == 2 || SRC1_COMPONENTS_COUNT == 3 || SRC1_COMPONENTS_COUNT == 4);
11274
11275         if (inputs.size() != 2 || outputAllocs.size() != 1)
11276                 return false;
11277
11278         vector<deUint8> input1Bytes;
11279         vector<deUint8> input2Bytes;
11280
11281         inputs[0].getBytes(input1Bytes);
11282         inputs[1].getBytes(input2Bytes);
11283
11284         DE_ASSERT(input1Bytes.size() > 0);
11285         DE_ASSERT(input2Bytes.size() > 0);
11286         DE_ASSERT(input2Bytes.size() % sizeof(deFloat16) == 0);
11287
11288         const size_t                    componentsStrideDst             = (DST_COMPONENTS_COUNT == 3) ? 4 : DST_COMPONENTS_COUNT;
11289         const size_t                    componentsStrideSrc0    = (SRC0_COMPONENTS_COUNT == 3) ? 4 : SRC0_COMPONENTS_COUNT;
11290         const size_t                    componentsStrideSrc1    = (SRC1_COMPONENTS_COUNT == 3) ? 4 : SRC1_COMPONENTS_COUNT;
11291         const size_t                    iterations                              = input1Bytes.size() / (componentsStrideSrc0 * sizeof(deFloat16));
11292         const deFloat16* const  input1AsFP16                    = (const deFloat16*)&input1Bytes[0];
11293         const deFloat16* const  input2AsFP16                    = (const deFloat16*)&input2Bytes[0];
11294         const deFloat16* const  outputAsFP16                    = (const deFloat16*)outputAllocs[0]->getHostPtr();
11295         std::string                             error;
11296
11297         DE_ASSERT(input1Bytes.size() == iterations * componentsStrideSrc0 * sizeof(deFloat16));
11298         DE_ASSERT(input2Bytes.size() == iterations * componentsStrideSrc1 * sizeof(deFloat16));
11299
11300         for (size_t idx = 0; idx < iterations; ++idx)
11301         {
11302                 const deFloat16*        input1Vec       = &input1AsFP16[componentsStrideSrc0 * idx];
11303                 const deFloat16*        input2Vec       = &input2AsFP16[componentsStrideSrc1 * idx];
11304                 const deFloat16*        outputVec       = &outputAsFP16[componentsStrideDst * idx];
11305
11306                 for (size_t compNdx = 0; compNdx < DST_COMPONENTS_COUNT; ++compNdx)
11307                 {
11308                         bool            validate        = true;
11309                         deFloat16       expected        = getShuffledComponent(idx, compNdx, input1Vec, input2Vec, SRC0_COMPONENTS_COUNT, SRC1_COMPONENTS_COUNT, validate);
11310
11311                         if (validate && !compare16BitFloat(expected, outputVec[compNdx], error))
11312                         {
11313                                 log << TestLog::Message << "At " << idx << "[" << compNdx << "]: " << error << TestLog::EndMessage;
11314
11315                                 return false;
11316                         }
11317                 }
11318         }
11319
11320         return true;
11321 }
11322
11323 VerifyIOFunc getFloat16VectorShuffleVerifyIOFunc (deUint32 dstComponentsCount, deUint32 src0ComponentsCount, deUint32 src1ComponentsCount)
11324 {
11325         DE_ASSERT(dstComponentsCount <= 4);
11326         DE_ASSERT(src0ComponentsCount <= 4);
11327         DE_ASSERT(src1ComponentsCount <= 4);
11328         deUint32 funcCode = 100 * dstComponentsCount + 10 * src0ComponentsCount + src1ComponentsCount;
11329
11330         switch (funcCode)
11331         {
11332                 case 222:return compareFP16VectorShuffleFunc<2, 2, 2>;
11333                 case 223:return compareFP16VectorShuffleFunc<2, 2, 3>;
11334                 case 224:return compareFP16VectorShuffleFunc<2, 2, 4>;
11335                 case 232:return compareFP16VectorShuffleFunc<2, 3, 2>;
11336                 case 233:return compareFP16VectorShuffleFunc<2, 3, 3>;
11337                 case 234:return compareFP16VectorShuffleFunc<2, 3, 4>;
11338                 case 242:return compareFP16VectorShuffleFunc<2, 4, 2>;
11339                 case 243:return compareFP16VectorShuffleFunc<2, 4, 3>;
11340                 case 244:return compareFP16VectorShuffleFunc<2, 4, 4>;
11341                 case 322:return compareFP16VectorShuffleFunc<3, 2, 2>;
11342                 case 323:return compareFP16VectorShuffleFunc<3, 2, 3>;
11343                 case 324:return compareFP16VectorShuffleFunc<3, 2, 4>;
11344                 case 332:return compareFP16VectorShuffleFunc<3, 3, 2>;
11345                 case 333:return compareFP16VectorShuffleFunc<3, 3, 3>;
11346                 case 334:return compareFP16VectorShuffleFunc<3, 3, 4>;
11347                 case 342:return compareFP16VectorShuffleFunc<3, 4, 2>;
11348                 case 343:return compareFP16VectorShuffleFunc<3, 4, 3>;
11349                 case 344:return compareFP16VectorShuffleFunc<3, 4, 4>;
11350                 case 422:return compareFP16VectorShuffleFunc<4, 2, 2>;
11351                 case 423:return compareFP16VectorShuffleFunc<4, 2, 3>;
11352                 case 424:return compareFP16VectorShuffleFunc<4, 2, 4>;
11353                 case 432:return compareFP16VectorShuffleFunc<4, 3, 2>;
11354                 case 433:return compareFP16VectorShuffleFunc<4, 3, 3>;
11355                 case 434:return compareFP16VectorShuffleFunc<4, 3, 4>;
11356                 case 442:return compareFP16VectorShuffleFunc<4, 4, 2>;
11357                 case 443:return compareFP16VectorShuffleFunc<4, 4, 3>;
11358                 case 444:return compareFP16VectorShuffleFunc<4, 4, 4>;
11359                 default: TCU_THROW(InternalError, "Invalid number of components specified.");
11360         }
11361 }
11362
11363 template<class SpecResource>
11364 tcu::TestCaseGroup* createFloat16VectorShuffleSet (tcu::TestContext& testCtx)
11365 {
11366         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorshuffle", "OpVectorShuffle tests"));
11367         const int                                                       testSpecificSeed        = deStringHash(testGroup->getName());
11368         const int                                                       seed                            = testCtx.getCommandLine().getBaseSeed() ^ testSpecificSeed;
11369         de::Random                                                      rnd                                     (seed);
11370         const deUint32                                          numDataPoints           = 128;
11371         map<string, string>                                     fragments;
11372
11373         struct TestType
11374         {
11375                 const deUint32  typeComponents;
11376                 const char*             typeName;
11377         };
11378
11379         const TestType  testTypes[]     =
11380         {
11381                 {
11382                         2,
11383                         "v2f16",
11384                 },
11385                 {
11386                         3,
11387                         "v3f16",
11388                 },
11389                 {
11390                         4,
11391                         "v4f16",
11392                 },
11393         };
11394
11395         const StringTemplate preMain
11396         (
11397                 "    %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
11398                 "     %c_i32_cc = OpConstant %i32 ${case_count}\n"
11399                 "          %f16 = OpTypeFloat 16\n"
11400                 "        %v2f16 = OpTypeVector %f16 2\n"
11401                 "        %v3f16 = OpTypeVector %f16 3\n"
11402                 "        %v4f16 = OpTypeVector %f16 4\n"
11403
11404                 "     %up_v2f16 = OpTypePointer Uniform %v2f16\n"
11405                 "     %ra_v2f16 = OpTypeArray %v2f16 %c_i32_ndp\n"
11406                 "   %SSBO_v2f16 = OpTypeStruct %ra_v2f16\n"
11407                 "%up_SSBO_v2f16 = OpTypePointer Uniform %SSBO_v2f16\n"
11408
11409                 "     %up_v3f16 = OpTypePointer Uniform %v3f16\n"
11410                 "     %ra_v3f16 = OpTypeArray %v3f16 %c_i32_ndp\n"
11411                 "   %SSBO_v3f16 = OpTypeStruct %ra_v3f16\n"
11412                 "%up_SSBO_v3f16 = OpTypePointer Uniform %SSBO_v3f16\n"
11413
11414                 "     %up_v4f16 = OpTypePointer Uniform %v4f16\n"
11415                 "     %ra_v4f16 = OpTypeArray %v4f16 %c_i32_ndp\n"
11416                 "   %SSBO_v4f16 = OpTypeStruct %ra_v4f16\n"
11417                 "%up_SSBO_v4f16 = OpTypePointer Uniform %SSBO_v4f16\n"
11418
11419                 "        %fun_t = OpTypeFunction %${tt_dst} %${tt_src0} %${tt_src1} %i32\n"
11420
11421                 "    %ssbo_src0 = OpVariable %up_SSBO_${tt_src0} Uniform\n"
11422                 "    %ssbo_src1 = OpVariable %up_SSBO_${tt_src1} Uniform\n"
11423                 "     %ssbo_dst = OpVariable %up_SSBO_${tt_dst} Uniform\n"
11424         );
11425
11426         const StringTemplate decoration
11427         (
11428                 "OpDecorate %ra_v2f16 ArrayStride 4\n"
11429                 "OpDecorate %ra_v3f16 ArrayStride 8\n"
11430                 "OpDecorate %ra_v4f16 ArrayStride 8\n"
11431
11432                 "OpMemberDecorate %SSBO_v2f16 0 Offset 0\n"
11433                 "OpDecorate %SSBO_v2f16 BufferBlock\n"
11434
11435                 "OpMemberDecorate %SSBO_v3f16 0 Offset 0\n"
11436                 "OpDecorate %SSBO_v3f16 BufferBlock\n"
11437
11438                 "OpMemberDecorate %SSBO_v4f16 0 Offset 0\n"
11439                 "OpDecorate %SSBO_v4f16 BufferBlock\n"
11440
11441                 "OpDecorate %ssbo_src0 DescriptorSet 0\n"
11442                 "OpDecorate %ssbo_src0 Binding 0\n"
11443                 "OpDecorate %ssbo_src1 DescriptorSet 0\n"
11444                 "OpDecorate %ssbo_src1 Binding 1\n"
11445                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11446                 "OpDecorate %ssbo_dst Binding 2\n"
11447         );
11448
11449         const StringTemplate testFun
11450         (
11451                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11452                 "    %param = OpFunctionParameter %v4f32\n"
11453                 "    %entry = OpLabel\n"
11454
11455                 "        %i = OpVariable %fp_i32 Function\n"
11456                 "             OpStore %i %c_i32_0\n"
11457
11458                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11459                 "             OpSelectionMerge %end_if None\n"
11460                 "             OpBranchConditional %will_run %run_test %end_if\n"
11461
11462                 " %run_test = OpLabel\n"
11463                 "             OpBranch %loop\n"
11464
11465                 "     %loop = OpLabel\n"
11466                 "    %i_cmp = OpLoad %i32 %i\n"
11467                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11468                 "             OpLoopMerge %merge %next None\n"
11469                 "             OpBranchConditional %lt %write %merge\n"
11470
11471                 "    %write = OpLabel\n"
11472                 "      %ndx = OpLoad %i32 %i\n"
11473                 "     %src0 = OpAccessChain %up_${tt_src0} %ssbo_src0 %c_i32_0 %ndx\n"
11474                 " %val_src0 = OpLoad %${tt_src0} %src0\n"
11475                 "     %src1 = OpAccessChain %up_${tt_src1} %ssbo_src1 %c_i32_0 %ndx\n"
11476                 " %val_src1 = OpLoad %${tt_src1} %src1\n"
11477                 "  %val_dst = OpFunctionCall %${tt_dst} %sw_fun %val_src0 %val_src1 %ndx\n"
11478                 "      %dst = OpAccessChain %up_${tt_dst} %ssbo_dst %c_i32_0 %ndx\n"
11479                 "             OpStore %dst %val_dst\n"
11480                 "             OpBranch %next\n"
11481
11482                 "     %next = OpLabel\n"
11483                 "    %i_cur = OpLoad %i32 %i\n"
11484                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11485                 "             OpStore %i %i_new\n"
11486                 "             OpBranch %loop\n"
11487
11488                 "    %merge = OpLabel\n"
11489                 "             OpBranch %end_if\n"
11490                 "   %end_if = OpLabel\n"
11491                 "             OpReturnValue %param\n"
11492                 "             OpFunctionEnd\n"
11493                 "\n"
11494
11495                 "   %sw_fun = OpFunction %${tt_dst} None %fun_t\n"
11496                 "%sw_param0 = OpFunctionParameter %${tt_src0}\n"
11497                 "%sw_param1 = OpFunctionParameter %${tt_src1}\n"
11498                 "%sw_paramn = OpFunctionParameter %i32\n"
11499                 " %sw_entry = OpLabel\n"
11500                 "   %modulo = OpSMod %i32 %sw_paramn %c_i32_cc\n"
11501                 "             OpSelectionMerge %switch_e None\n"
11502                 "             OpSwitch %modulo %default ${case_list}\n"
11503                 "${case_bodies}"
11504                 "%default   = OpLabel\n"
11505                 "             OpUnreachable\n" // Unreachable default case for switch statement
11506                 "%switch_e  = OpLabel\n"
11507                 "             OpUnreachable\n" // Unreachable merge block for switch statement
11508                 "             OpFunctionEnd\n"
11509         );
11510
11511         const StringTemplate testCaseBody
11512         (
11513                 "%case_${case_ndx}    = OpLabel\n"
11514                 "%val_dst_${case_ndx} = OpVectorShuffle %${tt_dst} %sw_param0 %sw_param1 ${shuffle}\n"
11515                 "             OpReturnValue %val_dst_${case_ndx}\n"
11516         );
11517
11518         for (deUint32 dstTypeIdx = 0; dstTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++dstTypeIdx)
11519         {
11520                 const TestType& dstType                 = testTypes[dstTypeIdx];
11521
11522                 for (deUint32 comp0Idx = 0; comp0Idx < DE_LENGTH_OF_ARRAY(testTypes); ++comp0Idx)
11523                 {
11524                         const TestType& src0Type        = testTypes[comp0Idx];
11525
11526                         for (deUint32 comp1Idx = 0; comp1Idx < DE_LENGTH_OF_ARRAY(testTypes); ++comp1Idx)
11527                         {
11528                                 const TestType&                 src1Type                        = testTypes[comp1Idx];
11529                                 const deUint32                  input0Stride            = (src0Type.typeComponents == 3) ? 4 : src0Type.typeComponents;
11530                                 const deUint32                  input1Stride            = (src1Type.typeComponents == 3) ? 4 : src1Type.typeComponents;
11531                                 const deUint32                  outputStride            = (dstType.typeComponents == 3) ? 4 : dstType.typeComponents;
11532                                 const vector<deFloat16> float16Input0Data       = getFloat16s(rnd, input0Stride * numDataPoints);
11533                                 const vector<deFloat16> float16Input1Data       = getFloat16s(rnd, input1Stride * numDataPoints);
11534                                 const vector<deFloat16> float16OutputDummy      (outputStride * numDataPoints, 0);
11535                                 const string                    testName                        = de::toString(dstType.typeComponents) + de::toString(src0Type.typeComponents) + de::toString(src1Type.typeComponents);
11536                                 deUint32                                caseCount                       = 0;
11537                                 SpecResource                    specResource;
11538                                 map<string, string>             specs;
11539                                 vector<string>                  extensions;
11540                                 VulkanFeatures                  features;
11541                                 string                                  caseBodies;
11542                                 string                                  caseList;
11543
11544                                 // Generate case
11545                                 {
11546                                         vector<string>  componentList;
11547
11548                                         // Generate component possible indices for OpVectorShuffle for components 0 and 1 in output vector
11549                                         {
11550                                                 deUint32                caseNo          = 0;
11551
11552                                                 for (deUint32 comp0IdxLocal = 0; comp0IdxLocal < src0Type.typeComponents; ++comp0IdxLocal)
11553                                                         componentList.push_back(de::toString(caseNo++));
11554                                                 for (deUint32 comp1IdxLocal = 0; comp1IdxLocal < src1Type.typeComponents; ++comp1IdxLocal)
11555                                                         componentList.push_back(de::toString(caseNo++));
11556                                                 componentList.push_back("0xFFFFFFFF");
11557                                         }
11558
11559                                         for (deUint32 comp0IdxLocal = 0; comp0IdxLocal < componentList.size(); ++comp0IdxLocal)
11560                                         {
11561                                                 for (deUint32 comp1IdxLocal = 0; comp1IdxLocal < componentList.size(); ++comp1IdxLocal)
11562                                                 {
11563                                                         map<string, string>     specCase;
11564                                                         string                          shuffle         = componentList[comp0IdxLocal] + " " + componentList[comp1IdxLocal];
11565
11566                                                         for (deUint32 compIdx = 2; compIdx < dstType.typeComponents; ++compIdx)
11567                                                                 shuffle += " " + de::toString(compIdx - 2);
11568
11569                                                         specCase["case_ndx"]    = de::toString(caseCount);
11570                                                         specCase["shuffle"]             = shuffle;
11571                                                         specCase["tt_dst"]              = dstType.typeName;
11572
11573                                                         caseBodies      += testCaseBody.specialize(specCase);
11574                                                         caseList        += de::toString(caseCount) + " %case_" + de::toString(caseCount) + " ";
11575
11576                                                         caseCount++;
11577                                                 }
11578                                         }
11579                                 }
11580
11581                                 specs["num_data_points"]        = de::toString(numDataPoints);
11582                                 specs["tt_dst"]                         = dstType.typeName;
11583                                 specs["tt_src0"]                        = src0Type.typeName;
11584                                 specs["tt_src1"]                        = src1Type.typeName;
11585                                 specs["case_bodies"]            = caseBodies;
11586                                 specs["case_list"]                      = caseList;
11587                                 specs["case_count"]                     = de::toString(caseCount);
11588
11589                                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11590                                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
11591                                 fragments["decoration"]         = decoration.specialize(specs);
11592                                 fragments["pre_main"]           = preMain.specialize(specs);
11593                                 fragments["testfun"]            = testFun.specialize(specs);
11594
11595                                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Input0Data)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11596                                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Input1Data)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11597                                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11598                                 specResource.verifyIO = getFloat16VectorShuffleVerifyIOFunc(dstType.typeComponents, src0Type.typeComponents, src1Type.typeComponents);
11599
11600                                 extensions.push_back("VK_KHR_16bit_storage");
11601                                 extensions.push_back("VK_KHR_shader_float16_int8");
11602
11603                                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11604                                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11605
11606                                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11607                         }
11608                 }
11609         }
11610
11611         return testGroup.release();
11612 }
11613
11614 bool compareFP16CompositeFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11615 {
11616         if (inputs.size() != 1 || outputAllocs.size() != 1)
11617                 return false;
11618
11619         vector<deUint8> input1Bytes;
11620
11621         inputs[0].getBytes(input1Bytes);
11622
11623         DE_ASSERT(input1Bytes.size() > 0);
11624         DE_ASSERT(input1Bytes.size() % sizeof(deFloat16) == 0);
11625
11626         const size_t                    iterations              = input1Bytes.size() / sizeof(deFloat16);
11627         const deFloat16* const  input1AsFP16    = (const deFloat16*)&input1Bytes[0];
11628         const deFloat16* const  outputAsFP16    = (const deFloat16*)outputAllocs[0]->getHostPtr();
11629         const deFloat16                 exceptionValue  = tcu::Float16(-1.0).bits();
11630         std::string                             error;
11631
11632         for (size_t idx = 0; idx < iterations; ++idx)
11633         {
11634                 if (input1AsFP16[idx] == exceptionValue)
11635                         continue;
11636
11637                 if (!compare16BitFloat(input1AsFP16[idx], outputAsFP16[idx], error))
11638                 {
11639                         log << TestLog::Message << "At " << idx << ":" << error << TestLog::EndMessage;
11640
11641                         return false;
11642                 }
11643         }
11644
11645         return true;
11646 }
11647
11648 template<class SpecResource>
11649 tcu::TestCaseGroup* createFloat16CompositeConstructSet (tcu::TestContext& testCtx)
11650 {
11651         de::MovePtr<tcu::TestCaseGroup>         testGroup                               (new tcu::TestCaseGroup(testCtx, "opcompositeconstruct", "OpCompositeConstruct tests"));
11652         const deUint32                                          numElements                             = 8;
11653         const string                                            testName                                = "struct";
11654         const deUint32                                          structItemsCount                = 88;
11655         const deUint32                                          exceptionIndices[]              = { 1, 7, 15, 17, 25, 33, 51, 55, 59, 63, 67, 71, 84, 85, 86, 87 };
11656         const deFloat16                                         exceptionValue                  = tcu::Float16(-1.0).bits();
11657         const deUint32                                          fieldModifier                   = 2;
11658         const deUint32                                          fieldModifiedMulIndex   = 60;
11659         const deUint32                                          fieldModifiedAddIndex   = 66;
11660
11661         const StringTemplate preMain
11662         (
11663                 "    %c_i32_ndp = OpConstant %i32 ${num_elements}\n"
11664                 "          %f16 = OpTypeFloat 16\n"
11665                 "        %v2f16 = OpTypeVector %f16 2\n"
11666                 "        %v3f16 = OpTypeVector %f16 3\n"
11667                 "        %v4f16 = OpTypeVector %f16 4\n"
11668                 "    %c_f16_mod = OpConstant %f16 ${field_modifier}\n"
11669
11670                 "${consts}"
11671
11672                 "      %c_u32_5 = OpConstant %u32 5\n"
11673
11674                 " %f16arr3      = OpTypeArray %f16 %c_u32_3\n"
11675                 " %v2f16arr3    = OpTypeArray %v2f16 %c_u32_3\n"
11676                 " %v2f16arr5    = OpTypeArray %v2f16 %c_u32_5\n"
11677                 " %v3f16arr5    = OpTypeArray %v3f16 %c_u32_5\n"
11678                 " %v4f16arr3    = OpTypeArray %v4f16 %c_u32_3\n"
11679                 " %struct16     = OpTypeStruct %f16 %v2f16arr3\n"
11680                 " %struct16arr3 = OpTypeArray %struct16 %c_u32_3\n"
11681                 " %st_test      = OpTypeStruct %f16 %v2f16 %v3f16 %v4f16 %f16arr3 %struct16arr3 %v2f16arr5 %f16 %v3f16arr5 %v4f16arr3\n"
11682
11683                 "        %up_st = OpTypePointer Uniform %st_test\n"
11684                 "        %ra_st = OpTypeArray %st_test %c_i32_ndp\n"
11685                 "      %SSBO_st = OpTypeStruct %ra_st\n"
11686                 "   %up_SSBO_st = OpTypePointer Uniform %SSBO_st\n"
11687
11688                 "     %ssbo_dst = OpVariable %up_SSBO_st Uniform\n"
11689         );
11690
11691         const StringTemplate decoration
11692         (
11693                 "OpDecorate %SSBO_st BufferBlock\n"
11694                 "OpDecorate %ra_st ArrayStride ${struct_item_size}\n"
11695                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11696                 "OpDecorate %ssbo_dst Binding 1\n"
11697
11698                 "OpMemberDecorate %SSBO_st 0 Offset 0\n"
11699
11700                 "OpDecorate %v2f16arr3 ArrayStride 4\n"
11701                 "OpMemberDecorate %struct16 0 Offset 0\n"
11702                 "OpMemberDecorate %struct16 1 Offset 4\n"
11703                 "OpDecorate %struct16arr3 ArrayStride 16\n"
11704                 "OpDecorate %f16arr3 ArrayStride 2\n"
11705                 "OpDecorate %v2f16arr5 ArrayStride 4\n"
11706                 "OpDecorate %v3f16arr5 ArrayStride 8\n"
11707                 "OpDecorate %v4f16arr3 ArrayStride 8\n"
11708
11709                 "OpMemberDecorate %st_test 0 Offset 0\n"
11710                 "OpMemberDecorate %st_test 1 Offset 4\n"
11711                 "OpMemberDecorate %st_test 2 Offset 8\n"
11712                 "OpMemberDecorate %st_test 3 Offset 16\n"
11713                 "OpMemberDecorate %st_test 4 Offset 24\n"
11714                 "OpMemberDecorate %st_test 5 Offset 32\n"
11715                 "OpMemberDecorate %st_test 6 Offset 80\n"
11716                 "OpMemberDecorate %st_test 7 Offset 100\n"
11717                 "OpMemberDecorate %st_test 8 Offset 104\n"
11718                 "OpMemberDecorate %st_test 9 Offset 144\n"
11719         );
11720
11721         const StringTemplate testFun
11722         (
11723                 " %test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11724                 "     %param = OpFunctionParameter %v4f32\n"
11725                 "     %entry = OpLabel\n"
11726
11727                 "         %i = OpVariable %fp_i32 Function\n"
11728                 "              OpStore %i %c_i32_0\n"
11729
11730                 "  %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11731                 "              OpSelectionMerge %end_if None\n"
11732                 "              OpBranchConditional %will_run %run_test %end_if\n"
11733
11734                 "  %run_test = OpLabel\n"
11735                 "              OpBranch %loop\n"
11736
11737                 "      %loop = OpLabel\n"
11738                 "     %i_cmp = OpLoad %i32 %i\n"
11739                 "        %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11740                 "              OpLoopMerge %merge %next None\n"
11741                 "              OpBranchConditional %lt %write %merge\n"
11742
11743                 "     %write = OpLabel\n"
11744                 "       %ndx = OpLoad %i32 %i\n"
11745
11746                 "      %fld1 = OpCompositeConstruct %v2f16 %c_f16_2 %c_f16_3\n"
11747                 "      %fld2 = OpCompositeConstruct %v3f16 %c_f16_4 %c_f16_5 %c_f16_6\n"
11748                 "      %fld3 = OpCompositeConstruct %v4f16 %c_f16_8 %c_f16_9 %c_f16_10 %c_f16_11\n"
11749
11750                 "      %fld4 = OpCompositeConstruct %f16arr3 %c_f16_12 %c_f16_13 %c_f16_14\n"
11751
11752                 "%fld5_0_1_0 = OpCompositeConstruct %v2f16 %c_f16_18 %c_f16_19\n"
11753                 "%fld5_0_1_1 = OpCompositeConstruct %v2f16 %c_f16_20 %c_f16_21\n"
11754                 "%fld5_0_1_2 = OpCompositeConstruct %v2f16 %c_f16_22 %c_f16_23\n"
11755                 "  %fld5_0_1 = OpCompositeConstruct %v2f16arr3 %fld5_0_1_0 %fld5_0_1_1 %fld5_0_1_2\n"
11756                 "    %fld5_0 = OpCompositeConstruct %struct16 %c_f16_16 %fld5_0_1\n"
11757
11758                 "%fld5_1_1_0 = OpCompositeConstruct %v2f16 %c_f16_26 %c_f16_27\n"
11759                 "%fld5_1_1_1 = OpCompositeConstruct %v2f16 %c_f16_28 %c_f16_29\n"
11760                 "%fld5_1_1_2 = OpCompositeConstruct %v2f16 %c_f16_30 %c_f16_31\n"
11761                 "  %fld5_1_1 = OpCompositeConstruct %v2f16arr3 %fld5_1_1_0 %fld5_1_1_1 %fld5_1_1_2\n"
11762                 "    %fld5_1 = OpCompositeConstruct %struct16 %c_f16_24 %fld5_1_1\n"
11763
11764                 "%fld5_2_1_0 = OpCompositeConstruct %v2f16 %c_f16_34 %c_f16_35\n"
11765                 "%fld5_2_1_1 = OpCompositeConstruct %v2f16 %c_f16_36 %c_f16_37\n"
11766                 "%fld5_2_1_2 = OpCompositeConstruct %v2f16 %c_f16_38 %c_f16_39\n"
11767                 "  %fld5_2_1 = OpCompositeConstruct %v2f16arr3 %fld5_2_1_0 %fld5_2_1_1 %fld5_2_1_2\n"
11768                 "    %fld5_2 = OpCompositeConstruct %struct16 %c_f16_32 %fld5_2_1\n"
11769
11770                 "      %fld5 = OpCompositeConstruct %struct16arr3 %fld5_0 %fld5_1 %fld5_2\n"
11771
11772                 "    %fld6_0 = OpCompositeConstruct %v2f16 %c_f16_40 %c_f16_41\n"
11773                 "    %fld6_1 = OpCompositeConstruct %v2f16 %c_f16_42 %c_f16_43\n"
11774                 "    %fld6_2 = OpCompositeConstruct %v2f16 %c_f16_44 %c_f16_45\n"
11775                 "    %fld6_3 = OpCompositeConstruct %v2f16 %c_f16_46 %c_f16_47\n"
11776                 "    %fld6_4 = OpCompositeConstruct %v2f16 %c_f16_48 %c_f16_49\n"
11777                 "      %fld6 = OpCompositeConstruct %v2f16arr5 %fld6_0 %fld6_1 %fld6_2 %fld6_3 %fld6_4\n"
11778
11779                 "      %fndx = OpConvertSToF %f16 %ndx\n"
11780                 "  %fld8_2a0 = OpFMul %f16 %fndx %c_f16_mod\n"
11781                 "  %fld8_3b1 = OpFAdd %f16 %fndx %c_f16_mod\n"
11782
11783                 "   %fld8_2a = OpCompositeConstruct %v2f16 %fld8_2a0 %c_f16_61\n"
11784                 "   %fld8_3b = OpCompositeConstruct %v2f16 %c_f16_65 %fld8_3b1\n"
11785                 "    %fld8_0 = OpCompositeConstruct %v3f16 %c_f16_52 %c_f16_53 %c_f16_54\n"
11786                 "    %fld8_1 = OpCompositeConstruct %v3f16 %c_f16_56 %c_f16_57 %c_f16_58\n"
11787                 "    %fld8_2 = OpCompositeConstruct %v3f16 %fld8_2a %c_f16_62\n"
11788                 "    %fld8_3 = OpCompositeConstruct %v3f16 %c_f16_64 %fld8_3b\n"
11789                 "    %fld8_4 = OpCompositeConstruct %v3f16 %c_f16_68 %c_f16_69 %c_f16_70\n"
11790                 "      %fld8 = OpCompositeConstruct %v3f16arr5 %fld8_0 %fld8_1 %fld8_2 %fld8_3 %fld8_4\n"
11791
11792                 "    %fld9_0 = OpCompositeConstruct %v4f16 %c_f16_72 %c_f16_73 %c_f16_74 %c_f16_75\n"
11793                 "    %fld9_1 = OpCompositeConstruct %v4f16 %c_f16_76 %c_f16_77 %c_f16_78 %c_f16_79\n"
11794                 "    %fld9_2 = OpCompositeConstruct %v4f16 %c_f16_80 %c_f16_81 %c_f16_82 %c_f16_83\n"
11795                 "      %fld9 = OpCompositeConstruct %v4f16arr3 %fld9_0 %fld9_1 %fld9_2\n"
11796
11797                 "    %st_val = OpCompositeConstruct %st_test %c_f16_0 %fld1 %fld2 %fld3 %fld4 %fld5 %fld6 %c_f16_50 %fld8 %fld9\n"
11798                 "       %dst = OpAccessChain %up_st %ssbo_dst %c_i32_0 %ndx\n"
11799                 "              OpStore %dst %st_val\n"
11800
11801                 "              OpBranch %next\n"
11802
11803                 "      %next = OpLabel\n"
11804                 "     %i_cur = OpLoad %i32 %i\n"
11805                 "     %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11806                 "              OpStore %i %i_new\n"
11807                 "              OpBranch %loop\n"
11808
11809                 "     %merge = OpLabel\n"
11810                 "              OpBranch %end_if\n"
11811                 "    %end_if = OpLabel\n"
11812                 "              OpReturnValue %param\n"
11813                 "              OpFunctionEnd\n"
11814         );
11815
11816         {
11817                 SpecResource            specResource;
11818                 map<string, string>     specs;
11819                 VulkanFeatures          features;
11820                 map<string, string>     fragments;
11821                 vector<string>          extensions;
11822                 vector<deFloat16>       expectedOutput;
11823                 string                          consts;
11824
11825                 for (deUint32 elementNdx = 0; elementNdx < numElements; ++elementNdx)
11826                 {
11827                         vector<deFloat16>       expectedIterationOutput;
11828
11829                         for (deUint32 structItemNdx = 0; structItemNdx < structItemsCount; ++structItemNdx)
11830                                 expectedIterationOutput.push_back(tcu::Float16(float(structItemNdx)).bits());
11831
11832                         for (deUint32 structItemNdx = 0; structItemNdx < DE_LENGTH_OF_ARRAY(exceptionIndices); ++structItemNdx)
11833                                 expectedIterationOutput[exceptionIndices[structItemNdx]] = exceptionValue;
11834
11835                         expectedIterationOutput[fieldModifiedMulIndex] = tcu::Float16(float(elementNdx * fieldModifier)).bits();
11836                         expectedIterationOutput[fieldModifiedAddIndex] = tcu::Float16(float(elementNdx + fieldModifier)).bits();
11837
11838                         expectedOutput.insert(expectedOutput.end(), expectedIterationOutput.begin(), expectedIterationOutput.end());
11839                 }
11840
11841                 for (deUint32 i = 0; i < structItemsCount; ++i)
11842                         consts += "     %c_f16_" + de::toString(i) + " = OpConstant %f16 "  + de::toString(i) + "\n";
11843
11844                 specs["num_elements"]           = de::toString(numElements);
11845                 specs["struct_item_size"]       = de::toString(structItemsCount * sizeof(deFloat16));
11846                 specs["field_modifier"]         = de::toString(fieldModifier);
11847                 specs["consts"]                         = consts;
11848
11849                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11850                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
11851                 fragments["decoration"]         = decoration.specialize(specs);
11852                 fragments["pre_main"]           = preMain.specialize(specs);
11853                 fragments["testfun"]            = testFun.specialize(specs);
11854
11855                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(expectedOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11856                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(expectedOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11857                 specResource.verifyIO = compareFP16CompositeFunc;
11858
11859                 extensions.push_back("VK_KHR_16bit_storage");
11860                 extensions.push_back("VK_KHR_shader_float16_int8");
11861
11862                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11863                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11864
11865                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11866         }
11867
11868         return testGroup.release();
11869 }
11870
11871 template<class SpecResource>
11872 tcu::TestCaseGroup* createFloat16CompositeInsertExtractSet (tcu::TestContext& testCtx, const char* op)
11873 {
11874         de::MovePtr<tcu::TestCaseGroup>         testGroup               (new tcu::TestCaseGroup(testCtx, de::toLower(op).c_str(), op));
11875         const deFloat16                                         exceptionValue  = tcu::Float16(-1.0).bits();
11876         const string                                            opName                  (op);
11877         const deUint32                                          opIndex                 = (opName == "OpCompositeInsert") ? 0
11878                                                                                                                 : (opName == "OpCompositeExtract") ? 1
11879                                                                                                                 : -1;
11880
11881         const StringTemplate preMain
11882         (
11883                 "   %c_i32_ndp = OpConstant %i32 ${num_elements}\n"
11884                 "         %f16 = OpTypeFloat 16\n"
11885                 "       %v2f16 = OpTypeVector %f16 2\n"
11886                 "       %v3f16 = OpTypeVector %f16 3\n"
11887                 "       %v4f16 = OpTypeVector %f16 4\n"
11888                 "    %c_f16_na = OpConstant %f16 -1.0\n"
11889                 "     %c_u32_5 = OpConstant %u32 5\n"
11890
11891                 "%f16arr3      = OpTypeArray %f16 %c_u32_3\n"
11892                 "%v2f16arr3    = OpTypeArray %v2f16 %c_u32_3\n"
11893                 "%v2f16arr5    = OpTypeArray %v2f16 %c_u32_5\n"
11894                 "%v3f16arr5    = OpTypeArray %v3f16 %c_u32_5\n"
11895                 "%v4f16arr3    = OpTypeArray %v4f16 %c_u32_3\n"
11896                 "%struct16     = OpTypeStruct %f16 %v2f16arr3\n"
11897                 "%struct16arr3 = OpTypeArray %struct16 %c_u32_3\n"
11898                 "%st_test      = OpTypeStruct %${field_type}\n"
11899
11900                 "      %up_f16 = OpTypePointer Uniform %f16\n"
11901                 "       %up_st = OpTypePointer Uniform %st_test\n"
11902                 "      %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
11903                 "       %ra_st = OpTypeArray %st_test %c_i32_1\n"
11904
11905                 "${op_premain_decls}"
11906
11907                 " %up_SSBO_src = OpTypePointer Uniform %SSBO_src\n"
11908                 " %up_SSBO_dst = OpTypePointer Uniform %SSBO_dst\n"
11909
11910                 "    %ssbo_src = OpVariable %up_SSBO_src Uniform\n"
11911                 "    %ssbo_dst = OpVariable %up_SSBO_dst Uniform\n"
11912         );
11913
11914         const StringTemplate decoration
11915         (
11916                 "OpDecorate %SSBO_src BufferBlock\n"
11917                 "OpDecorate %SSBO_dst BufferBlock\n"
11918                 "OpDecorate %ra_f16 ArrayStride 2\n"
11919                 "OpDecorate %ra_st ArrayStride ${struct_item_size}\n"
11920                 "OpDecorate %ssbo_src DescriptorSet 0\n"
11921                 "OpDecorate %ssbo_src Binding 0\n"
11922                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11923                 "OpDecorate %ssbo_dst Binding 1\n"
11924
11925                 "OpMemberDecorate %SSBO_src 0 Offset 0\n"
11926                 "OpMemberDecorate %SSBO_dst 0 Offset 0\n"
11927
11928                 "OpDecorate %v2f16arr3 ArrayStride 4\n"
11929                 "OpMemberDecorate %struct16 0 Offset 0\n"
11930                 "OpMemberDecorate %struct16 1 Offset 4\n"
11931                 "OpDecorate %struct16arr3 ArrayStride 16\n"
11932                 "OpDecorate %f16arr3 ArrayStride 2\n"
11933                 "OpDecorate %v2f16arr5 ArrayStride 4\n"
11934                 "OpDecorate %v3f16arr5 ArrayStride 8\n"
11935                 "OpDecorate %v4f16arr3 ArrayStride 8\n"
11936
11937                 "OpMemberDecorate %st_test 0 Offset 0\n"
11938         );
11939
11940         const StringTemplate testFun
11941         (
11942                 " %test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11943                 "     %param = OpFunctionParameter %v4f32\n"
11944                 "     %entry = OpLabel\n"
11945
11946                 "         %i = OpVariable %fp_i32 Function\n"
11947                 "              OpStore %i %c_i32_0\n"
11948
11949                 "  %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11950                 "              OpSelectionMerge %end_if None\n"
11951                 "              OpBranchConditional %will_run %run_test %end_if\n"
11952
11953                 "  %run_test = OpLabel\n"
11954                 "              OpBranch %loop\n"
11955
11956                 "      %loop = OpLabel\n"
11957                 "     %i_cmp = OpLoad %i32 %i\n"
11958                 "        %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11959                 "              OpLoopMerge %merge %next None\n"
11960                 "              OpBranchConditional %lt %write %merge\n"
11961
11962                 "     %write = OpLabel\n"
11963                 "       %ndx = OpLoad %i32 %i\n"
11964
11965                 "${op_sw_fun_call}"
11966
11967                 "              OpStore %dst %val_dst\n"
11968                 "              OpBranch %next\n"
11969
11970                 "      %next = OpLabel\n"
11971                 "     %i_cur = OpLoad %i32 %i\n"
11972                 "     %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11973                 "              OpStore %i %i_new\n"
11974                 "              OpBranch %loop\n"
11975
11976                 "     %merge = OpLabel\n"
11977                 "              OpBranch %end_if\n"
11978                 "    %end_if = OpLabel\n"
11979                 "              OpReturnValue %param\n"
11980                 "              OpFunctionEnd\n"
11981
11982                 "${op_sw_fun_header}"
11983                 " %sw_param = OpFunctionParameter %st_test\n"
11984                 "%sw_paramn = OpFunctionParameter %i32\n"
11985                 " %sw_entry = OpLabel\n"
11986                 "             OpSelectionMerge %switch_e None\n"
11987                 "             OpSwitch %sw_paramn %default ${case_list}\n"
11988
11989                 "${case_bodies}"
11990
11991                 "%default   = OpLabel\n"
11992                 "             OpReturnValue ${op_case_default_value}\n"
11993                 "%switch_e  = OpLabel\n"
11994                 "             OpUnreachable\n" // Unreachable merge block for switch statement
11995                 "             OpFunctionEnd\n"
11996         );
11997
11998         const StringTemplate testCaseBody
11999         (
12000                 "%case_${case_ndx}    = OpLabel\n"
12001                 "%val_ret_${case_ndx} = ${op_name} ${op_args_part} ${access_path}\n"
12002                 "             OpReturnValue %val_ret_${case_ndx}\n"
12003         );
12004
12005         struct OpParts
12006         {
12007                 const char*     premainDecls;
12008                 const char*     swFunCall;
12009                 const char*     swFunHeader;
12010                 const char*     caseDefaultValue;
12011                 const char*     argsPartial;
12012         };
12013
12014         OpParts                                                         opPartsArray[]                  =
12015         {
12016                 // OpCompositeInsert
12017                 {
12018                         "       %fun_t = OpTypeFunction %st_test %f16 %st_test %i32\n"
12019                         "    %SSBO_src = OpTypeStruct %ra_f16\n"
12020                         "    %SSBO_dst = OpTypeStruct %ra_st\n",
12021
12022                         "       %src = OpAccessChain %up_f16 %ssbo_src %c_i32_0 %ndx\n"
12023                         "       %dst = OpAccessChain %up_st %ssbo_dst %c_i32_0 %c_i32_0\n"
12024                         "   %val_new = OpLoad %f16 %src\n"
12025                         "   %val_old = OpLoad %st_test %dst\n"
12026                         "   %val_dst = OpFunctionCall %st_test %sw_fun %val_new %val_old %ndx\n",
12027
12028                         "   %sw_fun = OpFunction %st_test None %fun_t\n"
12029                         "%sw_paramv = OpFunctionParameter %f16\n",
12030
12031                         "%sw_param",
12032
12033                         "%st_test %sw_paramv %sw_param",
12034                 },
12035                 // OpCompositeExtract
12036                 {
12037                         "       %fun_t = OpTypeFunction %f16 %st_test %i32\n"
12038                         "    %SSBO_src = OpTypeStruct %ra_st\n"
12039                         "    %SSBO_dst = OpTypeStruct %ra_f16\n",
12040
12041                         "       %src = OpAccessChain %up_st %ssbo_src %c_i32_0 %c_i32_0\n"
12042                         "       %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
12043                         "   %val_src = OpLoad %st_test %src\n"
12044                         "   %val_dst = OpFunctionCall %f16 %sw_fun %val_src %ndx\n",
12045
12046                         "   %sw_fun = OpFunction %f16 None %fun_t\n",
12047
12048                         "%c_f16_na",
12049
12050                         "%f16 %sw_param",
12051                 },
12052         };
12053
12054         DE_ASSERT(opIndex >= 0 && opIndex < DE_LENGTH_OF_ARRAY(opPartsArray));
12055
12056         const char*     accessPathF16[] =
12057         {
12058                 "0",                    // %f16
12059                 DE_NULL,
12060         };
12061         const char*     accessPathV2F16[] =
12062         {
12063                 "0 0",                  // %v2f16
12064                 "0 1",
12065         };
12066         const char*     accessPathV3F16[] =
12067         {
12068                 "0 0",                  // %v3f16
12069                 "0 1",
12070                 "0 2",
12071                 DE_NULL,
12072         };
12073         const char*     accessPathV4F16[] =
12074         {
12075                 "0 0",                  // %v4f16"
12076                 "0 1",
12077                 "0 2",
12078                 "0 3",
12079         };
12080         const char*     accessPathF16Arr3[] =
12081         {
12082                 "0 0",                  // %f16arr3
12083                 "0 1",
12084                 "0 2",
12085                 DE_NULL,
12086         };
12087         const char*     accessPathStruct16Arr3[] =
12088         {
12089                 "0 0 0",                // %struct16arr3
12090                 DE_NULL,
12091                 "0 0 1 0 0",
12092                 "0 0 1 0 1",
12093                 "0 0 1 1 0",
12094                 "0 0 1 1 1",
12095                 "0 0 1 2 0",
12096                 "0 0 1 2 1",
12097                 "0 1 0",
12098                 DE_NULL,
12099                 "0 1 1 0 0",
12100                 "0 1 1 0 1",
12101                 "0 1 1 1 0",
12102                 "0 1 1 1 1",
12103                 "0 1 1 2 0",
12104                 "0 1 1 2 1",
12105                 "0 2 0",
12106                 DE_NULL,
12107                 "0 2 1 0 0",
12108                 "0 2 1 0 1",
12109                 "0 2 1 1 0",
12110                 "0 2 1 1 1",
12111                 "0 2 1 2 0",
12112                 "0 2 1 2 1",
12113         };
12114         const char*     accessPathV2F16Arr5[] =
12115         {
12116                 "0 0 0",                // %v2f16arr5
12117                 "0 0 1",
12118                 "0 1 0",
12119                 "0 1 1",
12120                 "0 2 0",
12121                 "0 2 1",
12122                 "0 3 0",
12123                 "0 3 1",
12124                 "0 4 0",
12125                 "0 4 1",
12126         };
12127         const char*     accessPathV3F16Arr5[] =
12128         {
12129                 "0 0 0",                // %v3f16arr5
12130                 "0 0 1",
12131                 "0 0 2",
12132                 DE_NULL,
12133                 "0 1 0",
12134                 "0 1 1",
12135                 "0 1 2",
12136                 DE_NULL,
12137                 "0 2 0",
12138                 "0 2 1",
12139                 "0 2 2",
12140                 DE_NULL,
12141                 "0 3 0",
12142                 "0 3 1",
12143                 "0 3 2",
12144                 DE_NULL,
12145                 "0 4 0",
12146                 "0 4 1",
12147                 "0 4 2",
12148                 DE_NULL,
12149         };
12150         const char*     accessPathV4F16Arr3[] =
12151         {
12152                 "0 0 0",                // %v4f16arr3
12153                 "0 0 1",
12154                 "0 0 2",
12155                 "0 0 3",
12156                 "0 1 0",
12157                 "0 1 1",
12158                 "0 1 2",
12159                 "0 1 3",
12160                 "0 2 0",
12161                 "0 2 1",
12162                 "0 2 2",
12163                 "0 2 3",
12164                 DE_NULL,
12165                 DE_NULL,
12166                 DE_NULL,
12167                 DE_NULL,
12168         };
12169
12170         struct TypeTestParameters
12171         {
12172                 const char*             name;
12173                 size_t                  accessPathLength;
12174                 const char**    accessPath;
12175         };
12176
12177         const TypeTestParameters typeTestParameters[] =
12178         {
12179                 {       "f16",                  DE_LENGTH_OF_ARRAY(accessPathF16),                      accessPathF16                   },
12180                 {       "v2f16",                DE_LENGTH_OF_ARRAY(accessPathV2F16),            accessPathV2F16                 },
12181                 {       "v3f16",                DE_LENGTH_OF_ARRAY(accessPathV3F16),            accessPathV3F16                 },
12182                 {       "v4f16",                DE_LENGTH_OF_ARRAY(accessPathV4F16),            accessPathV4F16                 },
12183                 {       "f16arr3",              DE_LENGTH_OF_ARRAY(accessPathF16Arr3),          accessPathF16Arr3               },
12184                 {       "v2f16arr5",    DE_LENGTH_OF_ARRAY(accessPathV2F16Arr5),        accessPathV2F16Arr5             },
12185                 {       "v3f16arr5",    DE_LENGTH_OF_ARRAY(accessPathV3F16Arr5),        accessPathV3F16Arr5             },
12186                 {       "v4f16arr3",    DE_LENGTH_OF_ARRAY(accessPathV4F16Arr3),        accessPathV4F16Arr3             },
12187                 {       "struct16arr3", DE_LENGTH_OF_ARRAY(accessPathStruct16Arr3),     accessPathStruct16Arr3  },
12188         };
12189
12190         for (size_t typeTestNdx = 0; typeTestNdx < DE_LENGTH_OF_ARRAY(typeTestParameters); ++typeTestNdx)
12191         {
12192                 const OpParts           opParts                         = opPartsArray[opIndex];
12193                 const string            testName                        = typeTestParameters[typeTestNdx].name;
12194                 const size_t            structItemsCount        = typeTestParameters[typeTestNdx].accessPathLength;
12195                 const char**            accessPath                      = typeTestParameters[typeTestNdx].accessPath;
12196                 SpecResource            specResource;
12197                 map<string, string>     specs;
12198                 VulkanFeatures          features;
12199                 map<string, string>     fragments;
12200                 vector<string>          extensions;
12201                 vector<deFloat16>       inputFP16;
12202                 vector<deFloat16>       dummyFP16Output;
12203
12204                 // Generate values for input
12205                 inputFP16.reserve(structItemsCount);
12206                 for (deUint32 structItemNdx = 0; structItemNdx < structItemsCount; ++structItemNdx)
12207                         inputFP16.push_back((accessPath[structItemNdx] == DE_NULL) ? exceptionValue : tcu::Float16(float(structItemNdx)).bits());
12208
12209                 dummyFP16Output.resize(structItemsCount);
12210
12211                 // Generate cases for OpSwitch
12212                 {
12213                         string  caseBodies;
12214                         string  caseList;
12215
12216                         for (deUint32 caseNdx = 0; caseNdx < structItemsCount; ++caseNdx)
12217                                 if (accessPath[caseNdx] != DE_NULL)
12218                                 {
12219                                         map<string, string>     specCase;
12220
12221                                         specCase["case_ndx"]            = de::toString(caseNdx);
12222                                         specCase["access_path"]         = accessPath[caseNdx];
12223                                         specCase["op_args_part"]        = opParts.argsPartial;
12224                                         specCase["op_name"]                     = opName;
12225
12226                                         caseBodies      += testCaseBody.specialize(specCase);
12227                                         caseList        += de::toString(caseNdx) + " %case_" + de::toString(caseNdx) + " ";
12228                                 }
12229
12230                         specs["case_bodies"]    = caseBodies;
12231                         specs["case_list"]              = caseList;
12232                 }
12233
12234                 specs["num_elements"]                   = de::toString(structItemsCount);
12235                 specs["field_type"]                             = typeTestParameters[typeTestNdx].name;
12236                 specs["struct_item_size"]               = de::toString(structItemsCount * sizeof(deFloat16));
12237                 specs["op_premain_decls"]               = opParts.premainDecls;
12238                 specs["op_sw_fun_call"]                 = opParts.swFunCall;
12239                 specs["op_sw_fun_header"]               = opParts.swFunHeader;
12240                 specs["op_case_default_value"]  = opParts.caseDefaultValue;
12241
12242                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
12243                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
12244                 fragments["decoration"]         = decoration.specialize(specs);
12245                 fragments["pre_main"]           = preMain.specialize(specs);
12246                 fragments["testfun"]            = testFun.specialize(specs);
12247
12248                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(inputFP16)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
12249                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(dummyFP16Output)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
12250                 specResource.verifyIO = compareFP16CompositeFunc;
12251
12252                 extensions.push_back("VK_KHR_16bit_storage");
12253                 extensions.push_back("VK_KHR_shader_float16_int8");
12254
12255                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
12256                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
12257
12258                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
12259         }
12260
12261         return testGroup.release();
12262 }
12263
12264 struct fp16PerComponent
12265 {
12266         fp16PerComponent()
12267                 : flavor(0)
12268                 , floatFormat16 (-14, 15, 10, true)
12269                 , outCompCount(0)
12270                 , argCompCount(3, 0)
12271         {
12272         }
12273
12274         bool                    callOncePerComponent    ()                                                                      { return true; }
12275         deUint32                getComponentValidity    ()                                                                      { return static_cast<deUint32>(-1); }
12276
12277         virtual double  getULPs                                 (vector<const deFloat16*>&)                     { return 1.0; }
12278         virtual double  getMin                                  (double value, double ulps)                     { return value - floatFormat16.ulp(deAbs(value), ulps); }
12279         virtual double  getMax                                  (double value, double ulps)                     { return value + floatFormat16.ulp(deAbs(value), ulps); }
12280
12281         virtual size_t  getFlavorCount                  ()                                                                      { return flavorNames.empty() ? 1 : flavorNames.size(); }
12282         virtual void    setFlavor                               (size_t flavorNo)                                       { DE_ASSERT(flavorNo < getFlavorCount()); flavor = flavorNo; }
12283         virtual size_t  getFlavor                               ()                                                                      { return flavor; }
12284         virtual string  getCurrentFlavorName    ()                                                                      { return flavorNames.empty() ? string("") : flavorNames[getFlavor()]; }
12285
12286         virtual void    setOutCompCount                 (size_t compCount)                                      { outCompCount = compCount; }
12287         virtual size_t  getOutCompCount                 ()                                                                      { return outCompCount; }
12288
12289         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)        { argCompCount[argNo] = compCount; }
12290         virtual size_t  getArgCompCount                 (size_t argNo)                                          { return argCompCount[argNo]; }
12291
12292 protected:
12293         size_t                          flavor;
12294         tcu::FloatFormat        floatFormat16;
12295         size_t                          outCompCount;
12296         vector<size_t>          argCompCount;
12297         vector<string>          flavorNames;
12298 };
12299
12300 struct fp16OpFNegate : public fp16PerComponent
12301 {
12302         template <class fp16type>
12303         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12304         {
12305                 const fp16type  x               (*in[0]);
12306                 const double    d               (x.asDouble());
12307                 const double    result  (0.0 - d);
12308
12309                 out[0] = fp16type(result).bits();
12310                 min[0] = getMin(result, getULPs(in));
12311                 max[0] = getMax(result, getULPs(in));
12312
12313                 return true;
12314         }
12315 };
12316
12317 struct fp16Round : public fp16PerComponent
12318 {
12319         fp16Round() : fp16PerComponent()
12320         {
12321                 flavorNames.push_back("Floor(x+0.5)");
12322                 flavorNames.push_back("Floor(x-0.5)");
12323                 flavorNames.push_back("RoundEven");
12324         }
12325
12326         template<class fp16type>
12327         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12328         {
12329                 const fp16type  x               (*in[0]);
12330                 const double    d               (x.asDouble());
12331                 double                  result  (0.0);
12332
12333                 switch (flavor)
12334                 {
12335                         case 0:         result = deRound(d);            break;
12336                         case 1:         result = deFloor(d - 0.5);      break;
12337                         case 2:         result = deRoundEven(d);        break;
12338                         default:        TCU_THROW(InternalError, "Invalid flavor specified");
12339                 }
12340
12341                 out[0] = fp16type(result).bits();
12342                 min[0] = getMin(result, getULPs(in));
12343                 max[0] = getMax(result, getULPs(in));
12344
12345                 return true;
12346         }
12347 };
12348
12349 struct fp16RoundEven : public fp16PerComponent
12350 {
12351         template<class fp16type>
12352         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12353         {
12354                 const fp16type  x               (*in[0]);
12355                 const double    d               (x.asDouble());
12356                 const double    result  (deRoundEven(d));
12357
12358                 out[0] = fp16type(result).bits();
12359                 min[0] = getMin(result, getULPs(in));
12360                 max[0] = getMax(result, getULPs(in));
12361
12362                 return true;
12363         }
12364 };
12365
12366 struct fp16Trunc : public fp16PerComponent
12367 {
12368         template<class fp16type>
12369         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12370         {
12371                 const fp16type  x               (*in[0]);
12372                 const double    d               (x.asDouble());
12373                 const double    result  (deTrunc(d));
12374
12375                 out[0] = fp16type(result).bits();
12376                 min[0] = getMin(result, getULPs(in));
12377                 max[0] = getMax(result, getULPs(in));
12378
12379                 return true;
12380         }
12381 };
12382
12383 struct fp16FAbs : public fp16PerComponent
12384 {
12385         template<class fp16type>
12386         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12387         {
12388                 const fp16type  x               (*in[0]);
12389                 const double    d               (x.asDouble());
12390                 const double    result  (deAbs(d));
12391
12392                 out[0] = fp16type(result).bits();
12393                 min[0] = getMin(result, getULPs(in));
12394                 max[0] = getMax(result, getULPs(in));
12395
12396                 return true;
12397         }
12398 };
12399
12400 struct fp16FSign : public fp16PerComponent
12401 {
12402         template<class fp16type>
12403         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12404         {
12405                 const fp16type  x               (*in[0]);
12406                 const double    d               (x.asDouble());
12407                 const double    result  (deSign(d));
12408
12409                 if (x.isNaN())
12410                         return false;
12411
12412                 out[0] = fp16type(result).bits();
12413                 min[0] = getMin(result, getULPs(in));
12414                 max[0] = getMax(result, getULPs(in));
12415
12416                 return true;
12417         }
12418 };
12419
12420 struct fp16Floor : public fp16PerComponent
12421 {
12422         template<class fp16type>
12423         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12424         {
12425                 const fp16type  x               (*in[0]);
12426                 const double    d               (x.asDouble());
12427                 const double    result  (deFloor(d));
12428
12429                 out[0] = fp16type(result).bits();
12430                 min[0] = getMin(result, getULPs(in));
12431                 max[0] = getMax(result, getULPs(in));
12432
12433                 return true;
12434         }
12435 };
12436
12437 struct fp16Ceil : public fp16PerComponent
12438 {
12439         template<class fp16type>
12440         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12441         {
12442                 const fp16type  x               (*in[0]);
12443                 const double    d               (x.asDouble());
12444                 const double    result  (deCeil(d));
12445
12446                 out[0] = fp16type(result).bits();
12447                 min[0] = getMin(result, getULPs(in));
12448                 max[0] = getMax(result, getULPs(in));
12449
12450                 return true;
12451         }
12452 };
12453
12454 struct fp16Fract : public fp16PerComponent
12455 {
12456         template<class fp16type>
12457         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12458         {
12459                 const fp16type  x               (*in[0]);
12460                 const double    d               (x.asDouble());
12461                 const double    result  (deFrac(d));
12462
12463                 out[0] = fp16type(result).bits();
12464                 min[0] = getMin(result, getULPs(in));
12465                 max[0] = getMax(result, getULPs(in));
12466
12467                 return true;
12468         }
12469 };
12470
12471 struct fp16Radians : public fp16PerComponent
12472 {
12473         virtual double getULPs (vector<const deFloat16*>& in)
12474         {
12475                 DE_UNREF(in);
12476
12477                 return 2.5;
12478         }
12479
12480         template<class fp16type>
12481         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12482         {
12483                 const fp16type  x               (*in[0]);
12484                 const float             d               (x.asFloat());
12485                 const float             result  (deFloatRadians(d));
12486
12487                 out[0] = fp16type(result).bits();
12488                 min[0] = getMin(result, getULPs(in));
12489                 max[0] = getMax(result, getULPs(in));
12490
12491                 return true;
12492         }
12493 };
12494
12495 struct fp16Degrees : public fp16PerComponent
12496 {
12497         virtual double getULPs (vector<const deFloat16*>& in)
12498         {
12499                 DE_UNREF(in);
12500
12501                 return 2.5;
12502         }
12503
12504         template<class fp16type>
12505         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12506         {
12507                 const fp16type  x               (*in[0]);
12508                 const float             d               (x.asFloat());
12509                 const float             result  (deFloatDegrees(d));
12510
12511                 out[0] = fp16type(result).bits();
12512                 min[0] = getMin(result, getULPs(in));
12513                 max[0] = getMax(result, getULPs(in));
12514
12515                 return true;
12516         }
12517 };
12518
12519 struct fp16Sin : public fp16PerComponent
12520 {
12521         template<class fp16type>
12522         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12523         {
12524                 const fp16type  x                       (*in[0]);
12525                 const double    d                       (x.asDouble());
12526                 const double    result          (deSin(d));
12527                 const double    unspecUlp       (16.0);
12528                 const double    err                     (de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE) ? deLdExp(1.0, -7) : floatFormat16.ulp(deAbs(result), unspecUlp));
12529
12530                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12531                         return false;
12532
12533                 out[0] = fp16type(result).bits();
12534                 min[0] = result - err;
12535                 max[0] = result + err;
12536
12537                 return true;
12538         }
12539 };
12540
12541 struct fp16Cos : public fp16PerComponent
12542 {
12543         template<class fp16type>
12544         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12545         {
12546                 const fp16type  x                       (*in[0]);
12547                 const double    d                       (x.asDouble());
12548                 const double    result          (deCos(d));
12549                 const double    unspecUlp       (16.0);
12550                 const double    err                     (de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE) ? deLdExp(1.0, -7) : floatFormat16.ulp(deAbs(result), unspecUlp));
12551
12552                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12553                         return false;
12554
12555                 out[0] = fp16type(result).bits();
12556                 min[0] = result - err;
12557                 max[0] = result + err;
12558
12559                 return true;
12560         }
12561 };
12562
12563 struct fp16Tan : public fp16PerComponent
12564 {
12565         template<class fp16type>
12566         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12567         {
12568                 const fp16type  x               (*in[0]);
12569                 const double    d               (x.asDouble());
12570                 const double    result  (deTan(d));
12571
12572                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12573                         return false;
12574
12575                 out[0] = fp16type(result).bits();
12576                 {
12577                         const double    err                     = deLdExp(1.0, -7);
12578                         const double    s1                      = deSin(d) + err;
12579                         const double    s2                      = deSin(d) - err;
12580                         const double    c1                      = deCos(d) + err;
12581                         const double    c2                      = deCos(d) - err;
12582                         const double    edgeVals[]      = {s1/c1, s1/c2, s2/c1, s2/c2};
12583                         double                  edgeLeft        = out[0];
12584                         double                  edgeRight       = out[0];
12585
12586                         if (deSign(c1 * c2) < 0.0)
12587                         {
12588                                 edgeLeft        = -std::numeric_limits<double>::infinity();
12589                                 edgeRight       = +std::numeric_limits<double>::infinity();
12590                         }
12591                         else
12592                         {
12593                                 edgeLeft        = *std::min_element(&edgeVals[0], &edgeVals[DE_LENGTH_OF_ARRAY(edgeVals)]);
12594                                 edgeRight       = *std::max_element(&edgeVals[0], &edgeVals[DE_LENGTH_OF_ARRAY(edgeVals)]);
12595                         }
12596
12597                         min[0] = edgeLeft;
12598                         max[0] = edgeRight;
12599                 }
12600
12601                 return true;
12602         }
12603 };
12604
12605 struct fp16Asin : public fp16PerComponent
12606 {
12607         template<class fp16type>
12608         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12609         {
12610                 const fp16type  x               (*in[0]);
12611                 const double    d               (x.asDouble());
12612                 const double    result  (deAsin(d));
12613                 const double    error   (deAtan2(d, sqrt(1.0 - d * d)));
12614
12615                 if (!x.isNaN() && deAbs(d) > 1.0)
12616                         return false;
12617
12618                 out[0] = fp16type(result).bits();
12619                 min[0] = result - floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12620                 max[0] = result + floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12621
12622                 return true;
12623         }
12624 };
12625
12626 struct fp16Acos : public fp16PerComponent
12627 {
12628         template<class fp16type>
12629         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12630         {
12631                 const fp16type  x               (*in[0]);
12632                 const double    d               (x.asDouble());
12633                 const double    result  (deAcos(d));
12634                 const double    error   (deAtan2(sqrt(1.0 - d * d), d));
12635
12636                 if (!x.isNaN() && deAbs(d) > 1.0)
12637                         return false;
12638
12639                 out[0] = fp16type(result).bits();
12640                 min[0] = result - floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12641                 max[0] = result + floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12642
12643                 return true;
12644         }
12645 };
12646
12647 struct fp16Atan : public fp16PerComponent
12648 {
12649         virtual double getULPs(vector<const deFloat16*>& in)
12650         {
12651                 DE_UNREF(in);
12652
12653                 return 2 * 5.0; // This is not a precision test. Value is not from spec
12654         }
12655
12656         template<class fp16type>
12657         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12658         {
12659                 const fp16type  x               (*in[0]);
12660                 const double    d               (x.asDouble());
12661                 const double    result  (deAtanOver(d));
12662
12663                 out[0] = fp16type(result).bits();
12664                 min[0] = getMin(result, getULPs(in));
12665                 max[0] = getMax(result, getULPs(in));
12666
12667                 return true;
12668         }
12669 };
12670
12671 struct fp16Sinh : public fp16PerComponent
12672 {
12673         fp16Sinh() : fp16PerComponent()
12674         {
12675                 flavorNames.push_back("Double");
12676                 flavorNames.push_back("ExpFP16");
12677         }
12678
12679         template<class fp16type>
12680         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12681         {
12682                 const fp16type  x               (*in[0]);
12683                 const double    d               (x.asDouble());
12684                 const double    ulps    (64 * (1.0 + 2 * deAbs(d))); // This is not a precision test. Value is not from spec
12685                 double                  result  (0.0);
12686                 double                  error   (0.0);
12687
12688                 if (getFlavor() == 0)
12689                 {
12690                         result  = deSinh(d);
12691                         error   = floatFormat16.ulp(deAbs(result), ulps);
12692                 }
12693                 else if (getFlavor() == 1)
12694                 {
12695                         const fp16type  epx     (deExp(d));
12696                         const fp16type  enx     (deExp(-d));
12697                         const fp16type  esx     (epx.asDouble() - enx.asDouble());
12698                         const fp16type  sx2     (esx.asDouble() / 2.0);
12699
12700                         result  = sx2.asDouble();
12701                         error   = deAbs(floatFormat16.ulp(epx.asDouble(), ulps)) + deAbs(floatFormat16.ulp(enx.asDouble(), ulps));
12702                 }
12703                 else
12704                 {
12705                         TCU_THROW(InternalError, "Unknown flavor");
12706                 }
12707
12708                 out[0] = fp16type(result).bits();
12709                 min[0] = result - error;
12710                 max[0] = result + error;
12711
12712                 return true;
12713         }
12714 };
12715
12716 struct fp16Cosh : public fp16PerComponent
12717 {
12718         fp16Cosh() : fp16PerComponent()
12719         {
12720                 flavorNames.push_back("Double");
12721                 flavorNames.push_back("ExpFP16");
12722         }
12723
12724         template<class fp16type>
12725         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12726         {
12727                 const fp16type  x               (*in[0]);
12728                 const double    d               (x.asDouble());
12729                 const double    ulps    (64 * (1.0 + 2 * deAbs(d))); // This is not a precision test. Value is not from spec
12730                 double                  result  (0.0);
12731
12732                 if (getFlavor() == 0)
12733                 {
12734                         result = deCosh(d);
12735                 }
12736                 else if (getFlavor() == 1)
12737                 {
12738                         const fp16type  epx     (deExp(d));
12739                         const fp16type  enx     (deExp(-d));
12740                         const fp16type  esx     (epx.asDouble() + enx.asDouble());
12741                         const fp16type  sx2     (esx.asDouble() / 2.0);
12742
12743                         result = sx2.asDouble();
12744                 }
12745                 else
12746                 {
12747                         TCU_THROW(InternalError, "Unknown flavor");
12748                 }
12749
12750                 out[0] = fp16type(result).bits();
12751                 min[0] = result - floatFormat16.ulp(deAbs(result), ulps);
12752                 max[0] = result + floatFormat16.ulp(deAbs(result), ulps);
12753
12754                 return true;
12755         }
12756 };
12757
12758 struct fp16Tanh : public fp16PerComponent
12759 {
12760         fp16Tanh() : fp16PerComponent()
12761         {
12762                 flavorNames.push_back("Tanh");
12763                 flavorNames.push_back("SinhCosh");
12764                 flavorNames.push_back("SinhCoshFP16");
12765                 flavorNames.push_back("PolyFP16");
12766         }
12767
12768         virtual double getULPs (vector<const deFloat16*>& in)
12769         {
12770                 const tcu::Float16      x       (*in[0]);
12771                 const double            d       (x.asDouble());
12772
12773                 return 2 * (1.0 + 2 * deAbs(d)); // This is not a precision test. Value is not from spec
12774         }
12775
12776         template<class fp16type>
12777         inline double calcPoly (const fp16type& espx, const fp16type& esnx, const fp16type& ecpx, const fp16type& ecnx)
12778         {
12779                 const fp16type  esx     (espx.asDouble() - esnx.asDouble());
12780                 const fp16type  sx2     (esx.asDouble() / 2.0);
12781                 const fp16type  ecx     (ecpx.asDouble() + ecnx.asDouble());
12782                 const fp16type  cx2     (ecx.asDouble() / 2.0);
12783                 const fp16type  tg      (sx2.asDouble() / cx2.asDouble());
12784                 const double    rez     (tg.asDouble());
12785
12786                 return rez;
12787         }
12788
12789         template<class fp16type>
12790         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12791         {
12792                 const fp16type  x               (*in[0]);
12793                 const double    d               (x.asDouble());
12794                 double                  result  (0.0);
12795
12796                 if (getFlavor() == 0)
12797                 {
12798                         result  = deTanh(d);
12799                         min[0]  = getMin(result, getULPs(in));
12800                         max[0]  = getMax(result, getULPs(in));
12801                 }
12802                 else if (getFlavor() == 1)
12803                 {
12804                         result  = deSinh(d) / deCosh(d);
12805                         min[0]  = getMin(result, getULPs(in));
12806                         max[0]  = getMax(result, getULPs(in));
12807                 }
12808                 else if (getFlavor() == 2)
12809                 {
12810                         const fp16type  s       (deSinh(d));
12811                         const fp16type  c       (deCosh(d));
12812
12813                         result  = s.asDouble() / c.asDouble();
12814                         min[0]  = getMin(result, getULPs(in));
12815                         max[0]  = getMax(result, getULPs(in));
12816                 }
12817                 else if (getFlavor() == 3)
12818                 {
12819                         const double    ulps    (getULPs(in));
12820                         const double    epxm    (deExp( d));
12821                         const double    enxm    (deExp(-d));
12822                         const double    epxmerr = floatFormat16.ulp(epxm, ulps);
12823                         const double    enxmerr = floatFormat16.ulp(enxm, ulps);
12824                         const fp16type  epx[]   = { fp16type(epxm - epxmerr), fp16type(epxm + epxmerr) };
12825                         const fp16type  enx[]   = { fp16type(enxm - enxmerr), fp16type(enxm + enxmerr) };
12826                         const fp16type  epxm16  (epxm);
12827                         const fp16type  enxm16  (enxm);
12828                         vector<double>  tgs;
12829
12830                         for (size_t spNdx = 0; spNdx < DE_LENGTH_OF_ARRAY(epx); ++spNdx)
12831                         for (size_t snNdx = 0; snNdx < DE_LENGTH_OF_ARRAY(enx); ++snNdx)
12832                         for (size_t cpNdx = 0; cpNdx < DE_LENGTH_OF_ARRAY(epx); ++cpNdx)
12833                         for (size_t cnNdx = 0; cnNdx < DE_LENGTH_OF_ARRAY(enx); ++cnNdx)
12834                         {
12835                                 const double tgh = calcPoly(epx[spNdx], enx[snNdx], epx[cpNdx], enx[cnNdx]);
12836
12837                                 tgs.push_back(tgh);
12838                         }
12839
12840                         result = calcPoly(epxm16, enxm16, epxm16, enxm16);
12841                         min[0] = *std::min_element(tgs.begin(), tgs.end());
12842                         max[0] = *std::max_element(tgs.begin(), tgs.end());
12843                 }
12844                 else
12845                 {
12846                         TCU_THROW(InternalError, "Unknown flavor");
12847                 }
12848
12849                 out[0] = fp16type(result).bits();
12850
12851                 return true;
12852         }
12853 };
12854
12855 struct fp16Asinh : public fp16PerComponent
12856 {
12857         fp16Asinh() : fp16PerComponent()
12858         {
12859                 flavorNames.push_back("Double");
12860                 flavorNames.push_back("PolyFP16Wiki");
12861                 flavorNames.push_back("PolyFP16Abs");
12862         }
12863
12864         virtual double getULPs (vector<const deFloat16*>& in)
12865         {
12866                 DE_UNREF(in);
12867
12868                 return 256.0; // This is not a precision test. Value is not from spec
12869         }
12870
12871         template<class fp16type>
12872         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12873         {
12874                 const fp16type  x               (*in[0]);
12875                 const double    d               (x.asDouble());
12876                 double                  result  (0.0);
12877
12878                 if (getFlavor() == 0)
12879                 {
12880                         result = deAsinh(d);
12881                 }
12882                 else if (getFlavor() == 1)
12883                 {
12884                         const fp16type  x2              (d * d);
12885                         const fp16type  x2p1    (x2.asDouble() + 1.0);
12886                         const fp16type  sq              (deSqrt(x2p1.asDouble()));
12887                         const fp16type  sxsq    (d + sq.asDouble());
12888                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
12889
12890                         if (lsxsq.isInf())
12891                                 return false;
12892
12893                         result = lsxsq.asDouble();
12894                 }
12895                 else if (getFlavor() == 2)
12896                 {
12897                         const fp16type  x2              (d * d);
12898                         const fp16type  x2p1    (x2.asDouble() + 1.0);
12899                         const fp16type  sq              (deSqrt(x2p1.asDouble()));
12900                         const fp16type  sxsq    (deAbs(d) + sq.asDouble());
12901                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
12902
12903                         result = deSign(d) * lsxsq.asDouble();
12904                 }
12905                 else
12906                 {
12907                         TCU_THROW(InternalError, "Unknown flavor");
12908                 }
12909
12910                 out[0] = fp16type(result).bits();
12911                 min[0] = getMin(result, getULPs(in));
12912                 max[0] = getMax(result, getULPs(in));
12913
12914                 return true;
12915         }
12916 };
12917
12918 struct fp16Acosh : public fp16PerComponent
12919 {
12920         fp16Acosh() : fp16PerComponent()
12921         {
12922                 flavorNames.push_back("Double");
12923                 flavorNames.push_back("PolyFP16");
12924         }
12925
12926         virtual double getULPs (vector<const deFloat16*>& in)
12927         {
12928                 DE_UNREF(in);
12929
12930                 return 16.0; // This is not a precision test. Value is not from spec
12931         }
12932
12933         template<class fp16type>
12934         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12935         {
12936                 const fp16type  x               (*in[0]);
12937                 const double    d               (x.asDouble());
12938                 double                  result  (0.0);
12939
12940                 if (!x.isNaN() && d < 1.0)
12941                         return false;
12942
12943                 if (getFlavor() == 0)
12944                 {
12945                         result = deAcosh(d);
12946                 }
12947                 else if (getFlavor() == 1)
12948                 {
12949                         const fp16type  x2              (d * d);
12950                         const fp16type  x2m1    (x2.asDouble() - 1.0);
12951                         const fp16type  sq              (deSqrt(x2m1.asDouble()));
12952                         const fp16type  sxsq    (d + sq.asDouble());
12953                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
12954
12955                         result = lsxsq.asDouble();
12956                 }
12957                 else
12958                 {
12959                         TCU_THROW(InternalError, "Unknown flavor");
12960                 }
12961
12962                 out[0] = fp16type(result).bits();
12963                 min[0] = getMin(result, getULPs(in));
12964                 max[0] = getMax(result, getULPs(in));
12965
12966                 return true;
12967         }
12968 };
12969
12970 struct fp16Atanh : public fp16PerComponent
12971 {
12972         fp16Atanh() : fp16PerComponent()
12973         {
12974                 flavorNames.push_back("Double");
12975                 flavorNames.push_back("PolyFP16");
12976         }
12977
12978         template<class fp16type>
12979         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12980         {
12981                 const fp16type  x               (*in[0]);
12982                 const double    d               (x.asDouble());
12983                 double                  result  (0.0);
12984
12985                 if (deAbs(d) >= 1.0)
12986                         return false;
12987
12988                 if (getFlavor() == 0)
12989                 {
12990                         const double    ulps    (16.0); // This is not a precision test. Value is not from spec
12991
12992                         result = deAtanh(d);
12993                         min[0] = getMin(result, ulps);
12994                         max[0] = getMax(result, ulps);
12995                 }
12996                 else if (getFlavor() == 1)
12997                 {
12998                         const fp16type  x1a             (1.0 + d);
12999                         const fp16type  x1b             (1.0 - d);
13000                         const fp16type  x1d             (x1a.asDouble() / x1b.asDouble());
13001                         const fp16type  lx1d    (deLog(x1d.asDouble()));
13002                         const fp16type  lx1d2   (0.5 * lx1d.asDouble());
13003                         const double    error   (2 * (de::inRange(deAbs(x1d.asDouble()), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(x1d.asDouble()), 3.0)));
13004
13005                         result = lx1d2.asDouble();
13006                         min[0] = result - error;
13007                         max[0] = result + error;
13008                 }
13009                 else
13010                 {
13011                         TCU_THROW(InternalError, "Unknown flavor");
13012                 }
13013
13014                 out[0] = fp16type(result).bits();
13015
13016                 return true;
13017         }
13018 };
13019
13020 struct fp16Exp : public fp16PerComponent
13021 {
13022         template<class fp16type>
13023         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13024         {
13025                 const fp16type  x               (*in[0]);
13026                 const double    d               (x.asDouble());
13027                 const double    ulps    (10.0 * (1.0 + 2.0 * deAbs(d)));
13028                 const double    result  (deExp(d));
13029
13030                 out[0] = fp16type(result).bits();
13031                 min[0] = getMin(result, ulps);
13032                 max[0] = getMax(result, ulps);
13033
13034                 return true;
13035         }
13036 };
13037
13038 struct fp16Log : public fp16PerComponent
13039 {
13040         template<class fp16type>
13041         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13042         {
13043                 const fp16type  x               (*in[0]);
13044                 const double    d               (x.asDouble());
13045                 const double    result  (deLog(d));
13046                 const double    error   (de::inRange(deAbs(d), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(result), 3.0));
13047
13048                 if (d <= 0.0)
13049                         return false;
13050
13051                 out[0] = fp16type(result).bits();
13052                 min[0] = result - error;
13053                 max[0] = result + error;
13054
13055                 return true;
13056         }
13057 };
13058
13059 struct fp16Exp2 : public fp16PerComponent
13060 {
13061         template<class fp16type>
13062         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13063         {
13064                 const fp16type  x               (*in[0]);
13065                 const double    d               (x.asDouble());
13066                 const double    result  (deExp2(d));
13067                 const double    ulps    (1.0 + 2.0 * deAbs(fp16type(in[0][0]).asDouble()));
13068
13069                 out[0] = fp16type(result).bits();
13070                 min[0] = getMin(result, ulps);
13071                 max[0] = getMax(result, ulps);
13072
13073                 return true;
13074         }
13075 };
13076
13077 struct fp16Log2 : public fp16PerComponent
13078 {
13079         template<class fp16type>
13080         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13081         {
13082                 const fp16type  x               (*in[0]);
13083                 const double    d               (x.asDouble());
13084                 const double    result  (deLog2(d));
13085                 const double    error   (de::inRange(deAbs(d), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(result), 3.0));
13086
13087                 if (d <= 0.0)
13088                         return false;
13089
13090                 out[0] = fp16type(result).bits();
13091                 min[0] = result - error;
13092                 max[0] = result + error;
13093
13094                 return true;
13095         }
13096 };
13097
13098 struct fp16Sqrt : public fp16PerComponent
13099 {
13100         virtual double getULPs (vector<const deFloat16*>& in)
13101         {
13102                 DE_UNREF(in);
13103
13104                 return 6.0;
13105         }
13106
13107         template<class fp16type>
13108         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13109         {
13110                 const fp16type  x               (*in[0]);
13111                 const double    d               (x.asDouble());
13112                 const double    result  (deSqrt(d));
13113
13114                 if (!x.isNaN() && d < 0.0)
13115                         return false;
13116
13117                 out[0] = fp16type(result).bits();
13118                 min[0] = getMin(result, getULPs(in));
13119                 max[0] = getMax(result, getULPs(in));
13120
13121                 return true;
13122         }
13123 };
13124
13125 struct fp16InverseSqrt : public fp16PerComponent
13126 {
13127         virtual double getULPs (vector<const deFloat16*>& in)
13128         {
13129                 DE_UNREF(in);
13130
13131                 return 2.0;
13132         }
13133
13134         template<class fp16type>
13135         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13136         {
13137                 const fp16type  x               (*in[0]);
13138                 const double    d               (x.asDouble());
13139                 const double    result  (1.0/deSqrt(d));
13140
13141                 if (!x.isNaN() && d <= 0.0)
13142                         return false;
13143
13144                 out[0] = fp16type(result).bits();
13145                 min[0] = getMin(result, getULPs(in));
13146                 max[0] = getMax(result, getULPs(in));
13147
13148                 return true;
13149         }
13150 };
13151
13152 struct fp16ModfFrac : public fp16PerComponent
13153 {
13154         template<class fp16type>
13155         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13156         {
13157                 const fp16type  x               (*in[0]);
13158                 const double    d               (x.asDouble());
13159                 double                  i               (0.0);
13160                 const double    result  (deModf(d, &i));
13161
13162                 if (x.isInf() || x.isNaN())
13163                         return false;
13164
13165                 out[0] = fp16type(result).bits();
13166                 min[0] = getMin(result, getULPs(in));
13167                 max[0] = getMax(result, getULPs(in));
13168
13169                 return true;
13170         }
13171 };
13172
13173 struct fp16ModfInt : public fp16PerComponent
13174 {
13175         template<class fp16type>
13176         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13177         {
13178                 const fp16type  x               (*in[0]);
13179                 const double    d               (x.asDouble());
13180                 double                  i               (0.0);
13181                 const double    dummy   (deModf(d, &i));
13182                 const double    result  (i);
13183
13184                 DE_UNREF(dummy);
13185
13186                 if (x.isInf() || x.isNaN())
13187                         return false;
13188
13189                 out[0] = fp16type(result).bits();
13190                 min[0] = getMin(result, getULPs(in));
13191                 max[0] = getMax(result, getULPs(in));
13192
13193                 return true;
13194         }
13195 };
13196
13197 struct fp16FrexpS : public fp16PerComponent
13198 {
13199         template<class fp16type>
13200         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13201         {
13202                 const fp16type  x               (*in[0]);
13203                 const double    d               (x.asDouble());
13204                 int                             e               (0);
13205                 const double    result  (deFrExp(d, &e));
13206
13207                 if (x.isNaN() || x.isInf())
13208                         return false;
13209
13210                 out[0] = fp16type(result).bits();
13211                 min[0] = getMin(result, getULPs(in));
13212                 max[0] = getMax(result, getULPs(in));
13213
13214                 return true;
13215         }
13216 };
13217
13218 struct fp16FrexpE : public fp16PerComponent
13219 {
13220         template<class fp16type>
13221         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13222         {
13223                 const fp16type  x               (*in[0]);
13224                 const double    d               (x.asDouble());
13225                 int                             e               (0);
13226                 const double    dummy   (deFrExp(d, &e));
13227                 const double    result  (static_cast<double>(e));
13228
13229                 DE_UNREF(dummy);
13230
13231                 if (x.isNaN() || x.isInf())
13232                         return false;
13233
13234                 out[0] = fp16type(result).bits();
13235                 min[0] = getMin(result, getULPs(in));
13236                 max[0] = getMax(result, getULPs(in));
13237
13238                 return true;
13239         }
13240 };
13241
13242 struct fp16OpFAdd : public fp16PerComponent
13243 {
13244         template<class fp16type>
13245         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13246         {
13247                 const fp16type  x               (*in[0]);
13248                 const fp16type  y               (*in[1]);
13249                 const double    xd              (x.asDouble());
13250                 const double    yd              (y.asDouble());
13251                 const double    result  (xd + yd);
13252
13253                 out[0] = fp16type(result).bits();
13254                 min[0] = getMin(result, getULPs(in));
13255                 max[0] = getMax(result, getULPs(in));
13256
13257                 return true;
13258         }
13259 };
13260
13261 struct fp16OpFSub : public fp16PerComponent
13262 {
13263         template<class fp16type>
13264         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13265         {
13266                 const fp16type  x               (*in[0]);
13267                 const fp16type  y               (*in[1]);
13268                 const double    xd              (x.asDouble());
13269                 const double    yd              (y.asDouble());
13270                 const double    result  (xd - yd);
13271
13272                 out[0] = fp16type(result).bits();
13273                 min[0] = getMin(result, getULPs(in));
13274                 max[0] = getMax(result, getULPs(in));
13275
13276                 return true;
13277         }
13278 };
13279
13280 struct fp16OpFMul : public fp16PerComponent
13281 {
13282         template<class fp16type>
13283         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13284         {
13285                 const fp16type  x               (*in[0]);
13286                 const fp16type  y               (*in[1]);
13287                 const double    xd              (x.asDouble());
13288                 const double    yd              (y.asDouble());
13289                 const double    result  (xd * yd);
13290
13291                 out[0] = fp16type(result).bits();
13292                 min[0] = getMin(result, getULPs(in));
13293                 max[0] = getMax(result, getULPs(in));
13294
13295                 return true;
13296         }
13297 };
13298
13299 struct fp16OpFDiv : public fp16PerComponent
13300 {
13301         fp16OpFDiv() : fp16PerComponent()
13302         {
13303                 flavorNames.push_back("DirectDiv");
13304                 flavorNames.push_back("InverseDiv");
13305         }
13306
13307         template<class fp16type>
13308         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13309         {
13310                 const fp16type  x                       (*in[0]);
13311                 const fp16type  y                       (*in[1]);
13312                 const double    xd                      (x.asDouble());
13313                 const double    yd                      (y.asDouble());
13314                 const double    unspecUlp       (16.0);
13315                 const double    ulpCnt          (de::inRange(deAbs(yd), deLdExp(1, -14), deLdExp(1, 14)) ? 2.5 : unspecUlp);
13316                 double                  result          (0.0);
13317
13318                 if (y.isZero())
13319                         return false;
13320
13321                 if (getFlavor() == 0)
13322                 {
13323                         result = (xd / yd);
13324                 }
13325                 else if (getFlavor() == 1)
13326                 {
13327                         const double    invyd   (1.0 / yd);
13328                         const fp16type  invy    (invyd);
13329
13330                         result = (xd * invy.asDouble());
13331                 }
13332                 else
13333                 {
13334                         TCU_THROW(InternalError, "Unknown flavor");
13335                 }
13336
13337                 out[0] = fp16type(result).bits();
13338                 min[0] = getMin(result, ulpCnt);
13339                 max[0] = getMax(result, ulpCnt);
13340
13341                 return true;
13342         }
13343 };
13344
13345 struct fp16Atan2 : public fp16PerComponent
13346 {
13347         fp16Atan2() : fp16PerComponent()
13348         {
13349                 flavorNames.push_back("DoubleCalc");
13350                 flavorNames.push_back("DoubleCalc_PI");
13351         }
13352
13353         virtual double getULPs(vector<const deFloat16*>& in)
13354         {
13355                 DE_UNREF(in);
13356
13357                 return 2 * 5.0; // This is not a precision test. Value is not from spec
13358         }
13359
13360         template<class fp16type>
13361         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13362         {
13363                 const fp16type  x               (*in[0]);
13364                 const fp16type  y               (*in[1]);
13365                 const double    xd              (x.asDouble());
13366                 const double    yd              (y.asDouble());
13367                 double                  result  (0.0);
13368
13369                 if (x.isZero() && y.isZero())
13370                         return false;
13371
13372                 if (getFlavor() == 0)
13373                 {
13374                         result  = deAtan2(xd, yd);
13375                 }
13376                 else if (getFlavor() == 1)
13377                 {
13378                         const double    ulps    (2.0 * 5.0); // This is not a precision test. Value is not from spec
13379                         const double    eps             (floatFormat16.ulp(DE_PI_DOUBLE, ulps));
13380
13381                         result  = deAtan2(xd, yd);
13382
13383                         if (de::inRange(deAbs(result), DE_PI_DOUBLE - eps, DE_PI_DOUBLE + eps))
13384                                 result  = -result;
13385                 }
13386                 else
13387                 {
13388                         TCU_THROW(InternalError, "Unknown flavor");
13389                 }
13390
13391                 out[0] = fp16type(result).bits();
13392                 min[0] = getMin(result, getULPs(in));
13393                 max[0] = getMax(result, getULPs(in));
13394
13395                 return true;
13396         }
13397 };
13398
13399 struct fp16Pow : public fp16PerComponent
13400 {
13401         fp16Pow() : fp16PerComponent()
13402         {
13403                 flavorNames.push_back("Pow");
13404                 flavorNames.push_back("PowLog2");
13405                 flavorNames.push_back("PowLog2FP16");
13406         }
13407
13408         template<class fp16type>
13409         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13410         {
13411                 const fp16type  x               (*in[0]);
13412                 const fp16type  y               (*in[1]);
13413                 const double    xd              (x.asDouble());
13414                 const double    yd              (y.asDouble());
13415                 const double    logxeps (de::inRange(deAbs(xd), 0.5, 2.0) ? deLdExp(1.0, -7) : floatFormat16.ulp(deLog2(xd), 3.0));
13416                 const double    ulps1   (1.0 + 4.0 * deAbs(yd * (deLog2(xd) - logxeps)));
13417                 const double    ulps2   (1.0 + 4.0 * deAbs(yd * (deLog2(xd) + logxeps)));
13418                 const double    ulps    (deMax(deAbs(ulps1), deAbs(ulps2)));
13419                 double                  result  (0.0);
13420
13421                 if (xd < 0.0)
13422                         return false;
13423
13424                 if (x.isZero() && yd <= 0.0)
13425                         return false;
13426
13427                 if (getFlavor() == 0)
13428                 {
13429                         result = dePow(xd, yd);
13430                 }
13431                 else if (getFlavor() == 1)
13432                 {
13433                         const double    l2d     (deLog2(xd));
13434                         const double    e2d     (deExp2(yd * l2d));
13435
13436                         result = e2d;
13437                 }
13438                 else if (getFlavor() == 2)
13439                 {
13440                         const double    l2d     (deLog2(xd));
13441                         const fp16type  l2      (l2d);
13442                         const double    e2d     (deExp2(yd * l2.asDouble()));
13443                         const fp16type  e2      (e2d);
13444
13445                         result = e2.asDouble();
13446                 }
13447                 else
13448                 {
13449                         TCU_THROW(InternalError, "Unknown flavor");
13450                 }
13451
13452                 out[0] = fp16type(result).bits();
13453                 min[0] = getMin(result, ulps);
13454                 max[0] = getMax(result, ulps);
13455
13456                 return true;
13457         }
13458 };
13459
13460 struct fp16FMin : public fp16PerComponent
13461 {
13462         template<class fp16type>
13463         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13464         {
13465                 const fp16type  x               (*in[0]);
13466                 const fp16type  y               (*in[1]);
13467                 const double    xd              (x.asDouble());
13468                 const double    yd              (y.asDouble());
13469                 const double    result  (deMin(xd, yd));
13470
13471                 if (x.isNaN() || y.isNaN())
13472                         return false;
13473
13474                 out[0] = fp16type(result).bits();
13475                 min[0] = getMin(result, getULPs(in));
13476                 max[0] = getMax(result, getULPs(in));
13477
13478                 return true;
13479         }
13480 };
13481
13482 struct fp16FMax : public fp16PerComponent
13483 {
13484         template<class fp16type>
13485         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13486         {
13487                 const fp16type  x               (*in[0]);
13488                 const fp16type  y               (*in[1]);
13489                 const double    xd              (x.asDouble());
13490                 const double    yd              (y.asDouble());
13491                 const double    result  (deMax(xd, yd));
13492
13493                 if (x.isNaN() || y.isNaN())
13494                         return false;
13495
13496                 out[0] = fp16type(result).bits();
13497                 min[0] = getMin(result, getULPs(in));
13498                 max[0] = getMax(result, getULPs(in));
13499
13500                 return true;
13501         }
13502 };
13503
13504 struct fp16Step : public fp16PerComponent
13505 {
13506         template<class fp16type>
13507         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13508         {
13509                 const fp16type  edge    (*in[0]);
13510                 const fp16type  x               (*in[1]);
13511                 const double    edged   (edge.asDouble());
13512                 const double    xd              (x.asDouble());
13513                 const double    result  (deStep(edged, xd));
13514
13515                 out[0] = fp16type(result).bits();
13516                 min[0] = getMin(result, getULPs(in));
13517                 max[0] = getMax(result, getULPs(in));
13518
13519                 return true;
13520         }
13521 };
13522
13523 struct fp16Ldexp : public fp16PerComponent
13524 {
13525         template<class fp16type>
13526         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13527         {
13528                 const fp16type  x               (*in[0]);
13529                 const fp16type  y               (*in[1]);
13530                 const double    xd              (x.asDouble());
13531                 const int               yd              (static_cast<int>(deTrunc(y.asDouble())));
13532                 const double    result  (deLdExp(xd, yd));
13533
13534                 if (y.isNaN() || y.isInf() || y.isDenorm() || yd < -14 || yd > 15)
13535                         return false;
13536
13537                 // Spec: "If this product is too large to be represented in the floating-point type, the result is undefined."
13538                 if (fp16type(result).isInf())
13539                         return false;
13540
13541                 out[0] = fp16type(result).bits();
13542                 min[0] = getMin(result, getULPs(in));
13543                 max[0] = getMax(result, getULPs(in));
13544
13545                 return true;
13546         }
13547 };
13548
13549 struct fp16FClamp : public fp16PerComponent
13550 {
13551         template<class fp16type>
13552         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13553         {
13554                 const fp16type  x               (*in[0]);
13555                 const fp16type  minVal  (*in[1]);
13556                 const fp16type  maxVal  (*in[2]);
13557                 const double    xd              (x.asDouble());
13558                 const double    minVald (minVal.asDouble());
13559                 const double    maxVald (maxVal.asDouble());
13560                 const double    result  (deClamp(xd, minVald, maxVald));
13561
13562                 if (minVal.isNaN() || maxVal.isNaN() || minVald > maxVald)
13563                         return false;
13564
13565                 out[0] = fp16type(result).bits();
13566                 min[0] = getMin(result, getULPs(in));
13567                 max[0] = getMax(result, getULPs(in));
13568
13569                 return true;
13570         }
13571 };
13572
13573 struct fp16FMix : public fp16PerComponent
13574 {
13575         fp16FMix() : fp16PerComponent()
13576         {
13577                 flavorNames.push_back("DoubleCalc");
13578                 flavorNames.push_back("EmulatingFP16");
13579                 flavorNames.push_back("EmulatingFP16YminusX");
13580         }
13581
13582         template<class fp16type>
13583         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13584         {
13585                 const fp16type  x               (*in[0]);
13586                 const fp16type  y               (*in[1]);
13587                 const fp16type  a               (*in[2]);
13588                 const double    ulps    (8.0); // This is not a precision test. Value is not from spec
13589                 double                  result  (0.0);
13590
13591                 if (getFlavor() == 0)
13592                 {
13593                         const double    xd              (x.asDouble());
13594                         const double    yd              (y.asDouble());
13595                         const double    ad              (a.asDouble());
13596                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13597                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13598                         const double    eps             (xeps + yeps);
13599
13600                         result = deMix(xd, yd, ad);
13601                         min[0] = result - eps;
13602                         max[0] = result + eps;
13603                 }
13604                 else if (getFlavor() == 1)
13605                 {
13606                         const double    xd              (x.asDouble());
13607                         const double    yd              (y.asDouble());
13608                         const double    ad              (a.asDouble());
13609                         const fp16type  am              (1.0 - ad);
13610                         const double    amd             (am.asDouble());
13611                         const fp16type  xam             (xd * amd);
13612                         const double    xamd    (xam.asDouble());
13613                         const fp16type  ya              (yd * ad);
13614                         const double    yad             (ya.asDouble());
13615                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13616                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13617                         const double    eps             (xeps + yeps);
13618
13619                         result = xamd + yad;
13620                         min[0] = result - eps;
13621                         max[0] = result + eps;
13622                 }
13623                 else if (getFlavor() == 2)
13624                 {
13625                         const double    xd              (x.asDouble());
13626                         const double    yd              (y.asDouble());
13627                         const double    ad              (a.asDouble());
13628                         const fp16type  ymx             (yd - xd);
13629                         const double    ymxd    (ymx.asDouble());
13630                         const fp16type  ymxa    (ymxd * ad);
13631                         const double    ymxad   (ymxa.asDouble());
13632                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13633                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13634                         const double    eps             (xeps + yeps);
13635
13636                         result = xd + ymxad;
13637                         min[0] = result - eps;
13638                         max[0] = result + eps;
13639                 }
13640                 else
13641                 {
13642                         TCU_THROW(InternalError, "Unknown flavor");
13643                 }
13644
13645                 out[0] = fp16type(result).bits();
13646
13647                 return true;
13648         }
13649 };
13650
13651 struct fp16SmoothStep : public fp16PerComponent
13652 {
13653         fp16SmoothStep() : fp16PerComponent()
13654         {
13655                 flavorNames.push_back("FloatCalc");
13656                 flavorNames.push_back("EmulatingFP16");
13657                 flavorNames.push_back("EmulatingFP16WClamp");
13658         }
13659
13660         virtual double getULPs(vector<const deFloat16*>& in)
13661         {
13662                 DE_UNREF(in);
13663
13664                 return 4.0; // This is not a precision test. Value is not from spec
13665         }
13666
13667         template<class fp16type>
13668         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13669         {
13670                 const fp16type  edge0   (*in[0]);
13671                 const fp16type  edge1   (*in[1]);
13672                 const fp16type  x               (*in[2]);
13673                 double                  result  (0.0);
13674
13675                 if (edge0.isNaN() || edge1.isNaN() || x.isNaN() || edge0.asDouble() >= edge1.asDouble())
13676                         return false;
13677
13678                 if (edge0.isInf() || edge1.isInf() || x.isInf())
13679                         return false;
13680
13681                 if (getFlavor() == 0)
13682                 {
13683                         const float     edge0d  (edge0.asFloat());
13684                         const float     edge1d  (edge1.asFloat());
13685                         const float     xd              (x.asFloat());
13686                         const float     sstep   (deFloatSmoothStep(edge0d, edge1d, xd));
13687
13688                         result = sstep;
13689                 }
13690                 else if (getFlavor() == 1)
13691                 {
13692                         const double    edge0d  (edge0.asDouble());
13693                         const double    edge1d  (edge1.asDouble());
13694                         const double    xd              (x.asDouble());
13695
13696                         if (xd <= edge0d)
13697                                 result = 0.0;
13698                         else if (xd >= edge1d)
13699                                 result = 1.0;
13700                         else
13701                         {
13702                                 const fp16type  a       (xd - edge0d);
13703                                 const fp16type  b       (edge1d - edge0d);
13704                                 const fp16type  t       (a.asDouble() / b.asDouble());
13705                                 const fp16type  t2      (2.0 * t.asDouble());
13706                                 const fp16type  t3      (3.0 - t2.asDouble());
13707                                 const fp16type  t4      (t.asDouble() * t3.asDouble());
13708                                 const fp16type  t5      (t.asDouble() * t4.asDouble());
13709
13710                                 result = t5.asDouble();
13711                         }
13712                 }
13713                 else if (getFlavor() == 2)
13714                 {
13715                         const double    edge0d  (edge0.asDouble());
13716                         const double    edge1d  (edge1.asDouble());
13717                         const double    xd              (x.asDouble());
13718                         const fp16type  a       (xd - edge0d);
13719                         const fp16type  b       (edge1d - edge0d);
13720                         const fp16type  bi      (1.0 / b.asDouble());
13721                         const fp16type  t0      (a.asDouble() * bi.asDouble());
13722                         const double    tc      (deClamp(t0.asDouble(), 0.0, 1.0));
13723                         const fp16type  t       (tc);
13724                         const fp16type  t2      (2.0 * t.asDouble());
13725                         const fp16type  t3      (3.0 - t2.asDouble());
13726                         const fp16type  t4      (t.asDouble() * t3.asDouble());
13727                         const fp16type  t5      (t.asDouble() * t4.asDouble());
13728
13729                         result = t5.asDouble();
13730                 }
13731                 else
13732                 {
13733                         TCU_THROW(InternalError, "Unknown flavor");
13734                 }
13735
13736                 out[0] = fp16type(result).bits();
13737                 min[0] = getMin(result, getULPs(in));
13738                 max[0] = getMax(result, getULPs(in));
13739
13740                 return true;
13741         }
13742 };
13743
13744 struct fp16Fma : public fp16PerComponent
13745 {
13746         virtual double getULPs(vector<const deFloat16*>& in)
13747         {
13748                 DE_UNREF(in);
13749
13750                 return 16.0;
13751         }
13752
13753         template<class fp16type>
13754         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13755         {
13756                 DE_ASSERT(in.size() == 3);
13757                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
13758                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
13759                 DE_ASSERT(getArgCompCount(2) == getOutCompCount());
13760                 DE_ASSERT(getOutCompCount() > 0);
13761
13762                 const fp16type  a               (*in[0]);
13763                 const fp16type  b               (*in[1]);
13764                 const fp16type  c               (*in[2]);
13765                 const double    ad              (a.asDouble());
13766                 const double    bd              (b.asDouble());
13767                 const double    cd              (c.asDouble());
13768                 const double    result  (deMadd(ad, bd, cd));
13769
13770                 out[0] = fp16type(result).bits();
13771                 min[0] = getMin(result, getULPs(in));
13772                 max[0] = getMax(result, getULPs(in));
13773
13774                 return true;
13775         }
13776 };
13777
13778
13779 struct fp16AllComponents : public fp16PerComponent
13780 {
13781         bool            callOncePerComponent    ()      { return false; }
13782 };
13783
13784 struct fp16Length : public fp16AllComponents
13785 {
13786         fp16Length() : fp16AllComponents()
13787         {
13788                 flavorNames.push_back("EmulatingFP16");
13789                 flavorNames.push_back("DoubleCalc");
13790         }
13791
13792         virtual double getULPs(vector<const deFloat16*>& in)
13793         {
13794                 DE_UNREF(in);
13795
13796                 return 4.0;
13797         }
13798
13799         template<class fp16type>
13800         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13801         {
13802                 DE_ASSERT(getOutCompCount() == 1);
13803                 DE_ASSERT(in.size() == 1);
13804
13805                 double  result  (0.0);
13806
13807                 if (getFlavor() == 0)
13808                 {
13809                         fp16type        r       (0.0);
13810
13811                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13812                         {
13813                                 const fp16type  x       (in[0][componentNdx]);
13814                                 const fp16type  q       (x.asDouble() * x.asDouble());
13815
13816                                 r = fp16type(r.asDouble() + q.asDouble());
13817                         }
13818
13819                         result = deSqrt(r.asDouble());
13820
13821                         out[0] = fp16type(result).bits();
13822                 }
13823                 else if (getFlavor() == 1)
13824                 {
13825                         double  r       (0.0);
13826
13827                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13828                         {
13829                                 const fp16type  x       (in[0][componentNdx]);
13830                                 const double    q       (x.asDouble() * x.asDouble());
13831
13832                                 r += q;
13833                         }
13834
13835                         result = deSqrt(r);
13836
13837                         out[0] = fp16type(result).bits();
13838                 }
13839                 else
13840                 {
13841                         TCU_THROW(InternalError, "Unknown flavor");
13842                 }
13843
13844                 min[0] = getMin(result, getULPs(in));
13845                 max[0] = getMax(result, getULPs(in));
13846
13847                 return true;
13848         }
13849 };
13850
13851 struct fp16Distance : public fp16AllComponents
13852 {
13853         fp16Distance() : fp16AllComponents()
13854         {
13855                 flavorNames.push_back("EmulatingFP16");
13856                 flavorNames.push_back("DoubleCalc");
13857         }
13858
13859         virtual double getULPs(vector<const deFloat16*>& in)
13860         {
13861                 DE_UNREF(in);
13862
13863                 return 4.0;
13864         }
13865
13866         template<class fp16type>
13867         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13868         {
13869                 DE_ASSERT(getOutCompCount() == 1);
13870                 DE_ASSERT(in.size() == 2);
13871                 DE_ASSERT(getArgCompCount(0) == getArgCompCount(1));
13872
13873                 double  result  (0.0);
13874
13875                 if (getFlavor() == 0)
13876                 {
13877                         fp16type        r       (0.0);
13878
13879                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13880                         {
13881                                 const fp16type  x       (in[0][componentNdx]);
13882                                 const fp16type  y       (in[1][componentNdx]);
13883                                 const fp16type  d       (x.asDouble() - y.asDouble());
13884                                 const fp16type  q       (d.asDouble() * d.asDouble());
13885
13886                                 r = fp16type(r.asDouble() + q.asDouble());
13887                         }
13888
13889                         result = deSqrt(r.asDouble());
13890                 }
13891                 else if (getFlavor() == 1)
13892                 {
13893                         double  r       (0.0);
13894
13895                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13896                         {
13897                                 const fp16type  x       (in[0][componentNdx]);
13898                                 const fp16type  y       (in[1][componentNdx]);
13899                                 const double    d       (x.asDouble() - y.asDouble());
13900                                 const double    q       (d * d);
13901
13902                                 r += q;
13903                         }
13904
13905                         result = deSqrt(r);
13906                 }
13907                 else
13908                 {
13909                         TCU_THROW(InternalError, "Unknown flavor");
13910                 }
13911
13912                 out[0] = fp16type(result).bits();
13913                 min[0] = getMin(result, getULPs(in));
13914                 max[0] = getMax(result, getULPs(in));
13915
13916                 return true;
13917         }
13918 };
13919
13920 struct fp16Cross : public fp16AllComponents
13921 {
13922         fp16Cross() : fp16AllComponents()
13923         {
13924                 flavorNames.push_back("EmulatingFP16");
13925                 flavorNames.push_back("DoubleCalc");
13926         }
13927
13928         virtual double getULPs(vector<const deFloat16*>& in)
13929         {
13930                 DE_UNREF(in);
13931
13932                 return 4.0;
13933         }
13934
13935         template<class fp16type>
13936         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13937         {
13938                 DE_ASSERT(getOutCompCount() == 3);
13939                 DE_ASSERT(in.size() == 2);
13940                 DE_ASSERT(getArgCompCount(0) == 3);
13941                 DE_ASSERT(getArgCompCount(1) == 3);
13942
13943                 if (getFlavor() == 0)
13944                 {
13945                         const fp16type  x0              (in[0][0]);
13946                         const fp16type  x1              (in[0][1]);
13947                         const fp16type  x2              (in[0][2]);
13948                         const fp16type  y0              (in[1][0]);
13949                         const fp16type  y1              (in[1][1]);
13950                         const fp16type  y2              (in[1][2]);
13951                         const fp16type  x1y2    (x1.asDouble() * y2.asDouble());
13952                         const fp16type  y1x2    (y1.asDouble() * x2.asDouble());
13953                         const fp16type  x2y0    (x2.asDouble() * y0.asDouble());
13954                         const fp16type  y2x0    (y2.asDouble() * x0.asDouble());
13955                         const fp16type  x0y1    (x0.asDouble() * y1.asDouble());
13956                         const fp16type  y0x1    (y0.asDouble() * x1.asDouble());
13957
13958                         out[0] = fp16type(x1y2.asDouble() - y1x2.asDouble()).bits();
13959                         out[1] = fp16type(x2y0.asDouble() - y2x0.asDouble()).bits();
13960                         out[2] = fp16type(x0y1.asDouble() - y0x1.asDouble()).bits();
13961                 }
13962                 else if (getFlavor() == 1)
13963                 {
13964                         const fp16type  x0              (in[0][0]);
13965                         const fp16type  x1              (in[0][1]);
13966                         const fp16type  x2              (in[0][2]);
13967                         const fp16type  y0              (in[1][0]);
13968                         const fp16type  y1              (in[1][1]);
13969                         const fp16type  y2              (in[1][2]);
13970                         const double    x1y2    (x1.asDouble() * y2.asDouble());
13971                         const double    y1x2    (y1.asDouble() * x2.asDouble());
13972                         const double    x2y0    (x2.asDouble() * y0.asDouble());
13973                         const double    y2x0    (y2.asDouble() * x0.asDouble());
13974                         const double    x0y1    (x0.asDouble() * y1.asDouble());
13975                         const double    y0x1    (y0.asDouble() * x1.asDouble());
13976
13977                         out[0] = fp16type(x1y2 - y1x2).bits();
13978                         out[1] = fp16type(x2y0 - y2x0).bits();
13979                         out[2] = fp16type(x0y1 - y0x1).bits();
13980                 }
13981                 else
13982                 {
13983                         TCU_THROW(InternalError, "Unknown flavor");
13984                 }
13985
13986                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
13987                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
13988                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
13989                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
13990
13991                 return true;
13992         }
13993 };
13994
13995 struct fp16Normalize : public fp16AllComponents
13996 {
13997         fp16Normalize() : fp16AllComponents()
13998         {
13999                 flavorNames.push_back("EmulatingFP16");
14000                 flavorNames.push_back("DoubleCalc");
14001
14002                 // flavorNames will be extended later
14003         }
14004
14005         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)
14006         {
14007                 DE_ASSERT(argCompCount[argNo] == 0); // Once only
14008
14009                 if (argNo == 0 && argCompCount[argNo] == 0)
14010                 {
14011                         const size_t            maxPermutationsCount    = 24u; // Equal to 4!
14012                         std::vector<int>        indices;
14013
14014                         for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14015                                 indices.push_back(static_cast<int>(componentNdx));
14016
14017                         m_permutations.reserve(maxPermutationsCount);
14018
14019                         permutationsFlavorStart = flavorNames.size();
14020
14021                         do
14022                         {
14023                                 tcu::UVec4      permutation;
14024                                 std::string     name            = "Permutted_";
14025
14026                                 for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14027                                 {
14028                                         permutation[static_cast<int>(componentNdx)] = indices[componentNdx];
14029                                         name += de::toString(indices[componentNdx]);
14030                                 }
14031
14032                                 m_permutations.push_back(permutation);
14033                                 flavorNames.push_back(name);
14034
14035                         } while(std::next_permutation(indices.begin(), indices.end()));
14036
14037                         permutationsFlavorEnd = flavorNames.size();
14038                 }
14039
14040                 fp16AllComponents::setArgCompCount(argNo, compCount);
14041         }
14042         virtual double getULPs(vector<const deFloat16*>& in)
14043         {
14044                 DE_UNREF(in);
14045
14046                 return 8.0;
14047         }
14048
14049         template<class fp16type>
14050         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14051         {
14052                 DE_ASSERT(in.size() == 1);
14053                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14054
14055                 if (getFlavor() == 0)
14056                 {
14057                         fp16type        r(0.0);
14058
14059                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14060                         {
14061                                 const fp16type  x       (in[0][componentNdx]);
14062                                 const fp16type  q       (x.asDouble() * x.asDouble());
14063
14064                                 r = fp16type(r.asDouble() + q.asDouble());
14065                         }
14066
14067                         r = fp16type(deSqrt(r.asDouble()));
14068
14069                         if (r.isZero())
14070                                 return false;
14071
14072                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14073                         {
14074                                 const fp16type  x       (in[0][componentNdx]);
14075
14076                                 out[componentNdx] = fp16type(x.asDouble() / r.asDouble()).bits();
14077                         }
14078                 }
14079                 else if (getFlavor() == 1)
14080                 {
14081                         double  r(0.0);
14082
14083                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14084                         {
14085                                 const fp16type  x       (in[0][componentNdx]);
14086                                 const double    q       (x.asDouble() * x.asDouble());
14087
14088                                 r += q;
14089                         }
14090
14091                         r = deSqrt(r);
14092
14093                         if (r == 0)
14094                                 return false;
14095
14096                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14097                         {
14098                                 const fp16type  x       (in[0][componentNdx]);
14099
14100                                 out[componentNdx] = fp16type(x.asDouble() / r).bits();
14101                         }
14102                 }
14103                 else if (de::inBounds<size_t>(getFlavor(), permutationsFlavorStart, permutationsFlavorEnd))
14104                 {
14105                         const int                       compCount               (static_cast<int>(getArgCompCount(0)));
14106                         const size_t            permutationNdx  (getFlavor() - permutationsFlavorStart);
14107                         const tcu::UVec4&       permutation             (m_permutations[permutationNdx]);
14108                         fp16type                        r                               (0.0);
14109
14110                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14111                         {
14112                                 const size_t    componentNdx    (permutation[permComponentNdx]);
14113                                 const fp16type  x                               (in[0][componentNdx]);
14114                                 const fp16type  q                               (x.asDouble() * x.asDouble());
14115
14116                                 r = fp16type(r.asDouble() + q.asDouble());
14117                         }
14118
14119                         r = fp16type(deSqrt(r.asDouble()));
14120
14121                         if (r.isZero())
14122                                 return false;
14123
14124                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14125                         {
14126                                 const size_t    componentNdx    (permutation[permComponentNdx]);
14127                                 const fp16type  x                               (in[0][componentNdx]);
14128
14129                                 out[componentNdx] = fp16type(x.asDouble() / r.asDouble()).bits();
14130                         }
14131                 }
14132                 else
14133                 {
14134                         TCU_THROW(InternalError, "Unknown flavor");
14135                 }
14136
14137                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14138                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14139                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14140                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14141
14142                 return true;
14143         }
14144
14145 private:
14146         std::vector<tcu::UVec4> m_permutations;
14147         size_t                                  permutationsFlavorStart;
14148         size_t                                  permutationsFlavorEnd;
14149 };
14150
14151 struct fp16FaceForward : public fp16AllComponents
14152 {
14153         virtual double getULPs(vector<const deFloat16*>& in)
14154         {
14155                 DE_UNREF(in);
14156
14157                 return 4.0;
14158         }
14159
14160         template<class fp16type>
14161         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14162         {
14163                 DE_ASSERT(in.size() == 3);
14164                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14165                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14166                 DE_ASSERT(getArgCompCount(2) == getOutCompCount());
14167
14168                 fp16type        dp(0.0);
14169
14170                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14171                 {
14172                         const fp16type  x       (in[1][componentNdx]);
14173                         const fp16type  y       (in[2][componentNdx]);
14174                         const double    xd      (x.asDouble());
14175                         const double    yd      (y.asDouble());
14176                         const fp16type  q       (xd * yd);
14177
14178                         dp = fp16type(dp.asDouble() + q.asDouble());
14179                 }
14180
14181                 if (dp.isNaN() || dp.isZero())
14182                         return false;
14183
14184                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14185                 {
14186                         const fp16type  n       (in[0][componentNdx]);
14187
14188                         out[componentNdx] = (dp.signBit() == 1) ? n.bits() : fp16type(-n.asDouble()).bits();
14189                 }
14190
14191                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14192                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14193                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14194                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14195
14196                 return true;
14197         }
14198 };
14199
14200 struct fp16Reflect : public fp16AllComponents
14201 {
14202         fp16Reflect() : fp16AllComponents()
14203         {
14204                 flavorNames.push_back("EmulatingFP16");
14205                 flavorNames.push_back("EmulatingFP16+KeepZeroSign");
14206                 flavorNames.push_back("FloatCalc");
14207                 flavorNames.push_back("FloatCalc+KeepZeroSign");
14208                 flavorNames.push_back("EmulatingFP16+2Nfirst");
14209                 flavorNames.push_back("EmulatingFP16+2Ifirst");
14210         }
14211
14212         virtual double getULPs(vector<const deFloat16*>& in)
14213         {
14214                 DE_UNREF(in);
14215
14216                 return 256.0; // This is not a precision test. Value is not from spec
14217         }
14218
14219         template<class fp16type>
14220         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14221         {
14222                 DE_ASSERT(in.size() == 2);
14223                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14224                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14225
14226                 if (getFlavor() < 4)
14227                 {
14228                         const bool      keepZeroSign    ((flavor & 1) != 0 ? true : false);
14229                         const bool      floatCalc               ((flavor & 2) != 0 ? true : false);
14230
14231                         if (floatCalc)
14232                         {
14233                                 float   dp(0.0f);
14234
14235                                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14236                                 {
14237                                         const fp16type  i       (in[0][componentNdx]);
14238                                         const fp16type  n       (in[1][componentNdx]);
14239                                         const float             id      (i.asFloat());
14240                                         const float             nd      (n.asFloat());
14241                                         const float             qd      (id * nd);
14242
14243                                         if (keepZeroSign)
14244                                                 dp = (componentNdx == 0) ? qd : dp + qd;
14245                                         else
14246                                                 dp = dp + qd;
14247                                 }
14248
14249                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14250                                 {
14251                                         const fp16type  i               (in[0][componentNdx]);
14252                                         const fp16type  n               (in[1][componentNdx]);
14253                                         const float             dpnd    (dp * n.asFloat());
14254                                         const float             dpn2d   (2.0f * dpnd);
14255                                         const float             idpn2d  (i.asFloat() - dpn2d);
14256                                         const fp16type  result  (idpn2d);
14257
14258                                         out[componentNdx] = result.bits();
14259                                 }
14260                         }
14261                         else
14262                         {
14263                                 fp16type        dp(0.0);
14264
14265                                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14266                                 {
14267                                         const fp16type  i       (in[0][componentNdx]);
14268                                         const fp16type  n       (in[1][componentNdx]);
14269                                         const double    id      (i.asDouble());
14270                                         const double    nd      (n.asDouble());
14271                                         const fp16type  q       (id * nd);
14272
14273                                         if (keepZeroSign)
14274                                                 dp = (componentNdx == 0) ? q : fp16type(dp.asDouble() + q.asDouble());
14275                                         else
14276                                                 dp = fp16type(dp.asDouble() + q.asDouble());
14277                                 }
14278
14279                                 if (dp.isNaN())
14280                                         return false;
14281
14282                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14283                                 {
14284                                         const fp16type  i               (in[0][componentNdx]);
14285                                         const fp16type  n               (in[1][componentNdx]);
14286                                         const fp16type  dpn             (dp.asDouble() * n.asDouble());
14287                                         const fp16type  dpn2    (2 * dpn.asDouble());
14288                                         const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
14289
14290                                         out[componentNdx] = idpn2.bits();
14291                                 }
14292                         }
14293                 }
14294                 else if (getFlavor() == 4)
14295                 {
14296                         fp16type        dp(0.0);
14297
14298                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14299                         {
14300                                 const fp16type  i       (in[0][componentNdx]);
14301                                 const fp16type  n       (in[1][componentNdx]);
14302                                 const double    id      (i.asDouble());
14303                                 const double    nd      (n.asDouble());
14304                                 const fp16type  q       (id * nd);
14305
14306                                 dp = fp16type(dp.asDouble() + q.asDouble());
14307                         }
14308
14309                         if (dp.isNaN())
14310                                 return false;
14311
14312                         for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14313                         {
14314                                 const fp16type  i               (in[0][componentNdx]);
14315                                 const fp16type  n               (in[1][componentNdx]);
14316                                 const fp16type  n2              (2 * n.asDouble());
14317                                 const fp16type  dpn2    (dp.asDouble() * n2.asDouble());
14318                                 const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
14319
14320                                 out[componentNdx] = idpn2.bits();
14321                         }
14322                 }
14323                 else if (getFlavor() == 5)
14324                 {
14325                         fp16type        dp2(0.0);
14326
14327                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14328                         {
14329                                 const fp16type  i       (in[0][componentNdx]);
14330                                 const fp16type  n       (in[1][componentNdx]);
14331                                 const fp16type  i2      (2.0 * i.asDouble());
14332                                 const double    i2d     (i2.asDouble());
14333                                 const double    nd      (n.asDouble());
14334                                 const fp16type  q       (i2d * nd);
14335
14336                                 dp2 = fp16type(dp2.asDouble() + q.asDouble());
14337                         }
14338
14339                         if (dp2.isNaN())
14340                                 return false;
14341
14342                         for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14343                         {
14344                                 const fp16type  i               (in[0][componentNdx]);
14345                                 const fp16type  n               (in[1][componentNdx]);
14346                                 const fp16type  dpn2    (dp2.asDouble() * n.asDouble());
14347                                 const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
14348
14349                                 out[componentNdx] = idpn2.bits();
14350                         }
14351                 }
14352                 else
14353                 {
14354                         TCU_THROW(InternalError, "Unknown flavor");
14355                 }
14356
14357                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14358                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14359                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14360                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14361
14362                 return true;
14363         }
14364 };
14365
14366 struct fp16Refract : public fp16AllComponents
14367 {
14368         fp16Refract() : fp16AllComponents()
14369         {
14370                 flavorNames.push_back("EmulatingFP16");
14371                 flavorNames.push_back("EmulatingFP16+KeepZeroSign");
14372                 flavorNames.push_back("FloatCalc");
14373                 flavorNames.push_back("FloatCalc+KeepZeroSign");
14374         }
14375
14376         virtual double getULPs(vector<const deFloat16*>& in)
14377         {
14378                 DE_UNREF(in);
14379
14380                 return 8192.0; // This is not a precision test. Value is not from spec
14381         }
14382
14383         template<class fp16type>
14384         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14385         {
14386                 DE_ASSERT(in.size() == 3);
14387                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14388                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14389                 DE_ASSERT(getArgCompCount(2) == 1);
14390
14391                 const bool              keepZeroSign    ((flavor & 1) != 0 ? true : false);
14392                 const bool              doubleCalc              ((flavor & 2) != 0 ? true : false);
14393                 const fp16type  eta                             (*in[2]);
14394
14395                 if (doubleCalc)
14396                 {
14397                         double  dp      (0.0);
14398
14399                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14400                         {
14401                                 const fp16type  i       (in[0][componentNdx]);
14402                                 const fp16type  n       (in[1][componentNdx]);
14403                                 const double    id      (i.asDouble());
14404                                 const double    nd      (n.asDouble());
14405                                 const double    qd      (id * nd);
14406
14407                                 if (keepZeroSign)
14408                                         dp = (componentNdx == 0) ? qd : dp + qd;
14409                                 else
14410                                         dp = dp + qd;
14411                         }
14412
14413                         const double    eta2    (eta.asDouble() * eta.asDouble());
14414                         const double    dp2             (dp * dp);
14415                         const double    dp1             (1.0 - dp2);
14416                         const double    dpe             (eta2 * dp1);
14417                         const double    k               (1.0 - dpe);
14418
14419                         if (k < 0.0)
14420                         {
14421                                 const fp16type  zero    (0.0);
14422
14423                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14424                                         out[componentNdx] = zero.bits();
14425                         }
14426                         else
14427                         {
14428                                 const double    sk      (deSqrt(k));
14429
14430                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14431                                 {
14432                                         const fp16type  i               (in[0][componentNdx]);
14433                                         const fp16type  n               (in[1][componentNdx]);
14434                                         const double    etai    (i.asDouble() * eta.asDouble());
14435                                         const double    etadp   (eta.asDouble() * dp);
14436                                         const double    etadpk  (etadp + sk);
14437                                         const double    etadpkn (etadpk * n.asDouble());
14438                                         const double    full    (etai - etadpkn);
14439                                         const fp16type  result  (full);
14440
14441                                         if (result.isInf())
14442                                                 return false;
14443
14444                                         out[componentNdx] = result.bits();
14445                                 }
14446                         }
14447                 }
14448                 else
14449                 {
14450                         fp16type        dp      (0.0);
14451
14452                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14453                         {
14454                                 const fp16type  i       (in[0][componentNdx]);
14455                                 const fp16type  n       (in[1][componentNdx]);
14456                                 const double    id      (i.asDouble());
14457                                 const double    nd      (n.asDouble());
14458                                 const fp16type  q       (id * nd);
14459
14460                                 if (keepZeroSign)
14461                                         dp = (componentNdx == 0) ? q : fp16type(dp.asDouble() + q.asDouble());
14462                                 else
14463                                         dp = fp16type(dp.asDouble() + q.asDouble());
14464                         }
14465
14466                         if (dp.isNaN())
14467                                 return false;
14468
14469                         const fp16type  eta2(eta.asDouble() * eta.asDouble());
14470                         const fp16type  dp2     (dp.asDouble() * dp.asDouble());
14471                         const fp16type  dp1     (1.0 - dp2.asDouble());
14472                         const fp16type  dpe     (eta2.asDouble() * dp1.asDouble());
14473                         const fp16type  k       (1.0 - dpe.asDouble());
14474
14475                         if (k.asDouble() < 0.0)
14476                         {
14477                                 const fp16type  zero    (0.0);
14478
14479                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14480                                         out[componentNdx] = zero.bits();
14481                         }
14482                         else
14483                         {
14484                                 const fp16type  sk      (deSqrt(k.asDouble()));
14485
14486                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14487                                 {
14488                                         const fp16type  i               (in[0][componentNdx]);
14489                                         const fp16type  n               (in[1][componentNdx]);
14490                                         const fp16type  etai    (i.asDouble() * eta.asDouble());
14491                                         const fp16type  etadp   (eta.asDouble() * dp.asDouble());
14492                                         const fp16type  etadpk  (etadp.asDouble() + sk.asDouble());
14493                                         const fp16type  etadpkn (etadpk.asDouble() * n.asDouble());
14494                                         const fp16type  full    (etai.asDouble() - etadpkn.asDouble());
14495
14496                                         if (full.isNaN() || full.isInf())
14497                                                 return false;
14498
14499                                         out[componentNdx] = full.bits();
14500                                 }
14501                         }
14502                 }
14503
14504                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14505                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14506                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14507                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14508
14509                 return true;
14510         }
14511 };
14512
14513 struct fp16Dot : public fp16AllComponents
14514 {
14515         fp16Dot() : fp16AllComponents()
14516         {
14517                 flavorNames.push_back("EmulatingFP16");
14518                 flavorNames.push_back("FloatCalc");
14519                 flavorNames.push_back("DoubleCalc");
14520
14521                 // flavorNames will be extended later
14522         }
14523
14524         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)
14525         {
14526                 DE_ASSERT(argCompCount[argNo] == 0); // Once only
14527
14528                 if (argNo == 0 && argCompCount[argNo] == 0)
14529                 {
14530                         const size_t            maxPermutationsCount    = 24u; // Equal to 4!
14531                         std::vector<int>        indices;
14532
14533                         for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14534                                 indices.push_back(static_cast<int>(componentNdx));
14535
14536                         m_permutations.reserve(maxPermutationsCount);
14537
14538                         permutationsFlavorStart = flavorNames.size();
14539
14540                         do
14541                         {
14542                                 tcu::UVec4      permutation;
14543                                 std::string     name            = "Permutted_";
14544
14545                                 for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14546                                 {
14547                                         permutation[static_cast<int>(componentNdx)] = indices[componentNdx];
14548                                         name += de::toString(indices[componentNdx]);
14549                                 }
14550
14551                                 m_permutations.push_back(permutation);
14552                                 flavorNames.push_back(name);
14553
14554                         } while(std::next_permutation(indices.begin(), indices.end()));
14555
14556                         permutationsFlavorEnd = flavorNames.size();
14557                 }
14558
14559                 fp16AllComponents::setArgCompCount(argNo, compCount);
14560         }
14561
14562         virtual double  getULPs(vector<const deFloat16*>& in)
14563         {
14564                 DE_UNREF(in);
14565
14566                 return 16.0; // This is not a precision test. Value is not from spec
14567         }
14568
14569         template<class fp16type>
14570         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14571         {
14572                 DE_ASSERT(in.size() == 2);
14573                 DE_ASSERT(getArgCompCount(0) == getArgCompCount(1));
14574                 DE_ASSERT(getOutCompCount() == 1);
14575
14576                 double  result  (0.0);
14577                 double  eps             (0.0);
14578
14579                 if (getFlavor() == 0)
14580                 {
14581                         fp16type        dp      (0.0);
14582
14583                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14584                         {
14585                                 const fp16type  x       (in[0][componentNdx]);
14586                                 const fp16type  y       (in[1][componentNdx]);
14587                                 const fp16type  q       (x.asDouble() * y.asDouble());
14588
14589                                 dp = fp16type(dp.asDouble() + q.asDouble());
14590                                 eps += floatFormat16.ulp(q.asDouble(), 2.0);
14591                         }
14592
14593                         result = dp.asDouble();
14594                 }
14595                 else if (getFlavor() == 1)
14596                 {
14597                         float   dp      (0.0);
14598
14599                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14600                         {
14601                                 const fp16type  x       (in[0][componentNdx]);
14602                                 const fp16type  y       (in[1][componentNdx]);
14603                                 const float             q       (x.asFloat() * y.asFloat());
14604
14605                                 dp += q;
14606                                 eps += floatFormat16.ulp(static_cast<double>(q), 2.0);
14607                         }
14608
14609                         result = dp;
14610                 }
14611                 else if (getFlavor() == 2)
14612                 {
14613                         double  dp      (0.0);
14614
14615                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14616                         {
14617                                 const fp16type  x       (in[0][componentNdx]);
14618                                 const fp16type  y       (in[1][componentNdx]);
14619                                 const double    q       (x.asDouble() * y.asDouble());
14620
14621                                 dp += q;
14622                                 eps += floatFormat16.ulp(q, 2.0);
14623                         }
14624
14625                         result = dp;
14626                 }
14627                 else if (de::inBounds<size_t>(getFlavor(), permutationsFlavorStart, permutationsFlavorEnd))
14628                 {
14629                         const int                       compCount               (static_cast<int>(getArgCompCount(1)));
14630                         const size_t            permutationNdx  (getFlavor() - permutationsFlavorStart);
14631                         const tcu::UVec4&       permutation             (m_permutations[permutationNdx]);
14632                         fp16type                        dp                              (0.0);
14633
14634                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14635                         {
14636                                 const size_t            componentNdx    (permutation[permComponentNdx]);
14637                                 const fp16type          x                               (in[0][componentNdx]);
14638                                 const fp16type          y                               (in[1][componentNdx]);
14639                                 const fp16type          q                               (x.asDouble() * y.asDouble());
14640
14641                                 dp = fp16type(dp.asDouble() + q.asDouble());
14642                                 eps += floatFormat16.ulp(q.asDouble(), 2.0);
14643                         }
14644
14645                         result = dp.asDouble();
14646                 }
14647                 else
14648                 {
14649                         TCU_THROW(InternalError, "Unknown flavor");
14650                 }
14651
14652                 out[0] = fp16type(result).bits();
14653                 min[0] = result - eps;
14654                 max[0] = result + eps;
14655
14656                 return true;
14657         }
14658
14659 private:
14660         std::vector<tcu::UVec4> m_permutations;
14661         size_t                                  permutationsFlavorStart;
14662         size_t                                  permutationsFlavorEnd;
14663 };
14664
14665 struct fp16VectorTimesScalar : public fp16AllComponents
14666 {
14667         virtual double getULPs(vector<const deFloat16*>& in)
14668         {
14669                 DE_UNREF(in);
14670
14671                 return 2.0;
14672         }
14673
14674         template<class fp16type>
14675         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14676         {
14677                 DE_ASSERT(in.size() == 2);
14678                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14679                 DE_ASSERT(getArgCompCount(1) == 1);
14680
14681                 fp16type        s       (*in[1]);
14682
14683                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14684                 {
14685                         const fp16type  x          (in[0][componentNdx]);
14686                         const double    result (s.asDouble() * x.asDouble());
14687                         const fp16type  m          (result);
14688
14689                         out[componentNdx] = m.bits();
14690                         min[componentNdx] = getMin(result, getULPs(in));
14691                         max[componentNdx] = getMax(result, getULPs(in));
14692                 }
14693
14694                 return true;
14695         }
14696 };
14697
14698 struct fp16MatrixBase : public fp16AllComponents
14699 {
14700         deUint32                getComponentValidity                    ()
14701         {
14702                 return static_cast<deUint32>(-1);
14703         }
14704
14705         inline size_t   getNdx                                                  (const size_t rowCount, const size_t col, const size_t row)
14706         {
14707                 const size_t minComponentCount  = 0;
14708                 const size_t maxComponentCount  = 3;
14709                 const size_t alignedRowsCount   = (rowCount == 3) ? 4 : rowCount;
14710
14711                 DE_ASSERT(de::inRange(rowCount, minComponentCount + 1, maxComponentCount + 1));
14712                 DE_ASSERT(de::inRange(col, minComponentCount, maxComponentCount));
14713                 DE_ASSERT(de::inBounds(row, minComponentCount, rowCount));
14714                 DE_UNREF(minComponentCount);
14715                 DE_UNREF(maxComponentCount);
14716
14717                 return col * alignedRowsCount + row;
14718         }
14719
14720         deUint32                getComponentMatrixValidityMask  (size_t cols, size_t rows)
14721         {
14722                 deUint32        result  = 0u;
14723
14724                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14725                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14726                         {
14727                                 const size_t bitNdx = getNdx(rows, colNdx, rowNdx);
14728
14729                                 DE_ASSERT(bitNdx < sizeof(result) * 8);
14730
14731                                 result |= (1<<bitNdx);
14732                         }
14733
14734                 return result;
14735         }
14736 };
14737
14738 template<size_t cols, size_t rows>
14739 struct fp16Transpose : public fp16MatrixBase
14740 {
14741         virtual double getULPs(vector<const deFloat16*>& in)
14742         {
14743                 DE_UNREF(in);
14744
14745                 return 1.0;
14746         }
14747
14748         deUint32        getComponentValidity    ()
14749         {
14750                 return getComponentMatrixValidityMask(rows, cols);
14751         }
14752
14753         template<class fp16type>
14754         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14755         {
14756                 DE_ASSERT(in.size() == 1);
14757
14758                 const size_t            alignedCols     = (cols == 3) ? 4 : cols;
14759                 const size_t            alignedRows     = (rows == 3) ? 4 : rows;
14760                 vector<deFloat16>       output          (alignedCols * alignedRows, 0);
14761
14762                 DE_ASSERT(output.size() == alignedCols * alignedRows);
14763
14764                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14765                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14766                                 output[rowNdx * alignedCols + colNdx] = in[0][colNdx * alignedRows + rowNdx];
14767
14768                 deMemcpy(out, &output[0], sizeof(deFloat16) * output.size());
14769                 deMemcpy(min, &output[0], sizeof(deFloat16) * output.size());
14770                 deMemcpy(max, &output[0], sizeof(deFloat16) * output.size());
14771
14772                 return true;
14773         }
14774 };
14775
14776 template<size_t cols, size_t rows>
14777 struct fp16MatrixTimesScalar : public fp16MatrixBase
14778 {
14779         virtual double getULPs(vector<const deFloat16*>& in)
14780         {
14781                 DE_UNREF(in);
14782
14783                 return 4.0;
14784         }
14785
14786         deUint32        getComponentValidity    ()
14787         {
14788                 return getComponentMatrixValidityMask(cols, rows);
14789         }
14790
14791         template<class fp16type>
14792         bool calc(vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14793         {
14794                 DE_ASSERT(in.size() == 2);
14795                 DE_ASSERT(getArgCompCount(1) == 1);
14796
14797                 const fp16type  y                       (in[1][0]);
14798                 const float             scalar          (y.asFloat());
14799                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
14800                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
14801
14802                 DE_ASSERT(getArgCompCount(0) == alignedCols * alignedRows);
14803                 DE_ASSERT(getOutCompCount() == alignedCols * alignedRows);
14804                 DE_UNREF(alignedCols);
14805
14806                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14807                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14808                         {
14809                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
14810                                 const fp16type  x       (in[0][ndx]);
14811                                 const double    result  (scalar * x.asFloat());
14812
14813                                 out[ndx] = fp16type(result).bits();
14814                                 min[ndx] = getMin(result, getULPs(in));
14815                                 max[ndx] = getMax(result, getULPs(in));
14816                         }
14817
14818                 return true;
14819         }
14820 };
14821
14822 template<size_t cols, size_t rows>
14823 struct fp16VectorTimesMatrix : public fp16MatrixBase
14824 {
14825         fp16VectorTimesMatrix() : fp16MatrixBase()
14826         {
14827                 flavorNames.push_back("EmulatingFP16");
14828                 flavorNames.push_back("FloatCalc");
14829         }
14830
14831         virtual double getULPs (vector<const deFloat16*>& in)
14832         {
14833                 DE_UNREF(in);
14834
14835                 return (8.0 * cols);
14836         }
14837
14838         deUint32 getComponentValidity ()
14839         {
14840                 return getComponentMatrixValidityMask(cols, 1);
14841         }
14842
14843         template<class fp16type>
14844         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14845         {
14846                 DE_ASSERT(in.size() == 2);
14847
14848                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
14849                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
14850
14851                 DE_ASSERT(getOutCompCount() == cols);
14852                 DE_ASSERT(getArgCompCount(0) == rows);
14853                 DE_ASSERT(getArgCompCount(1) == alignedCols * alignedRows);
14854                 DE_UNREF(alignedCols);
14855
14856                 if (getFlavor() == 0)
14857                 {
14858                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14859                         {
14860                                 fp16type        s       (fp16type::zero(1));
14861
14862                                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14863                                 {
14864                                         const fp16type  v       (in[0][rowNdx]);
14865                                         const float             vf      (v.asFloat());
14866                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
14867                                         const fp16type  x       (in[1][ndx]);
14868                                         const float             xf      (x.asFloat());
14869                                         const fp16type  m       (vf * xf);
14870
14871                                         s = fp16type(s.asFloat() + m.asFloat());
14872                                 }
14873
14874                                 out[colNdx] = s.bits();
14875                                 min[colNdx] = getMin(s.asDouble(), getULPs(in));
14876                                 max[colNdx] = getMax(s.asDouble(), getULPs(in));
14877                         }
14878                 }
14879                 else if (getFlavor() == 1)
14880                 {
14881                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14882                         {
14883                                 float   s       (0.0f);
14884
14885                                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14886                                 {
14887                                         const fp16type  v       (in[0][rowNdx]);
14888                                         const float             vf      (v.asFloat());
14889                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
14890                                         const fp16type  x       (in[1][ndx]);
14891                                         const float             xf      (x.asFloat());
14892                                         const float             m       (vf * xf);
14893
14894                                         s += m;
14895                                 }
14896
14897                                 out[colNdx] = fp16type(s).bits();
14898                                 min[colNdx] = getMin(static_cast<double>(s), getULPs(in));
14899                                 max[colNdx] = getMax(static_cast<double>(s), getULPs(in));
14900                         }
14901                 }
14902                 else
14903                 {
14904                         TCU_THROW(InternalError, "Unknown flavor");
14905                 }
14906
14907                 return true;
14908         }
14909 };
14910
14911 template<size_t cols, size_t rows>
14912 struct fp16MatrixTimesVector : public fp16MatrixBase
14913 {
14914         fp16MatrixTimesVector() : fp16MatrixBase()
14915         {
14916                 flavorNames.push_back("EmulatingFP16");
14917                 flavorNames.push_back("FloatCalc");
14918         }
14919
14920         virtual double getULPs (vector<const deFloat16*>& in)
14921         {
14922                 DE_UNREF(in);
14923
14924                 return (8.0 * rows);
14925         }
14926
14927         deUint32 getComponentValidity ()
14928         {
14929                 return getComponentMatrixValidityMask(rows, 1);
14930         }
14931
14932         template<class fp16type>
14933         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14934         {
14935                 DE_ASSERT(in.size() == 2);
14936
14937                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
14938                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
14939
14940                 DE_ASSERT(getOutCompCount() == rows);
14941                 DE_ASSERT(getArgCompCount(0) == alignedCols * alignedRows);
14942                 DE_ASSERT(getArgCompCount(1) == cols);
14943                 DE_UNREF(alignedCols);
14944
14945                 if (getFlavor() == 0)
14946                 {
14947                         for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14948                         {
14949                                 fp16type        s       (fp16type::zero(1));
14950
14951                                 for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14952                                 {
14953                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
14954                                         const fp16type  x       (in[0][ndx]);
14955                                         const float             xf      (x.asFloat());
14956                                         const fp16type  v       (in[1][colNdx]);
14957                                         const float             vf      (v.asFloat());
14958                                         const fp16type  m       (vf * xf);
14959
14960                                         s = fp16type(s.asFloat() + m.asFloat());
14961                                 }
14962
14963                                 out[rowNdx] = s.bits();
14964                                 min[rowNdx] = getMin(s.asDouble(), getULPs(in));
14965                                 max[rowNdx] = getMax(s.asDouble(), getULPs(in));
14966                         }
14967                 }
14968                 else if (getFlavor() == 1)
14969                 {
14970                         for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14971                         {
14972                                 float   s       (0.0f);
14973
14974                                 for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14975                                 {
14976                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
14977                                         const fp16type  x       (in[0][ndx]);
14978                                         const float             xf      (x.asFloat());
14979                                         const fp16type  v       (in[1][colNdx]);
14980                                         const float             vf      (v.asFloat());
14981                                         const float             m       (vf * xf);
14982
14983                                         s += m;
14984                                 }
14985
14986                                 out[rowNdx] = fp16type(s).bits();
14987                                 min[rowNdx] = getMin(static_cast<double>(s), getULPs(in));
14988                                 max[rowNdx] = getMax(static_cast<double>(s), getULPs(in));
14989                         }
14990                 }
14991                 else
14992                 {
14993                         TCU_THROW(InternalError, "Unknown flavor");
14994                 }
14995
14996                 return true;
14997         }
14998 };
14999
15000 template<size_t colsL, size_t rowsL, size_t colsR, size_t rowsR>
15001 struct fp16MatrixTimesMatrix : public fp16MatrixBase
15002 {
15003         fp16MatrixTimesMatrix() : fp16MatrixBase()
15004         {
15005                 flavorNames.push_back("EmulatingFP16");
15006                 flavorNames.push_back("FloatCalc");
15007         }
15008
15009         virtual double getULPs (vector<const deFloat16*>& in)
15010         {
15011                 DE_UNREF(in);
15012
15013                 return 32.0;
15014         }
15015
15016         deUint32 getComponentValidity ()
15017         {
15018                 return getComponentMatrixValidityMask(colsR, rowsL);
15019         }
15020
15021         template<class fp16type>
15022         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15023         {
15024                 DE_STATIC_ASSERT(colsL == rowsR);
15025
15026                 DE_ASSERT(in.size() == 2);
15027
15028                 const size_t    alignedColsL    = (colsL == 3) ? 4 : colsL;
15029                 const size_t    alignedRowsL    = (rowsL == 3) ? 4 : rowsL;
15030                 const size_t    alignedColsR    = (colsR == 3) ? 4 : colsR;
15031                 const size_t    alignedRowsR    = (rowsR == 3) ? 4 : rowsR;
15032
15033                 DE_ASSERT(getOutCompCount() == alignedColsR * alignedRowsL);
15034                 DE_ASSERT(getArgCompCount(0) == alignedColsL * alignedRowsL);
15035                 DE_ASSERT(getArgCompCount(1) == alignedColsR * alignedRowsR);
15036                 DE_UNREF(alignedColsL);
15037                 DE_UNREF(alignedColsR);
15038
15039                 if (getFlavor() == 0)
15040                 {
15041                         for (size_t rowNdx = 0; rowNdx < rowsL; ++rowNdx)
15042                         {
15043                                 for (size_t colNdx = 0; colNdx < colsR; ++colNdx)
15044                                 {
15045                                         const size_t    ndx     (colNdx * alignedRowsL + rowNdx);
15046                                         fp16type                s       (fp16type::zero(1));
15047
15048                                         for (size_t commonNdx = 0; commonNdx < colsL; ++commonNdx)
15049                                         {
15050                                                 const size_t    ndxl    (commonNdx * alignedRowsL + rowNdx);
15051                                                 const fp16type  l               (in[0][ndxl]);
15052                                                 const float             lf              (l.asFloat());
15053                                                 const size_t    ndxr    (colNdx * alignedRowsR + commonNdx);
15054                                                 const fp16type  r               (in[1][ndxr]);
15055                                                 const float             rf              (r.asFloat());
15056                                                 const fp16type  m               (lf * rf);
15057
15058                                                 s = fp16type(s.asFloat() + m.asFloat());
15059                                         }
15060
15061                                         out[ndx] = s.bits();
15062                                         min[ndx] = getMin(s.asDouble(), getULPs(in));
15063                                         max[ndx] = getMax(s.asDouble(), getULPs(in));
15064                                 }
15065                         }
15066                 }
15067                 else if (getFlavor() == 1)
15068                 {
15069                         for (size_t rowNdx = 0; rowNdx < rowsL; ++rowNdx)
15070                         {
15071                                 for (size_t colNdx = 0; colNdx < colsR; ++colNdx)
15072                                 {
15073                                         const size_t    ndx     (colNdx * alignedRowsL + rowNdx);
15074                                         float                   s       (0.0f);
15075
15076                                         for (size_t commonNdx = 0; commonNdx < colsL; ++commonNdx)
15077                                         {
15078                                                 const size_t    ndxl    (commonNdx * alignedRowsL + rowNdx);
15079                                                 const fp16type  l               (in[0][ndxl]);
15080                                                 const float             lf              (l.asFloat());
15081                                                 const size_t    ndxr    (colNdx * alignedRowsR + commonNdx);
15082                                                 const fp16type  r               (in[1][ndxr]);
15083                                                 const float             rf              (r.asFloat());
15084                                                 const float             m               (lf * rf);
15085
15086                                                 s += m;
15087                                         }
15088
15089                                         out[ndx] = fp16type(s).bits();
15090                                         min[ndx] = getMin(static_cast<double>(s), getULPs(in));
15091                                         max[ndx] = getMax(static_cast<double>(s), getULPs(in));
15092                                 }
15093                         }
15094                 }
15095                 else
15096                 {
15097                         TCU_THROW(InternalError, "Unknown flavor");
15098                 }
15099
15100                 return true;
15101         }
15102 };
15103
15104 template<size_t cols, size_t rows>
15105 struct fp16OuterProduct : public fp16MatrixBase
15106 {
15107         virtual double getULPs (vector<const deFloat16*>& in)
15108         {
15109                 DE_UNREF(in);
15110
15111                 return 2.0;
15112         }
15113
15114         deUint32 getComponentValidity ()
15115         {
15116                 return getComponentMatrixValidityMask(cols, rows);
15117         }
15118
15119         template<class fp16type>
15120         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15121         {
15122                 DE_ASSERT(in.size() == 2);
15123
15124                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15125                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15126
15127                 DE_ASSERT(getArgCompCount(0) == rows);
15128                 DE_ASSERT(getArgCompCount(1) == cols);
15129                 DE_ASSERT(getOutCompCount() == alignedCols * alignedRows);
15130                 DE_UNREF(alignedCols);
15131
15132                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15133                 {
15134                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15135                         {
15136                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
15137                                 const fp16type  x       (in[0][rowNdx]);
15138                                 const float             xf      (x.asFloat());
15139                                 const fp16type  y       (in[1][colNdx]);
15140                                 const float             yf      (y.asFloat());
15141                                 const fp16type  m       (xf * yf);
15142
15143                                 out[ndx] = m.bits();
15144                                 min[ndx] = getMin(m.asDouble(), getULPs(in));
15145                                 max[ndx] = getMax(m.asDouble(), getULPs(in));
15146                         }
15147                 }
15148
15149                 return true;
15150         }
15151 };
15152
15153 template<size_t size>
15154 struct fp16Determinant;
15155
15156 template<>
15157 struct fp16Determinant<2> : public fp16MatrixBase
15158 {
15159         virtual double getULPs (vector<const deFloat16*>& in)
15160         {
15161                 DE_UNREF(in);
15162
15163                 return 128.0; // This is not a precision test. Value is not from spec
15164         }
15165
15166         deUint32 getComponentValidity ()
15167         {
15168                 return 1;
15169         }
15170
15171         template<class fp16type>
15172         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15173         {
15174                 const size_t    cols            = 2;
15175                 const size_t    rows            = 2;
15176                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15177                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15178
15179                 DE_ASSERT(in.size() == 1);
15180                 DE_ASSERT(getOutCompCount() == 1);
15181                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15182                 DE_UNREF(alignedCols);
15183                 DE_UNREF(alignedRows);
15184
15185                 // [ a b ]
15186                 // [ c d ]
15187                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15188                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15189                 const float             c               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15190                 const float             d               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15191                 const float             ad              (a * d);
15192                 const fp16type  adf16   (ad);
15193                 const float             bc              (b * c);
15194                 const fp16type  bcf16   (bc);
15195                 const float             r               (adf16.asFloat() - bcf16.asFloat());
15196                 const fp16type  rf16    (r);
15197
15198                 out[0] = rf16.bits();
15199                 min[0] = getMin(r, getULPs(in));
15200                 max[0] = getMax(r, getULPs(in));
15201
15202                 return true;
15203         }
15204 };
15205
15206 template<>
15207 struct fp16Determinant<3> : public fp16MatrixBase
15208 {
15209         virtual double getULPs (vector<const deFloat16*>& in)
15210         {
15211                 DE_UNREF(in);
15212
15213                 return 128.0; // This is not a precision test. Value is not from spec
15214         }
15215
15216         deUint32 getComponentValidity ()
15217         {
15218                 return 1;
15219         }
15220
15221         template<class fp16type>
15222         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15223         {
15224                 const size_t    cols            = 3;
15225                 const size_t    rows            = 3;
15226                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15227                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15228
15229                 DE_ASSERT(in.size() == 1);
15230                 DE_ASSERT(getOutCompCount() == 1);
15231                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15232                 DE_UNREF(alignedCols);
15233                 DE_UNREF(alignedRows);
15234
15235                 // [ a b c ]
15236                 // [ d e f ]
15237                 // [ g h i ]
15238                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15239                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15240                 const float             c               (fp16type(in[0][getNdx(rows, 2, 0)]).asFloat());
15241                 const float             d               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15242                 const float             e               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15243                 const float             f               (fp16type(in[0][getNdx(rows, 2, 1)]).asFloat());
15244                 const float             g               (fp16type(in[0][getNdx(rows, 0, 2)]).asFloat());
15245                 const float             h               (fp16type(in[0][getNdx(rows, 1, 2)]).asFloat());
15246                 const float             i               (fp16type(in[0][getNdx(rows, 2, 2)]).asFloat());
15247                 const fp16type  aei             (a * e * i);
15248                 const fp16type  bfg             (b * f * g);
15249                 const fp16type  cdh             (c * d * h);
15250                 const fp16type  ceg             (c * e * g);
15251                 const fp16type  bdi             (b * d * i);
15252                 const fp16type  afh             (a * f * h);
15253                 const float             r               (aei.asFloat() + bfg.asFloat() + cdh.asFloat() - ceg.asFloat() - bdi.asFloat() - afh.asFloat());
15254                 const fp16type  rf16    (r);
15255
15256                 out[0] = rf16.bits();
15257                 min[0] = getMin(r, getULPs(in));
15258                 max[0] = getMax(r, getULPs(in));
15259
15260                 return true;
15261         }
15262 };
15263
15264 template<>
15265 struct fp16Determinant<4> : public fp16MatrixBase
15266 {
15267         virtual double getULPs (vector<const deFloat16*>& in)
15268         {
15269                 DE_UNREF(in);
15270
15271                 return 128.0; // This is not a precision test. Value is not from spec
15272         }
15273
15274         deUint32 getComponentValidity ()
15275         {
15276                 return 1;
15277         }
15278
15279         template<class fp16type>
15280         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15281         {
15282                 const size_t    rows            = 4;
15283                 const size_t    cols            = 4;
15284                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15285                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15286
15287                 DE_ASSERT(in.size() == 1);
15288                 DE_ASSERT(getOutCompCount() == 1);
15289                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15290                 DE_UNREF(alignedCols);
15291                 DE_UNREF(alignedRows);
15292
15293                 // [ a b c d ]
15294                 // [ e f g h ]
15295                 // [ i j k l ]
15296                 // [ m n o p ]
15297                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15298                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15299                 const float             c               (fp16type(in[0][getNdx(rows, 2, 0)]).asFloat());
15300                 const float             d               (fp16type(in[0][getNdx(rows, 3, 0)]).asFloat());
15301                 const float             e               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15302                 const float             f               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15303                 const float             g               (fp16type(in[0][getNdx(rows, 2, 1)]).asFloat());
15304                 const float             h               (fp16type(in[0][getNdx(rows, 3, 1)]).asFloat());
15305                 const float             i               (fp16type(in[0][getNdx(rows, 0, 2)]).asFloat());
15306                 const float             j               (fp16type(in[0][getNdx(rows, 1, 2)]).asFloat());
15307                 const float             k               (fp16type(in[0][getNdx(rows, 2, 2)]).asFloat());
15308                 const float             l               (fp16type(in[0][getNdx(rows, 3, 2)]).asFloat());
15309                 const float             m               (fp16type(in[0][getNdx(rows, 0, 3)]).asFloat());
15310                 const float             n               (fp16type(in[0][getNdx(rows, 1, 3)]).asFloat());
15311                 const float             o               (fp16type(in[0][getNdx(rows, 2, 3)]).asFloat());
15312                 const float             p               (fp16type(in[0][getNdx(rows, 3, 3)]).asFloat());
15313
15314                 // [ f g h ]
15315                 // [ j k l ]
15316                 // [ n o p ]
15317                 const fp16type  fkp             (f * k * p);
15318                 const fp16type  gln             (g * l * n);
15319                 const fp16type  hjo             (h * j * o);
15320                 const fp16type  hkn             (h * k * n);
15321                 const fp16type  gjp             (g * j * p);
15322                 const fp16type  flo             (f * l * o);
15323                 const fp16type  detA    (a * (fkp.asFloat() + gln.asFloat() + hjo.asFloat() - hkn.asFloat() - gjp.asFloat() - flo.asFloat()));
15324
15325                 // [ e g h ]
15326                 // [ i k l ]
15327                 // [ m o p ]
15328                 const fp16type  ekp             (e * k * p);
15329                 const fp16type  glm             (g * l * m);
15330                 const fp16type  hio             (h * i * o);
15331                 const fp16type  hkm             (h * k * m);
15332                 const fp16type  gip             (g * i * p);
15333                 const fp16type  elo             (e * l * o);
15334                 const fp16type  detB    (b * (ekp.asFloat() + glm.asFloat() + hio.asFloat() - hkm.asFloat() - gip.asFloat() - elo.asFloat()));
15335
15336                 // [ e f h ]
15337                 // [ i j l ]
15338                 // [ m n p ]
15339                 const fp16type  ejp             (e * j * p);
15340                 const fp16type  flm             (f * l * m);
15341                 const fp16type  hin             (h * i * n);
15342                 const fp16type  hjm             (h * j * m);
15343                 const fp16type  fip             (f * i * p);
15344                 const fp16type  eln             (e * l * n);
15345                 const fp16type  detC    (c * (ejp.asFloat() + flm.asFloat() + hin.asFloat() - hjm.asFloat() - fip.asFloat() - eln.asFloat()));
15346
15347                 // [ e f g ]
15348                 // [ i j k ]
15349                 // [ m n o ]
15350                 const fp16type  ejo             (e * j * o);
15351                 const fp16type  fkm             (f * k * m);
15352                 const fp16type  gin             (g * i * n);
15353                 const fp16type  gjm             (g * j * m);
15354                 const fp16type  fio             (f * i * o);
15355                 const fp16type  ekn             (e * k * n);
15356                 const fp16type  detD    (d * (ejo.asFloat() + fkm.asFloat() + gin.asFloat() - gjm.asFloat() - fio.asFloat() - ekn.asFloat()));
15357
15358                 const float             r               (detA.asFloat() - detB.asFloat() + detC.asFloat() - detD.asFloat());
15359                 const fp16type  rf16    (r);
15360
15361                 out[0] = rf16.bits();
15362                 min[0] = getMin(r, getULPs(in));
15363                 max[0] = getMax(r, getULPs(in));
15364
15365                 return true;
15366         }
15367 };
15368
15369 template<size_t size>
15370 struct fp16Inverse;
15371
15372 template<>
15373 struct fp16Inverse<2> : public fp16MatrixBase
15374 {
15375         virtual double getULPs (vector<const deFloat16*>& in)
15376         {
15377                 DE_UNREF(in);
15378
15379                 return 128.0; // This is not a precision test. Value is not from spec
15380         }
15381
15382         deUint32 getComponentValidity ()
15383         {
15384                 return getComponentMatrixValidityMask(2, 2);
15385         }
15386
15387         template<class fp16type>
15388         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15389         {
15390                 const size_t    cols            = 2;
15391                 const size_t    rows            = 2;
15392                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15393                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15394
15395                 DE_ASSERT(in.size() == 1);
15396                 DE_ASSERT(getOutCompCount() == alignedRows * alignedCols);
15397                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15398                 DE_UNREF(alignedCols);
15399
15400                 // [ a b ]
15401                 // [ c d ]
15402                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15403                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15404                 const float             c               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15405                 const float             d               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15406                 const float             ad              (a * d);
15407                 const fp16type  adf16   (ad);
15408                 const float             bc              (b * c);
15409                 const fp16type  bcf16   (bc);
15410                 const float             det             (adf16.asFloat() - bcf16.asFloat());
15411                 const fp16type  det16   (det);
15412
15413                 out[0] = fp16type( d / det16.asFloat()).bits();
15414                 out[1] = fp16type(-c / det16.asFloat()).bits();
15415                 out[2] = fp16type(-b / det16.asFloat()).bits();
15416                 out[3] = fp16type( a / det16.asFloat()).bits();
15417
15418                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15419                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15420                         {
15421                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
15422                                 const fp16type  s       (out[ndx]);
15423
15424                                 min[ndx] = getMin(s.asDouble(), getULPs(in));
15425                                 max[ndx] = getMax(s.asDouble(), getULPs(in));
15426                         }
15427
15428                 return true;
15429         }
15430 };
15431
15432 inline std::string fp16ToString(deFloat16 val)
15433 {
15434         return tcu::toHex<4>(val).toString() + " (" + de::floatToString(tcu::Float16(val).asFloat(), 10) + ")";
15435 }
15436
15437 template <size_t RES_COMPONENTS, size_t ARG0_COMPONENTS, size_t ARG1_COMPONENTS, size_t ARG2_COMPONENTS, class TestedArithmeticFunction>
15438 bool compareFP16ArithmeticFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
15439 {
15440         if (inputs.size() < 1 || inputs.size() > 3 || outputAllocs.size() != 1 || expectedOutputs.size() != 1)
15441                 return false;
15442
15443         const size_t    resultStep                      = (RES_COMPONENTS == 3) ? 4 : RES_COMPONENTS;
15444         const size_t    iterationsCount         = expectedOutputs[0].getByteSize() / (sizeof(deFloat16) * resultStep);
15445         const size_t    inputsSteps[3]          =
15446         {
15447                 (ARG0_COMPONENTS == 3) ? 4 : ARG0_COMPONENTS,
15448                 (ARG1_COMPONENTS == 3) ? 4 : ARG1_COMPONENTS,
15449                 (ARG2_COMPONENTS == 3) ? 4 : ARG2_COMPONENTS,
15450         };
15451
15452         DE_ASSERT(expectedOutputs[0].getByteSize() > 0);
15453         DE_ASSERT(expectedOutputs[0].getByteSize() == sizeof(deFloat16) * iterationsCount * resultStep);
15454
15455         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15456         {
15457                 DE_ASSERT(inputs[inputNdx].getByteSize() > 0);
15458                 DE_ASSERT(inputs[inputNdx].getByteSize() == sizeof(deFloat16) * iterationsCount * inputsSteps[inputNdx]);
15459         }
15460
15461         const deFloat16* const          outputAsFP16                                    = (const deFloat16*)outputAllocs[0]->getHostPtr();
15462         TestedArithmeticFunction        func;
15463
15464         func.setOutCompCount(RES_COMPONENTS);
15465         func.setArgCompCount(0, ARG0_COMPONENTS);
15466         func.setArgCompCount(1, ARG1_COMPONENTS);
15467         func.setArgCompCount(2, ARG2_COMPONENTS);
15468
15469         const bool                                      callOncePerComponent                    = func.callOncePerComponent();
15470         const deUint32                          componentValidityMask                   = func.getComponentValidity();
15471         const size_t                            denormModesCount                                = 2;
15472         const char*                                     denormModes[denormModesCount]   = { "keep denormal numbers", "flush to zero" };
15473         const size_t                            successfulRunsPerComponent              = denormModesCount * func.getFlavorCount();
15474         bool                                            success                                                 = true;
15475         size_t                                          validatedCount                                  = 0;
15476
15477         vector<deUint8> inputBytes[3];
15478
15479         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15480                 inputs[inputNdx].getBytes(inputBytes[inputNdx]);
15481
15482         const deFloat16* const                  inputsAsFP16[3]                 =
15483         {
15484                 inputs.size() >= 1 ? (const deFloat16*)&inputBytes[0][0] : DE_NULL,
15485                 inputs.size() >= 2 ? (const deFloat16*)&inputBytes[1][0] : DE_NULL,
15486                 inputs.size() >= 3 ? (const deFloat16*)&inputBytes[2][0] : DE_NULL,
15487         };
15488
15489         for (size_t idx = 0; idx < iterationsCount; ++idx)
15490         {
15491                 std::vector<size_t>                     successfulRuns          (RES_COMPONENTS, successfulRunsPerComponent);
15492                 std::vector<std::string>        errors                          (RES_COMPONENTS);
15493                 bool                                            iterationValidated      (true);
15494
15495                 for (size_t denormNdx = 0; denormNdx < 2; ++denormNdx)
15496                 {
15497                         for (size_t flavorNdx = 0; flavorNdx < func.getFlavorCount(); ++flavorNdx)
15498                         {
15499                                 func.setFlavor(flavorNdx);
15500
15501                                 const deFloat16*                        iterationOutputFP16             = &outputAsFP16[idx * resultStep];
15502                                 vector<deFloat16>                       iterationCalculatedFP16 (resultStep, 0);
15503                                 vector<double>                          iterationEdgeMin                (resultStep, 0.0);
15504                                 vector<double>                          iterationEdgeMax                (resultStep, 0.0);
15505                                 vector<const deFloat16*>        arguments;
15506
15507                                 for (size_t componentNdx = 0; componentNdx < RES_COMPONENTS; ++componentNdx)
15508                                 {
15509                                         std::string     error;
15510                                         bool            reportError = false;
15511
15512                                         if (callOncePerComponent || componentNdx == 0)
15513                                         {
15514                                                 bool funcCallResult;
15515
15516                                                 arguments.clear();
15517
15518                                                 for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15519                                                         arguments.push_back(&inputsAsFP16[inputNdx][idx * inputsSteps[inputNdx] + componentNdx]);
15520
15521                                                 if (denormNdx == 0)
15522                                                         funcCallResult = func.template calc<tcu::Float16>(arguments, &iterationCalculatedFP16[componentNdx], &iterationEdgeMin[componentNdx], &iterationEdgeMax[componentNdx]);
15523                                                 else
15524                                                         funcCallResult = func.template calc<tcu::Float16Denormless>(arguments, &iterationCalculatedFP16[componentNdx], &iterationEdgeMin[componentNdx], &iterationEdgeMax[componentNdx]);
15525
15526                                                 if (!funcCallResult)
15527                                                 {
15528                                                         iterationValidated = false;
15529
15530                                                         if (callOncePerComponent)
15531                                                                 continue;
15532                                                         else
15533                                                                 break;
15534                                                 }
15535                                         }
15536
15537                                         if ((componentValidityMask != 0) && (componentValidityMask & (1<<componentNdx)) == 0)
15538                                                 continue;
15539
15540                                         reportError = !compare16BitFloat(iterationCalculatedFP16[componentNdx], iterationOutputFP16[componentNdx], error);
15541
15542                                         if (reportError)
15543                                         {
15544                                                 tcu::Float16 expected   (iterationCalculatedFP16[componentNdx]);
15545                                                 tcu::Float16 outputted  (iterationOutputFP16[componentNdx]);
15546
15547                                                 if (reportError && expected.isNaN())
15548                                                         reportError = false;
15549
15550                                                 if (reportError && !expected.isNaN() && !outputted.isNaN())
15551                                                 {
15552                                                         if (reportError && !expected.isInf() && !outputted.isInf())
15553                                                         {
15554                                                                 // Ignore rounding
15555                                                                 if (expected.bits() == outputted.bits() + 1 || expected.bits() + 1 == outputted.bits())
15556                                                                         reportError = false;
15557                                                         }
15558
15559                                                         if (reportError && expected.isInf())
15560                                                         {
15561                                                                 // RTZ rounding mode returns +/-65504 instead of Inf on overflow
15562                                                                 if (expected.sign() == 1 && outputted.bits() == 0x7bff && iterationEdgeMin[componentNdx] <= std::numeric_limits<double>::max())
15563                                                                         reportError = false;
15564                                                                 else if (expected.sign() == -1 && outputted.bits() == 0xfbff && iterationEdgeMax[componentNdx] >= -std::numeric_limits<double>::max())
15565                                                                         reportError = false;
15566                                                         }
15567
15568                                                         if (reportError)
15569                                                         {
15570                                                                 const double    outputtedDouble = outputted.asDouble();
15571
15572                                                                 DE_ASSERT(iterationEdgeMin[componentNdx] <= iterationEdgeMax[componentNdx]);
15573
15574                                                                 if (de::inRange(outputtedDouble, iterationEdgeMin[componentNdx], iterationEdgeMax[componentNdx]))
15575                                                                         reportError = false;
15576                                                         }
15577                                                 }
15578
15579                                                 if (reportError)
15580                                                 {
15581                                                         const size_t            inputsComps[3]  =
15582                                                         {
15583                                                                 ARG0_COMPONENTS,
15584                                                                 ARG1_COMPONENTS,
15585                                                                 ARG2_COMPONENTS,
15586                                                         };
15587                                                         string                          inputsValues    ("Inputs:");
15588                                                         string                          flavorName              (func.getFlavorCount() == 1 ? "" : string(" flavor ") + de::toString(flavorNdx) + " (" + func.getCurrentFlavorName() + ")");
15589                                                         std::stringstream       errStream;
15590
15591                                                         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15592                                                         {
15593                                                                 const size_t    inputCompsCount = inputsComps[inputNdx];
15594
15595                                                                 inputsValues += " [" + de::toString(inputNdx) + "]=(";
15596
15597                                                                 for (size_t compNdx = 0; compNdx < inputCompsCount; ++compNdx)
15598                                                                 {
15599                                                                         const deFloat16 inputComponentValue = inputsAsFP16[inputNdx][idx * inputsSteps[inputNdx] + compNdx];
15600
15601                                                                         inputsValues += fp16ToString(inputComponentValue) + ((compNdx + 1 == inputCompsCount) ? ")": ", ");
15602                                                                 }
15603                                                         }
15604
15605                                                         errStream       << "At"
15606                                                                                 << " iteration " << de::toString(idx)
15607                                                                                 << " component " << de::toString(componentNdx)
15608                                                                                 << " denormMode " << de::toString(denormNdx)
15609                                                                                 << " (" << denormModes[denormNdx] << ")"
15610                                                                                 << " " << flavorName
15611                                                                                 << " " << inputsValues
15612                                                                                 << " outputted:" + fp16ToString(iterationOutputFP16[componentNdx])
15613                                                                                 << " expected:" + fp16ToString(iterationCalculatedFP16[componentNdx])
15614                                                                                 << " or in range: [" << iterationEdgeMin[componentNdx] << ", " << iterationEdgeMax[componentNdx] << "]."
15615                                                                                 << " " << error << "."
15616                                                                                 << std::endl;
15617
15618                                                         errors[componentNdx] += errStream.str();
15619
15620                                                         successfulRuns[componentNdx]--;
15621                                                 }
15622                                         }
15623                                 }
15624                         }
15625                 }
15626
15627                 for (size_t componentNdx = 0; componentNdx < RES_COMPONENTS; ++componentNdx)
15628                 {
15629                         // Check if any component has total failure
15630                         if (successfulRuns[componentNdx] == 0)
15631                         {
15632                                 // Test failed in all denorm modes and all flavors for certain component: dump errors
15633                                 log << TestLog::Message << errors[componentNdx] << TestLog::EndMessage;
15634
15635                                 success = false;
15636                         }
15637                 }
15638
15639                 if (iterationValidated)
15640                         validatedCount++;
15641         }
15642
15643         if (validatedCount < 16)
15644                 TCU_THROW(InternalError, "Too few samples has been validated.");
15645
15646         return success;
15647 }
15648
15649 // IEEE-754 floating point numbers:
15650 // +--------+------+----------+-------------+
15651 // | binary | sign | exponent | significand |
15652 // +--------+------+----------+-------------+
15653 // | 16-bit |  1   |    5     |     10      |
15654 // +--------+------+----------+-------------+
15655 // | 32-bit |  1   |    8     |     23      |
15656 // +--------+------+----------+-------------+
15657 //
15658 // 16-bit floats:
15659 //
15660 // 0   000 00   00 0000 0001 (0x0001: 2e-24:         minimum positive denormalized)
15661 // 0   000 00   11 1111 1111 (0x03ff: 2e-14 - 2e-24: maximum positive denormalized)
15662 // 0   000 01   00 0000 0000 (0x0400: 2e-14:         minimum positive normalized)
15663 // 0   111 10   11 1111 1111 (0x7bff: 65504:         maximum positive normalized)
15664 //
15665 // 0   000 00   00 0000 0000 (0x0000: +0)
15666 // 0   111 11   00 0000 0000 (0x7c00: +Inf)
15667 // 0   000 00   11 1111 0000 (0x03f0: +Denorm)
15668 // 0   000 01   00 0000 0001 (0x0401: +Norm)
15669 // 0   111 11   00 0000 1111 (0x7c0f: +SNaN)
15670 // 0   111 11   11 1111 0000 (0x7ff0: +QNaN)
15671 // Generate and return 16-bit floats and their corresponding 32-bit values.
15672 //
15673 // The first 14 number pairs are manually picked, while the rest are randomly generated.
15674 // Expected count to be at least 14 (numPicks).
15675 vector<deFloat16> getFloat16a (de::Random& rnd, deUint32 count)
15676 {
15677         vector<deFloat16>       float16;
15678
15679         float16.reserve(count);
15680
15681         // Zero
15682         float16.push_back(deUint16(0x0000));
15683         float16.push_back(deUint16(0x8000));
15684         // Infinity
15685         float16.push_back(deUint16(0x7c00));
15686         float16.push_back(deUint16(0xfc00));
15687         // Normalized
15688         float16.push_back(deUint16(0x0401));
15689         float16.push_back(deUint16(0x8401));
15690         // Some normal number
15691         float16.push_back(deUint16(0x14cb));
15692         float16.push_back(deUint16(0x94cb));
15693         // Min/max positive normal
15694         float16.push_back(deUint16(0x0400));
15695         float16.push_back(deUint16(0x7bff));
15696         // Min/max negative normal
15697         float16.push_back(deUint16(0x8400));
15698         float16.push_back(deUint16(0xfbff));
15699         // PI
15700         float16.push_back(deUint16(0x4248)); // 3.140625
15701         float16.push_back(deUint16(0xb248)); // -3.140625
15702         // PI/2
15703         float16.push_back(deUint16(0x3e48)); // 1.5703125
15704         float16.push_back(deUint16(0xbe48)); // -1.5703125
15705         float16.push_back(deUint16(0x3c00)); // 1.0
15706         float16.push_back(deUint16(0x3800)); // 0.5
15707         // Some useful constants
15708         float16.push_back(tcu::Float16(-2.5f).bits());
15709         float16.push_back(tcu::Float16(-1.0f).bits());
15710         float16.push_back(tcu::Float16( 0.4f).bits());
15711         float16.push_back(tcu::Float16( 2.5f).bits());
15712
15713         const deUint32          numPicks        = static_cast<deUint32>(float16.size());
15714
15715         DE_ASSERT(count >= numPicks);
15716         count -= numPicks;
15717
15718         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
15719         {
15720                 int                     sign            = (rnd.getUint16() % 2 == 0) ? +1 : -1;
15721                 int                     exponent        = (rnd.getUint16() % 29) - 14 + 1;
15722                 deUint16        mantissa        = static_cast<deUint16>(2 * (rnd.getUint16() % 512));
15723
15724                 // Exclude power of -14 to avoid denorms
15725                 DE_ASSERT(de::inRange(exponent, -13, 15));
15726
15727                 float16.push_back(tcu::Float16::constructBits(sign, exponent, mantissa).bits());
15728         }
15729
15730         return float16;
15731 }
15732
15733 static inline vector<deFloat16> getInputData1 (deUint32 seed, size_t count, size_t argNo)
15734 {
15735         DE_UNREF(argNo);
15736
15737         de::Random      rnd(seed);
15738
15739         return getFloat16a(rnd, static_cast<deUint32>(count));
15740 }
15741
15742 static inline vector<deFloat16> getInputData2 (deUint32 seed, size_t count, size_t argNo)
15743 {
15744         de::Random      rnd             (seed);
15745         size_t          newCount = static_cast<size_t>(deSqrt(double(count)));
15746
15747         DE_ASSERT(newCount * newCount == count);
15748
15749         vector<deFloat16>       float16 = getFloat16a(rnd, static_cast<deUint32>(newCount));
15750
15751         return squarize(float16, static_cast<deUint32>(argNo));
15752 }
15753
15754 static inline vector<deFloat16> getInputData3 (deUint32 seed, size_t count, size_t argNo)
15755 {
15756         if (argNo == 0 || argNo == 1)
15757                 return getInputData2(seed, count, argNo);
15758         else
15759                 return getInputData1(seed<<argNo, count, argNo);
15760 }
15761
15762 vector<deFloat16> getInputData (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15763 {
15764         DE_UNREF(stride);
15765
15766         vector<deFloat16>       result;
15767
15768         switch (argCount)
15769         {
15770                 case 1:result = getInputData1(seed, count, argNo); break;
15771                 case 2:result = getInputData2(seed, count, argNo); break;
15772                 case 3:result = getInputData3(seed, count, argNo); break;
15773                 default: TCU_THROW(InternalError, "Invalid argument count specified");
15774         }
15775
15776         if (compCount == 3)
15777         {
15778                 const size_t            newCount = (3 * count) / 4;
15779                 vector<deFloat16>       newResult;
15780
15781                 newResult.reserve(result.size());
15782
15783                 for (size_t ndx = 0; ndx < newCount; ++ndx)
15784                 {
15785                         newResult.push_back(result[ndx]);
15786
15787                         if (ndx % 3 == 2)
15788                                 newResult.push_back(0);
15789                 }
15790
15791                 result = newResult;
15792         }
15793
15794         DE_ASSERT(result.size() == count);
15795
15796         return result;
15797 }
15798
15799 // Generator for functions requiring data in range [1, inf]
15800 vector<deFloat16> getInputDataAC (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15801 {
15802         vector<deFloat16>       result;
15803
15804         result = getInputData(seed, count, compCount, stride, argCount, argNo);
15805
15806         // Filter out values below 1.0 from upper half of numbers
15807         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15808         {
15809                 const float f = tcu::Float16(result[idx]).asFloat();
15810
15811                 if (f < 1.0f)
15812                         result[idx] = tcu::Float16(1.0f - f).bits();
15813         }
15814
15815         return result;
15816 }
15817
15818 // Generator for functions requiring data in range [-1, 1]
15819 vector<deFloat16> getInputDataA (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15820 {
15821         vector<deFloat16>       result;
15822
15823         result = getInputData(seed, count, compCount, stride, argCount, argNo);
15824
15825         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15826         {
15827                 const float f = tcu::Float16(result[idx]).asFloat();
15828
15829                 if (!de::inRange(f, -1.0f, 1.0f))
15830                         result[idx] = tcu::Float16(deFloatFrac(f)).bits();
15831         }
15832
15833         return result;
15834 }
15835
15836 // Generator for functions requiring data in range [-pi, pi]
15837 vector<deFloat16> getInputDataPI (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15838 {
15839         vector<deFloat16>       result;
15840
15841         result = getInputData(seed, count, compCount, stride, argCount, argNo);
15842
15843         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15844         {
15845                 const float f = tcu::Float16(result[idx]).asFloat();
15846
15847                 if (!de::inRange(f, -DE_PI, DE_PI))
15848                         result[idx] = tcu::Float16(fmodf(f, DE_PI)).bits();
15849         }
15850
15851         return result;
15852 }
15853
15854 // Generator for functions requiring data in range [0, inf]
15855 vector<deFloat16> getInputDataP (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15856 {
15857         vector<deFloat16>       result;
15858
15859         result = getInputData(seed, count, compCount, stride, argCount, argNo);
15860
15861         if (argNo == 0)
15862         {
15863                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15864                         result[idx] &= static_cast<deFloat16>(~0x8000);
15865         }
15866
15867         return result;
15868 }
15869
15870 vector<deFloat16> getInputDataV (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15871 {
15872         DE_UNREF(stride);
15873         DE_UNREF(argCount);
15874
15875         vector<deFloat16>       result;
15876
15877         if (argNo == 0)
15878                 result = getInputData2(seed, count, argNo);
15879         else
15880         {
15881                 const size_t            alignedCount    = (compCount == 3) ? 4 : compCount;
15882                 const size_t            newCountX               = static_cast<size_t>(deSqrt(double(count * alignedCount)));
15883                 const size_t            newCountY               = count / newCountX;
15884                 de::Random                      rnd                             (seed);
15885                 vector<deFloat16>       float16                 = getFloat16a(rnd, static_cast<deUint32>(newCountX));
15886
15887                 DE_ASSERT(newCountX * newCountX == alignedCount * count);
15888
15889                 for (size_t numIdx = 0; numIdx < newCountX; ++numIdx)
15890                 {
15891                         const vector<deFloat16> tmp(newCountY, float16[numIdx]);
15892
15893                         result.insert(result.end(), tmp.begin(), tmp.end());
15894                 }
15895         }
15896
15897         DE_ASSERT(result.size() == count);
15898
15899         return result;
15900 }
15901
15902 vector<deFloat16> getInputDataM (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15903 {
15904         DE_UNREF(compCount);
15905         DE_UNREF(stride);
15906         DE_UNREF(argCount);
15907
15908         de::Random                      rnd             (seed << argNo);
15909         vector<deFloat16>       result;
15910
15911         result = getFloat16a(rnd, static_cast<deUint32>(count));
15912
15913         DE_ASSERT(result.size() == count);
15914
15915         return result;
15916 }
15917
15918 vector<deFloat16> getInputDataD (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15919 {
15920         DE_UNREF(compCount);
15921         DE_UNREF(argCount);
15922
15923         de::Random                      rnd             (seed << argNo);
15924         vector<deFloat16>       result;
15925
15926         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
15927         {
15928                 int num = (rnd.getUint16() % 16) - 8;
15929
15930                 result.push_back(tcu::Float16(float(num)).bits());
15931         }
15932
15933         result[0 * stride] = deUint16(0x7c00); // +Inf
15934         result[1 * stride] = deUint16(0xfc00); // -Inf
15935
15936         DE_ASSERT(result.size() == count);
15937
15938         return result;
15939 }
15940
15941 // Generator for smoothstep function
15942 vector<deFloat16> getInputDataSS (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15943 {
15944         vector<deFloat16>       result;
15945
15946         result = getInputDataD(seed, count, compCount, stride, argCount, argNo);
15947
15948         if (argNo == 0)
15949         {
15950                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15951                 {
15952                         const float f = tcu::Float16(result[idx]).asFloat();
15953
15954                         if (f > 4.0f)
15955                                 result[idx] = tcu::Float16(-f).bits();
15956                 }
15957         }
15958
15959         if (argNo == 1)
15960         {
15961                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15962                 {
15963                         const float f = tcu::Float16(result[idx]).asFloat();
15964
15965                         if (f < 4.0f)
15966                                 result[idx] = tcu::Float16(-f).bits();
15967                 }
15968         }
15969
15970         return result;
15971 }
15972
15973 // Generates normalized vectors for arguments 0 and 1
15974 vector<deFloat16> getInputDataN (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15975 {
15976         DE_UNREF(compCount);
15977         DE_UNREF(argCount);
15978
15979         de::Random                      rnd             (seed << argNo);
15980         vector<deFloat16>       result;
15981
15982         if (argNo == 0 || argNo == 1)
15983         {
15984                 // The input parameters for the incident vector I and the surface normal N must already be normalized
15985                 for (size_t numIdx = 0; numIdx < count; numIdx += stride)
15986                 {
15987                         vector <float>  unnormolized;
15988                         float                   sum                             = 0;
15989
15990                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
15991                                 unnormolized.push_back(float((rnd.getUint16() % 16) - 8));
15992
15993                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
15994                                 sum += unnormolized[compIdx] * unnormolized[compIdx];
15995
15996                         sum = deFloatSqrt(sum);
15997                         if (sum == 0.0f)
15998                                 unnormolized[0] = sum = 1.0f;
15999
16000                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
16001                                 result.push_back(tcu::Float16(unnormolized[compIdx] / sum).bits());
16002
16003                         for (size_t compIdx = compCount; compIdx < stride; ++compIdx)
16004                                 result.push_back(0);
16005                 }
16006         }
16007         else
16008         {
16009                 // Input parameter eta
16010                 for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
16011                 {
16012                         int num = (rnd.getUint16() % 16) - 8;
16013
16014                         result.push_back(tcu::Float16(float(num)).bits());
16015                 }
16016         }
16017
16018         DE_ASSERT(result.size() == count);
16019
16020         return result;
16021 }
16022
16023 // Data generator for complex matrix functions like determinant and inverse
16024 vector<deFloat16> getInputDataC (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16025 {
16026         DE_UNREF(compCount);
16027         DE_UNREF(stride);
16028         DE_UNREF(argCount);
16029
16030         de::Random                      rnd             (seed << argNo);
16031         vector<deFloat16>       result;
16032
16033         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
16034         {
16035                 int num = (rnd.getUint16() % 16) - 8;
16036
16037                 result.push_back(tcu::Float16(float(num)).bits());
16038         }
16039
16040         DE_ASSERT(result.size() == count);
16041
16042         return result;
16043 }
16044
16045 struct Math16TestType
16046 {
16047         const char*             typePrefix;
16048         const size_t    typeComponents;
16049         const size_t    typeArrayStride;
16050         const size_t    typeStructStride;
16051 };
16052
16053 enum Math16DataTypes
16054 {
16055         NONE    = 0,
16056         SCALAR  = 1,
16057         VEC2    = 2,
16058         VEC3    = 3,
16059         VEC4    = 4,
16060         MAT2X2,
16061         MAT2X3,
16062         MAT2X4,
16063         MAT3X2,
16064         MAT3X3,
16065         MAT3X4,
16066         MAT4X2,
16067         MAT4X3,
16068         MAT4X4,
16069         MATH16_TYPE_LAST
16070 };
16071
16072 struct Math16ArgFragments
16073 {
16074         const char*     bodies;
16075         const char*     variables;
16076         const char*     decorations;
16077         const char*     funcVariables;
16078 };
16079
16080 typedef vector<deFloat16> Math16GetInputData (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo);
16081
16082 struct Math16TestFunc
16083 {
16084         const char*                                     funcName;
16085         const char*                                     funcSuffix;
16086         size_t                                          funcArgsCount;
16087         size_t                                          typeResult;
16088         size_t                                          typeArg0;
16089         size_t                                          typeArg1;
16090         size_t                                          typeArg2;
16091         Math16GetInputData*                     getInputDataFunc;
16092         VerifyIOFunc                            verifyFunc;
16093 };
16094
16095 template<class SpecResource>
16096 void createFloat16ArithmeticFuncTest (tcu::TestContext& testCtx, tcu::TestCaseGroup& testGroup, const size_t testTypeIdx, const Math16TestFunc& testFunc)
16097 {
16098         const int                                       testSpecificSeed                        = deStringHash(testGroup.getName());
16099         const int                                       seed                                            = testCtx.getCommandLine().getBaseSeed() ^ testSpecificSeed;
16100         const size_t                            numDataPointsByAxis                     = 32;
16101         const size_t                            numDataPoints                           = numDataPointsByAxis * numDataPointsByAxis;
16102         const char*                                     componentType                           = "f16";
16103         const Math16TestType            testTypes[MATH16_TYPE_LAST]     =
16104         {
16105                 { "",           0,       0,                                              0,                                             },
16106                 { "",           1,       1 * sizeof(deFloat16),  2 * sizeof(deFloat16)  },
16107                 { "v2",         2,       2 * sizeof(deFloat16),  2 * sizeof(deFloat16)  },
16108                 { "v3",         3,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
16109                 { "v4",         4,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
16110                 { "m2x2",       0,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
16111                 { "m2x3",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16112                 { "m2x4",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16113                 { "m3x2",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16114                 { "m3x3",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16115                 { "m3x4",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16116                 { "m4x2",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16117                 { "m4x3",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16118                 { "m4x4",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16119         };
16120
16121         DE_ASSERT(testTypeIdx == testTypes[testTypeIdx].typeComponents);
16122
16123
16124         const StringTemplate preMain
16125         (
16126                 "     %c_i32_ndp  = OpConstant %i32 ${num_data_points}\n"
16127
16128                 "        %f16     = OpTypeFloat 16\n"
16129                 "        %v2f16   = OpTypeVector %f16 2\n"
16130                 "        %v3f16   = OpTypeVector %f16 3\n"
16131                 "        %v4f16   = OpTypeVector %f16 4\n"
16132                 "        %m2x2f16 = OpTypeMatrix %v2f16 2\n"
16133                 "        %m2x3f16 = OpTypeMatrix %v3f16 2\n"
16134                 "        %m2x4f16 = OpTypeMatrix %v4f16 2\n"
16135                 "        %m3x2f16 = OpTypeMatrix %v2f16 3\n"
16136                 "        %m3x3f16 = OpTypeMatrix %v3f16 3\n"
16137                 "        %m3x4f16 = OpTypeMatrix %v4f16 3\n"
16138                 "        %m4x2f16 = OpTypeMatrix %v2f16 4\n"
16139                 "        %m4x3f16 = OpTypeMatrix %v3f16 4\n"
16140                 "        %m4x4f16 = OpTypeMatrix %v4f16 4\n"
16141
16142                 "     %up_f16     = OpTypePointer Uniform %f16    \n"
16143                 "     %up_v2f16   = OpTypePointer Uniform %v2f16  \n"
16144                 "     %up_v3f16   = OpTypePointer Uniform %v3f16  \n"
16145                 "     %up_v4f16   = OpTypePointer Uniform %v4f16  \n"
16146                 "     %up_m2x2f16 = OpTypePointer Uniform %m2x2f16\n"
16147                 "     %up_m2x3f16 = OpTypePointer Uniform %m2x3f16\n"
16148                 "     %up_m2x4f16 = OpTypePointer Uniform %m2x4f16\n"
16149                 "     %up_m3x2f16 = OpTypePointer Uniform %m3x2f16\n"
16150                 "     %up_m3x3f16 = OpTypePointer Uniform %m3x3f16\n"
16151                 "     %up_m3x4f16 = OpTypePointer Uniform %m3x4f16\n"
16152                 "     %up_m4x2f16 = OpTypePointer Uniform %m4x2f16\n"
16153                 "     %up_m4x3f16 = OpTypePointer Uniform %m4x3f16\n"
16154                 "     %up_m4x4f16 = OpTypePointer Uniform %m4x4f16\n"
16155
16156                 "     %ra_f16     = OpTypeArray %f16     %c_i32_ndp\n"
16157                 "     %ra_v2f16   = OpTypeArray %v2f16   %c_i32_ndp\n"
16158                 "     %ra_v3f16   = OpTypeArray %v3f16   %c_i32_ndp\n"
16159                 "     %ra_v4f16   = OpTypeArray %v4f16   %c_i32_ndp\n"
16160                 "     %ra_m2x2f16 = OpTypeArray %m2x2f16 %c_i32_ndp\n"
16161                 "     %ra_m2x3f16 = OpTypeArray %m2x3f16 %c_i32_ndp\n"
16162                 "     %ra_m2x4f16 = OpTypeArray %m2x4f16 %c_i32_ndp\n"
16163                 "     %ra_m3x2f16 = OpTypeArray %m3x2f16 %c_i32_ndp\n"
16164                 "     %ra_m3x3f16 = OpTypeArray %m3x3f16 %c_i32_ndp\n"
16165                 "     %ra_m3x4f16 = OpTypeArray %m3x4f16 %c_i32_ndp\n"
16166                 "     %ra_m4x2f16 = OpTypeArray %m4x2f16 %c_i32_ndp\n"
16167                 "     %ra_m4x3f16 = OpTypeArray %m4x3f16 %c_i32_ndp\n"
16168                 "     %ra_m4x4f16 = OpTypeArray %m4x4f16 %c_i32_ndp\n"
16169
16170                 "   %SSBO_f16     = OpTypeStruct %ra_f16    \n"
16171                 "   %SSBO_v2f16   = OpTypeStruct %ra_v2f16  \n"
16172                 "   %SSBO_v3f16   = OpTypeStruct %ra_v3f16  \n"
16173                 "   %SSBO_v4f16   = OpTypeStruct %ra_v4f16  \n"
16174                 "   %SSBO_m2x2f16 = OpTypeStruct %ra_m2x2f16\n"
16175                 "   %SSBO_m2x3f16 = OpTypeStruct %ra_m2x3f16\n"
16176                 "   %SSBO_m2x4f16 = OpTypeStruct %ra_m2x4f16\n"
16177                 "   %SSBO_m3x2f16 = OpTypeStruct %ra_m3x2f16\n"
16178                 "   %SSBO_m3x3f16 = OpTypeStruct %ra_m3x3f16\n"
16179                 "   %SSBO_m3x4f16 = OpTypeStruct %ra_m3x4f16\n"
16180                 "   %SSBO_m4x2f16 = OpTypeStruct %ra_m4x2f16\n"
16181                 "   %SSBO_m4x3f16 = OpTypeStruct %ra_m4x3f16\n"
16182                 "   %SSBO_m4x4f16 = OpTypeStruct %ra_m4x4f16\n"
16183
16184                 "%up_SSBO_f16     = OpTypePointer Uniform %SSBO_f16    \n"
16185                 "%up_SSBO_v2f16   = OpTypePointer Uniform %SSBO_v2f16  \n"
16186                 "%up_SSBO_v3f16   = OpTypePointer Uniform %SSBO_v3f16  \n"
16187                 "%up_SSBO_v4f16   = OpTypePointer Uniform %SSBO_v4f16  \n"
16188                 "%up_SSBO_m2x2f16 = OpTypePointer Uniform %SSBO_m2x2f16\n"
16189                 "%up_SSBO_m2x3f16 = OpTypePointer Uniform %SSBO_m2x3f16\n"
16190                 "%up_SSBO_m2x4f16 = OpTypePointer Uniform %SSBO_m2x4f16\n"
16191                 "%up_SSBO_m3x2f16 = OpTypePointer Uniform %SSBO_m3x2f16\n"
16192                 "%up_SSBO_m3x3f16 = OpTypePointer Uniform %SSBO_m3x3f16\n"
16193                 "%up_SSBO_m3x4f16 = OpTypePointer Uniform %SSBO_m3x4f16\n"
16194                 "%up_SSBO_m4x2f16 = OpTypePointer Uniform %SSBO_m4x2f16\n"
16195                 "%up_SSBO_m4x3f16 = OpTypePointer Uniform %SSBO_m4x3f16\n"
16196                 "%up_SSBO_m4x4f16 = OpTypePointer Uniform %SSBO_m4x4f16\n"
16197
16198                 "       %fp_v2i32 = OpTypePointer Function %v2i32\n"
16199                 "       %fp_v3i32 = OpTypePointer Function %v3i32\n"
16200                 "       %fp_v4i32 = OpTypePointer Function %v4i32\n"
16201                 "${arg_vars}"
16202         );
16203
16204         const StringTemplate decoration
16205         (
16206                 "OpDecorate %ra_f16     ArrayStride 2 \n"
16207                 "OpDecorate %ra_v2f16   ArrayStride 4 \n"
16208                 "OpDecorate %ra_v3f16   ArrayStride 8 \n"
16209                 "OpDecorate %ra_v4f16   ArrayStride 8 \n"
16210                 "OpDecorate %ra_m2x2f16 ArrayStride 8 \n"
16211                 "OpDecorate %ra_m2x3f16 ArrayStride 16\n"
16212                 "OpDecorate %ra_m2x4f16 ArrayStride 16\n"
16213                 "OpDecorate %ra_m3x2f16 ArrayStride 16\n"
16214                 "OpDecorate %ra_m3x3f16 ArrayStride 32\n"
16215                 "OpDecorate %ra_m3x4f16 ArrayStride 32\n"
16216                 "OpDecorate %ra_m4x2f16 ArrayStride 16\n"
16217                 "OpDecorate %ra_m4x3f16 ArrayStride 32\n"
16218                 "OpDecorate %ra_m4x4f16 ArrayStride 32\n"
16219
16220                 "OpMemberDecorate %SSBO_f16     0 Offset 0\n"
16221                 "OpMemberDecorate %SSBO_v2f16   0 Offset 0\n"
16222                 "OpMemberDecorate %SSBO_v3f16   0 Offset 0\n"
16223                 "OpMemberDecorate %SSBO_v4f16   0 Offset 0\n"
16224                 "OpMemberDecorate %SSBO_m2x2f16 0 Offset 0\n"
16225                 "OpMemberDecorate %SSBO_m2x3f16 0 Offset 0\n"
16226                 "OpMemberDecorate %SSBO_m2x4f16 0 Offset 0\n"
16227                 "OpMemberDecorate %SSBO_m3x2f16 0 Offset 0\n"
16228                 "OpMemberDecorate %SSBO_m3x3f16 0 Offset 0\n"
16229                 "OpMemberDecorate %SSBO_m3x4f16 0 Offset 0\n"
16230                 "OpMemberDecorate %SSBO_m4x2f16 0 Offset 0\n"
16231                 "OpMemberDecorate %SSBO_m4x3f16 0 Offset 0\n"
16232                 "OpMemberDecorate %SSBO_m4x4f16 0 Offset 0\n"
16233
16234                 "OpDecorate %SSBO_f16     BufferBlock\n"
16235                 "OpDecorate %SSBO_v2f16   BufferBlock\n"
16236                 "OpDecorate %SSBO_v3f16   BufferBlock\n"
16237                 "OpDecorate %SSBO_v4f16   BufferBlock\n"
16238                 "OpDecorate %SSBO_m2x2f16 BufferBlock\n"
16239                 "OpDecorate %SSBO_m2x3f16 BufferBlock\n"
16240                 "OpDecorate %SSBO_m2x4f16 BufferBlock\n"
16241                 "OpDecorate %SSBO_m3x2f16 BufferBlock\n"
16242                 "OpDecorate %SSBO_m3x3f16 BufferBlock\n"
16243                 "OpDecorate %SSBO_m3x4f16 BufferBlock\n"
16244                 "OpDecorate %SSBO_m4x2f16 BufferBlock\n"
16245                 "OpDecorate %SSBO_m4x3f16 BufferBlock\n"
16246                 "OpDecorate %SSBO_m4x4f16 BufferBlock\n"
16247
16248                 "OpMemberDecorate %SSBO_m2x2f16 0 ColMajor\n"
16249                 "OpMemberDecorate %SSBO_m2x3f16 0 ColMajor\n"
16250                 "OpMemberDecorate %SSBO_m2x4f16 0 ColMajor\n"
16251                 "OpMemberDecorate %SSBO_m3x2f16 0 ColMajor\n"
16252                 "OpMemberDecorate %SSBO_m3x3f16 0 ColMajor\n"
16253                 "OpMemberDecorate %SSBO_m3x4f16 0 ColMajor\n"
16254                 "OpMemberDecorate %SSBO_m4x2f16 0 ColMajor\n"
16255                 "OpMemberDecorate %SSBO_m4x3f16 0 ColMajor\n"
16256                 "OpMemberDecorate %SSBO_m4x4f16 0 ColMajor\n"
16257
16258                 "OpMemberDecorate %SSBO_m2x2f16 0 MatrixStride 4\n"
16259                 "OpMemberDecorate %SSBO_m2x3f16 0 MatrixStride 8\n"
16260                 "OpMemberDecorate %SSBO_m2x4f16 0 MatrixStride 8\n"
16261                 "OpMemberDecorate %SSBO_m3x2f16 0 MatrixStride 4\n"
16262                 "OpMemberDecorate %SSBO_m3x3f16 0 MatrixStride 8\n"
16263                 "OpMemberDecorate %SSBO_m3x4f16 0 MatrixStride 8\n"
16264                 "OpMemberDecorate %SSBO_m4x2f16 0 MatrixStride 4\n"
16265                 "OpMemberDecorate %SSBO_m4x3f16 0 MatrixStride 8\n"
16266                 "OpMemberDecorate %SSBO_m4x4f16 0 MatrixStride 8\n"
16267
16268                 "${arg_decorations}"
16269         );
16270
16271         const StringTemplate testFun
16272         (
16273                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
16274                 "    %param = OpFunctionParameter %v4f32\n"
16275                 "    %entry = OpLabel\n"
16276
16277                 "        %i = OpVariable %fp_i32 Function\n"
16278                 "${arg_infunc_vars}"
16279                 "             OpStore %i %c_i32_0\n"
16280                 "             OpBranch %loop\n"
16281
16282                 "     %loop = OpLabel\n"
16283                 "    %i_cmp = OpLoad %i32 %i\n"
16284                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
16285                 "             OpLoopMerge %merge %next None\n"
16286                 "             OpBranchConditional %lt %write %merge\n"
16287
16288                 "    %write = OpLabel\n"
16289                 "      %ndx = OpLoad %i32 %i\n"
16290
16291                 "${arg_func_call}"
16292
16293                 "             OpBranch %next\n"
16294
16295                 "     %next = OpLabel\n"
16296                 "    %i_cur = OpLoad %i32 %i\n"
16297                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
16298                 "             OpStore %i %i_new\n"
16299                 "             OpBranch %loop\n"
16300
16301                 "    %merge = OpLabel\n"
16302                 "             OpReturnValue %param\n"
16303                 "             OpFunctionEnd\n"
16304         );
16305
16306         const Math16ArgFragments        argFragment1    =
16307         {
16308                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16309                 " %val_src0 = OpLoad %${t0} %src0\n"
16310                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0\n"
16311                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16312                 "             OpStore %dst %val_dst\n",
16313                 "",
16314                 "",
16315                 "",
16316         };
16317
16318         const Math16ArgFragments        argFragment2    =
16319         {
16320                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16321                 " %val_src0 = OpLoad %${t0} %src0\n"
16322                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16323                 " %val_src1 = OpLoad %${t1} %src1\n"
16324                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1\n"
16325                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16326                 "             OpStore %dst %val_dst\n",
16327                 "",
16328                 "",
16329                 "",
16330         };
16331
16332         const Math16ArgFragments        argFragment3    =
16333         {
16334                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16335                 " %val_src0 = OpLoad %${t0} %src0\n"
16336                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16337                 " %val_src1 = OpLoad %${t1} %src1\n"
16338                 "     %src2 = OpAccessChain %up_${t2} %ssbo_src2 %c_i32_0 %ndx\n"
16339                 " %val_src2 = OpLoad %${t2} %src2\n"
16340                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1 %val_src2\n"
16341                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16342                 "             OpStore %dst %val_dst\n",
16343                 "",
16344                 "",
16345                 "",
16346         };
16347
16348         const Math16ArgFragments        argFragmentLdExp        =
16349         {
16350                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16351                 " %val_src0 = OpLoad %${t0} %src0\n"
16352                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16353                 " %val_src1 = OpLoad %${t1} %src1\n"
16354                 "%val_src1i = OpConvertFToS %${dr}i32 %val_src1\n"
16355                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1i\n"
16356                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16357                 "             OpStore %dst %val_dst\n",
16358
16359                 "",
16360
16361                 "",
16362
16363                 "",
16364         };
16365
16366         const Math16ArgFragments        argFragmentModfFrac     =
16367         {
16368                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16369                 " %val_src0 = OpLoad %${t0} %src0\n"
16370                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %tmp\n"
16371                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16372                 "             OpStore %dst %val_dst\n",
16373
16374                 "   %fp_tmp = OpTypePointer Function %${tr}\n",
16375
16376                 "",
16377
16378                 "      %tmp = OpVariable %fp_tmp Function\n",
16379         };
16380
16381         const Math16ArgFragments        argFragmentModfInt      =
16382         {
16383                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16384                 " %val_src0 = OpLoad %${t0} %src0\n"
16385                 "%val_dummy = ${op} %${tr} ${ext_inst} %val_src0 %tmp\n"
16386                 "     %tmp0 = OpAccessChain %fp_tmp %tmp\n"
16387                 "  %val_dst = OpLoad %${tr} %tmp0\n"
16388                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16389                 "             OpStore %dst %val_dst\n",
16390
16391                 "   %fp_tmp = OpTypePointer Function %${tr}\n",
16392
16393                 "",
16394
16395                 "      %tmp = OpVariable %fp_tmp Function\n",
16396         };
16397
16398         const Math16ArgFragments        argFragmentModfStruct   =
16399         {
16400                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16401                 " %val_src0 = OpLoad %${t0} %src0\n"
16402                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16403                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16404                 "             OpStore %tmp_ptr_s %val_tmp\n"
16405                 "%tmp_ptr_l = OpAccessChain %fp_${tr} %tmp %c_${struct_member}\n"
16406                 "  %val_dst = OpLoad %${tr} %tmp_ptr_l\n"
16407                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16408                 "             OpStore %dst %val_dst\n",
16409
16410                 "  %fp_${tr} = OpTypePointer Function %${tr}\n"
16411                 "   %st_tmp = OpTypeStruct %${tr} %${tr}\n"
16412                 "   %fp_tmp = OpTypePointer Function %st_tmp\n"
16413                 "   %c_frac = OpConstant %i32 0\n"
16414                 "    %c_int = OpConstant %i32 1\n",
16415
16416                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16417                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16418
16419                 "      %tmp = OpVariable %fp_tmp Function\n",
16420         };
16421
16422         const Math16ArgFragments        argFragmentFrexpStructS =
16423         {
16424                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16425                 " %val_src0 = OpLoad %${t0} %src0\n"
16426                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16427                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16428                 "             OpStore %tmp_ptr_s %val_tmp\n"
16429                 "%tmp_ptr_l = OpAccessChain %fp_${tr} %tmp %c_i32_0\n"
16430                 "  %val_dst = OpLoad %${tr} %tmp_ptr_l\n"
16431                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16432                 "             OpStore %dst %val_dst\n",
16433
16434                 "  %fp_${tr} = OpTypePointer Function %${tr}\n"
16435                 "   %st_tmp = OpTypeStruct %${tr} %${dr}i32\n"
16436                 "   %fp_tmp = OpTypePointer Function %st_tmp\n",
16437
16438                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16439                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16440
16441                 "      %tmp = OpVariable %fp_tmp Function\n",
16442         };
16443
16444         const Math16ArgFragments        argFragmentFrexpStructE =
16445         {
16446                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16447                 " %val_src0 = OpLoad %${t0} %src0\n"
16448                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16449                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16450                 "             OpStore %tmp_ptr_s %val_tmp\n"
16451                 "%tmp_ptr_l = OpAccessChain %fp_${dr}i32 %tmp %c_i32_1\n"
16452                 "%val_dst_i = OpLoad %${dr}i32 %tmp_ptr_l\n"
16453                 "  %val_dst = OpConvertSToF %${tr} %val_dst_i\n"
16454                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16455                 "             OpStore %dst %val_dst\n",
16456
16457                 "   %st_tmp = OpTypeStruct %${tr} %${dr}i32\n"
16458                 "   %fp_tmp = OpTypePointer Function %st_tmp\n",
16459
16460                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16461                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16462
16463                 "      %tmp = OpVariable %fp_tmp Function\n",
16464         };
16465
16466         const Math16ArgFragments        argFragmentFrexpS               =
16467         {
16468                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16469                 " %val_src0 = OpLoad %${t0} %src0\n"
16470                 "  %out_exp = OpAccessChain %fp_${dr}i32 %tmp\n"
16471                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %out_exp\n"
16472                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16473                 "             OpStore %dst %val_dst\n",
16474
16475                 "",
16476
16477                 "",
16478
16479                 "      %tmp = OpVariable %fp_${dr}i32 Function\n",
16480         };
16481
16482         const Math16ArgFragments        argFragmentFrexpE               =
16483         {
16484                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16485                 " %val_src0 = OpLoad %${t0} %src0\n"
16486                 "  %out_exp = OpAccessChain %fp_${dr}i32 %tmp\n"
16487                 "%val_dummy = ${op} %${tr} ${ext_inst} %val_src0 %out_exp\n"
16488                 "%val_dst_i = OpLoad %${dr}i32 %out_exp\n"
16489                 "  %val_dst = OpConvertSToF %${tr} %val_dst_i\n"
16490                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16491                 "             OpStore %dst %val_dst\n",
16492
16493                 "",
16494
16495                 "",
16496
16497                 "      %tmp = OpVariable %fp_${dr}i32 Function\n",
16498         };
16499
16500         const Math16TestType&           testType                                = testTypes[testTypeIdx];
16501         const string                            funcNameString                  = string(testFunc.funcName) + string(testFunc.funcSuffix);
16502         const string                            testName                                = de::toLower(funcNameString);
16503         const Math16ArgFragments*       argFragments                    = DE_NULL;
16504         const size_t                            typeStructStride                = testType.typeStructStride;
16505         const bool                                      extInst                                 = !(testFunc.funcName[0] == 'O' && testFunc.funcName[1] == 'p');
16506         const size_t                            numFloatsPerArg0Type    = testTypes[testFunc.typeArg0].typeArrayStride / sizeof(deFloat16);
16507         const size_t                            iterations                              = numDataPoints / numFloatsPerArg0Type;
16508         const size_t                            numFloatsPerResultType  = testTypes[testFunc.typeResult].typeArrayStride / sizeof(deFloat16);
16509         const vector<deFloat16>         float16DummyOutput              (iterations * numFloatsPerResultType, 0);
16510         VulkanFeatures                          features;
16511         SpecResource                            specResource;
16512         map<string, string>                     specs;
16513         map<string, string>                     fragments;
16514         vector<string>                          extensions;
16515         string                                          funcCall;
16516         string                                          funcVariables;
16517         string                                          variables;
16518         string                                          declarations;
16519         string                                          decorations;
16520
16521         switch (testFunc.funcArgsCount)
16522         {
16523                 case 1:
16524                 {
16525                         argFragments = &argFragment1;
16526
16527                         if (funcNameString == "ModfFrac")               argFragments = &argFragmentModfFrac;
16528                         if (funcNameString == "ModfInt")                argFragments = &argFragmentModfInt;
16529                         if (funcNameString == "ModfStructFrac") argFragments = &argFragmentModfStruct;
16530                         if (funcNameString == "ModfStructInt")  argFragments = &argFragmentModfStruct;
16531                         if (funcNameString == "FrexpS")                 argFragments = &argFragmentFrexpS;
16532                         if (funcNameString == "FrexpE")                 argFragments = &argFragmentFrexpE;
16533                         if (funcNameString == "FrexpStructS")   argFragments = &argFragmentFrexpStructS;
16534                         if (funcNameString == "FrexpStructE")   argFragments = &argFragmentFrexpStructE;
16535
16536                         break;
16537                 }
16538                 case 2:
16539                 {
16540                         argFragments = &argFragment2;
16541
16542                         if (funcNameString == "Ldexp")                  argFragments = &argFragmentLdExp;
16543
16544                         break;
16545                 }
16546                 case 3:
16547                 {
16548                         argFragments = &argFragment3;
16549
16550                         break;
16551                 }
16552                 default:
16553                 {
16554                         TCU_THROW(InternalError, "Invalid number of arguments");
16555                 }
16556         }
16557
16558         if (testFunc.funcArgsCount == 1)
16559         {
16560                 variables +=
16561                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16562                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16563
16564                 decorations +=
16565                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16566                         "OpDecorate %ssbo_src0 Binding 0\n"
16567                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16568                         "OpDecorate %ssbo_dst Binding 1\n";
16569         }
16570         else if (testFunc.funcArgsCount == 2)
16571         {
16572                 variables +=
16573                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16574                         " %ssbo_src1 = OpVariable %up_SSBO_${t1} Uniform\n"
16575                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16576
16577                 decorations +=
16578                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16579                         "OpDecorate %ssbo_src0 Binding 0\n"
16580                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
16581                         "OpDecorate %ssbo_src1 Binding 1\n"
16582                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16583                         "OpDecorate %ssbo_dst Binding 2\n";
16584         }
16585         else if (testFunc.funcArgsCount == 3)
16586         {
16587                 variables +=
16588                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16589                         " %ssbo_src1 = OpVariable %up_SSBO_${t1} Uniform\n"
16590                         " %ssbo_src2 = OpVariable %up_SSBO_${t2} Uniform\n"
16591                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16592
16593                 decorations +=
16594                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16595                         "OpDecorate %ssbo_src0 Binding 0\n"
16596                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
16597                         "OpDecorate %ssbo_src1 Binding 1\n"
16598                         "OpDecorate %ssbo_src2 DescriptorSet 0\n"
16599                         "OpDecorate %ssbo_src2 Binding 2\n"
16600                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16601                         "OpDecorate %ssbo_dst Binding 3\n";
16602         }
16603         else
16604         {
16605                 TCU_THROW(InternalError, "Invalid number of function arguments");
16606         }
16607
16608         variables       += argFragments->variables;
16609         decorations     += argFragments->decorations;
16610
16611         specs["dr"]                                     = testTypes[testFunc.typeResult].typePrefix;
16612         specs["d0"]                                     = testTypes[testFunc.typeArg0].typePrefix;
16613         specs["d1"]                                     = testTypes[testFunc.typeArg1].typePrefix;
16614         specs["d2"]                                     = testTypes[testFunc.typeArg2].typePrefix;
16615         specs["tr"]                                     = string(testTypes[testFunc.typeResult].typePrefix) + componentType;
16616         specs["t0"]                                     = string(testTypes[testFunc.typeArg0].typePrefix) + componentType;
16617         specs["t1"]                                     = string(testTypes[testFunc.typeArg1].typePrefix) + componentType;
16618         specs["t2"]                                     = string(testTypes[testFunc.typeArg2].typePrefix) + componentType;
16619         specs["struct_stride"]          = de::toString(typeStructStride);
16620         specs["op"]                                     = extInst ? "OpExtInst" : testFunc.funcName;
16621         specs["ext_inst"]                       = extInst ? string("%ext_import ") + testFunc.funcName : "";
16622         specs["struct_member"]          = de::toLower(testFunc.funcSuffix);
16623
16624         variables                                       = StringTemplate(variables).specialize(specs);
16625         decorations                                     = StringTemplate(decorations).specialize(specs);
16626         funcVariables                           = StringTemplate(argFragments->funcVariables).specialize(specs);
16627         funcCall                                        = StringTemplate(argFragments->bodies).specialize(specs);
16628
16629         specs["num_data_points"]        = de::toString(iterations);
16630         specs["arg_vars"]                       = variables;
16631         specs["arg_decorations"]        = decorations;
16632         specs["arg_infunc_vars"]        = funcVariables;
16633         specs["arg_func_call"]          = funcCall;
16634
16635         fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"\n%ext_import = OpExtInstImport \"GLSL.std.450\"";
16636         fragments["capability"]         = "OpCapability Matrix\nOpCapability StorageUniformBufferBlock16";
16637         fragments["decoration"]         = decoration.specialize(specs);
16638         fragments["pre_main"]           = preMain.specialize(specs);
16639         fragments["testfun"]            = testFun.specialize(specs);
16640
16641         for (size_t inputArgNdx = 0; inputArgNdx < testFunc.funcArgsCount; ++inputArgNdx)
16642         {
16643                 const size_t                    numFloatsPerItem        = (inputArgNdx == 0) ? testTypes[testFunc.typeArg0].typeArrayStride / sizeof(deFloat16)
16644                                                                                                         : (inputArgNdx == 1) ? testTypes[testFunc.typeArg1].typeArrayStride / sizeof(deFloat16)
16645                                                                                                         : (inputArgNdx == 2) ? testTypes[testFunc.typeArg2].typeArrayStride / sizeof(deFloat16)
16646                                                                                                         : -1;
16647                 const vector<deFloat16> inputData                       = testFunc.getInputDataFunc(seed, numFloatsPerItem * iterations, testTypeIdx, numFloatsPerItem, testFunc.funcArgsCount, inputArgNdx);
16648
16649                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(inputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
16650         }
16651
16652         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16DummyOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
16653         specResource.verifyIO = testFunc.verifyFunc;
16654
16655         extensions.push_back("VK_KHR_16bit_storage");
16656         extensions.push_back("VK_KHR_shader_float16_int8");
16657
16658         features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
16659         features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
16660
16661         finalizeTestsCreation(specResource, fragments, testCtx, testGroup, testName, features, extensions, IVec3(1, 1, 1));
16662 }
16663
16664 template<size_t C, class SpecResource>
16665 tcu::TestCaseGroup* createFloat16ArithmeticSet (tcu::TestContext& testCtx)
16666 {
16667         DE_STATIC_ASSERT(C >= 1 && C <= 4);
16668
16669         const std::string                               testGroupName   (string("arithmetic_") + de::toString(C));
16670         de::MovePtr<tcu::TestCaseGroup> testGroup               (new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Float 16 arithmetic and related tests"));
16671         const Math16TestFunc                    testFuncs[]             =
16672         {
16673                 {       "OpFNegate",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16OpFNegate>                                       },
16674                 {       "Round",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Round>                                           },
16675                 {       "RoundEven",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16RoundEven>                                       },
16676                 {       "Trunc",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Trunc>                                           },
16677                 {       "FAbs",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FAbs>                                            },
16678                 {       "FSign",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FSign>                                           },
16679                 {       "Floor",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Floor>                                           },
16680                 {       "Ceil",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Ceil>                                            },
16681                 {       "Fract",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Fract>                                           },
16682                 {       "Radians",                              "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Radians>                                         },
16683                 {       "Degrees",                              "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Degrees>                                         },
16684                 {       "Sin",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sin>                                                     },
16685                 {       "Cos",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Cos>                                                     },
16686                 {       "Tan",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Tan>                                                     },
16687                 {       "Asin",                                 "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Asin>                                            },
16688                 {       "Acos",                                 "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Acos>                                            },
16689                 {       "Atan",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Atan>                                            },
16690                 {       "Sinh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sinh>                                            },
16691                 {       "Cosh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Cosh>                                            },
16692                 {       "Tanh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Tanh>                                            },
16693                 {       "Asinh",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Asinh>                                           },
16694                 {       "Acosh",                                "",                     1,      C,              C,              0,              0, &getInputDataAC,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Acosh>                                           },
16695                 {       "Atanh",                                "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Atanh>                                           },
16696                 {       "Exp",                                  "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Exp>                                                     },
16697                 {       "Log",                                  "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Log>                                                     },
16698                 {       "Exp2",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Exp2>                                            },
16699                 {       "Log2",                                 "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Log2>                                            },
16700                 {       "Sqrt",                                 "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sqrt>                                            },
16701                 {       "InverseSqrt",                  "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16InverseSqrt>                                     },
16702                 {       "Modf",                                 "Frac",         1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfFrac>                                        },
16703                 {       "Modf",                                 "Int",          1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfInt>                                         },
16704                 {       "ModfStruct",                   "Frac",         1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfFrac>                                        },
16705                 {       "ModfStruct",                   "Int",          1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfInt>                                         },
16706                 {       "Frexp",                                "S",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpS>                                          },
16707                 {       "Frexp",                                "E",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpE>                                          },
16708                 {       "FrexpStruct",                  "S",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpS>                                          },
16709                 {       "FrexpStruct",                  "E",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpE>                                          },
16710                 {       "OpFAdd",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFAdd>                                          },
16711                 {       "OpFSub",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFSub>                                          },
16712                 {       "OpFMul",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFMul>                                          },
16713                 {       "OpFDiv",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFDiv>                                          },
16714                 {       "Atan2",                                "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Atan2>                                           },
16715                 {       "Pow",                                  "",                     2,      C,              C,              C,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Pow>                                                     },
16716                 {       "FMin",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16FMin>                                            },
16717                 {       "FMax",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16FMax>                                            },
16718                 {       "Step",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Step>                                            },
16719                 {       "Ldexp",                                "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Ldexp>                                           },
16720                 {       "FClamp",                               "",                     3,      C,              C,              C,              C, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FClamp>                                          },
16721                 {       "FMix",                                 "",                     3,      C,              C,              C,              C, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FMix>                                            },
16722                 {       "SmoothStep",                   "",                     3,      C,              C,              C,              C, &getInputDataSS,     compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16SmoothStep>                                      },
16723                 {       "Fma",                                  "",                     3,      C,              C,              C,              C, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16Fma>                                                     },
16724                 {       "Length",                               "",                     1,      1,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  1,  C,  0,  0, fp16Length>                                          },
16725                 {       "Distance",                             "",                     2,      1,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  1,  C,  C,  0, fp16Distance>                                        },
16726                 {       "Cross",                                "",                     2,      C,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Cross>                                           },
16727                 {       "Normalize",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Normalize>                                       },
16728                 {       "FaceForward",                  "",                     3,      C,              C,              C,              C, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FaceForward>                                     },
16729                 {       "Reflect",                              "",                     2,      C,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Reflect>                                         },
16730                 {       "Refract",                              "",                     3,      C,              C,              C,              1, &getInputDataN,      compareFP16ArithmeticFunc<  C,  C,  C,  1, fp16Refract>                                         },
16731                 {       "OpDot",                                "",                     2,      1,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  1,  C,  C,  0, fp16Dot>                                                     },
16732                 {       "OpVectorTimesScalar",  "",                     2,      C,              C,              1,              0, &getInputDataV,      compareFP16ArithmeticFunc<  C,  C,  1,  0, fp16VectorTimesScalar>                       },
16733         };
16734
16735         for (deUint32 testFuncIdx = 0; testFuncIdx < DE_LENGTH_OF_ARRAY(testFuncs); ++testFuncIdx)
16736         {
16737                 const Math16TestFunc&   testFunc                = testFuncs[testFuncIdx];
16738                 const string                    funcNameString  = testFunc.funcName;
16739
16740                 if ((C != 3) && funcNameString == "Cross")
16741                         continue;
16742
16743                 if ((C < 2) && funcNameString == "OpDot")
16744                         continue;
16745
16746                 if ((C < 2) && funcNameString == "OpVectorTimesScalar")
16747                         continue;
16748
16749                 createFloat16ArithmeticFuncTest<SpecResource>(testCtx, *testGroup.get(), C, testFunc);
16750         }
16751
16752         return testGroup.release();
16753 }
16754
16755 template<class SpecResource>
16756 tcu::TestCaseGroup* createFloat16ArithmeticSet (tcu::TestContext& testCtx)
16757 {
16758         const std::string                               testGroupName   ("arithmetic");
16759         de::MovePtr<tcu::TestCaseGroup> testGroup               (new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Float 16 arithmetic and related tests"));
16760         const Math16TestFunc                    testFuncs[]             =
16761         {
16762                 {       "OpTranspose",                  "2x2",          1,      MAT2X2, MAT2X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  4,  4,  0,  0, fp16Transpose<2,2> >                         },
16763                 {       "OpTranspose",                  "3x2",          1,      MAT2X3, MAT3X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<3,2> >                         },
16764                 {       "OpTranspose",                  "4x2",          1,      MAT2X4, MAT4X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<4,2> >                         },
16765                 {       "OpTranspose",                  "2x3",          1,      MAT3X2, MAT2X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<2,3> >                         },
16766                 {       "OpTranspose",                  "3x3",          1,      MAT3X3, MAT3X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<3,3> >                         },
16767                 {       "OpTranspose",                  "4x3",          1,      MAT3X4, MAT4X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<4,3> >                         },
16768                 {       "OpTranspose",                  "2x4",          1,      MAT4X2, MAT2X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<2,4> >                         },
16769                 {       "OpTranspose",                  "3x4",          1,      MAT4X3, MAT3X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<3,4> >                         },
16770                 {       "OpTranspose",                  "4x4",          1,      MAT4X4, MAT4X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<4,4> >                         },
16771                 {       "OpMatrixTimesScalar",  "2x2",          2,      MAT2X2, MAT2X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4,  1,  0, fp16MatrixTimesScalar<2,2> >         },
16772                 {       "OpMatrixTimesScalar",  "2x3",          2,      MAT2X3, MAT2X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<2,3> >         },
16773                 {       "OpMatrixTimesScalar",  "2x4",          2,      MAT2X4, MAT2X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<2,4> >         },
16774                 {       "OpMatrixTimesScalar",  "3x2",          2,      MAT3X2, MAT3X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<3,2> >         },
16775                 {       "OpMatrixTimesScalar",  "3x3",          2,      MAT3X3, MAT3X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<3,3> >         },
16776                 {       "OpMatrixTimesScalar",  "3x4",          2,      MAT3X4, MAT3X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<3,4> >         },
16777                 {       "OpMatrixTimesScalar",  "4x2",          2,      MAT4X2, MAT4X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<4,2> >         },
16778                 {       "OpMatrixTimesScalar",  "4x3",          2,      MAT4X3, MAT4X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<4,3> >         },
16779                 {       "OpMatrixTimesScalar",  "4x4",          2,      MAT4X4, MAT4X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<4,4> >         },
16780                 {       "OpVectorTimesMatrix",  "2x2",          2,      VEC2,   VEC2,   MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  2,  4,  0, fp16VectorTimesMatrix<2,2> >         },
16781                 {       "OpVectorTimesMatrix",  "2x3",          2,      VEC2,   VEC3,   MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  3,  8,  0, fp16VectorTimesMatrix<2,3> >         },
16782                 {       "OpVectorTimesMatrix",  "2x4",          2,      VEC2,   VEC4,   MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  4,  8,  0, fp16VectorTimesMatrix<2,4> >         },
16783                 {       "OpVectorTimesMatrix",  "3x2",          2,      VEC3,   VEC2,   MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  2,  8,  0, fp16VectorTimesMatrix<3,2> >         },
16784                 {       "OpVectorTimesMatrix",  "3x3",          2,      VEC3,   VEC3,   MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  3, 16,  0, fp16VectorTimesMatrix<3,3> >         },
16785                 {       "OpVectorTimesMatrix",  "3x4",          2,      VEC3,   VEC4,   MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  4, 16,  0, fp16VectorTimesMatrix<3,4> >         },
16786                 {       "OpVectorTimesMatrix",  "4x2",          2,      VEC4,   VEC2,   MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  2,  8,  0, fp16VectorTimesMatrix<4,2> >         },
16787                 {       "OpVectorTimesMatrix",  "4x3",          2,      VEC4,   VEC3,   MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  3, 16,  0, fp16VectorTimesMatrix<4,3> >         },
16788                 {       "OpVectorTimesMatrix",  "4x4",          2,      VEC4,   VEC4,   MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4, 16,  0, fp16VectorTimesMatrix<4,4> >         },
16789                 {       "OpMatrixTimesVector",  "2x2",          2,      VEC2,   MAT2X2, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  4,  2,  0, fp16MatrixTimesVector<2,2> >         },
16790                 {       "OpMatrixTimesVector",  "2x3",          2,      VEC3,   MAT2X3, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  8,  2,  0, fp16MatrixTimesVector<2,3> >         },
16791                 {       "OpMatrixTimesVector",  "2x4",          2,      VEC4,   MAT2X4, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  2,  0, fp16MatrixTimesVector<2,4> >         },
16792                 {       "OpMatrixTimesVector",  "3x2",          2,      VEC2,   MAT3X2, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  8,  3,  0, fp16MatrixTimesVector<3,2> >         },
16793                 {       "OpMatrixTimesVector",  "3x3",          2,      VEC3,   MAT3X3, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3, 16,  3,  0, fp16MatrixTimesVector<3,3> >         },
16794                 {       "OpMatrixTimesVector",  "3x4",          2,      VEC4,   MAT3X4, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4, 16,  3,  0, fp16MatrixTimesVector<3,4> >         },
16795                 {       "OpMatrixTimesVector",  "4x2",          2,      VEC2,   MAT4X2, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  8,  4,  0, fp16MatrixTimesVector<4,2> >         },
16796                 {       "OpMatrixTimesVector",  "4x3",          2,      VEC3,   MAT4X3, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3, 16,  4,  0, fp16MatrixTimesVector<4,3> >         },
16797                 {       "OpMatrixTimesVector",  "4x4",          2,      VEC4,   MAT4X4, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4, 16,  4,  0, fp16MatrixTimesVector<4,4> >         },
16798                 {       "OpMatrixTimesMatrix",  "2x2_2x2",      2,      MAT2X2, MAT2X2, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4,  4,  0, fp16MatrixTimesMatrix<2,2,2,2> >     },
16799                 {       "OpMatrixTimesMatrix",  "2x2_3x2",      2,      MAT3X2, MAT2X2, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  8,  0, fp16MatrixTimesMatrix<2,2,3,2> >     },
16800                 {       "OpMatrixTimesMatrix",  "2x2_4x2",      2,      MAT4X2, MAT2X2, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  8,  0, fp16MatrixTimesMatrix<2,2,4,2> >     },
16801                 {       "OpMatrixTimesMatrix",  "2x3_2x2",      2,      MAT2X3, MAT2X3, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  4,  0, fp16MatrixTimesMatrix<2,3,2,2> >     },
16802                 {       "OpMatrixTimesMatrix",  "2x3_3x2",      2,      MAT3X3, MAT2X3, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,3,3,2> >     },
16803                 {       "OpMatrixTimesMatrix",  "2x3_4x2",      2,      MAT4X3, MAT2X3, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,3,4,2> >     },
16804                 {       "OpMatrixTimesMatrix",  "2x4_2x2",      2,      MAT2X4, MAT2X4, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  4,  0, fp16MatrixTimesMatrix<2,4,2,2> >     },
16805                 {       "OpMatrixTimesMatrix",  "2x4_3x2",      2,      MAT3X4, MAT2X4, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,4,3,2> >     },
16806                 {       "OpMatrixTimesMatrix",  "2x4_4x2",      2,      MAT4X4, MAT2X4, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,4,4,2> >     },
16807                 {       "OpMatrixTimesMatrix",  "3x2_2x3",      2,      MAT2X2, MAT3X2, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  8,  0, fp16MatrixTimesMatrix<3,2,2,3> >     },
16808                 {       "OpMatrixTimesMatrix",  "3x2_3x3",      2,      MAT3X2, MAT3X2, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<3,2,3,3> >     },
16809                 {       "OpMatrixTimesMatrix",  "3x2_4x3",      2,      MAT4X2, MAT3X2, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<3,2,4,3> >     },
16810                 {       "OpMatrixTimesMatrix",  "3x3_2x3",      2,      MAT2X3, MAT3X3, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<3,3,2,3> >     },
16811                 {       "OpMatrixTimesMatrix",  "3x3_3x3",      2,      MAT3X3, MAT3X3, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,3,3,3> >     },
16812                 {       "OpMatrixTimesMatrix",  "3x3_4x3",      2,      MAT4X3, MAT3X3, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,3,4,3> >     },
16813                 {       "OpMatrixTimesMatrix",  "3x4_2x3",      2,      MAT2X4, MAT3X4, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<3,4,2,3> >     },
16814                 {       "OpMatrixTimesMatrix",  "3x4_3x3",      2,      MAT3X4, MAT3X4, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,4,3,3> >     },
16815                 {       "OpMatrixTimesMatrix",  "3x4_4x3",      2,      MAT4X4, MAT3X4, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,4,4,3> >     },
16816                 {       "OpMatrixTimesMatrix",  "4x2_2x4",      2,      MAT2X2, MAT4X2, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  8,  0, fp16MatrixTimesMatrix<4,2,2,4> >     },
16817                 {       "OpMatrixTimesMatrix",  "4x2_3x4",      2,      MAT3X2, MAT4X2, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<4,2,3,4> >     },
16818                 {       "OpMatrixTimesMatrix",  "4x2_4x4",      2,      MAT4X2, MAT4X2, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<4,2,4,4> >     },
16819                 {       "OpMatrixTimesMatrix",  "4x3_2x4",      2,      MAT2X3, MAT4X3, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<4,3,2,4> >     },
16820                 {       "OpMatrixTimesMatrix",  "4x3_3x4",      2,      MAT3X3, MAT4X3, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,3,3,4> >     },
16821                 {       "OpMatrixTimesMatrix",  "4x3_4x4",      2,      MAT4X3, MAT4X3, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,3,4,4> >     },
16822                 {       "OpMatrixTimesMatrix",  "4x4_2x4",      2,      MAT2X4, MAT4X4, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<4,4,2,4> >     },
16823                 {       "OpMatrixTimesMatrix",  "4x4_3x4",      2,      MAT3X4, MAT4X4, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,4,3,4> >     },
16824                 {       "OpMatrixTimesMatrix",  "4x4_4x4",      2,      MAT4X4, MAT4X4, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,4,4,4> >     },
16825                 {       "OpOuterProduct",               "2x2",          2,      MAT2X2, VEC2,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  2,  2,  0, fp16OuterProduct<2,2> >                      },
16826                 {       "OpOuterProduct",               "2x3",          2,      MAT2X3, VEC3,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  3,  2,  0, fp16OuterProduct<2,3> >                      },
16827                 {       "OpOuterProduct",               "2x4",          2,      MAT2X4, VEC4,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  2,  0, fp16OuterProduct<2,4> >                      },
16828                 {       "OpOuterProduct",               "3x2",          2,      MAT3X2, VEC2,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  2,  3,  0, fp16OuterProduct<3,2> >                      },
16829                 {       "OpOuterProduct",               "3x3",          2,      MAT3X3, VEC3,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  3,  3,  0, fp16OuterProduct<3,3> >                      },
16830                 {       "OpOuterProduct",               "3x4",          2,      MAT3X4, VEC4,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  4,  3,  0, fp16OuterProduct<3,4> >                      },
16831                 {       "OpOuterProduct",               "4x2",          2,      MAT4X2, VEC2,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  2,  4,  0, fp16OuterProduct<4,2> >                      },
16832                 {       "OpOuterProduct",               "4x3",          2,      MAT4X3, VEC3,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  3,  4,  0, fp16OuterProduct<4,3> >                      },
16833                 {       "OpOuterProduct",               "4x4",          2,      MAT4X4, VEC4,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  4,  4,  0, fp16OuterProduct<4,4> >                      },
16834                 {       "Determinant",                  "2x2",          1,      SCALAR, MAT2X2, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1,  4,  0,  0, fp16Determinant<2> >                         },
16835                 {       "Determinant",                  "3x3",          1,      SCALAR, MAT3X3, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1, 16,  0,  0, fp16Determinant<3> >                         },
16836                 {       "Determinant",                  "4x4",          1,      SCALAR, MAT4X4, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1, 16,  0,  0, fp16Determinant<4> >                         },
16837                 {       "MatrixInverse",                "2x2",          1,      MAT2X2, MAT2X2, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  4,  4,  0,  0, fp16Inverse<2> >                                     },
16838         };
16839
16840         for (deUint32 testFuncIdx = 0; testFuncIdx < DE_LENGTH_OF_ARRAY(testFuncs); ++testFuncIdx)
16841         {
16842                 const Math16TestFunc&   testFunc        = testFuncs[testFuncIdx];
16843
16844                 createFloat16ArithmeticFuncTest<SpecResource>(testCtx, *testGroup.get(), 0, testFunc);
16845         }
16846
16847         return testGroup.release();
16848 }
16849
16850 const string getNumberTypeName (const NumberType type)
16851 {
16852         if (type == NUMBERTYPE_INT32)
16853         {
16854                 return "int";
16855         }
16856         else if (type == NUMBERTYPE_UINT32)
16857         {
16858                 return "uint";
16859         }
16860         else if (type == NUMBERTYPE_FLOAT32)
16861         {
16862                 return "float";
16863         }
16864         else
16865         {
16866                 DE_ASSERT(false);
16867                 return "";
16868         }
16869 }
16870
16871 deInt32 getInt(de::Random& rnd)
16872 {
16873         return rnd.getInt(std::numeric_limits<int>::min(), std::numeric_limits<int>::max());
16874 }
16875
16876 const string repeatString (const string& str, int times)
16877 {
16878         string filler;
16879         for (int i = 0; i < times; ++i)
16880         {
16881                 filler += str;
16882         }
16883         return filler;
16884 }
16885
16886 const string getRandomConstantString (const NumberType type, de::Random& rnd)
16887 {
16888         if (type == NUMBERTYPE_INT32)
16889         {
16890                 return numberToString<deInt32>(getInt(rnd));
16891         }
16892         else if (type == NUMBERTYPE_UINT32)
16893         {
16894                 return numberToString<deUint32>(rnd.getUint32());
16895         }
16896         else if (type == NUMBERTYPE_FLOAT32)
16897         {
16898                 return numberToString<float>(rnd.getFloat());
16899         }
16900         else
16901         {
16902                 DE_ASSERT(false);
16903                 return "";
16904         }
16905 }
16906
16907 void createVectorCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16908 {
16909         map<string, string> params;
16910
16911         // Vec2 to Vec4
16912         for (int width = 2; width <= 4; ++width)
16913         {
16914                 const string randomConst = numberToString(getInt(rnd));
16915                 const string widthStr = numberToString(width);
16916                 const string composite_type = "${customType}vec" + widthStr;
16917                 const int index = rnd.getInt(0, width-1);
16918
16919                 params["type"]                  = "vec";
16920                 params["name"]                  = params["type"] + "_" + widthStr;
16921                 params["compositeDecl"]         = composite_type + " = OpTypeVector ${customType} " + widthStr +"\n";
16922                 params["compositeType"]         = composite_type;
16923                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
16924                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct " + composite_type + repeatString(" %filler", width) + "\n";
16925                 params["indexes"]               = numberToString(index);
16926                 testCases.push_back(params);
16927         }
16928 }
16929
16930 void createArrayCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16931 {
16932         const int limit = 10;
16933         map<string, string> params;
16934
16935         for (int width = 2; width <= limit; ++width)
16936         {
16937                 string randomConst = numberToString(getInt(rnd));
16938                 string widthStr = numberToString(width);
16939                 int index = rnd.getInt(0, width-1);
16940
16941                 params["type"]                  = "array";
16942                 params["name"]                  = params["type"] + "_" + widthStr;
16943                 params["compositeDecl"]         = string("%arraywidth = OpConstant %u32 " + widthStr + "\n")
16944                                                                                         +        "%composite = OpTypeArray ${customType} %arraywidth\n";
16945                 params["compositeType"]         = "%composite";
16946                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
16947                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
16948                 params["indexes"]               = numberToString(index);
16949                 testCases.push_back(params);
16950         }
16951 }
16952
16953 void createStructCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16954 {
16955         const int limit = 10;
16956         map<string, string> params;
16957
16958         for (int width = 2; width <= limit; ++width)
16959         {
16960                 string randomConst = numberToString(getInt(rnd));
16961                 int index = rnd.getInt(0, width-1);
16962
16963                 params["type"]                  = "struct";
16964                 params["name"]                  = params["type"] + "_" + numberToString(width);
16965                 params["compositeDecl"]         = "%composite = OpTypeStruct" + repeatString(" ${customType}", width) + "\n";
16966                 params["compositeType"]         = "%composite";
16967                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
16968                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
16969                 params["indexes"]               = numberToString(index);
16970                 testCases.push_back(params);
16971         }
16972 }
16973
16974 void createMatrixCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16975 {
16976         map<string, string> params;
16977
16978         // Vec2 to Vec4
16979         for (int width = 2; width <= 4; ++width)
16980         {
16981                 string widthStr = numberToString(width);
16982
16983                 for (int column = 2 ; column <= 4; ++column)
16984                 {
16985                         int index_0 = rnd.getInt(0, column-1);
16986                         int index_1 = rnd.getInt(0, width-1);
16987                         string columnStr = numberToString(column);
16988
16989                         params["type"]          = "matrix";
16990                         params["name"]          = params["type"] + "_" + widthStr + "x" + columnStr;
16991                         params["compositeDecl"] = string("%vectype   = OpTypeVector ${customType} " + widthStr + "\n")
16992                                                                                                 +        "%composite = OpTypeMatrix %vectype " + columnStr + "\n";
16993                         params["compositeType"] = "%composite";
16994
16995                         params["filler"]        = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n"
16996                                                                                                 +        "%fillerVec = OpConstantComposite %vectype" + repeatString(" %filler", width) + "\n";
16997
16998                         params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %fillerVec", column) + "\n";
16999                         params["indexes"]       = numberToString(index_0) + " " + numberToString(index_1);
17000                         testCases.push_back(params);
17001                 }
17002         }
17003 }
17004
17005 void createCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
17006 {
17007         createVectorCompositeCases(testCases, rnd, type);
17008         createArrayCompositeCases(testCases, rnd, type);
17009         createStructCompositeCases(testCases, rnd, type);
17010         // Matrix only supports float types
17011         if (type == NUMBERTYPE_FLOAT32)
17012         {
17013                 createMatrixCompositeCases(testCases, rnd, type);
17014         }
17015 }
17016
17017 const string getAssemblyTypeDeclaration (const NumberType type)
17018 {
17019         switch (type)
17020         {
17021                 case NUMBERTYPE_INT32:          return "OpTypeInt 32 1";
17022                 case NUMBERTYPE_UINT32:         return "OpTypeInt 32 0";
17023                 case NUMBERTYPE_FLOAT32:        return "OpTypeFloat 32";
17024                 default:                        DE_ASSERT(false); return "";
17025         }
17026 }
17027
17028 const string getAssemblyTypeName (const NumberType type)
17029 {
17030         switch (type)
17031         {
17032                 case NUMBERTYPE_INT32:          return "%i32";
17033                 case NUMBERTYPE_UINT32:         return "%u32";
17034                 case NUMBERTYPE_FLOAT32:        return "%f32";
17035                 default:                        DE_ASSERT(false); return "";
17036         }
17037 }
17038
17039 const string specializeCompositeInsertShaderTemplate (const NumberType type, const map<string, string>& params)
17040 {
17041         map<string, string>     parameters(params);
17042
17043         const string customType = getAssemblyTypeName(type);
17044         map<string, string> substCustomType;
17045         substCustomType["customType"] = customType;
17046         parameters["compositeDecl"] = StringTemplate(parameters.at("compositeDecl")).specialize(substCustomType);
17047         parameters["compositeType"] = StringTemplate(parameters.at("compositeType")).specialize(substCustomType);
17048         parameters["compositeConstruct"] = StringTemplate(parameters.at("compositeConstruct")).specialize(substCustomType);
17049         parameters["filler"] = StringTemplate(parameters.at("filler")).specialize(substCustomType);
17050         parameters["customType"] = customType;
17051         parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
17052
17053         if (parameters.at("compositeType") != "%u32vec3")
17054         {
17055                 parameters["u32vec3Decl"] = "%u32vec3   = OpTypeVector %u32 3\n";
17056         }
17057
17058         return StringTemplate(
17059                 "OpCapability Shader\n"
17060                 "OpCapability Matrix\n"
17061                 "OpMemoryModel Logical GLSL450\n"
17062                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17063                 "OpExecutionMode %main LocalSize 1 1 1\n"
17064
17065                 "OpSource GLSL 430\n"
17066                 "OpName %main           \"main\"\n"
17067                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17068
17069                 // Decorators
17070                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17071                 "OpDecorate %buf BufferBlock\n"
17072                 "OpDecorate %indata DescriptorSet 0\n"
17073                 "OpDecorate %indata Binding 0\n"
17074                 "OpDecorate %outdata DescriptorSet 0\n"
17075                 "OpDecorate %outdata Binding 1\n"
17076                 "OpDecorate %customarr ArrayStride 4\n"
17077                 "${compositeDecorator}"
17078                 "OpMemberDecorate %buf 0 Offset 0\n"
17079
17080                 // General types
17081                 "%void      = OpTypeVoid\n"
17082                 "%voidf     = OpTypeFunction %void\n"
17083                 "%u32       = OpTypeInt 32 0\n"
17084                 "%i32       = OpTypeInt 32 1\n"
17085                 "%f32       = OpTypeFloat 32\n"
17086
17087                 // Composite declaration
17088                 "${compositeDecl}"
17089
17090                 // Constants
17091                 "${filler}"
17092
17093                 "${u32vec3Decl:opt}"
17094                 "%uvec3ptr  = OpTypePointer Input %u32vec3\n"
17095
17096                 // Inherited from custom
17097                 "%customptr = OpTypePointer Uniform ${customType}\n"
17098                 "%customarr = OpTypeRuntimeArray ${customType}\n"
17099                 "%buf       = OpTypeStruct %customarr\n"
17100                 "%bufptr    = OpTypePointer Uniform %buf\n"
17101
17102                 "%indata    = OpVariable %bufptr Uniform\n"
17103                 "%outdata   = OpVariable %bufptr Uniform\n"
17104
17105                 "%id        = OpVariable %uvec3ptr Input\n"
17106                 "%zero      = OpConstant %i32 0\n"
17107
17108                 "%main      = OpFunction %void None %voidf\n"
17109                 "%label     = OpLabel\n"
17110                 "%idval     = OpLoad %u32vec3 %id\n"
17111                 "%x         = OpCompositeExtract %u32 %idval 0\n"
17112
17113                 "%inloc     = OpAccessChain %customptr %indata %zero %x\n"
17114                 "%outloc    = OpAccessChain %customptr %outdata %zero %x\n"
17115                 // Read the input value
17116                 "%inval     = OpLoad ${customType} %inloc\n"
17117                 // Create the composite and fill it
17118                 "${compositeConstruct}"
17119                 // Insert the input value to a place
17120                 "%instance2 = OpCompositeInsert ${compositeType} %inval %instance ${indexes}\n"
17121                 // Read back the value from the position
17122                 "%out_val   = OpCompositeExtract ${customType} %instance2 ${indexes}\n"
17123                 // Store it in the output position
17124                 "             OpStore %outloc %out_val\n"
17125                 "             OpReturn\n"
17126                 "             OpFunctionEnd\n"
17127         ).specialize(parameters);
17128 }
17129
17130 template<typename T>
17131 BufferSp createCompositeBuffer(T number)
17132 {
17133         return BufferSp(new Buffer<T>(vector<T>(1, number)));
17134 }
17135
17136 tcu::TestCaseGroup* createOpCompositeInsertGroup (tcu::TestContext& testCtx)
17137 {
17138         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "opcompositeinsert", "Test the OpCompositeInsert instruction"));
17139         de::Random                                              rnd             (deStringHash(group->getName()));
17140
17141         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17142         {
17143                 NumberType                                              numberType              = NumberType(type);
17144                 const string                                    typeName                = getNumberTypeName(numberType);
17145                 const string                                    description             = "Test the OpCompositeInsert instruction with " + typeName + "s";
17146                 de::MovePtr<tcu::TestCaseGroup> subGroup                (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17147                 vector<map<string, string> >    testCases;
17148
17149                 createCompositeCases(testCases, rnd, numberType);
17150
17151                 for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
17152                 {
17153                         ComputeShaderSpec       spec;
17154
17155                         spec.assembly = specializeCompositeInsertShaderTemplate(numberType, *test);
17156
17157                         switch (numberType)
17158                         {
17159                                 case NUMBERTYPE_INT32:
17160                                 {
17161                                         deInt32 number = getInt(rnd);
17162                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17163                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17164                                         break;
17165                                 }
17166                                 case NUMBERTYPE_UINT32:
17167                                 {
17168                                         deUint32 number = rnd.getUint32();
17169                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17170                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17171                                         break;
17172                                 }
17173                                 case NUMBERTYPE_FLOAT32:
17174                                 {
17175                                         float number = rnd.getFloat();
17176                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
17177                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
17178                                         break;
17179                                 }
17180                                 default:
17181                                         DE_ASSERT(false);
17182                         }
17183
17184                         spec.numWorkGroups = IVec3(1, 1, 1);
17185                         subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpCompositeInsert test", spec));
17186                 }
17187                 group->addChild(subGroup.release());
17188         }
17189         return group.release();
17190 }
17191
17192 struct AssemblyStructInfo
17193 {
17194         AssemblyStructInfo (const deUint32 comp, const deUint32 idx)
17195         : components    (comp)
17196         , index                 (idx)
17197         {}
17198
17199         deUint32 components;
17200         deUint32 index;
17201 };
17202
17203 const string specializeInBoundsShaderTemplate (const NumberType type, const AssemblyStructInfo& structInfo, const map<string, string>& params)
17204 {
17205         // Create the full index string
17206         string                          fullIndex       = numberToString(structInfo.index) + " " + params.at("indexes");
17207         // Convert it to list of indexes
17208         vector<string>          indexes         = de::splitString(fullIndex, ' ');
17209
17210         map<string, string>     parameters      (params);
17211         parameters["structType"]        = repeatString(" ${compositeType}", structInfo.components);
17212         parameters["structConstruct"]   = repeatString(" %instance", structInfo.components);
17213         parameters["insertIndexes"]     = fullIndex;
17214
17215         // In matrix cases the last two index is the CompositeExtract indexes
17216         const deUint32 extractIndexes = (parameters["type"] == "matrix") ? 2 : 1;
17217
17218         // Construct the extractIndex
17219         for (vector<string>::const_iterator index = indexes.end() - extractIndexes; index != indexes.end(); ++index)
17220         {
17221                 parameters["extractIndexes"] += " " + *index;
17222         }
17223
17224         // Remove the last 1 or 2 element depends on matrix case or not
17225         indexes.erase(indexes.end() - extractIndexes, indexes.end());
17226
17227         deUint32 id = 0;
17228         // Generate AccessChain index expressions (except for the last one, because we use ptr to the composite)
17229         for (vector<string>::const_iterator index = indexes.begin(); index != indexes.end(); ++index)
17230         {
17231                 string indexId = "%index_" + numberToString(id++);
17232                 parameters["accessChainConstDeclaration"] += indexId + "   = OpConstant %u32 " + *index + "\n";
17233                 parameters["accessChainIndexes"] += " " + indexId;
17234         }
17235
17236         parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
17237
17238         const string customType = getAssemblyTypeName(type);
17239         map<string, string> substCustomType;
17240         substCustomType["customType"] = customType;
17241         parameters["compositeDecl"] = StringTemplate(parameters.at("compositeDecl")).specialize(substCustomType);
17242         parameters["compositeType"] = StringTemplate(parameters.at("compositeType")).specialize(substCustomType);
17243         parameters["compositeConstruct"] = StringTemplate(parameters.at("compositeConstruct")).specialize(substCustomType);
17244         parameters["filler"] = StringTemplate(parameters.at("filler")).specialize(substCustomType);
17245         parameters["customType"] = customType;
17246
17247         const string compositeType = parameters.at("compositeType");
17248         map<string, string> substCompositeType;
17249         substCompositeType["compositeType"] = compositeType;
17250         parameters["structType"] = StringTemplate(parameters.at("structType")).specialize(substCompositeType);
17251         if (compositeType != "%u32vec3")
17252         {
17253                 parameters["u32vec3Decl"] = "%u32vec3   = OpTypeVector %u32 3\n";
17254         }
17255
17256         return StringTemplate(
17257                 "OpCapability Shader\n"
17258                 "OpCapability Matrix\n"
17259                 "OpMemoryModel Logical GLSL450\n"
17260                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17261                 "OpExecutionMode %main LocalSize 1 1 1\n"
17262
17263                 "OpSource GLSL 430\n"
17264                 "OpName %main           \"main\"\n"
17265                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17266                 // Decorators
17267                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17268                 "OpDecorate %buf BufferBlock\n"
17269                 "OpDecorate %indata DescriptorSet 0\n"
17270                 "OpDecorate %indata Binding 0\n"
17271                 "OpDecorate %outdata DescriptorSet 0\n"
17272                 "OpDecorate %outdata Binding 1\n"
17273                 "OpDecorate %customarr ArrayStride 4\n"
17274                 "${compositeDecorator}"
17275                 "OpMemberDecorate %buf 0 Offset 0\n"
17276                 // General types
17277                 "%void      = OpTypeVoid\n"
17278                 "%voidf     = OpTypeFunction %void\n"
17279                 "%i32       = OpTypeInt 32 1\n"
17280                 "%u32       = OpTypeInt 32 0\n"
17281                 "%f32       = OpTypeFloat 32\n"
17282                 // Custom types
17283                 "${compositeDecl}"
17284                 // %u32vec3 if not already declared in ${compositeDecl}
17285                 "${u32vec3Decl:opt}"
17286                 "%uvec3ptr  = OpTypePointer Input %u32vec3\n"
17287                 // Inherited from composite
17288                 "%composite_p = OpTypePointer Function ${compositeType}\n"
17289                 "%struct_t  = OpTypeStruct${structType}\n"
17290                 "%struct_p  = OpTypePointer Function %struct_t\n"
17291                 // Constants
17292                 "${filler}"
17293                 "${accessChainConstDeclaration}"
17294                 // Inherited from custom
17295                 "%customptr = OpTypePointer Uniform ${customType}\n"
17296                 "%customarr = OpTypeRuntimeArray ${customType}\n"
17297                 "%buf       = OpTypeStruct %customarr\n"
17298                 "%bufptr    = OpTypePointer Uniform %buf\n"
17299                 "%indata    = OpVariable %bufptr Uniform\n"
17300                 "%outdata   = OpVariable %bufptr Uniform\n"
17301
17302                 "%id        = OpVariable %uvec3ptr Input\n"
17303                 "%zero      = OpConstant %u32 0\n"
17304                 "%main      = OpFunction %void None %voidf\n"
17305                 "%label     = OpLabel\n"
17306                 "%struct_v  = OpVariable %struct_p Function\n"
17307                 "%idval     = OpLoad %u32vec3 %id\n"
17308                 "%x         = OpCompositeExtract %u32 %idval 0\n"
17309                 // Create the input/output type
17310                 "%inloc     = OpInBoundsAccessChain %customptr %indata %zero %x\n"
17311                 "%outloc    = OpInBoundsAccessChain %customptr %outdata %zero %x\n"
17312                 // Read the input value
17313                 "%inval     = OpLoad ${customType} %inloc\n"
17314                 // Create the composite and fill it
17315                 "${compositeConstruct}"
17316                 // Create the struct and fill it with the composite
17317                 "%struct    = OpCompositeConstruct %struct_t${structConstruct}\n"
17318                 // Insert the value
17319                 "%comp_obj  = OpCompositeInsert %struct_t %inval %struct ${insertIndexes}\n"
17320                 // Store the object
17321                 "             OpStore %struct_v %comp_obj\n"
17322                 // Get deepest possible composite pointer
17323                 "%inner_ptr = OpInBoundsAccessChain %composite_p %struct_v${accessChainIndexes}\n"
17324                 "%read_obj  = OpLoad ${compositeType} %inner_ptr\n"
17325                 // Read back the stored value
17326                 "%read_val  = OpCompositeExtract ${customType} %read_obj${extractIndexes}\n"
17327                 "             OpStore %outloc %read_val\n"
17328                 "             OpReturn\n"
17329                 "             OpFunctionEnd\n"
17330         ).specialize(parameters);
17331 }
17332
17333 tcu::TestCaseGroup* createOpInBoundsAccessChainGroup (tcu::TestContext& testCtx)
17334 {
17335         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opinboundsaccesschain", "Test the OpInBoundsAccessChain instruction"));
17336         de::Random                                              rnd                             (deStringHash(group->getName()));
17337
17338         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17339         {
17340                 NumberType                                              numberType      = NumberType(type);
17341                 const string                                    typeName        = getNumberTypeName(numberType);
17342                 const string                                    description     = "Test the OpInBoundsAccessChain instruction with " + typeName + "s";
17343                 de::MovePtr<tcu::TestCaseGroup> subGroup        (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17344
17345                 vector<map<string, string> >    testCases;
17346                 createCompositeCases(testCases, rnd, numberType);
17347
17348                 for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
17349                 {
17350                         ComputeShaderSpec       spec;
17351
17352                         // Number of components inside of a struct
17353                         deUint32 structComponents = rnd.getInt(2, 8);
17354                         // Component index value
17355                         deUint32 structIndex = rnd.getInt(0, structComponents - 1);
17356                         AssemblyStructInfo structInfo(structComponents, structIndex);
17357
17358                         spec.assembly = specializeInBoundsShaderTemplate(numberType, structInfo, *test);
17359
17360                         switch (numberType)
17361                         {
17362                                 case NUMBERTYPE_INT32:
17363                                 {
17364                                         deInt32 number = getInt(rnd);
17365                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17366                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17367                                         break;
17368                                 }
17369                                 case NUMBERTYPE_UINT32:
17370                                 {
17371                                         deUint32 number = rnd.getUint32();
17372                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17373                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17374                                         break;
17375                                 }
17376                                 case NUMBERTYPE_FLOAT32:
17377                                 {
17378                                         float number = rnd.getFloat();
17379                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
17380                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
17381                                         break;
17382                                 }
17383                                 default:
17384                                         DE_ASSERT(false);
17385                         }
17386                         spec.numWorkGroups = IVec3(1, 1, 1);
17387                         subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpInBoundsAccessChain test", spec));
17388                 }
17389                 group->addChild(subGroup.release());
17390         }
17391         return group.release();
17392 }
17393
17394 // If the params missing, uninitialized case
17395 const string specializeDefaultOutputShaderTemplate (const NumberType type, const map<string, string>& params = map<string, string>())
17396 {
17397         map<string, string> parameters(params);
17398
17399         parameters["customType"]        = getAssemblyTypeName(type);
17400
17401         // Declare the const value, and use it in the initializer
17402         if (params.find("constValue") != params.end())
17403         {
17404                 parameters["variableInitializer"]       = " %const";
17405         }
17406         // Uninitialized case
17407         else
17408         {
17409                 parameters["commentDecl"]       = ";";
17410         }
17411
17412         return StringTemplate(
17413                 "OpCapability Shader\n"
17414                 "OpMemoryModel Logical GLSL450\n"
17415                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17416                 "OpExecutionMode %main LocalSize 1 1 1\n"
17417                 "OpSource GLSL 430\n"
17418                 "OpName %main           \"main\"\n"
17419                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17420                 // Decorators
17421                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17422                 "OpDecorate %indata DescriptorSet 0\n"
17423                 "OpDecorate %indata Binding 0\n"
17424                 "OpDecorate %outdata DescriptorSet 0\n"
17425                 "OpDecorate %outdata Binding 1\n"
17426                 "OpDecorate %in_arr ArrayStride 4\n"
17427                 "OpDecorate %in_buf BufferBlock\n"
17428                 "OpMemberDecorate %in_buf 0 Offset 0\n"
17429                 // Base types
17430                 "%void       = OpTypeVoid\n"
17431                 "%voidf      = OpTypeFunction %void\n"
17432                 "%u32        = OpTypeInt 32 0\n"
17433                 "%i32        = OpTypeInt 32 1\n"
17434                 "%f32        = OpTypeFloat 32\n"
17435                 "%uvec3      = OpTypeVector %u32 3\n"
17436                 "%uvec3ptr   = OpTypePointer Input %uvec3\n"
17437                 "${commentDecl:opt}%const      = OpConstant ${customType} ${constValue:opt}\n"
17438                 // Derived types
17439                 "%in_ptr     = OpTypePointer Uniform ${customType}\n"
17440                 "%in_arr     = OpTypeRuntimeArray ${customType}\n"
17441                 "%in_buf     = OpTypeStruct %in_arr\n"
17442                 "%in_bufptr  = OpTypePointer Uniform %in_buf\n"
17443                 "%indata     = OpVariable %in_bufptr Uniform\n"
17444                 "%outdata    = OpVariable %in_bufptr Uniform\n"
17445                 "%id         = OpVariable %uvec3ptr Input\n"
17446                 "%var_ptr    = OpTypePointer Function ${customType}\n"
17447                 // Constants
17448                 "%zero       = OpConstant %i32 0\n"
17449                 // Main function
17450                 "%main       = OpFunction %void None %voidf\n"
17451                 "%label      = OpLabel\n"
17452                 "%out_var    = OpVariable %var_ptr Function${variableInitializer:opt}\n"
17453                 "%idval      = OpLoad %uvec3 %id\n"
17454                 "%x          = OpCompositeExtract %u32 %idval 0\n"
17455                 "%inloc      = OpAccessChain %in_ptr %indata %zero %x\n"
17456                 "%outloc     = OpAccessChain %in_ptr %outdata %zero %x\n"
17457
17458                 "%outval     = OpLoad ${customType} %out_var\n"
17459                 "              OpStore %outloc %outval\n"
17460                 "              OpReturn\n"
17461                 "              OpFunctionEnd\n"
17462         ).specialize(parameters);
17463 }
17464
17465 bool compareFloats (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
17466 {
17467         DE_ASSERT(outputAllocs.size() != 0);
17468         DE_ASSERT(outputAllocs.size() == expectedOutputs.size());
17469
17470         // Use custom epsilon because of the float->string conversion
17471         const float     epsilon = 0.00001f;
17472
17473         for (size_t outputNdx = 0; outputNdx < outputAllocs.size(); ++outputNdx)
17474         {
17475                 vector<deUint8> expectedBytes;
17476                 float                   expected;
17477                 float                   actual;
17478
17479                 expectedOutputs[outputNdx].getBytes(expectedBytes);
17480                 memcpy(&expected, &expectedBytes.front(), expectedBytes.size());
17481                 memcpy(&actual, outputAllocs[outputNdx]->getHostPtr(), expectedBytes.size());
17482
17483                 // Test with epsilon
17484                 if (fabs(expected - actual) > epsilon)
17485                 {
17486                         log << TestLog::Message << "Error: The actual and expected values not matching."
17487                                 << " Expected: " << expected << " Actual: " << actual << " Epsilon: " << epsilon << TestLog::EndMessage;
17488                         return false;
17489                 }
17490         }
17491         return true;
17492 }
17493
17494 // Checks if the driver crash with uninitialized cases
17495 bool passthruVerify (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
17496 {
17497         DE_ASSERT(outputAllocs.size() != 0);
17498         DE_ASSERT(outputAllocs.size() == expectedOutputs.size());
17499
17500         // Copy and discard the result.
17501         for (size_t outputNdx = 0; outputNdx < outputAllocs.size(); ++outputNdx)
17502         {
17503                 vector<deUint8> expectedBytes;
17504                 expectedOutputs[outputNdx].getBytes(expectedBytes);
17505
17506                 const size_t    width                   = expectedBytes.size();
17507                 vector<char>    data                    (width);
17508
17509                 memcpy(&data[0], outputAllocs[outputNdx]->getHostPtr(), width);
17510         }
17511         return true;
17512 }
17513
17514 tcu::TestCaseGroup* createShaderDefaultOutputGroup (tcu::TestContext& testCtx)
17515 {
17516         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "shader_default_output", "Test shader default output."));
17517         de::Random                                              rnd             (deStringHash(group->getName()));
17518
17519         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17520         {
17521                 NumberType                                              numberType      = NumberType(type);
17522                 const string                                    typeName        = getNumberTypeName(numberType);
17523                 const string                                    description     = "Test the OpVariable initializer with " + typeName + ".";
17524                 de::MovePtr<tcu::TestCaseGroup> subGroup        (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17525
17526                 // 2 similar subcases (initialized and uninitialized)
17527                 for (int subCase = 0; subCase < 2; ++subCase)
17528                 {
17529                         ComputeShaderSpec spec;
17530                         spec.numWorkGroups = IVec3(1, 1, 1);
17531
17532                         map<string, string>                             params;
17533
17534                         switch (numberType)
17535                         {
17536                                 case NUMBERTYPE_INT32:
17537                                 {
17538                                         deInt32 number = getInt(rnd);
17539                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17540                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17541                                         params["constValue"] = numberToString(number);
17542                                         break;
17543                                 }
17544                                 case NUMBERTYPE_UINT32:
17545                                 {
17546                                         deUint32 number = rnd.getUint32();
17547                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17548                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17549                                         params["constValue"] = numberToString(number);
17550                                         break;
17551                                 }
17552                                 case NUMBERTYPE_FLOAT32:
17553                                 {
17554                                         float number = rnd.getFloat();
17555                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
17556                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
17557                                         spec.verifyIO = &compareFloats;
17558                                         params["constValue"] = numberToString(number);
17559                                         break;
17560                                 }
17561                                 default:
17562                                         DE_ASSERT(false);
17563                         }
17564
17565                         // Initialized subcase
17566                         if (!subCase)
17567                         {
17568                                 spec.assembly = specializeDefaultOutputShaderTemplate(numberType, params);
17569                                 subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "initialized", "OpVariable initializer tests.", spec));
17570                         }
17571                         // Uninitialized subcase
17572                         else
17573                         {
17574                                 spec.assembly = specializeDefaultOutputShaderTemplate(numberType);
17575                                 spec.verifyIO = &passthruVerify;
17576                                 subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "uninitialized", "OpVariable initializer tests.", spec));
17577                         }
17578                 }
17579                 group->addChild(subGroup.release());
17580         }
17581         return group.release();
17582 }
17583
17584 tcu::TestCaseGroup* createOpNopTests (tcu::TestContext& testCtx)
17585 {
17586         de::MovePtr<tcu::TestCaseGroup> testGroup (new tcu::TestCaseGroup(testCtx, "opnop", "Test OpNop"));
17587         RGBA                                                    defaultColors[4];
17588         map<string, string>                             opNopFragments;
17589
17590         getDefaultColors(defaultColors);
17591
17592         opNopFragments["testfun"]               =
17593                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17594                 "%param1 = OpFunctionParameter %v4f32\n"
17595                 "%label_testfun = OpLabel\n"
17596                 "OpNop\n"
17597                 "OpNop\n"
17598                 "OpNop\n"
17599                 "OpNop\n"
17600                 "OpNop\n"
17601                 "OpNop\n"
17602                 "OpNop\n"
17603                 "OpNop\n"
17604                 "%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17605                 "%b = OpFAdd %f32 %a %a\n"
17606                 "OpNop\n"
17607                 "%c = OpFSub %f32 %b %a\n"
17608                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
17609                 "OpNop\n"
17610                 "OpNop\n"
17611                 "OpReturnValue %ret\n"
17612                 "OpFunctionEnd\n";
17613
17614         createTestsForAllStages("opnop", defaultColors, defaultColors, opNopFragments, testGroup.get());
17615
17616         return testGroup.release();
17617 }
17618
17619 tcu::TestCaseGroup* createOpNameTests (tcu::TestContext& testCtx)
17620 {
17621         de::MovePtr<tcu::TestCaseGroup> testGroup       (new tcu::TestCaseGroup(testCtx, "opname","Test OpName"));
17622         RGBA                                                    defaultColors[4];
17623         map<string, string>                             opNameFragments;
17624
17625         getDefaultColors(defaultColors);
17626
17627         opNameFragments["testfun"] =
17628                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17629                 "%param1     = OpFunctionParameter %v4f32\n"
17630                 "%label_func = OpLabel\n"
17631                 "%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17632                 "%b          = OpFAdd %f32 %a %a\n"
17633                 "%c          = OpFSub %f32 %b %a\n"
17634                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
17635                 "OpReturnValue %ret\n"
17636                 "OpFunctionEnd\n";
17637
17638         opNameFragments["debug"] =
17639                 "OpName %BP_main \"not_main\"";
17640
17641         createTestsForAllStages("opname", defaultColors, defaultColors, opNameFragments, testGroup.get());
17642
17643         return testGroup.release();
17644 }
17645
17646 tcu::TestCaseGroup* createFloat16Tests (tcu::TestContext& testCtx)
17647 {
17648         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "float16", "Float 16 tests"));
17649
17650         testGroup->addChild(createOpConstantFloat16Tests(testCtx));
17651         testGroup->addChild(createFloat16LogicalSet<GraphicsResources>(testCtx, TEST_WITH_NAN));
17652         testGroup->addChild(createFloat16LogicalSet<GraphicsResources>(testCtx, TEST_WITHOUT_NAN));
17653         testGroup->addChild(createFloat16FuncSet<GraphicsResources>(testCtx));
17654         testGroup->addChild(createDerivativeTests<256, 1>(testCtx));
17655         testGroup->addChild(createDerivativeTests<256, 2>(testCtx));
17656         testGroup->addChild(createDerivativeTests<256, 4>(testCtx));
17657         testGroup->addChild(createFloat16VectorExtractSet<GraphicsResources>(testCtx));
17658         testGroup->addChild(createFloat16VectorInsertSet<GraphicsResources>(testCtx));
17659         testGroup->addChild(createFloat16VectorShuffleSet<GraphicsResources>(testCtx));
17660         testGroup->addChild(createFloat16CompositeConstructSet<GraphicsResources>(testCtx));
17661         testGroup->addChild(createFloat16CompositeInsertExtractSet<GraphicsResources>(testCtx, "OpCompositeExtract"));
17662         testGroup->addChild(createFloat16CompositeInsertExtractSet<GraphicsResources>(testCtx, "OpCompositeInsert"));
17663         testGroup->addChild(createFloat16ArithmeticSet<GraphicsResources>(testCtx));
17664         testGroup->addChild(createFloat16ArithmeticSet<1, GraphicsResources>(testCtx));
17665         testGroup->addChild(createFloat16ArithmeticSet<2, GraphicsResources>(testCtx));
17666         testGroup->addChild(createFloat16ArithmeticSet<3, GraphicsResources>(testCtx));
17667         testGroup->addChild(createFloat16ArithmeticSet<4, GraphicsResources>(testCtx));
17668
17669         return testGroup.release();
17670 }
17671
17672 tcu::TestCaseGroup* createFloat16Group (tcu::TestContext& testCtx)
17673 {
17674         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "float16", "Float 16 tests"));
17675
17676         testGroup->addChild(createFloat16OpConstantCompositeGroup(testCtx));
17677         testGroup->addChild(createFloat16LogicalSet<ComputeShaderSpec>(testCtx, TEST_WITH_NAN));
17678         testGroup->addChild(createFloat16LogicalSet<ComputeShaderSpec>(testCtx, TEST_WITHOUT_NAN));
17679         testGroup->addChild(createFloat16FuncSet<ComputeShaderSpec>(testCtx));
17680         testGroup->addChild(createFloat16VectorExtractSet<ComputeShaderSpec>(testCtx));
17681         testGroup->addChild(createFloat16VectorInsertSet<ComputeShaderSpec>(testCtx));
17682         testGroup->addChild(createFloat16VectorShuffleSet<ComputeShaderSpec>(testCtx));
17683         testGroup->addChild(createFloat16CompositeConstructSet<ComputeShaderSpec>(testCtx));
17684         testGroup->addChild(createFloat16CompositeInsertExtractSet<ComputeShaderSpec>(testCtx, "OpCompositeExtract"));
17685         testGroup->addChild(createFloat16CompositeInsertExtractSet<ComputeShaderSpec>(testCtx, "OpCompositeInsert"));
17686         testGroup->addChild(createFloat16ArithmeticSet<ComputeShaderSpec>(testCtx));
17687         testGroup->addChild(createFloat16ArithmeticSet<1, ComputeShaderSpec>(testCtx));
17688         testGroup->addChild(createFloat16ArithmeticSet<2, ComputeShaderSpec>(testCtx));
17689         testGroup->addChild(createFloat16ArithmeticSet<3, ComputeShaderSpec>(testCtx));
17690         testGroup->addChild(createFloat16ArithmeticSet<4, ComputeShaderSpec>(testCtx));
17691
17692         return testGroup.release();
17693 }
17694
17695 tcu::TestCaseGroup* createBoolMixedBitSizeGroup (tcu::TestContext& testCtx)
17696 {
17697         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "mixed_bitsize", "Tests boolean operands produced from instructions of different bit-sizes"));
17698
17699         de::Random                                              rnd                             (deStringHash(group->getName()));
17700         const int               numElements             = 100;
17701         vector<float>   inputData               (numElements, 0);
17702         vector<float>   outputData              (numElements, 0);
17703         fillRandomScalars(rnd, 0.0f, 100.0f, &inputData[0], 100);
17704
17705         const StringTemplate                    shaderTemplate  (
17706                 "${CAPS}\n"
17707                 "OpMemoryModel Logical GLSL450\n"
17708                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17709                 "OpExecutionMode %main LocalSize 1 1 1\n"
17710                 "OpSource GLSL 430\n"
17711                 "OpName %main           \"main\"\n"
17712                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17713
17714                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17715
17716                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
17717
17718                 "%id        = OpVariable %uvec3ptr Input\n"
17719                 "${CONST}\n"
17720                 "%main      = OpFunction %void None %voidf\n"
17721                 "%label     = OpLabel\n"
17722                 "%idval     = OpLoad %uvec3 %id\n"
17723                 "%x         = OpCompositeExtract %u32 %idval 0\n"
17724                 "%inloc     = OpAccessChain %f32ptr %indata %c0i32 %x\n"
17725
17726                 "${TEST}\n"
17727
17728                 "%outloc    = OpAccessChain %f32ptr %outdata %c0i32 %x\n"
17729                 "             OpStore %outloc %res\n"
17730                 "             OpReturn\n"
17731                 "             OpFunctionEnd\n"
17732         );
17733
17734         // Each test case produces 4 boolean values, and we want each of these values
17735         // to come froma different combination of the available bit-sizes, so compute
17736         // all possible combinations here.
17737         vector<deUint32>        widths;
17738         widths.push_back(32);
17739         widths.push_back(16);
17740         widths.push_back(8);
17741
17742         vector<IVec4>   cases;
17743         for (size_t width0 = 0; width0 < widths.size(); width0++)
17744         {
17745                 for (size_t width1 = 0; width1 < widths.size(); width1++)
17746                 {
17747                         for (size_t width2 = 0; width2 < widths.size(); width2++)
17748                         {
17749                                 for (size_t width3 = 0; width3 < widths.size(); width3++)
17750                                 {
17751                                         cases.push_back(IVec4(widths[width0], widths[width1], widths[width2], widths[width3]));
17752                                 }
17753                         }
17754                 }
17755         }
17756
17757         for (size_t caseNdx = 0; caseNdx < cases.size(); caseNdx++)
17758         {
17759                 /// Skip cases where all bitsizes are the same, we are only interested in testing booleans produced from instructions with different native bit-sizes
17760                 if (cases[caseNdx][0] == cases[caseNdx][1] && cases[caseNdx][0] == cases[caseNdx][2] && cases[caseNdx][0] == cases[caseNdx][3])
17761                         continue;
17762
17763                 map<string, string>     specializations;
17764                 ComputeShaderSpec       spec;
17765
17766                 // Inject appropriate capabilities and reference constants depending
17767                 // on the bit-sizes required by this test case
17768                 bool hasFloat32 = cases[caseNdx][0] == 32 || cases[caseNdx][1] == 32 || cases[caseNdx][2] == 32 || cases[caseNdx][3] == 32;
17769                 bool hasFloat16 = cases[caseNdx][0] == 16 || cases[caseNdx][1] == 16 || cases[caseNdx][2] == 16 || cases[caseNdx][3] == 16;
17770                 bool hasInt8    = cases[caseNdx][0] == 8 || cases[caseNdx][1] == 8 || cases[caseNdx][2] == 8 || cases[caseNdx][3] == 8;
17771
17772                 string capsStr  = "OpCapability Shader\n";
17773                 string constStr =
17774                         "%c0i32     = OpConstant %i32 0\n"
17775                         "%c1f32     = OpConstant %f32 1.0\n"
17776                         "%c0f32     = OpConstant %f32 0.0\n";
17777
17778                 if (hasFloat32)
17779                 {
17780                         constStr        +=
17781                                 "%c10f32    = OpConstant %f32 10.0\n"
17782                                 "%c25f32    = OpConstant %f32 25.0\n"
17783                                 "%c50f32    = OpConstant %f32 50.0\n"
17784                                 "%c90f32    = OpConstant %f32 90.0\n";
17785                 }
17786
17787                 if (hasFloat16)
17788                 {
17789                         capsStr         += "OpCapability Float16\n";
17790                         constStr        +=
17791                                 "%f16       = OpTypeFloat 16\n"
17792                                 "%c10f16    = OpConstant %f16 10.0\n"
17793                                 "%c25f16    = OpConstant %f16 25.0\n"
17794                                 "%c50f16    = OpConstant %f16 50.0\n"
17795                                 "%c90f16    = OpConstant %f16 90.0\n";
17796                 }
17797
17798                 if (hasInt8)
17799                 {
17800                         capsStr         += "OpCapability Int8\n";
17801                         constStr        +=
17802                                 "%i8        = OpTypeInt 8 1\n"
17803                                 "%c10i8     = OpConstant %i8 10\n"
17804                                 "%c25i8     = OpConstant %i8 25\n"
17805                                 "%c50i8     = OpConstant %i8 50\n"
17806                                 "%c90i8     = OpConstant %i8 90\n";
17807                 }
17808
17809                 // Each invocation reads a different float32 value as input. Depending on
17810                 // the bit-sizes required by the particular test case, we also produce
17811                 // float16 and/or and int8 values by converting from the 32-bit float.
17812                 string testStr  = "";
17813                 testStr                 += "%inval32   = OpLoad %f32 %inloc\n";
17814                 if (hasFloat16)
17815                         testStr         += "%inval16   = OpFConvert %f16 %inval32\n";
17816                 if (hasInt8)
17817                         testStr         += "%inval8    = OpConvertFToS %i8 %inval32\n";
17818
17819                 // Because conversions from Float to Int round towards 0 we want our "greater" comparisons to be >=,
17820                 // that way a float32/float16 comparison such as 50.6f >= 50.0f will preserve its result
17821                 // when converted to int8, since FtoS(50.6f) results in 50. For "less" comparisons, it is the
17822                 // other way around, so in this case we want < instead of <=.
17823                 if (cases[caseNdx][0] == 32)
17824                         testStr         += "%cmp1      = OpFOrdGreaterThanEqual %bool %inval32 %c25f32\n";
17825                 else if (cases[caseNdx][0] == 16)
17826                         testStr         += "%cmp1      = OpFOrdGreaterThanEqual %bool %inval16 %c25f16\n";
17827                 else
17828                         testStr         += "%cmp1      = OpSGreaterThanEqual %bool %inval8 %c25i8\n";
17829
17830                 if (cases[caseNdx][1] == 32)
17831                         testStr         += "%cmp2      = OpFOrdLessThan %bool %inval32 %c50f32\n";
17832                 else if (cases[caseNdx][1] == 16)
17833                         testStr         += "%cmp2      = OpFOrdLessThan %bool %inval16 %c50f16\n";
17834                 else
17835                         testStr         += "%cmp2      = OpSLessThan %bool %inval8 %c50i8\n";
17836
17837                 if (cases[caseNdx][2] == 32)
17838                         testStr         += "%cmp3      = OpFOrdLessThan %bool %inval32 %c10f32\n";
17839                 else if (cases[caseNdx][2] == 16)
17840                         testStr         += "%cmp3      = OpFOrdLessThan %bool %inval16 %c10f16\n";
17841                 else
17842                         testStr         += "%cmp3      = OpSLessThan %bool %inval8 %c10i8\n";
17843
17844                 if (cases[caseNdx][3] == 32)
17845                         testStr         += "%cmp4      = OpFOrdGreaterThanEqual %bool %inval32 %c90f32\n";
17846                 else if (cases[caseNdx][3] == 16)
17847                         testStr         += "%cmp4      = OpFOrdGreaterThanEqual %bool %inval16 %c90f16\n";
17848                 else
17849                         testStr         += "%cmp4      = OpSGreaterThanEqual %bool %inval8 %c90i8\n";
17850
17851                 testStr                 += "%and1      = OpLogicalAnd %bool %cmp1 %cmp2\n";
17852                 testStr                 += "%or1       = OpLogicalOr %bool %cmp3 %cmp4\n";
17853                 testStr                 += "%or2       = OpLogicalOr %bool %and1 %or1\n";
17854                 testStr                 += "%not1      = OpLogicalNot %bool %or2\n";
17855                 testStr                 += "%res       = OpSelect %f32 %not1 %c1f32 %c0f32\n";
17856
17857                 specializations["CAPS"]         = capsStr;
17858                 specializations["CONST"]        = constStr;
17859                 specializations["TEST"]         = testStr;
17860
17861                 // Compute expected result by evaluating the boolean expression computed in the shader for each input value
17862                 for (size_t ndx = 0; ndx < numElements; ++ndx)
17863                         outputData[ndx] = !((inputData[ndx] >= 25.0f && inputData[ndx] < 50.0f) || (inputData[ndx] < 10.0f || inputData[ndx] >= 90.0f));
17864
17865                 spec.assembly = shaderTemplate.specialize(specializations);
17866                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputData)));
17867                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputData)));
17868                 spec.numWorkGroups = IVec3(numElements, 1, 1);
17869                 if (hasFloat16)
17870                         spec.requestedVulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_FLOAT16;
17871                 if (hasInt8)
17872                         spec.requestedVulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_INT8;
17873                 spec.extensions.push_back("VK_KHR_shader_float16_int8");
17874
17875                 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]);
17876                 group->addChild(new SpvAsmComputeShaderCase(testCtx, testName.c_str(), "", spec));
17877         }
17878
17879         return group.release();
17880 }
17881
17882 tcu::TestCaseGroup* createBoolGroup (tcu::TestContext& testCtx)
17883 {
17884         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "bool", "Boolean tests"));
17885
17886         testGroup->addChild(createBoolMixedBitSizeGroup(testCtx));
17887
17888         return testGroup.release();
17889 }
17890
17891 tcu::TestCaseGroup* createOpNameAbuseTests (tcu::TestContext& testCtx)
17892 {
17893         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "opname_abuse", "OpName abuse tests"));
17894         vector<CaseParameter>                   abuseCases;
17895         RGBA                                                    defaultColors[4];
17896         map<string, string>                             opNameFragments;
17897
17898         getOpNameAbuseCases(abuseCases);
17899         getDefaultColors(defaultColors);
17900
17901         opNameFragments["testfun"] =
17902                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17903                 "%param1     = OpFunctionParameter %v4f32\n"
17904                 "%label_func = OpLabel\n"
17905                 "%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17906                 "%b          = OpFAdd %f32 %a %a\n"
17907                 "%c          = OpFSub %f32 %b %a\n"
17908                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
17909                 "OpReturnValue %ret\n"
17910                 "OpFunctionEnd\n";
17911
17912         for (unsigned int i = 0; i < abuseCases.size(); i++)
17913         {
17914                 string casename;
17915                 casename = string("main") + abuseCases[i].name;
17916
17917                 opNameFragments["debug"] =
17918                         "OpName %BP_main \"" + abuseCases[i].param + "\"";
17919
17920                 createTestsForAllStages(casename, defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17921         }
17922
17923         for (unsigned int i = 0; i < abuseCases.size(); i++)
17924         {
17925                 string casename;
17926                 casename = string("b") + abuseCases[i].name;
17927
17928                 opNameFragments["debug"] =
17929                         "OpName %b \"" + abuseCases[i].param + "\"";
17930
17931                 createTestsForAllStages(casename, defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17932         }
17933
17934         {
17935                 opNameFragments["debug"] =
17936                         "OpName %test_code \"name1\"\n"
17937                         "OpName %param1    \"name2\"\n"
17938                         "OpName %a         \"name3\"\n"
17939                         "OpName %b         \"name4\"\n"
17940                         "OpName %c         \"name5\"\n"
17941                         "OpName %ret       \"name6\"\n";
17942
17943                 createTestsForAllStages("everything_named", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17944         }
17945
17946         {
17947                 opNameFragments["debug"] =
17948                         "OpName %test_code \"the_same\"\n"
17949                         "OpName %param1    \"the_same\"\n"
17950                         "OpName %a         \"the_same\"\n"
17951                         "OpName %b         \"the_same\"\n"
17952                         "OpName %c         \"the_same\"\n"
17953                         "OpName %ret       \"the_same\"\n";
17954
17955                 createTestsForAllStages("everything_named_the_same", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17956         }
17957
17958         {
17959                 opNameFragments["debug"] =
17960                         "OpName %BP_main \"to_be\"\n"
17961                         "OpName %BP_main \"or_not\"\n"
17962                         "OpName %BP_main \"to_be\"\n";
17963
17964                 createTestsForAllStages("main_has_multiple_names", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17965         }
17966
17967         {
17968                 opNameFragments["debug"] =
17969                         "OpName %b \"to_be\"\n"
17970                         "OpName %b \"or_not\"\n"
17971                         "OpName %b \"to_be\"\n";
17972
17973                 createTestsForAllStages("b_has_multiple_names", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17974         }
17975
17976         return abuseGroup.release();
17977 }
17978
17979
17980 tcu::TestCaseGroup* createOpMemberNameAbuseTests (tcu::TestContext& testCtx)
17981 {
17982         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "opmembername_abuse", "OpName abuse tests"));
17983         vector<CaseParameter>                   abuseCases;
17984         RGBA                                                    defaultColors[4];
17985         map<string, string>                             opMemberNameFragments;
17986
17987         getOpNameAbuseCases(abuseCases);
17988         getDefaultColors(defaultColors);
17989
17990         opMemberNameFragments["pre_main"] =
17991                 "%f3str = OpTypeStruct %f32 %f32 %f32\n";
17992
17993         opMemberNameFragments["testfun"] =
17994                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17995                 "%param1     = OpFunctionParameter %v4f32\n"
17996                 "%label_func = OpLabel\n"
17997                 "%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17998                 "%b          = OpFAdd %f32 %a %a\n"
17999                 "%c          = OpFSub %f32 %b %a\n"
18000                 "%cstr       = OpCompositeConstruct %f3str %c %c %c\n"
18001                 "%d          = OpCompositeExtract %f32 %cstr 0\n"
18002                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %d %c_i32_0\n"
18003                 "OpReturnValue %ret\n"
18004                 "OpFunctionEnd\n";
18005
18006         for (unsigned int i = 0; i < abuseCases.size(); i++)
18007         {
18008                 string casename;
18009                 casename = string("f3str_x") + abuseCases[i].name;
18010
18011                 opMemberNameFragments["debug"] =
18012                         "OpMemberName %f3str 0 \"" + abuseCases[i].param + "\"";
18013
18014                 createTestsForAllStages(casename, defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18015         }
18016
18017         {
18018                 opMemberNameFragments["debug"] =
18019                         "OpMemberName %f3str 0 \"name1\"\n"
18020                         "OpMemberName %f3str 1 \"name2\"\n"
18021                         "OpMemberName %f3str 2 \"name3\"\n";
18022
18023                 createTestsForAllStages("everything_named", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18024         }
18025
18026         {
18027                 opMemberNameFragments["debug"] =
18028                         "OpMemberName %f3str 0 \"the_same\"\n"
18029                         "OpMemberName %f3str 1 \"the_same\"\n"
18030                         "OpMemberName %f3str 2 \"the_same\"\n";
18031
18032                 createTestsForAllStages("everything_named_the_same", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18033         }
18034
18035         {
18036                 opMemberNameFragments["debug"] =
18037                         "OpMemberName %f3str 0 \"to_be\"\n"
18038                         "OpMemberName %f3str 1 \"or_not\"\n"
18039                         "OpMemberName %f3str 0 \"to_be\"\n"
18040                         "OpMemberName %f3str 2 \"makes_no\"\n"
18041                         "OpMemberName %f3str 0 \"difference\"\n"
18042                         "OpMemberName %f3str 0 \"to_me\"\n";
18043
18044
18045                 createTestsForAllStages("f3str_x_has_multiple_names", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18046         }
18047
18048         return abuseGroup.release();
18049 }
18050
18051 vector<deUint32> getSparseIdsAbuseData (const deUint32 numDataPoints, const deUint32 seed)
18052 {
18053         vector<deUint32>        result;
18054         de::Random                      rnd             (seed);
18055
18056         result.reserve(numDataPoints);
18057
18058         for (deUint32 dataPointNdx = 0; dataPointNdx < numDataPoints; ++dataPointNdx)
18059                 result.push_back(rnd.getUint32());
18060
18061         return result;
18062 }
18063
18064 vector<deUint32> getSparseIdsAbuseResults (const vector<deUint32>& inData1, const vector<deUint32>& inData2)
18065 {
18066         vector<deUint32>        result;
18067
18068         result.reserve(inData1.size());
18069
18070         for (size_t dataPointNdx = 0; dataPointNdx < inData1.size(); ++dataPointNdx)
18071                 result.push_back(inData1[dataPointNdx] + inData2[dataPointNdx]);
18072
18073         return result;
18074 }
18075
18076 template<class SpecResource>
18077 void createSparseIdsAbuseTest (tcu::TestContext& testCtx, de::MovePtr<tcu::TestCaseGroup>& testGroup)
18078 {
18079         const deUint32                  numDataPoints   = 16;
18080         const std::string               testName                ("sparse_ids");
18081         const deUint32                  seed                    (deStringHash(testName.c_str()));
18082         const vector<deUint32>  inData1                 (getSparseIdsAbuseData(numDataPoints, seed + 1));
18083         const vector<deUint32>  inData2                 (getSparseIdsAbuseData(numDataPoints, seed + 2));
18084         const vector<deUint32>  outData                 (getSparseIdsAbuseResults(inData1, inData2));
18085         const StringTemplate    preMain
18086         (
18087                 "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
18088                 "   %up_u32 = OpTypePointer Uniform %u32\n"
18089                 "   %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
18090                 "   %SSBO32 = OpTypeStruct %ra_u32\n"
18091                 "%up_SSBO32 = OpTypePointer Uniform %SSBO32\n"
18092                 "%ssbo_src0 = OpVariable %up_SSBO32 Uniform\n"
18093                 "%ssbo_src1 = OpVariable %up_SSBO32 Uniform\n"
18094                 " %ssbo_dst = OpVariable %up_SSBO32 Uniform\n"
18095         );
18096         const StringTemplate    decoration
18097         (
18098                 "OpDecorate %ra_u32 ArrayStride 4\n"
18099                 "OpMemberDecorate %SSBO32 0 Offset 0\n"
18100                 "OpDecorate %SSBO32 BufferBlock\n"
18101                 "OpDecorate %ssbo_src0 DescriptorSet 0\n"
18102                 "OpDecorate %ssbo_src0 Binding 0\n"
18103                 "OpDecorate %ssbo_src1 DescriptorSet 0\n"
18104                 "OpDecorate %ssbo_src1 Binding 1\n"
18105                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
18106                 "OpDecorate %ssbo_dst Binding 2\n"
18107         );
18108         const StringTemplate    testFun
18109         (
18110                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
18111                 "    %param = OpFunctionParameter %v4f32\n"
18112
18113                 "    %entry = OpLabel\n"
18114                 "        %i = OpVariable %fp_i32 Function\n"
18115                 "             OpStore %i %c_i32_0\n"
18116                 "             OpBranch %loop\n"
18117
18118                 "     %loop = OpLabel\n"
18119                 "    %i_cmp = OpLoad %i32 %i\n"
18120                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
18121                 "             OpLoopMerge %merge %next None\n"
18122                 "             OpBranchConditional %lt %write %merge\n"
18123
18124                 "    %write = OpLabel\n"
18125                 "      %ndx = OpLoad %i32 %i\n"
18126
18127                 "      %127 = OpAccessChain %up_u32 %ssbo_src0 %c_i32_0 %ndx\n"
18128                 "      %128 = OpLoad %u32 %127\n"
18129
18130                 // The test relies on SPIR-V compiler option SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS set in assembleSpirV()
18131                 "  %4194000 = OpAccessChain %up_u32 %ssbo_src1 %c_i32_0 %ndx\n"
18132                 "  %4194001 = OpLoad %u32 %4194000\n"
18133
18134                 "  %2097151 = OpIAdd %u32 %128 %4194001\n"
18135                 "  %2097152 = OpAccessChain %up_u32 %ssbo_dst %c_i32_0 %ndx\n"
18136                 "             OpStore %2097152 %2097151\n"
18137                 "             OpBranch %next\n"
18138
18139                 "     %next = OpLabel\n"
18140                 "    %i_cur = OpLoad %i32 %i\n"
18141                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
18142                 "             OpStore %i %i_new\n"
18143                 "             OpBranch %loop\n"
18144
18145                 "    %merge = OpLabel\n"
18146                 "             OpReturnValue %param\n"
18147
18148                 "             OpFunctionEnd\n"
18149         );
18150         SpecResource                    specResource;
18151         map<string, string>             specs;
18152         VulkanFeatures                  features;
18153         map<string, string>             fragments;
18154         vector<string>                  extensions;
18155
18156         specs["num_data_points"]        = de::toString(numDataPoints);
18157
18158         fragments["decoration"]         = decoration.specialize(specs);
18159         fragments["pre_main"]           = preMain.specialize(specs);
18160         fragments["testfun"]            = testFun.specialize(specs);
18161
18162         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18163         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18164         specResource.outputs.push_back(Resource(BufferSp(new Uint32Buffer(outData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18165
18166         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
18167 }
18168
18169 vector<deUint32> getLotsIdsAbuseData (const deUint32 numDataPoints, const deUint32 seed)
18170 {
18171         vector<deUint32>        result;
18172         de::Random                      rnd             (seed);
18173
18174         result.reserve(numDataPoints);
18175
18176         // Fixed value
18177         result.push_back(1u);
18178
18179         // Random values
18180         for (deUint32 dataPointNdx = 1; dataPointNdx < numDataPoints; ++dataPointNdx)
18181                 result.push_back(rnd.getUint8());
18182
18183         return result;
18184 }
18185
18186 vector<deUint32> getLotsIdsAbuseResults (const vector<deUint32>& inData1, const vector<deUint32>& inData2, const deUint32 count)
18187 {
18188         vector<deUint32>        result;
18189
18190         result.reserve(inData1.size());
18191
18192         for (size_t dataPointNdx = 0; dataPointNdx < inData1.size(); ++dataPointNdx)
18193                 result.push_back(inData1[dataPointNdx] + count * inData2[dataPointNdx]);
18194
18195         return result;
18196 }
18197
18198 template<class SpecResource>
18199 void createLotsIdsAbuseTest (tcu::TestContext& testCtx, de::MovePtr<tcu::TestCaseGroup>& testGroup)
18200 {
18201         const deUint32                  numDataPoints   = 16;
18202         const deUint32                  firstNdx                = 100u;
18203         const deUint32                  sequenceCount   = 10000u;
18204         const std::string               testName                ("lots_ids");
18205         const deUint32                  seed                    (deStringHash(testName.c_str()));
18206         const vector<deUint32>  inData1                 (getLotsIdsAbuseData(numDataPoints, seed + 1));
18207         const vector<deUint32>  inData2                 (getLotsIdsAbuseData(numDataPoints, seed + 2));
18208         const vector<deUint32>  outData                 (getLotsIdsAbuseResults(inData1, inData2, sequenceCount));
18209         const StringTemplate preMain
18210         (
18211                 "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
18212                 "   %up_u32 = OpTypePointer Uniform %u32\n"
18213                 "   %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
18214                 "   %SSBO32 = OpTypeStruct %ra_u32\n"
18215                 "%up_SSBO32 = OpTypePointer Uniform %SSBO32\n"
18216                 "%ssbo_src0 = OpVariable %up_SSBO32 Uniform\n"
18217                 "%ssbo_src1 = OpVariable %up_SSBO32 Uniform\n"
18218                 " %ssbo_dst = OpVariable %up_SSBO32 Uniform\n"
18219         );
18220         const StringTemplate decoration
18221         (
18222                 "OpDecorate %ra_u32 ArrayStride 4\n"
18223                 "OpMemberDecorate %SSBO32 0 Offset 0\n"
18224                 "OpDecorate %SSBO32 BufferBlock\n"
18225                 "OpDecorate %ssbo_src0 DescriptorSet 0\n"
18226                 "OpDecorate %ssbo_src0 Binding 0\n"
18227                 "OpDecorate %ssbo_src1 DescriptorSet 0\n"
18228                 "OpDecorate %ssbo_src1 Binding 1\n"
18229                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
18230                 "OpDecorate %ssbo_dst Binding 2\n"
18231         );
18232         const StringTemplate testFun
18233         (
18234                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
18235                 "    %param = OpFunctionParameter %v4f32\n"
18236
18237                 "    %entry = OpLabel\n"
18238                 "        %i = OpVariable %fp_i32 Function\n"
18239                 "             OpStore %i %c_i32_0\n"
18240                 "             OpBranch %loop\n"
18241
18242                 "     %loop = OpLabel\n"
18243                 "    %i_cmp = OpLoad %i32 %i\n"
18244                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
18245                 "             OpLoopMerge %merge %next None\n"
18246                 "             OpBranchConditional %lt %write %merge\n"
18247
18248                 "    %write = OpLabel\n"
18249                 "      %ndx = OpLoad %i32 %i\n"
18250
18251                 "       %90 = OpAccessChain %up_u32 %ssbo_src1 %c_i32_0 %ndx\n"
18252                 "       %91 = OpLoad %u32 %90\n"
18253
18254                 "       %98 = OpAccessChain %up_u32 %ssbo_src0 %c_i32_0 %ndx\n"
18255                 "       %${zeroth_id} = OpLoad %u32 %98\n"
18256
18257                 "${seq}\n"
18258
18259                 // The test relies on SPIR-V compiler option SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS set in assembleSpirV()
18260                 "      %dst = OpAccessChain %up_u32 %ssbo_dst %c_i32_0 %ndx\n"
18261                 "             OpStore %dst %${last_id}\n"
18262                 "             OpBranch %next\n"
18263
18264                 "     %next = OpLabel\n"
18265                 "    %i_cur = OpLoad %i32 %i\n"
18266                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
18267                 "             OpStore %i %i_new\n"
18268                 "             OpBranch %loop\n"
18269
18270                 "    %merge = OpLabel\n"
18271                 "             OpReturnValue %param\n"
18272
18273                 "             OpFunctionEnd\n"
18274         );
18275         deUint32                                lastId                  = firstNdx;
18276         SpecResource                    specResource;
18277         map<string, string>             specs;
18278         VulkanFeatures                  features;
18279         map<string, string>             fragments;
18280         vector<string>                  extensions;
18281         std::string                             sequence;
18282
18283         for (deUint32 sequenceNdx = 0; sequenceNdx < sequenceCount; ++sequenceNdx)
18284         {
18285                 const deUint32          sequenceId              = sequenceNdx + firstNdx;
18286                 const std::string       sequenceIdStr   = de::toString(sequenceId);
18287
18288                 sequence += "%" + sequenceIdStr + " = OpIAdd %u32 %91 %" + de::toString(sequenceId - 1) + "\n";
18289                 lastId = sequenceId;
18290
18291                 if (sequenceNdx == 0)
18292                         sequence.reserve((10 + sequence.length()) * sequenceCount);
18293         }
18294
18295         specs["num_data_points"]        = de::toString(numDataPoints);
18296         specs["zeroth_id"]                      = de::toString(firstNdx - 1);
18297         specs["last_id"]                        = de::toString(lastId);
18298         specs["seq"]                            = sequence;
18299
18300         fragments["decoration"]         = decoration.specialize(specs);
18301         fragments["pre_main"]           = preMain.specialize(specs);
18302         fragments["testfun"]            = testFun.specialize(specs);
18303
18304         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18305         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18306         specResource.outputs.push_back(Resource(BufferSp(new Uint32Buffer(outData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18307
18308         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
18309 }
18310
18311 tcu::TestCaseGroup* createSpirvIdsAbuseTests (tcu::TestContext& testCtx)
18312 {
18313         de::MovePtr<tcu::TestCaseGroup> testGroup       (new tcu::TestCaseGroup(testCtx, "spirv_ids_abuse", "SPIR-V abuse tests"));
18314
18315         createSparseIdsAbuseTest<GraphicsResources>(testCtx, testGroup);
18316         createLotsIdsAbuseTest<GraphicsResources>(testCtx, testGroup);
18317
18318         return testGroup.release();
18319 }
18320
18321 tcu::TestCaseGroup* createSpirvIdsAbuseGroup (tcu::TestContext& testCtx)
18322 {
18323         de::MovePtr<tcu::TestCaseGroup> testGroup       (new tcu::TestCaseGroup(testCtx, "spirv_ids_abuse", "SPIR-V abuse tests"));
18324
18325         createSparseIdsAbuseTest<ComputeShaderSpec>(testCtx, testGroup);
18326         createLotsIdsAbuseTest<ComputeShaderSpec>(testCtx, testGroup);
18327
18328         return testGroup.release();
18329 }
18330
18331 tcu::TestCaseGroup* createInstructionTests (tcu::TestContext& testCtx)
18332 {
18333         const bool testComputePipeline = true;
18334
18335         de::MovePtr<tcu::TestCaseGroup> instructionTests        (new tcu::TestCaseGroup(testCtx, "instruction", "Instructions with special opcodes/operands"));
18336         de::MovePtr<tcu::TestCaseGroup> computeTests            (new tcu::TestCaseGroup(testCtx, "compute", "Compute Instructions with special opcodes/operands"));
18337         de::MovePtr<tcu::TestCaseGroup> graphicsTests           (new tcu::TestCaseGroup(testCtx, "graphics", "Graphics Instructions with special opcodes/operands"));
18338
18339         computeTests->addChild(createSpivVersionCheckTests(testCtx, testComputePipeline));
18340         computeTests->addChild(createLocalSizeGroup(testCtx));
18341         computeTests->addChild(createOpNopGroup(testCtx));
18342         computeTests->addChild(createOpFUnordGroup(testCtx, TEST_WITHOUT_NAN));
18343         computeTests->addChild(createOpFUnordGroup(testCtx, TEST_WITH_NAN));
18344         computeTests->addChild(createOpAtomicGroup(testCtx, false));
18345         computeTests->addChild(createOpAtomicGroup(testCtx, true));                                     // Using new StorageBuffer decoration
18346         computeTests->addChild(createOpAtomicGroup(testCtx, false, 1024, true));        // Return value validation
18347         computeTests->addChild(createOpLineGroup(testCtx));
18348         computeTests->addChild(createOpModuleProcessedGroup(testCtx));
18349         computeTests->addChild(createOpNoLineGroup(testCtx));
18350         computeTests->addChild(createOpConstantNullGroup(testCtx));
18351         computeTests->addChild(createOpConstantCompositeGroup(testCtx));
18352         computeTests->addChild(createOpConstantUsageGroup(testCtx));
18353         computeTests->addChild(createSpecConstantGroup(testCtx));
18354         computeTests->addChild(createOpSourceGroup(testCtx));
18355         computeTests->addChild(createOpSourceExtensionGroup(testCtx));
18356         computeTests->addChild(createDecorationGroupGroup(testCtx));
18357         computeTests->addChild(createOpPhiGroup(testCtx));
18358         computeTests->addChild(createLoopControlGroup(testCtx));
18359         computeTests->addChild(createFunctionControlGroup(testCtx));
18360         computeTests->addChild(createSelectionControlGroup(testCtx));
18361         computeTests->addChild(createBlockOrderGroup(testCtx));
18362         computeTests->addChild(createMultipleShaderGroup(testCtx));
18363         computeTests->addChild(createMemoryAccessGroup(testCtx));
18364         computeTests->addChild(createOpCopyMemoryGroup(testCtx));
18365         computeTests->addChild(createOpCopyObjectGroup(testCtx));
18366         computeTests->addChild(createNoContractionGroup(testCtx));
18367         computeTests->addChild(createOpUndefGroup(testCtx));
18368         computeTests->addChild(createOpUnreachableGroup(testCtx));
18369         computeTests->addChild(createOpQuantizeToF16Group(testCtx));
18370         computeTests->addChild(createOpFRemGroup(testCtx));
18371         computeTests->addChild(createOpSRemComputeGroup(testCtx, QP_TEST_RESULT_PASS));
18372         computeTests->addChild(createOpSRemComputeGroup64(testCtx, QP_TEST_RESULT_PASS));
18373         computeTests->addChild(createOpSModComputeGroup(testCtx, QP_TEST_RESULT_PASS));
18374         computeTests->addChild(createOpSModComputeGroup64(testCtx, QP_TEST_RESULT_PASS));
18375         computeTests->addChild(createConvertComputeTests(testCtx, "OpSConvert", "sconvert"));
18376         computeTests->addChild(createConvertComputeTests(testCtx, "OpUConvert", "uconvert"));
18377         computeTests->addChild(createConvertComputeTests(testCtx, "OpFConvert", "fconvert"));
18378         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertSToF", "convertstof"));
18379         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertFToS", "convertftos"));
18380         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertUToF", "convertutof"));
18381         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertFToU", "convertftou"));
18382         computeTests->addChild(createOpCompositeInsertGroup(testCtx));
18383         computeTests->addChild(createOpInBoundsAccessChainGroup(testCtx));
18384         computeTests->addChild(createShaderDefaultOutputGroup(testCtx));
18385         computeTests->addChild(createOpNMinGroup(testCtx));
18386         computeTests->addChild(createOpNMaxGroup(testCtx));
18387         computeTests->addChild(createOpNClampGroup(testCtx));
18388         {
18389                 de::MovePtr<tcu::TestCaseGroup> computeAndroidTests     (new tcu::TestCaseGroup(testCtx, "android", "Android CTS Tests"));
18390
18391                 computeAndroidTests->addChild(createOpSRemComputeGroup(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18392                 computeAndroidTests->addChild(createOpSModComputeGroup(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18393
18394                 computeTests->addChild(computeAndroidTests.release());
18395         }
18396
18397         computeTests->addChild(create8BitStorageComputeGroup(testCtx));
18398         computeTests->addChild(create16BitStorageComputeGroup(testCtx));
18399         computeTests->addChild(createFloatControlsComputeGroup(testCtx));
18400         computeTests->addChild(createUboMatrixPaddingComputeGroup(testCtx));
18401         computeTests->addChild(createCompositeInsertComputeGroup(testCtx));
18402         computeTests->addChild(createVariableInitComputeGroup(testCtx));
18403         computeTests->addChild(createConditionalBranchComputeGroup(testCtx));
18404         computeTests->addChild(createIndexingComputeGroup(testCtx));
18405         computeTests->addChild(createVariablePointersComputeGroup(testCtx));
18406         computeTests->addChild(createPhysicalPointersComputeGroup(testCtx));
18407         computeTests->addChild(createImageSamplerComputeGroup(testCtx));
18408         computeTests->addChild(createOpNameGroup(testCtx));
18409         computeTests->addChild(createOpMemberNameGroup(testCtx));
18410         computeTests->addChild(createPointerParameterComputeGroup(testCtx));
18411         computeTests->addChild(createFloat16Group(testCtx));
18412         computeTests->addChild(createBoolGroup(testCtx));
18413         computeTests->addChild(createWorkgroupMemoryComputeGroup(testCtx));
18414         computeTests->addChild(createSpirvIdsAbuseGroup(testCtx));
18415
18416         graphicsTests->addChild(createCrossStageInterfaceTests(testCtx));
18417         graphicsTests->addChild(createSpivVersionCheckTests(testCtx, !testComputePipeline));
18418         graphicsTests->addChild(createOpNopTests(testCtx));
18419         graphicsTests->addChild(createOpSourceTests(testCtx));
18420         graphicsTests->addChild(createOpSourceContinuedTests(testCtx));
18421         graphicsTests->addChild(createOpModuleProcessedTests(testCtx));
18422         graphicsTests->addChild(createOpLineTests(testCtx));
18423         graphicsTests->addChild(createOpNoLineTests(testCtx));
18424         graphicsTests->addChild(createOpConstantNullTests(testCtx));
18425         graphicsTests->addChild(createOpConstantCompositeTests(testCtx));
18426         graphicsTests->addChild(createMemoryAccessTests(testCtx));
18427         graphicsTests->addChild(createOpUndefTests(testCtx));
18428         graphicsTests->addChild(createSelectionBlockOrderTests(testCtx));
18429         graphicsTests->addChild(createModuleTests(testCtx));
18430         graphicsTests->addChild(createSwitchBlockOrderTests(testCtx));
18431         graphicsTests->addChild(createOpPhiTests(testCtx));
18432         graphicsTests->addChild(createNoContractionTests(testCtx));
18433         graphicsTests->addChild(createOpQuantizeTests(testCtx));
18434         graphicsTests->addChild(createLoopTests(testCtx));
18435         graphicsTests->addChild(createSpecConstantTests(testCtx));
18436         graphicsTests->addChild(createSpecConstantOpQuantizeToF16Group(testCtx));
18437         graphicsTests->addChild(createBarrierTests(testCtx));
18438         graphicsTests->addChild(createDecorationGroupTests(testCtx));
18439         graphicsTests->addChild(createFRemTests(testCtx));
18440         graphicsTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
18441         graphicsTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
18442
18443         {
18444                 de::MovePtr<tcu::TestCaseGroup> graphicsAndroidTests    (new tcu::TestCaseGroup(testCtx, "android", "Android CTS Tests"));
18445
18446                 graphicsAndroidTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18447                 graphicsAndroidTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18448
18449                 graphicsTests->addChild(graphicsAndroidTests.release());
18450         }
18451         graphicsTests->addChild(createOpNameTests(testCtx));
18452         graphicsTests->addChild(createOpNameAbuseTests(testCtx));
18453         graphicsTests->addChild(createOpMemberNameAbuseTests(testCtx));
18454
18455         graphicsTests->addChild(create8BitStorageGraphicsGroup(testCtx));
18456         graphicsTests->addChild(create16BitStorageGraphicsGroup(testCtx));
18457         graphicsTests->addChild(createFloatControlsGraphicsGroup(testCtx));
18458         graphicsTests->addChild(createUboMatrixPaddingGraphicsGroup(testCtx));
18459         graphicsTests->addChild(createCompositeInsertGraphicsGroup(testCtx));
18460         graphicsTests->addChild(createVariableInitGraphicsGroup(testCtx));
18461         graphicsTests->addChild(createConditionalBranchGraphicsGroup(testCtx));
18462         graphicsTests->addChild(createIndexingGraphicsGroup(testCtx));
18463         graphicsTests->addChild(createVariablePointersGraphicsGroup(testCtx));
18464         graphicsTests->addChild(createImageSamplerGraphicsGroup(testCtx));
18465         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpSConvert", "sconvert"));
18466         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpUConvert", "uconvert"));
18467         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpFConvert", "fconvert"));
18468         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertSToF", "convertstof"));
18469         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertFToS", "convertftos"));
18470         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertUToF", "convertutof"));
18471         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertFToU", "convertftou"));
18472         graphicsTests->addChild(createPointerParameterGraphicsGroup(testCtx));
18473         graphicsTests->addChild(createVaryingNameGraphicsGroup(testCtx));
18474         graphicsTests->addChild(createFloat16Tests(testCtx));
18475         graphicsTests->addChild(createSpirvIdsAbuseTests(testCtx));
18476
18477         instructionTests->addChild(computeTests.release());
18478         instructionTests->addChild(graphicsTests.release());
18479
18480         return instructionTests.release();
18481 }
18482
18483 } // SpirVAssembly
18484 } // vkt