Merge vk-gl-cts/vulkan-cts-1.1.1 into vk-gl-cts/vulkan-cts-1.1.2
[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
72 #include <cmath>
73 #include <limits>
74 #include <map>
75 #include <string>
76 #include <sstream>
77 #include <utility>
78 #include <stack>
79
80 namespace vkt
81 {
82 namespace SpirVAssembly
83 {
84
85 namespace
86 {
87
88 using namespace vk;
89 using std::map;
90 using std::string;
91 using std::vector;
92 using tcu::IVec3;
93 using tcu::IVec4;
94 using tcu::RGBA;
95 using tcu::TestLog;
96 using tcu::TestStatus;
97 using tcu::Vec4;
98 using de::UniquePtr;
99 using tcu::StringTemplate;
100 using tcu::Vec4;
101
102 const bool TEST_WITHOUT_NAN     = false;
103
104 template<typename T>
105 static void fillRandomScalars (de::Random& rnd, T minValue, T maxValue, void* dst, int numValues, int offset = 0)
106 {
107         T* const typedPtr = (T*)dst;
108         for (int ndx = 0; ndx < numValues; ndx++)
109                 typedPtr[offset + ndx] = randomScalar<T>(rnd, minValue, maxValue);
110 }
111
112 // Filter is a function that returns true if a value should pass, false otherwise.
113 template<typename T, typename FilterT>
114 static void fillRandomScalars (de::Random& rnd, T minValue, T maxValue, void* dst, int numValues, FilterT filter, int offset = 0)
115 {
116         T* const typedPtr = (T*)dst;
117         T value;
118         for (int ndx = 0; ndx < numValues; ndx++)
119         {
120                 do
121                         value = randomScalar<T>(rnd, minValue, maxValue);
122                 while (!filter(value));
123
124                 typedPtr[offset + ndx] = value;
125         }
126 }
127
128 // Gets a 64-bit integer with a more logarithmic distribution
129 deInt64 randomInt64LogDistributed (de::Random& rnd)
130 {
131         deInt64 val = rnd.getUint64();
132         val &= (1ull << rnd.getInt(1, 63)) - 1;
133         if (rnd.getBool())
134                 val = -val;
135         return val;
136 }
137
138 static void fillRandomInt64sLogDistributed (de::Random& rnd, vector<deInt64>& dst, int numValues)
139 {
140         for (int ndx = 0; ndx < numValues; ndx++)
141                 dst[ndx] = randomInt64LogDistributed(rnd);
142 }
143
144 template<typename FilterT>
145 static void fillRandomInt64sLogDistributed (de::Random& rnd, vector<deInt64>& dst, int numValues, FilterT filter)
146 {
147         for (int ndx = 0; ndx < numValues; ndx++)
148         {
149                 deInt64 value;
150                 do {
151                         value = randomInt64LogDistributed(rnd);
152                 } while (!filter(value));
153                 dst[ndx] = value;
154         }
155 }
156
157 inline bool filterNonNegative (const deInt64 value)
158 {
159         return value >= 0;
160 }
161
162 inline bool filterPositive (const deInt64 value)
163 {
164         return value > 0;
165 }
166
167 inline bool filterNotZero (const deInt64 value)
168 {
169         return value != 0;
170 }
171
172 static void floorAll (vector<float>& values)
173 {
174         for (size_t i = 0; i < values.size(); i++)
175                 values[i] = deFloatFloor(values[i]);
176 }
177
178 static void floorAll (vector<Vec4>& values)
179 {
180         for (size_t i = 0; i < values.size(); i++)
181                 values[i] = floor(values[i]);
182 }
183
184 struct CaseParameter
185 {
186         const char*             name;
187         string                  param;
188
189         CaseParameter   (const char* case_, const string& param_) : name(case_), param(param_) {}
190 };
191
192 // Assembly code used for testing LocalSize, OpNop, OpConstant{Null|Composite}, Op[No]Line, OpSource[Continued], OpSourceExtension, OpUndef is based on GLSL source code:
193 //
194 // #version 430
195 //
196 // layout(std140, set = 0, binding = 0) readonly buffer Input {
197 //   float elements[];
198 // } input_data;
199 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
200 //   float elements[];
201 // } output_data;
202 //
203 // layout (local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
204 //
205 // void main() {
206 //   uint x = gl_GlobalInvocationID.x;
207 //   output_data.elements[x] = -input_data.elements[x];
208 // }
209
210 static string getAsmForLocalSizeTest(bool useLiteralLocalSize, bool useSpecConstantWorkgroupSize, IVec3 workGroupSize, deUint32 ndx)
211 {
212         std::ostringstream out;
213         out << getComputeAsmShaderPreambleWithoutLocalSize();
214
215         if (useLiteralLocalSize)
216         {
217                 out << "OpExecutionMode %main LocalSize "
218                         << workGroupSize.x() << " " << workGroupSize.y() << " " << workGroupSize.z() << "\n";
219         }
220
221         out << "OpSource GLSL 430\n"
222                 "OpName %main           \"main\"\n"
223                 "OpName %id             \"gl_GlobalInvocationID\"\n"
224                 "OpDecorate %id BuiltIn GlobalInvocationId\n";
225
226         if (useSpecConstantWorkgroupSize)
227         {
228                 out << "OpDecorate %spec_0 SpecId 100\n"
229                         << "OpDecorate %spec_1 SpecId 101\n"
230                         << "OpDecorate %spec_2 SpecId 102\n"
231                         << "OpDecorate %gl_WorkGroupSize BuiltIn WorkgroupSize\n";
232         }
233
234         out << getComputeAsmInputOutputBufferTraits()
235                 << getComputeAsmCommonTypes()
236                 << getComputeAsmInputOutputBuffer()
237                 << "%id        = OpVariable %uvec3ptr Input\n"
238                 << "%zero      = OpConstant %i32 0 \n";
239
240         if (useSpecConstantWorkgroupSize)
241         {
242                 out     << "%spec_0   = OpSpecConstant %u32 "<< workGroupSize.x() << "\n"
243                         << "%spec_1   = OpSpecConstant %u32 "<< workGroupSize.y() << "\n"
244                         << "%spec_2   = OpSpecConstant %u32 "<< workGroupSize.z() << "\n"
245                         << "%gl_WorkGroupSize = OpSpecConstantComposite %uvec3 %spec_0 %spec_1 %spec_2\n";
246         }
247
248         out << "%main      = OpFunction %void None %voidf\n"
249                 << "%label     = OpLabel\n"
250                 << "%idval     = OpLoad %uvec3 %id\n"
251                 << "%ndx         = OpCompositeExtract %u32 %idval " << ndx << "\n"
252
253                         "%inloc     = OpAccessChain %f32ptr %indata %zero %ndx\n"
254                         "%inval     = OpLoad %f32 %inloc\n"
255                         "%neg       = OpFNegate %f32 %inval\n"
256                         "%outloc    = OpAccessChain %f32ptr %outdata %zero %ndx\n"
257                         "             OpStore %outloc %neg\n"
258                         "             OpReturn\n"
259                         "             OpFunctionEnd\n";
260         return out.str();
261 }
262
263 tcu::TestCaseGroup* createLocalSizeGroup (tcu::TestContext& testCtx)
264 {
265         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "localsize", ""));
266         ComputeShaderSpec                               spec;
267         de::Random                                              rnd                             (deStringHash(group->getName()));
268         const deUint32                                  numElements             = 64u;
269         vector<float>                                   positiveFloats  (numElements, 0);
270         vector<float>                                   negativeFloats  (numElements, 0);
271
272         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
273
274         for (size_t ndx = 0; ndx < numElements; ++ndx)
275                 negativeFloats[ndx] = -positiveFloats[ndx];
276
277         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
278         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
279
280         spec.numWorkGroups = IVec3(numElements, 1, 1);
281
282         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, 1, 1), 0u);
283         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize", "", spec));
284
285         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, 1, 1), 0u);
286         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize", "", spec));
287
288         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, 1, 1), 0u);
289         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize", "", spec));
290
291         spec.numWorkGroups = IVec3(1, 1, 1);
292
293         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(numElements, 1, 1), 0u);
294         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_x", "", spec));
295
296         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(numElements, 1, 1), 0u);
297         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_x", "", spec));
298
299         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(numElements, 1, 1), 0u);
300         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_x", "", spec));
301
302         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, numElements, 1), 1u);
303         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_y", "", spec));
304
305         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, numElements, 1), 1u);
306         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_y", "", spec));
307
308         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, numElements, 1), 1u);
309         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_y", "", spec));
310
311         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, 1, numElements), 2u);
312         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_z", "", spec));
313
314         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, 1, numElements), 2u);
315         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_z", "", spec));
316
317         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, 1, numElements), 2u);
318         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_z", "", spec));
319
320         return group.release();
321 }
322
323 tcu::TestCaseGroup* createOpNopGroup (tcu::TestContext& testCtx)
324 {
325         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnop", "Test the OpNop instruction"));
326         ComputeShaderSpec                               spec;
327         de::Random                                              rnd                             (deStringHash(group->getName()));
328         const int                                               numElements             = 100;
329         vector<float>                                   positiveFloats  (numElements, 0);
330         vector<float>                                   negativeFloats  (numElements, 0);
331
332         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
333
334         for (size_t ndx = 0; ndx < numElements; ++ndx)
335                 negativeFloats[ndx] = -positiveFloats[ndx];
336
337         spec.assembly =
338                 string(getComputeAsmShaderPreamble()) +
339
340                 "OpSource GLSL 430\n"
341                 "OpName %main           \"main\"\n"
342                 "OpName %id             \"gl_GlobalInvocationID\"\n"
343
344                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
345
346                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes())
347
348                 + string(getComputeAsmInputOutputBuffer()) +
349
350                 "%id        = OpVariable %uvec3ptr Input\n"
351                 "%zero      = OpConstant %i32 0\n"
352
353                 "%main      = OpFunction %void None %voidf\n"
354                 "%label     = OpLabel\n"
355                 "%idval     = OpLoad %uvec3 %id\n"
356                 "%x         = OpCompositeExtract %u32 %idval 0\n"
357
358                 "             OpNop\n" // Inside a function body
359
360                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
361                 "%inval     = OpLoad %f32 %inloc\n"
362                 "%neg       = OpFNegate %f32 %inval\n"
363                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
364                 "             OpStore %outloc %neg\n"
365                 "             OpReturn\n"
366                 "             OpFunctionEnd\n";
367         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
368         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
369         spec.numWorkGroups = IVec3(numElements, 1, 1);
370
371         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpNop appearing at different places", spec));
372
373         return group.release();
374 }
375
376 bool compareFUnord (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
377 {
378         if (outputAllocs.size() != 1)
379                 return false;
380
381         vector<deUint8> input1Bytes;
382         vector<deUint8> input2Bytes;
383         vector<deUint8> expectedBytes;
384
385         inputs[0].getBytes(input1Bytes);
386         inputs[1].getBytes(input2Bytes);
387         expectedOutputs[0].getBytes(expectedBytes);
388
389         const deInt32* const    expectedOutputAsInt             = reinterpret_cast<const deInt32*>(&expectedBytes.front());
390         const deInt32* const    outputAsInt                             = static_cast<const deInt32*>(outputAllocs[0]->getHostPtr());
391         const float* const              input1AsFloat                   = reinterpret_cast<const float*>(&input1Bytes.front());
392         const float* const              input2AsFloat                   = reinterpret_cast<const float*>(&input2Bytes.front());
393         bool returnValue                                                                = true;
394
395         for (size_t idx = 0; idx < expectedBytes.size() / sizeof(deInt32); ++idx)
396         {
397                 if (outputAsInt[idx] != expectedOutputAsInt[idx])
398                 {
399                         log << TestLog::Message << "ERROR: Sub-case failed. inputs: " << input1AsFloat[idx] << "," << input2AsFloat[idx] << " output: " << outputAsInt[idx]<< " expected output: " << expectedOutputAsInt[idx] << TestLog::EndMessage;
400                         returnValue = false;
401                 }
402         }
403         return returnValue;
404 }
405
406 typedef VkBool32 (*compareFuncType) (float, float);
407
408 struct OpFUnordCase
409 {
410         const char*             name;
411         const char*             opCode;
412         compareFuncType compareFunc;
413
414                                         OpFUnordCase                    (const char* _name, const char* _opCode, compareFuncType _compareFunc)
415                                                 : name                          (_name)
416                                                 , opCode                        (_opCode)
417                                                 , compareFunc           (_compareFunc) {}
418 };
419
420 #define ADD_OPFUNORD_CASE(NAME, OPCODE, OPERATOR) \
421 do { \
422         struct compare_##NAME { static VkBool32 compare(float x, float y) { return (x OPERATOR y) ? VK_TRUE : VK_FALSE; } }; \
423         cases.push_back(OpFUnordCase(#NAME, OPCODE, compare_##NAME::compare)); \
424 } while (deGetFalse())
425
426 tcu::TestCaseGroup* createOpFUnordGroup (tcu::TestContext& testCtx)
427 {
428         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opfunord", "Test the OpFUnord* opcodes"));
429         de::Random                                              rnd                             (deStringHash(group->getName()));
430         const int                                               numElements             = 100;
431         vector<OpFUnordCase>                    cases;
432
433         const StringTemplate                    shaderTemplate  (
434
435                 string(getComputeAsmShaderPreamble()) +
436
437                 "OpSource GLSL 430\n"
438                 "OpName %main           \"main\"\n"
439                 "OpName %id             \"gl_GlobalInvocationID\"\n"
440
441                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
442
443                 "OpDecorate %buf BufferBlock\n"
444                 "OpDecorate %buf2 BufferBlock\n"
445                 "OpDecorate %indata1 DescriptorSet 0\n"
446                 "OpDecorate %indata1 Binding 0\n"
447                 "OpDecorate %indata2 DescriptorSet 0\n"
448                 "OpDecorate %indata2 Binding 1\n"
449                 "OpDecorate %outdata DescriptorSet 0\n"
450                 "OpDecorate %outdata Binding 2\n"
451                 "OpDecorate %f32arr ArrayStride 4\n"
452                 "OpDecorate %i32arr ArrayStride 4\n"
453                 "OpMemberDecorate %buf 0 Offset 0\n"
454                 "OpMemberDecorate %buf2 0 Offset 0\n"
455
456                 + string(getComputeAsmCommonTypes()) +
457
458                 "%buf        = OpTypeStruct %f32arr\n"
459                 "%bufptr     = OpTypePointer Uniform %buf\n"
460                 "%indata1    = OpVariable %bufptr Uniform\n"
461                 "%indata2    = OpVariable %bufptr Uniform\n"
462
463                 "%buf2       = OpTypeStruct %i32arr\n"
464                 "%buf2ptr    = OpTypePointer Uniform %buf2\n"
465                 "%outdata    = OpVariable %buf2ptr Uniform\n"
466
467                 "%id        = OpVariable %uvec3ptr Input\n"
468                 "%zero      = OpConstant %i32 0\n"
469                 "%consti1   = OpConstant %i32 1\n"
470                 "%constf1   = OpConstant %f32 1.0\n"
471
472                 "%main      = OpFunction %void None %voidf\n"
473                 "%label     = OpLabel\n"
474                 "%idval     = OpLoad %uvec3 %id\n"
475                 "%x         = OpCompositeExtract %u32 %idval 0\n"
476
477                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
478                 "%inval1    = OpLoad %f32 %inloc1\n"
479                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
480                 "%inval2    = OpLoad %f32 %inloc2\n"
481                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
482
483                 "%result    = ${OPCODE} %bool %inval1 %inval2\n"
484                 "%int_res   = OpSelect %i32 %result %consti1 %zero\n"
485                 "             OpStore %outloc %int_res\n"
486
487                 "             OpReturn\n"
488                 "             OpFunctionEnd\n");
489
490         ADD_OPFUNORD_CASE(equal, "OpFUnordEqual", ==);
491         ADD_OPFUNORD_CASE(less, "OpFUnordLessThan", <);
492         ADD_OPFUNORD_CASE(lessequal, "OpFUnordLessThanEqual", <=);
493         ADD_OPFUNORD_CASE(greater, "OpFUnordGreaterThan", >);
494         ADD_OPFUNORD_CASE(greaterequal, "OpFUnordGreaterThanEqual", >=);
495         ADD_OPFUNORD_CASE(notequal, "OpFUnordNotEqual", !=);
496
497         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
498         {
499                 map<string, string>                     specializations;
500                 ComputeShaderSpec                       spec;
501                 const float                                     NaN                             = std::numeric_limits<float>::quiet_NaN();
502                 vector<float>                           inputFloats1    (numElements, 0);
503                 vector<float>                           inputFloats2    (numElements, 0);
504                 vector<deInt32>                         expectedInts    (numElements, 0);
505
506                 specializations["OPCODE"]       = cases[caseNdx].opCode;
507                 spec.assembly                           = shaderTemplate.specialize(specializations);
508
509                 fillRandomScalars(rnd, 1.f, 100.f, &inputFloats1[0], numElements);
510                 for (size_t ndx = 0; ndx < numElements; ++ndx)
511                 {
512                         switch (ndx % 6)
513                         {
514                                 case 0:         inputFloats2[ndx] = inputFloats1[ndx] + 1.0f; break;
515                                 case 1:         inputFloats2[ndx] = inputFloats1[ndx] - 1.0f; break;
516                                 case 2:         inputFloats2[ndx] = inputFloats1[ndx]; break;
517                                 case 3:         inputFloats2[ndx] = NaN; break;
518                                 case 4:         inputFloats2[ndx] = inputFloats1[ndx];  inputFloats1[ndx] = NaN; break;
519                                 case 5:         inputFloats2[ndx] = NaN;                                inputFloats1[ndx] = NaN; break;
520                         }
521                         expectedInts[ndx] = tcu::Float32(inputFloats1[ndx]).isNaN() || tcu::Float32(inputFloats2[ndx]).isNaN() || cases[caseNdx].compareFunc(inputFloats1[ndx], inputFloats2[ndx]);
522                 }
523
524                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
525                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
526                 spec.outputs.push_back(BufferSp(new Int32Buffer(expectedInts)));
527                 spec.numWorkGroups = IVec3(numElements, 1, 1);
528                 spec.verifyIO = &compareFUnord;
529                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
530         }
531
532         return group.release();
533 }
534
535 struct OpAtomicCase
536 {
537         const char*             name;
538         const char*             assembly;
539         const char*             retValAssembly;
540         OpAtomicType    opAtomic;
541         deInt32                 numOutputElements;
542
543                                         OpAtomicCase(const char* _name, const char* _assembly, const char* _retValAssembly, OpAtomicType _opAtomic, deInt32 _numOutputElements)
544                                                 : name                          (_name)
545                                                 , assembly                      (_assembly)
546                                                 , retValAssembly        (_retValAssembly)
547                                                 , opAtomic                      (_opAtomic)
548                                                 , numOutputElements     (_numOutputElements) {}
549 };
550
551 tcu::TestCaseGroup* createOpAtomicGroup (tcu::TestContext& testCtx, bool useStorageBuffer, int numElements = 65535, bool verifyReturnValues = false)
552 {
553         std::string                                             groupName                       ("opatomic");
554         if (useStorageBuffer)
555                 groupName += "_storage_buffer";
556         if (verifyReturnValues)
557                 groupName += "_return_values";
558         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Test the OpAtomic* opcodes"));
559         vector<OpAtomicCase>                    cases;
560
561         const StringTemplate                    shaderTemplate  (
562
563                 string("OpCapability Shader\n") +
564                 (useStorageBuffer ? "OpExtension \"SPV_KHR_storage_buffer_storage_class\"\n" : "") +
565                 "OpMemoryModel Logical GLSL450\n"
566                 "OpEntryPoint GLCompute %main \"main\" %id\n"
567                 "OpExecutionMode %main LocalSize 1 1 1\n" +
568
569                 "OpSource GLSL 430\n"
570                 "OpName %main           \"main\"\n"
571                 "OpName %id             \"gl_GlobalInvocationID\"\n"
572
573                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
574
575                 "OpDecorate %buf ${BLOCK_DECORATION}\n"
576                 "OpDecorate %indata DescriptorSet 0\n"
577                 "OpDecorate %indata Binding 0\n"
578                 "OpDecorate %i32arr ArrayStride 4\n"
579                 "OpMemberDecorate %buf 0 Offset 0\n"
580
581                 "OpDecorate %sumbuf ${BLOCK_DECORATION}\n"
582                 "OpDecorate %sum DescriptorSet 0\n"
583                 "OpDecorate %sum Binding 1\n"
584                 "OpMemberDecorate %sumbuf 0 Coherent\n"
585                 "OpMemberDecorate %sumbuf 0 Offset 0\n"
586
587                 "${RETVAL_BUF_DECORATE}"
588
589                 + getComputeAsmCommonTypes("${BLOCK_POINTER_TYPE}") +
590
591                 "%buf       = OpTypeStruct %i32arr\n"
592                 "%bufptr    = OpTypePointer ${BLOCK_POINTER_TYPE} %buf\n"
593                 "%indata    = OpVariable %bufptr ${BLOCK_POINTER_TYPE}\n"
594
595                 "%sumbuf    = OpTypeStruct %i32arr\n"
596                 "%sumbufptr = OpTypePointer ${BLOCK_POINTER_TYPE} %sumbuf\n"
597                 "%sum       = OpVariable %sumbufptr ${BLOCK_POINTER_TYPE}\n"
598
599                 "${RETVAL_BUF_DECL}"
600
601                 "%id        = OpVariable %uvec3ptr Input\n"
602                 "%minusone  = OpConstant %i32 -1\n"
603                 "%zero      = OpConstant %i32 0\n"
604                 "%one       = OpConstant %u32 1\n"
605                 "%two       = OpConstant %i32 2\n"
606
607                 "%main      = OpFunction %void None %voidf\n"
608                 "%label     = OpLabel\n"
609                 "%idval     = OpLoad %uvec3 %id\n"
610                 "%x         = OpCompositeExtract %u32 %idval 0\n"
611
612                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
613                 "%inval     = OpLoad %i32 %inloc\n"
614
615                 "%outloc    = OpAccessChain %i32ptr %sum %zero ${INDEX}\n"
616                 "${INSTRUCTION}"
617                 "${RETVAL_ASSEMBLY}"
618
619                 "             OpReturn\n"
620                 "             OpFunctionEnd\n");
621
622         #define ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, NUM_OUTPUT_ELEMENTS) \
623         do { \
624                 DE_ASSERT((NUM_OUTPUT_ELEMENTS) == 1 || (NUM_OUTPUT_ELEMENTS) == numElements); \
625                 cases.push_back(OpAtomicCase(#NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, NUM_OUTPUT_ELEMENTS)); \
626         } while (deGetFalse())
627         #define ADD_OPATOMIC_CASE_1(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, 1)
628         #define ADD_OPATOMIC_CASE_N(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, numElements)
629
630         ADD_OPATOMIC_CASE_1(iadd,       "%retv      = OpAtomicIAdd %i32 %outloc %one %zero %inval\n",
631                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IADD );
632         ADD_OPATOMIC_CASE_1(isub,       "%retv      = OpAtomicISub %i32 %outloc %one %zero %inval\n",
633                                                                 "             OpStore %retloc %retv\n", OPATOMIC_ISUB );
634         ADD_OPATOMIC_CASE_1(iinc,       "%retv      = OpAtomicIIncrement %i32 %outloc %one %zero\n",
635                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IINC );
636         ADD_OPATOMIC_CASE_1(idec,       "%retv      = OpAtomicIDecrement %i32 %outloc %one %zero\n",
637                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IDEC );
638         if (!verifyReturnValues)
639         {
640                 ADD_OPATOMIC_CASE_N(load,       "%inval2    = OpAtomicLoad %i32 %inloc %one %zero\n"
641                                                                         "             OpStore %outloc %inval2\n", "", OPATOMIC_LOAD );
642                 ADD_OPATOMIC_CASE_N(store,      "             OpAtomicStore %outloc %one %zero %inval\n", "", OPATOMIC_STORE );
643         }
644
645         ADD_OPATOMIC_CASE_N(compex, "%even      = OpSMod %i32 %inval %two\n"
646                                                                 "             OpStore %outloc %even\n"
647                                                                 "%retv      = OpAtomicCompareExchange %i32 %outloc %one %zero %zero %minusone %zero\n",
648                                                                 "                         OpStore %retloc %retv\n", OPATOMIC_COMPEX );
649
650
651         #undef ADD_OPATOMIC_CASE
652         #undef ADD_OPATOMIC_CASE_1
653         #undef ADD_OPATOMIC_CASE_N
654
655         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
656         {
657                 map<string, string>                     specializations;
658                 ComputeShaderSpec                       spec;
659                 vector<deInt32>                         inputInts               (numElements, 0);
660                 vector<deInt32>                         expected                (cases[caseNdx].numOutputElements, -1);
661
662                 specializations["INDEX"]                                = (cases[caseNdx].numOutputElements == 1) ? "%zero" : "%x";
663                 specializations["INSTRUCTION"]                  = cases[caseNdx].assembly;
664                 specializations["BLOCK_DECORATION"]             = useStorageBuffer ? "Block" : "BufferBlock";
665                 specializations["BLOCK_POINTER_TYPE"]   = useStorageBuffer ? "StorageBuffer" : "Uniform";
666
667                 if (verifyReturnValues)
668                 {
669                         const StringTemplate blockDecoration    (
670                                 "\n"
671                                 "OpDecorate %retbuf ${BLOCK_DECORATION}\n"
672                                 "OpDecorate %ret DescriptorSet 0\n"
673                                 "OpDecorate %ret Binding 2\n"
674                                 "OpMemberDecorate %retbuf 0 Offset 0\n\n");
675
676                         const StringTemplate blockDeclaration   (
677                                 "\n"
678                                 "%retbuf    = OpTypeStruct %i32arr\n"
679                                 "%retbufptr = OpTypePointer ${BLOCK_POINTER_TYPE} %retbuf\n"
680                                 "%ret       = OpVariable %retbufptr ${BLOCK_POINTER_TYPE}\n\n");
681
682                         specializations["RETVAL_ASSEMBLY"] =
683                                 "%retloc    = OpAccessChain %i32ptr %ret %zero %x\n"
684                                 + std::string(cases[caseNdx].retValAssembly);
685
686                         specializations["RETVAL_BUF_DECORATE"]  = blockDecoration.specialize(specializations);
687                         specializations["RETVAL_BUF_DECL"]              = blockDeclaration.specialize(specializations);
688                 }
689                 else
690                 {
691                         specializations["RETVAL_ASSEMBLY"]              = "";
692                         specializations["RETVAL_BUF_DECORATE"]  = "";
693                         specializations["RETVAL_BUF_DECL"]              = "";
694                 }
695
696                 spec.assembly                                                   = shaderTemplate.specialize(specializations);
697
698                 if (useStorageBuffer)
699                         spec.extensions.push_back("VK_KHR_storage_buffer_storage_class");
700
701                 spec.inputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_INPUT)));
702                 spec.outputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_EXPECTED)));
703                 if (verifyReturnValues)
704                         spec.outputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_ATOMIC_RET)));
705                 spec.numWorkGroups = IVec3(numElements, 1, 1);
706
707                 if (verifyReturnValues)
708                 {
709                         switch (cases[caseNdx].opAtomic)
710                         {
711                                 case OPATOMIC_IADD:
712                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IADD>;
713                                         break;
714                                 case OPATOMIC_ISUB:
715                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_ISUB>;
716                                         break;
717                                 case OPATOMIC_IINC:
718                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IINC>;
719                                         break;
720                                 case OPATOMIC_IDEC:
721                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IDEC>;
722                                         break;
723                                 case OPATOMIC_COMPEX:
724                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_COMPEX>;
725                                         break;
726                                 default:
727                                         DE_FATAL("Unsupported OpAtomic type for return value verification");
728                         }
729                 }
730                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
731         }
732
733         return group.release();
734 }
735
736 tcu::TestCaseGroup* createOpLineGroup (tcu::TestContext& testCtx)
737 {
738         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opline", "Test the OpLine instruction"));
739         ComputeShaderSpec                               spec;
740         de::Random                                              rnd                             (deStringHash(group->getName()));
741         const int                                               numElements             = 100;
742         vector<float>                                   positiveFloats  (numElements, 0);
743         vector<float>                                   negativeFloats  (numElements, 0);
744
745         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
746
747         for (size_t ndx = 0; ndx < numElements; ++ndx)
748                 negativeFloats[ndx] = -positiveFloats[ndx];
749
750         spec.assembly =
751                 string(getComputeAsmShaderPreamble()) +
752
753                 "%fname1 = OpString \"negateInputs.comp\"\n"
754                 "%fname2 = OpString \"negateInputs\"\n"
755
756                 "OpSource GLSL 430\n"
757                 "OpName %main           \"main\"\n"
758                 "OpName %id             \"gl_GlobalInvocationID\"\n"
759
760                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
761
762                 + string(getComputeAsmInputOutputBufferTraits()) +
763
764                 "OpLine %fname1 0 0\n" // At the earliest possible position
765
766                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
767
768                 "OpLine %fname1 0 1\n" // Multiple OpLines in sequence
769                 "OpLine %fname2 1 0\n" // Different filenames
770                 "OpLine %fname1 1000 100000\n"
771
772                 "%id        = OpVariable %uvec3ptr Input\n"
773                 "%zero      = OpConstant %i32 0\n"
774
775                 "OpLine %fname1 1 1\n" // Before a function
776
777                 "%main      = OpFunction %void None %voidf\n"
778                 "%label     = OpLabel\n"
779
780                 "OpLine %fname1 1 1\n" // In a function
781
782                 "%idval     = OpLoad %uvec3 %id\n"
783                 "%x         = OpCompositeExtract %u32 %idval 0\n"
784                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
785                 "%inval     = OpLoad %f32 %inloc\n"
786                 "%neg       = OpFNegate %f32 %inval\n"
787                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
788                 "             OpStore %outloc %neg\n"
789                 "             OpReturn\n"
790                 "             OpFunctionEnd\n";
791         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
792         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
793         spec.numWorkGroups = IVec3(numElements, 1, 1);
794
795         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpLine appearing at different places", spec));
796
797         return group.release();
798 }
799
800 bool veryfiBinaryShader (const ProgramBinary& binary)
801 {
802         const size_t    paternCount                     = 3u;
803         bool paternsCheck[paternCount]          =
804         {
805                 false, false, false
806         };
807         const string patersns[paternCount]      =
808         {
809                 "VULKAN CTS",
810                 "Negative values",
811                 "Date: 2017/09/21"
812         };
813         size_t                  paternNdx               = 0u;
814
815         for (size_t ndx = 0u; ndx < binary.getSize(); ++ndx)
816         {
817                 if (false == paternsCheck[paternNdx] &&
818                         patersns[paternNdx][0] == static_cast<char>(binary.getBinary()[ndx]) &&
819                         deMemoryEqual((const char*)&binary.getBinary()[ndx], &patersns[paternNdx][0], patersns[paternNdx].length()))
820                 {
821                         paternsCheck[paternNdx]= true;
822                         paternNdx++;
823                         if (paternNdx == paternCount)
824                                 break;
825                 }
826         }
827
828         for (size_t ndx = 0u; ndx < paternCount; ++ndx)
829         {
830                 if (!paternsCheck[ndx])
831                         return false;
832         }
833
834         return true;
835 }
836
837 tcu::TestCaseGroup* createOpModuleProcessedGroup (tcu::TestContext& testCtx)
838 {
839         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opmoduleprocessed", "Test the OpModuleProcessed instruction"));
840         ComputeShaderSpec                               spec;
841         de::Random                                              rnd                             (deStringHash(group->getName()));
842         const int                                               numElements             = 10;
843         vector<float>                                   positiveFloats  (numElements, 0);
844         vector<float>                                   negativeFloats  (numElements, 0);
845
846         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
847
848         for (size_t ndx = 0; ndx < numElements; ++ndx)
849                 negativeFloats[ndx] = -positiveFloats[ndx];
850
851         spec.assembly =
852                 string(getComputeAsmShaderPreamble()) +
853                 "%fname = OpString \"negateInputs.comp\"\n"
854
855                 "OpSource GLSL 430\n"
856                 "OpName %main           \"main\"\n"
857                 "OpName %id             \"gl_GlobalInvocationID\"\n"
858                 "OpModuleProcessed \"VULKAN CTS\"\n"                                    //OpModuleProcessed;
859                 "OpModuleProcessed \"Negative values\"\n"
860                 "OpModuleProcessed \"Date: 2017/09/21\"\n"
861                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
862
863                 + string(getComputeAsmInputOutputBufferTraits())
864
865                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
866
867                 "OpLine %fname 0 1\n"
868
869                 "OpLine %fname 1000 1\n"
870
871                 "%id        = OpVariable %uvec3ptr Input\n"
872                 "%zero      = OpConstant %i32 0\n"
873                 "%main      = OpFunction %void None %voidf\n"
874
875                 "%label     = OpLabel\n"
876                 "%idval     = OpLoad %uvec3 %id\n"
877                 "%x         = OpCompositeExtract %u32 %idval 0\n"
878
879                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
880                 "%inval     = OpLoad %f32 %inloc\n"
881                 "%neg       = OpFNegate %f32 %inval\n"
882                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
883                 "             OpStore %outloc %neg\n"
884                 "             OpReturn\n"
885                 "             OpFunctionEnd\n";
886         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
887         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
888         spec.numWorkGroups = IVec3(numElements, 1, 1);
889         spec.verifyBinary = veryfiBinaryShader;
890         spec.spirvVersion = SPIRV_VERSION_1_3;
891
892         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpModuleProcessed Tests", spec));
893
894         return group.release();
895 }
896
897 tcu::TestCaseGroup* createOpNoLineGroup (tcu::TestContext& testCtx)
898 {
899         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnoline", "Test the OpNoLine instruction"));
900         ComputeShaderSpec                               spec;
901         de::Random                                              rnd                             (deStringHash(group->getName()));
902         const int                                               numElements             = 100;
903         vector<float>                                   positiveFloats  (numElements, 0);
904         vector<float>                                   negativeFloats  (numElements, 0);
905
906         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
907
908         for (size_t ndx = 0; ndx < numElements; ++ndx)
909                 negativeFloats[ndx] = -positiveFloats[ndx];
910
911         spec.assembly =
912                 string(getComputeAsmShaderPreamble()) +
913
914                 "%fname = OpString \"negateInputs.comp\"\n"
915
916                 "OpSource GLSL 430\n"
917                 "OpName %main           \"main\"\n"
918                 "OpName %id             \"gl_GlobalInvocationID\"\n"
919
920                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
921
922                 + string(getComputeAsmInputOutputBufferTraits()) +
923
924                 "OpNoLine\n" // At the earliest possible position, without preceding OpLine
925
926                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
927
928                 "OpLine %fname 0 1\n"
929                 "OpNoLine\n" // Immediately following a preceding OpLine
930
931                 "OpLine %fname 1000 1\n"
932
933                 "%id        = OpVariable %uvec3ptr Input\n"
934                 "%zero      = OpConstant %i32 0\n"
935
936                 "OpNoLine\n" // Contents after the previous OpLine
937
938                 "%main      = OpFunction %void None %voidf\n"
939                 "%label     = OpLabel\n"
940                 "%idval     = OpLoad %uvec3 %id\n"
941                 "%x         = OpCompositeExtract %u32 %idval 0\n"
942
943                 "OpNoLine\n" // Multiple OpNoLine
944                 "OpNoLine\n"
945                 "OpNoLine\n"
946
947                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
948                 "%inval     = OpLoad %f32 %inloc\n"
949                 "%neg       = OpFNegate %f32 %inval\n"
950                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
951                 "             OpStore %outloc %neg\n"
952                 "             OpReturn\n"
953                 "             OpFunctionEnd\n";
954         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
955         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
956         spec.numWorkGroups = IVec3(numElements, 1, 1);
957
958         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpNoLine appearing at different places", spec));
959
960         return group.release();
961 }
962
963 // Compare instruction for the contraction compute case.
964 // Returns true if the output is what is expected from the test case.
965 bool compareNoContractCase(const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
966 {
967         if (outputAllocs.size() != 1)
968                 return false;
969
970         // Only size is needed because we are not comparing the exact values.
971         size_t byteSize = expectedOutputs[0].getByteSize();
972
973         const float*    outputAsFloat   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
974
975         for(size_t i = 0; i < byteSize / sizeof(float); ++i) {
976                 if (outputAsFloat[i] != 0.f &&
977                         outputAsFloat[i] != -ldexp(1, -24)) {
978                         return false;
979                 }
980         }
981
982         return true;
983 }
984
985 tcu::TestCaseGroup* createNoContractionGroup (tcu::TestContext& testCtx)
986 {
987         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
988         vector<CaseParameter>                   cases;
989         const int                                               numElements             = 100;
990         vector<float>                                   inputFloats1    (numElements, 0);
991         vector<float>                                   inputFloats2    (numElements, 0);
992         vector<float>                                   outputFloats    (numElements, 0);
993         const StringTemplate                    shaderTemplate  (
994                 string(getComputeAsmShaderPreamble()) +
995
996                 "OpName %main           \"main\"\n"
997                 "OpName %id             \"gl_GlobalInvocationID\"\n"
998
999                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1000
1001                 "${DECORATION}\n"
1002
1003                 "OpDecorate %buf BufferBlock\n"
1004                 "OpDecorate %indata1 DescriptorSet 0\n"
1005                 "OpDecorate %indata1 Binding 0\n"
1006                 "OpDecorate %indata2 DescriptorSet 0\n"
1007                 "OpDecorate %indata2 Binding 1\n"
1008                 "OpDecorate %outdata DescriptorSet 0\n"
1009                 "OpDecorate %outdata Binding 2\n"
1010                 "OpDecorate %f32arr ArrayStride 4\n"
1011                 "OpMemberDecorate %buf 0 Offset 0\n"
1012
1013                 + string(getComputeAsmCommonTypes()) +
1014
1015                 "%buf        = OpTypeStruct %f32arr\n"
1016                 "%bufptr     = OpTypePointer Uniform %buf\n"
1017                 "%indata1    = OpVariable %bufptr Uniform\n"
1018                 "%indata2    = OpVariable %bufptr Uniform\n"
1019                 "%outdata    = OpVariable %bufptr Uniform\n"
1020
1021                 "%id         = OpVariable %uvec3ptr Input\n"
1022                 "%zero       = OpConstant %i32 0\n"
1023                 "%c_f_m1     = OpConstant %f32 -1.\n"
1024
1025                 "%main       = OpFunction %void None %voidf\n"
1026                 "%label      = OpLabel\n"
1027                 "%idval      = OpLoad %uvec3 %id\n"
1028                 "%x          = OpCompositeExtract %u32 %idval 0\n"
1029                 "%inloc1     = OpAccessChain %f32ptr %indata1 %zero %x\n"
1030                 "%inval1     = OpLoad %f32 %inloc1\n"
1031                 "%inloc2     = OpAccessChain %f32ptr %indata2 %zero %x\n"
1032                 "%inval2     = OpLoad %f32 %inloc2\n"
1033                 "%mul        = OpFMul %f32 %inval1 %inval2\n"
1034                 "%add        = OpFAdd %f32 %mul %c_f_m1\n"
1035                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
1036                 "              OpStore %outloc %add\n"
1037                 "              OpReturn\n"
1038                 "              OpFunctionEnd\n");
1039
1040         cases.push_back(CaseParameter("multiplication", "OpDecorate %mul NoContraction"));
1041         cases.push_back(CaseParameter("addition",               "OpDecorate %add NoContraction"));
1042         cases.push_back(CaseParameter("both",                   "OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"));
1043
1044         for (size_t ndx = 0; ndx < numElements; ++ndx)
1045         {
1046                 inputFloats1[ndx]       = 1.f + std::ldexp(1.f, -23); // 1 + 2^-23.
1047                 inputFloats2[ndx]       = 1.f - std::ldexp(1.f, -23); // 1 - 2^-23.
1048                 // Result for (1 + 2^-23) * (1 - 2^-23) - 1. With NoContraction, the multiplication will be
1049                 // conducted separately and the result is rounded to 1, or 0x1.fffffcp-1
1050                 // So the final result will be 0.f or 0x1p-24.
1051                 // If the operation is combined into a precise fused multiply-add, then the result would be
1052                 // 2^-46 (0xa8800000).
1053                 outputFloats[ndx]       = 0.f;
1054         }
1055
1056         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
1057         {
1058                 map<string, string>             specializations;
1059                 ComputeShaderSpec               spec;
1060
1061                 specializations["DECORATION"] = cases[caseNdx].param;
1062                 spec.assembly = shaderTemplate.specialize(specializations);
1063                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1064                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1065                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1066                 spec.numWorkGroups = IVec3(numElements, 1, 1);
1067                 // Check against the two possible answers based on rounding mode.
1068                 spec.verifyIO = &compareNoContractCase;
1069
1070                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
1071         }
1072         return group.release();
1073 }
1074
1075 bool compareFRem(const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1076 {
1077         if (outputAllocs.size() != 1)
1078                 return false;
1079
1080         vector<deUint8> expectedBytes;
1081         expectedOutputs[0].getBytes(expectedBytes);
1082
1083         const float*    expectedOutputAsFloat   = reinterpret_cast<const float*>(&expectedBytes.front());
1084         const float*    outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1085
1086         for (size_t idx = 0; idx < expectedBytes.size() / sizeof(float); ++idx)
1087         {
1088                 const float f0 = expectedOutputAsFloat[idx];
1089                 const float f1 = outputAsFloat[idx];
1090                 // \todo relative error needs to be fairly high because FRem may be implemented as
1091                 // (roughly) frac(a/b)*b, so LSB errors can be magnified. But this should be fine for now.
1092                 if (deFloatAbs((f1 - f0) / f0) > 0.02)
1093                         return false;
1094         }
1095
1096         return true;
1097 }
1098
1099 tcu::TestCaseGroup* createOpFRemGroup (tcu::TestContext& testCtx)
1100 {
1101         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opfrem", "Test the OpFRem instruction"));
1102         ComputeShaderSpec                               spec;
1103         de::Random                                              rnd                             (deStringHash(group->getName()));
1104         const int                                               numElements             = 200;
1105         vector<float>                                   inputFloats1    (numElements, 0);
1106         vector<float>                                   inputFloats2    (numElements, 0);
1107         vector<float>                                   outputFloats    (numElements, 0);
1108
1109         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1110         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats2[0], numElements);
1111
1112         for (size_t ndx = 0; ndx < numElements; ++ndx)
1113         {
1114                 // Guard against divisors near zero.
1115                 if (std::fabs(inputFloats2[ndx]) < 1e-3)
1116                         inputFloats2[ndx] = 8.f;
1117
1118                 // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1119                 outputFloats[ndx] = std::fmod(inputFloats1[ndx], inputFloats2[ndx]);
1120         }
1121
1122         spec.assembly =
1123                 string(getComputeAsmShaderPreamble()) +
1124
1125                 "OpName %main           \"main\"\n"
1126                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1127
1128                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1129
1130                 "OpDecorate %buf BufferBlock\n"
1131                 "OpDecorate %indata1 DescriptorSet 0\n"
1132                 "OpDecorate %indata1 Binding 0\n"
1133                 "OpDecorate %indata2 DescriptorSet 0\n"
1134                 "OpDecorate %indata2 Binding 1\n"
1135                 "OpDecorate %outdata DescriptorSet 0\n"
1136                 "OpDecorate %outdata Binding 2\n"
1137                 "OpDecorate %f32arr ArrayStride 4\n"
1138                 "OpMemberDecorate %buf 0 Offset 0\n"
1139
1140                 + string(getComputeAsmCommonTypes()) +
1141
1142                 "%buf        = OpTypeStruct %f32arr\n"
1143                 "%bufptr     = OpTypePointer Uniform %buf\n"
1144                 "%indata1    = OpVariable %bufptr Uniform\n"
1145                 "%indata2    = OpVariable %bufptr Uniform\n"
1146                 "%outdata    = OpVariable %bufptr Uniform\n"
1147
1148                 "%id        = OpVariable %uvec3ptr Input\n"
1149                 "%zero      = OpConstant %i32 0\n"
1150
1151                 "%main      = OpFunction %void None %voidf\n"
1152                 "%label     = OpLabel\n"
1153                 "%idval     = OpLoad %uvec3 %id\n"
1154                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1155                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1156                 "%inval1    = OpLoad %f32 %inloc1\n"
1157                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1158                 "%inval2    = OpLoad %f32 %inloc2\n"
1159                 "%rem       = OpFRem %f32 %inval1 %inval2\n"
1160                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1161                 "             OpStore %outloc %rem\n"
1162                 "             OpReturn\n"
1163                 "             OpFunctionEnd\n";
1164
1165         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1166         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1167         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1168         spec.numWorkGroups = IVec3(numElements, 1, 1);
1169         spec.verifyIO = &compareFRem;
1170
1171         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1172
1173         return group.release();
1174 }
1175
1176 bool compareNMin (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1177 {
1178         if (outputAllocs.size() != 1)
1179                 return false;
1180
1181         const BufferSp&                 expectedOutput                  (expectedOutputs[0].getBuffer());
1182         std::vector<deUint8>    data;
1183         expectedOutput->getBytes(data);
1184
1185         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1186         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1187
1188         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float); ++idx)
1189         {
1190                 const float f0 = expectedOutputAsFloat[idx];
1191                 const float f1 = outputAsFloat[idx];
1192
1193                 // For NMin, we accept NaN as output if both inputs were NaN.
1194                 // Otherwise the NaN is the wrong choise, as on architectures that
1195                 // do not handle NaN, those are huge values.
1196                 if (!(tcu::Float32(f1).isNaN() && tcu::Float32(f0).isNaN()) && deFloatAbs(f1 - f0) > 0.00001f)
1197                         return false;
1198         }
1199
1200         return true;
1201 }
1202
1203 tcu::TestCaseGroup* createOpNMinGroup (tcu::TestContext& testCtx)
1204 {
1205         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnmin", "Test the OpNMin instruction"));
1206         ComputeShaderSpec                               spec;
1207         de::Random                                              rnd                             (deStringHash(group->getName()));
1208         const int                                               numElements             = 200;
1209         vector<float>                                   inputFloats1    (numElements, 0);
1210         vector<float>                                   inputFloats2    (numElements, 0);
1211         vector<float>                                   outputFloats    (numElements, 0);
1212
1213         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1214         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1215
1216         // Make the first case a full-NAN case.
1217         inputFloats1[0] = TCU_NAN;
1218         inputFloats2[0] = TCU_NAN;
1219
1220         for (size_t ndx = 0; ndx < numElements; ++ndx)
1221         {
1222                 // By default, pick the smallest
1223                 outputFloats[ndx] = std::min(inputFloats1[ndx], inputFloats2[ndx]);
1224
1225                 // Make half of the cases NaN cases
1226                 if ((ndx & 1) == 0)
1227                 {
1228                         // Alternate between the NaN operand
1229                         if ((ndx & 2) == 0)
1230                         {
1231                                 outputFloats[ndx] = inputFloats2[ndx];
1232                                 inputFloats1[ndx] = TCU_NAN;
1233                         }
1234                         else
1235                         {
1236                                 outputFloats[ndx] = inputFloats1[ndx];
1237                                 inputFloats2[ndx] = TCU_NAN;
1238                         }
1239                 }
1240         }
1241
1242         spec.assembly =
1243                 "OpCapability Shader\n"
1244                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1245                 "OpMemoryModel Logical GLSL450\n"
1246                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1247                 "OpExecutionMode %main LocalSize 1 1 1\n"
1248
1249                 "OpName %main           \"main\"\n"
1250                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1251
1252                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1253
1254                 "OpDecorate %buf BufferBlock\n"
1255                 "OpDecorate %indata1 DescriptorSet 0\n"
1256                 "OpDecorate %indata1 Binding 0\n"
1257                 "OpDecorate %indata2 DescriptorSet 0\n"
1258                 "OpDecorate %indata2 Binding 1\n"
1259                 "OpDecorate %outdata DescriptorSet 0\n"
1260                 "OpDecorate %outdata Binding 2\n"
1261                 "OpDecorate %f32arr ArrayStride 4\n"
1262                 "OpMemberDecorate %buf 0 Offset 0\n"
1263
1264                 + string(getComputeAsmCommonTypes()) +
1265
1266                 "%buf        = OpTypeStruct %f32arr\n"
1267                 "%bufptr     = OpTypePointer Uniform %buf\n"
1268                 "%indata1    = OpVariable %bufptr Uniform\n"
1269                 "%indata2    = OpVariable %bufptr Uniform\n"
1270                 "%outdata    = OpVariable %bufptr Uniform\n"
1271
1272                 "%id        = OpVariable %uvec3ptr Input\n"
1273                 "%zero      = OpConstant %i32 0\n"
1274
1275                 "%main      = OpFunction %void None %voidf\n"
1276                 "%label     = OpLabel\n"
1277                 "%idval     = OpLoad %uvec3 %id\n"
1278                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1279                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1280                 "%inval1    = OpLoad %f32 %inloc1\n"
1281                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1282                 "%inval2    = OpLoad %f32 %inloc2\n"
1283                 "%rem       = OpExtInst %f32 %std450 NMin %inval1 %inval2\n"
1284                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1285                 "             OpStore %outloc %rem\n"
1286                 "             OpReturn\n"
1287                 "             OpFunctionEnd\n";
1288
1289         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1290         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1291         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1292         spec.numWorkGroups = IVec3(numElements, 1, 1);
1293         spec.verifyIO = &compareNMin;
1294
1295         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1296
1297         return group.release();
1298 }
1299
1300 bool compareNMax (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1301 {
1302         if (outputAllocs.size() != 1)
1303                 return false;
1304
1305         const BufferSp&                 expectedOutput                  = expectedOutputs[0].getBuffer();
1306         std::vector<deUint8>    data;
1307         expectedOutput->getBytes(data);
1308
1309         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1310         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1311
1312         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float); ++idx)
1313         {
1314                 const float f0 = expectedOutputAsFloat[idx];
1315                 const float f1 = outputAsFloat[idx];
1316
1317                 // For NMax, NaN is considered acceptable result, since in
1318                 // architectures that do not handle NaNs, those are huge values.
1319                 if (!tcu::Float32(f1).isNaN() && deFloatAbs(f1 - f0) > 0.00001f)
1320                         return false;
1321         }
1322
1323         return true;
1324 }
1325
1326 tcu::TestCaseGroup* createOpNMaxGroup (tcu::TestContext& testCtx)
1327 {
1328         de::MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "opnmax", "Test the OpNMax instruction"));
1329         ComputeShaderSpec                               spec;
1330         de::Random                                              rnd                             (deStringHash(group->getName()));
1331         const int                                               numElements             = 200;
1332         vector<float>                                   inputFloats1    (numElements, 0);
1333         vector<float>                                   inputFloats2    (numElements, 0);
1334         vector<float>                                   outputFloats    (numElements, 0);
1335
1336         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1337         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1338
1339         // Make the first case a full-NAN case.
1340         inputFloats1[0] = TCU_NAN;
1341         inputFloats2[0] = TCU_NAN;
1342
1343         for (size_t ndx = 0; ndx < numElements; ++ndx)
1344         {
1345                 // By default, pick the biggest
1346                 outputFloats[ndx] = std::max(inputFloats1[ndx], inputFloats2[ndx]);
1347
1348                 // Make half of the cases NaN cases
1349                 if ((ndx & 1) == 0)
1350                 {
1351                         // Alternate between the NaN operand
1352                         if ((ndx & 2) == 0)
1353                         {
1354                                 outputFloats[ndx] = inputFloats2[ndx];
1355                                 inputFloats1[ndx] = TCU_NAN;
1356                         }
1357                         else
1358                         {
1359                                 outputFloats[ndx] = inputFloats1[ndx];
1360                                 inputFloats2[ndx] = TCU_NAN;
1361                         }
1362                 }
1363         }
1364
1365         spec.assembly =
1366                 "OpCapability Shader\n"
1367                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1368                 "OpMemoryModel Logical GLSL450\n"
1369                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1370                 "OpExecutionMode %main LocalSize 1 1 1\n"
1371
1372                 "OpName %main           \"main\"\n"
1373                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1374
1375                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1376
1377                 "OpDecorate %buf BufferBlock\n"
1378                 "OpDecorate %indata1 DescriptorSet 0\n"
1379                 "OpDecorate %indata1 Binding 0\n"
1380                 "OpDecorate %indata2 DescriptorSet 0\n"
1381                 "OpDecorate %indata2 Binding 1\n"
1382                 "OpDecorate %outdata DescriptorSet 0\n"
1383                 "OpDecorate %outdata Binding 2\n"
1384                 "OpDecorate %f32arr ArrayStride 4\n"
1385                 "OpMemberDecorate %buf 0 Offset 0\n"
1386
1387                 + string(getComputeAsmCommonTypes()) +
1388
1389                 "%buf        = OpTypeStruct %f32arr\n"
1390                 "%bufptr     = OpTypePointer Uniform %buf\n"
1391                 "%indata1    = OpVariable %bufptr Uniform\n"
1392                 "%indata2    = OpVariable %bufptr Uniform\n"
1393                 "%outdata    = OpVariable %bufptr Uniform\n"
1394
1395                 "%id        = OpVariable %uvec3ptr Input\n"
1396                 "%zero      = OpConstant %i32 0\n"
1397
1398                 "%main      = OpFunction %void None %voidf\n"
1399                 "%label     = OpLabel\n"
1400                 "%idval     = OpLoad %uvec3 %id\n"
1401                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1402                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1403                 "%inval1    = OpLoad %f32 %inloc1\n"
1404                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1405                 "%inval2    = OpLoad %f32 %inloc2\n"
1406                 "%rem       = OpExtInst %f32 %std450 NMax %inval1 %inval2\n"
1407                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1408                 "             OpStore %outloc %rem\n"
1409                 "             OpReturn\n"
1410                 "             OpFunctionEnd\n";
1411
1412         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1413         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1414         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1415         spec.numWorkGroups = IVec3(numElements, 1, 1);
1416         spec.verifyIO = &compareNMax;
1417
1418         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1419
1420         return group.release();
1421 }
1422
1423 bool compareNClamp (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1424 {
1425         if (outputAllocs.size() != 1)
1426                 return false;
1427
1428         const BufferSp&                 expectedOutput                  = expectedOutputs[0].getBuffer();
1429         std::vector<deUint8>    data;
1430         expectedOutput->getBytes(data);
1431
1432         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1433         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1434
1435         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float) / 2; ++idx)
1436         {
1437                 const float e0 = expectedOutputAsFloat[idx * 2];
1438                 const float e1 = expectedOutputAsFloat[idx * 2 + 1];
1439                 const float res = outputAsFloat[idx];
1440
1441                 // For NClamp, we have two possible outcomes based on
1442                 // whether NaNs are handled or not.
1443                 // If either min or max value is NaN, the result is undefined,
1444                 // so this test doesn't stress those. If the clamped value is
1445                 // NaN, and NaNs are handled, the result is min; if NaNs are not
1446                 // handled, they are big values that result in max.
1447                 // If all three parameters are NaN, the result should be NaN.
1448                 if (!((tcu::Float32(e0).isNaN() && tcu::Float32(res).isNaN()) ||
1449                          (deFloatAbs(e0 - res) < 0.00001f) ||
1450                          (deFloatAbs(e1 - res) < 0.00001f)))
1451                         return false;
1452         }
1453
1454         return true;
1455 }
1456
1457 tcu::TestCaseGroup* createOpNClampGroup (tcu::TestContext& testCtx)
1458 {
1459         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnclamp", "Test the OpNClamp instruction"));
1460         ComputeShaderSpec                               spec;
1461         de::Random                                              rnd                             (deStringHash(group->getName()));
1462         const int                                               numElements             = 200;
1463         vector<float>                                   inputFloats1    (numElements, 0);
1464         vector<float>                                   inputFloats2    (numElements, 0);
1465         vector<float>                                   inputFloats3    (numElements, 0);
1466         vector<float>                                   outputFloats    (numElements * 2, 0);
1467
1468         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1469         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1470         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats3[0], numElements);
1471
1472         for (size_t ndx = 0; ndx < numElements; ++ndx)
1473         {
1474                 // Results are only defined if max value is bigger than min value.
1475                 if (inputFloats2[ndx] > inputFloats3[ndx])
1476                 {
1477                         float t = inputFloats2[ndx];
1478                         inputFloats2[ndx] = inputFloats3[ndx];
1479                         inputFloats3[ndx] = t;
1480                 }
1481
1482                 // By default, do the clamp, setting both possible answers
1483                 float defaultRes = std::min(std::max(inputFloats1[ndx], inputFloats2[ndx]), inputFloats3[ndx]);
1484
1485                 float maxResA = std::max(inputFloats1[ndx], inputFloats2[ndx]);
1486                 float maxResB = maxResA;
1487
1488                 // Alternate between the NaN cases
1489                 if (ndx & 1)
1490                 {
1491                         inputFloats1[ndx] = TCU_NAN;
1492                         // If NaN is handled, the result should be same as the clamp minimum.
1493                         // If NaN is not handled, the result should clamp to the clamp maximum.
1494                         maxResA = inputFloats2[ndx];
1495                         maxResB = inputFloats3[ndx];
1496                 }
1497                 else
1498                 {
1499                         // Not a NaN case - only one legal result.
1500                         maxResA = defaultRes;
1501                         maxResB = defaultRes;
1502                 }
1503
1504                 outputFloats[ndx * 2] = maxResA;
1505                 outputFloats[ndx * 2 + 1] = maxResB;
1506         }
1507
1508         // Make the first case a full-NAN case.
1509         inputFloats1[0] = TCU_NAN;
1510         inputFloats2[0] = TCU_NAN;
1511         inputFloats3[0] = TCU_NAN;
1512         outputFloats[0] = TCU_NAN;
1513         outputFloats[1] = TCU_NAN;
1514
1515         spec.assembly =
1516                 "OpCapability Shader\n"
1517                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1518                 "OpMemoryModel Logical GLSL450\n"
1519                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1520                 "OpExecutionMode %main LocalSize 1 1 1\n"
1521
1522                 "OpName %main           \"main\"\n"
1523                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1524
1525                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1526
1527                 "OpDecorate %buf BufferBlock\n"
1528                 "OpDecorate %indata1 DescriptorSet 0\n"
1529                 "OpDecorate %indata1 Binding 0\n"
1530                 "OpDecorate %indata2 DescriptorSet 0\n"
1531                 "OpDecorate %indata2 Binding 1\n"
1532                 "OpDecorate %indata3 DescriptorSet 0\n"
1533                 "OpDecorate %indata3 Binding 2\n"
1534                 "OpDecorate %outdata DescriptorSet 0\n"
1535                 "OpDecorate %outdata Binding 3\n"
1536                 "OpDecorate %f32arr ArrayStride 4\n"
1537                 "OpMemberDecorate %buf 0 Offset 0\n"
1538
1539                 + string(getComputeAsmCommonTypes()) +
1540
1541                 "%buf        = OpTypeStruct %f32arr\n"
1542                 "%bufptr     = OpTypePointer Uniform %buf\n"
1543                 "%indata1    = OpVariable %bufptr Uniform\n"
1544                 "%indata2    = OpVariable %bufptr Uniform\n"
1545                 "%indata3    = OpVariable %bufptr Uniform\n"
1546                 "%outdata    = OpVariable %bufptr Uniform\n"
1547
1548                 "%id        = OpVariable %uvec3ptr Input\n"
1549                 "%zero      = OpConstant %i32 0\n"
1550
1551                 "%main      = OpFunction %void None %voidf\n"
1552                 "%label     = OpLabel\n"
1553                 "%idval     = OpLoad %uvec3 %id\n"
1554                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1555                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1556                 "%inval1    = OpLoad %f32 %inloc1\n"
1557                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1558                 "%inval2    = OpLoad %f32 %inloc2\n"
1559                 "%inloc3    = OpAccessChain %f32ptr %indata3 %zero %x\n"
1560                 "%inval3    = OpLoad %f32 %inloc3\n"
1561                 "%rem       = OpExtInst %f32 %std450 NClamp %inval1 %inval2 %inval3\n"
1562                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1563                 "             OpStore %outloc %rem\n"
1564                 "             OpReturn\n"
1565                 "             OpFunctionEnd\n";
1566
1567         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1568         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1569         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
1570         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1571         spec.numWorkGroups = IVec3(numElements, 1, 1);
1572         spec.verifyIO = &compareNClamp;
1573
1574         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1575
1576         return group.release();
1577 }
1578
1579 tcu::TestCaseGroup* createOpSRemComputeGroup (tcu::TestContext& testCtx, qpTestResult negFailResult)
1580 {
1581         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsrem", "Test the OpSRem instruction"));
1582         de::Random                                              rnd                             (deStringHash(group->getName()));
1583         const int                                               numElements             = 200;
1584
1585         const struct CaseParams
1586         {
1587                 const char*             name;
1588                 const char*             failMessage;            // customized status message
1589                 qpTestResult    failResult;                     // override status on failure
1590                 int                             op1Min, op1Max;         // operand ranges
1591                 int                             op2Min, op2Max;
1592         } cases[] =
1593         {
1594                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    0,              65536,  0,              100 },
1595                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  -65536, 65536,  -100,   100 },  // see below
1596         };
1597         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1598
1599         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1600         {
1601                 const CaseParams&       params          = cases[caseNdx];
1602                 ComputeShaderSpec       spec;
1603                 vector<deInt32>         inputInts1      (numElements, 0);
1604                 vector<deInt32>         inputInts2      (numElements, 0);
1605                 vector<deInt32>         outputInts      (numElements, 0);
1606
1607                 fillRandomScalars(rnd, params.op1Min, params.op1Max, &inputInts1[0], numElements);
1608                 fillRandomScalars(rnd, params.op2Min, params.op2Max, &inputInts2[0], numElements, filterNotZero);
1609
1610                 for (int ndx = 0; ndx < numElements; ++ndx)
1611                 {
1612                         // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1613                         outputInts[ndx] = inputInts1[ndx] % inputInts2[ndx];
1614                 }
1615
1616                 spec.assembly =
1617                         string(getComputeAsmShaderPreamble()) +
1618
1619                         "OpName %main           \"main\"\n"
1620                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1621
1622                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1623
1624                         "OpDecorate %buf BufferBlock\n"
1625                         "OpDecorate %indata1 DescriptorSet 0\n"
1626                         "OpDecorate %indata1 Binding 0\n"
1627                         "OpDecorate %indata2 DescriptorSet 0\n"
1628                         "OpDecorate %indata2 Binding 1\n"
1629                         "OpDecorate %outdata DescriptorSet 0\n"
1630                         "OpDecorate %outdata Binding 2\n"
1631                         "OpDecorate %i32arr ArrayStride 4\n"
1632                         "OpMemberDecorate %buf 0 Offset 0\n"
1633
1634                         + string(getComputeAsmCommonTypes()) +
1635
1636                         "%buf        = OpTypeStruct %i32arr\n"
1637                         "%bufptr     = OpTypePointer Uniform %buf\n"
1638                         "%indata1    = OpVariable %bufptr Uniform\n"
1639                         "%indata2    = OpVariable %bufptr Uniform\n"
1640                         "%outdata    = OpVariable %bufptr Uniform\n"
1641
1642                         "%id        = OpVariable %uvec3ptr Input\n"
1643                         "%zero      = OpConstant %i32 0\n"
1644
1645                         "%main      = OpFunction %void None %voidf\n"
1646                         "%label     = OpLabel\n"
1647                         "%idval     = OpLoad %uvec3 %id\n"
1648                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1649                         "%inloc1    = OpAccessChain %i32ptr %indata1 %zero %x\n"
1650                         "%inval1    = OpLoad %i32 %inloc1\n"
1651                         "%inloc2    = OpAccessChain %i32ptr %indata2 %zero %x\n"
1652                         "%inval2    = OpLoad %i32 %inloc2\n"
1653                         "%rem       = OpSRem %i32 %inval1 %inval2\n"
1654                         "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
1655                         "             OpStore %outloc %rem\n"
1656                         "             OpReturn\n"
1657                         "             OpFunctionEnd\n";
1658
1659                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts1)));
1660                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts2)));
1661                 spec.outputs.push_back  (BufferSp(new Int32Buffer(outputInts)));
1662                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1663                 spec.failResult                 = params.failResult;
1664                 spec.failMessage                = params.failMessage;
1665
1666                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1667         }
1668
1669         return group.release();
1670 }
1671
1672 tcu::TestCaseGroup* createOpSRemComputeGroup64 (tcu::TestContext& testCtx, qpTestResult negFailResult)
1673 {
1674         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsrem64", "Test the 64-bit OpSRem instruction"));
1675         de::Random                                              rnd                             (deStringHash(group->getName()));
1676         const int                                               numElements             = 200;
1677
1678         const struct CaseParams
1679         {
1680                 const char*             name;
1681                 const char*             failMessage;            // customized status message
1682                 qpTestResult    failResult;                     // override status on failure
1683                 bool                    positive;
1684         } cases[] =
1685         {
1686                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    true },
1687                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  false },        // see below
1688         };
1689         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1690
1691         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1692         {
1693                 const CaseParams&       params          = cases[caseNdx];
1694                 ComputeShaderSpec       spec;
1695                 vector<deInt64>         inputInts1      (numElements, 0);
1696                 vector<deInt64>         inputInts2      (numElements, 0);
1697                 vector<deInt64>         outputInts      (numElements, 0);
1698
1699                 if (params.positive)
1700                 {
1701                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements, filterNonNegative);
1702                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterPositive);
1703                 }
1704                 else
1705                 {
1706                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements);
1707                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterNotZero);
1708                 }
1709
1710                 for (int ndx = 0; ndx < numElements; ++ndx)
1711                 {
1712                         // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1713                         outputInts[ndx] = inputInts1[ndx] % inputInts2[ndx];
1714                 }
1715
1716                 spec.assembly =
1717                         "OpCapability Int64\n"
1718
1719                         + string(getComputeAsmShaderPreamble()) +
1720
1721                         "OpName %main           \"main\"\n"
1722                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1723
1724                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1725
1726                         "OpDecorate %buf BufferBlock\n"
1727                         "OpDecorate %indata1 DescriptorSet 0\n"
1728                         "OpDecorate %indata1 Binding 0\n"
1729                         "OpDecorate %indata2 DescriptorSet 0\n"
1730                         "OpDecorate %indata2 Binding 1\n"
1731                         "OpDecorate %outdata DescriptorSet 0\n"
1732                         "OpDecorate %outdata Binding 2\n"
1733                         "OpDecorate %i64arr ArrayStride 8\n"
1734                         "OpMemberDecorate %buf 0 Offset 0\n"
1735
1736                         + string(getComputeAsmCommonTypes())
1737                         + string(getComputeAsmCommonInt64Types()) +
1738
1739                         "%buf        = OpTypeStruct %i64arr\n"
1740                         "%bufptr     = OpTypePointer Uniform %buf\n"
1741                         "%indata1    = OpVariable %bufptr Uniform\n"
1742                         "%indata2    = OpVariable %bufptr Uniform\n"
1743                         "%outdata    = OpVariable %bufptr Uniform\n"
1744
1745                         "%id        = OpVariable %uvec3ptr Input\n"
1746                         "%zero      = OpConstant %i64 0\n"
1747
1748                         "%main      = OpFunction %void None %voidf\n"
1749                         "%label     = OpLabel\n"
1750                         "%idval     = OpLoad %uvec3 %id\n"
1751                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1752                         "%inloc1    = OpAccessChain %i64ptr %indata1 %zero %x\n"
1753                         "%inval1    = OpLoad %i64 %inloc1\n"
1754                         "%inloc2    = OpAccessChain %i64ptr %indata2 %zero %x\n"
1755                         "%inval2    = OpLoad %i64 %inloc2\n"
1756                         "%rem       = OpSRem %i64 %inval1 %inval2\n"
1757                         "%outloc    = OpAccessChain %i64ptr %outdata %zero %x\n"
1758                         "             OpStore %outloc %rem\n"
1759                         "             OpReturn\n"
1760                         "             OpFunctionEnd\n";
1761
1762                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts1)));
1763                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts2)));
1764                 spec.outputs.push_back  (BufferSp(new Int64Buffer(outputInts)));
1765                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1766                 spec.failResult                 = params.failResult;
1767                 spec.failMessage                = params.failMessage;
1768
1769                 spec.requestedVulkanFeatures.coreFeatures.shaderInt64 = VK_TRUE;
1770
1771                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1772         }
1773
1774         return group.release();
1775 }
1776
1777 tcu::TestCaseGroup* createOpSModComputeGroup (tcu::TestContext& testCtx, qpTestResult negFailResult)
1778 {
1779         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsmod", "Test the OpSMod instruction"));
1780         de::Random                                              rnd                             (deStringHash(group->getName()));
1781         const int                                               numElements             = 200;
1782
1783         const struct CaseParams
1784         {
1785                 const char*             name;
1786                 const char*             failMessage;            // customized status message
1787                 qpTestResult    failResult;                     // override status on failure
1788                 int                             op1Min, op1Max;         // operand ranges
1789                 int                             op2Min, op2Max;
1790         } cases[] =
1791         {
1792                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    0,              65536,  0,              100 },
1793                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  -65536, 65536,  -100,   100 },  // see below
1794         };
1795         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1796
1797         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1798         {
1799                 const CaseParams&       params          = cases[caseNdx];
1800
1801                 ComputeShaderSpec       spec;
1802                 vector<deInt32>         inputInts1      (numElements, 0);
1803                 vector<deInt32>         inputInts2      (numElements, 0);
1804                 vector<deInt32>         outputInts      (numElements, 0);
1805
1806                 fillRandomScalars(rnd, params.op1Min, params.op1Max, &inputInts1[0], numElements);
1807                 fillRandomScalars(rnd, params.op2Min, params.op2Max, &inputInts2[0], numElements, filterNotZero);
1808
1809                 for (int ndx = 0; ndx < numElements; ++ndx)
1810                 {
1811                         deInt32 rem = inputInts1[ndx] % inputInts2[ndx];
1812                         if (rem == 0)
1813                         {
1814                                 outputInts[ndx] = 0;
1815                         }
1816                         else if ((inputInts1[ndx] >= 0) == (inputInts2[ndx] >= 0))
1817                         {
1818                                 // They have the same sign
1819                                 outputInts[ndx] = rem;
1820                         }
1821                         else
1822                         {
1823                                 // They have opposite sign.  The remainder operation takes the
1824                                 // sign inputInts1[ndx] but OpSMod is supposed to take ths sign
1825                                 // of inputInts2[ndx].  Adding inputInts2[ndx] will ensure that
1826                                 // the result has the correct sign and that it is still
1827                                 // congruent to inputInts1[ndx] modulo inputInts2[ndx]
1828                                 //
1829                                 // See also http://mathforum.org/library/drmath/view/52343.html
1830                                 outputInts[ndx] = rem + inputInts2[ndx];
1831                         }
1832                 }
1833
1834                 spec.assembly =
1835                         string(getComputeAsmShaderPreamble()) +
1836
1837                         "OpName %main           \"main\"\n"
1838                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1839
1840                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1841
1842                         "OpDecorate %buf BufferBlock\n"
1843                         "OpDecorate %indata1 DescriptorSet 0\n"
1844                         "OpDecorate %indata1 Binding 0\n"
1845                         "OpDecorate %indata2 DescriptorSet 0\n"
1846                         "OpDecorate %indata2 Binding 1\n"
1847                         "OpDecorate %outdata DescriptorSet 0\n"
1848                         "OpDecorate %outdata Binding 2\n"
1849                         "OpDecorate %i32arr ArrayStride 4\n"
1850                         "OpMemberDecorate %buf 0 Offset 0\n"
1851
1852                         + string(getComputeAsmCommonTypes()) +
1853
1854                         "%buf        = OpTypeStruct %i32arr\n"
1855                         "%bufptr     = OpTypePointer Uniform %buf\n"
1856                         "%indata1    = OpVariable %bufptr Uniform\n"
1857                         "%indata2    = OpVariable %bufptr Uniform\n"
1858                         "%outdata    = OpVariable %bufptr Uniform\n"
1859
1860                         "%id        = OpVariable %uvec3ptr Input\n"
1861                         "%zero      = OpConstant %i32 0\n"
1862
1863                         "%main      = OpFunction %void None %voidf\n"
1864                         "%label     = OpLabel\n"
1865                         "%idval     = OpLoad %uvec3 %id\n"
1866                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1867                         "%inloc1    = OpAccessChain %i32ptr %indata1 %zero %x\n"
1868                         "%inval1    = OpLoad %i32 %inloc1\n"
1869                         "%inloc2    = OpAccessChain %i32ptr %indata2 %zero %x\n"
1870                         "%inval2    = OpLoad %i32 %inloc2\n"
1871                         "%rem       = OpSMod %i32 %inval1 %inval2\n"
1872                         "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
1873                         "             OpStore %outloc %rem\n"
1874                         "             OpReturn\n"
1875                         "             OpFunctionEnd\n";
1876
1877                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts1)));
1878                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts2)));
1879                 spec.outputs.push_back  (BufferSp(new Int32Buffer(outputInts)));
1880                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1881                 spec.failResult                 = params.failResult;
1882                 spec.failMessage                = params.failMessage;
1883
1884                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1885         }
1886
1887         return group.release();
1888 }
1889
1890 tcu::TestCaseGroup* createOpSModComputeGroup64 (tcu::TestContext& testCtx, qpTestResult negFailResult)
1891 {
1892         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsmod64", "Test the OpSMod instruction"));
1893         de::Random                                              rnd                             (deStringHash(group->getName()));
1894         const int                                               numElements             = 200;
1895
1896         const struct CaseParams
1897         {
1898                 const char*             name;
1899                 const char*             failMessage;            // customized status message
1900                 qpTestResult    failResult;                     // override status on failure
1901                 bool                    positive;
1902         } cases[] =
1903         {
1904                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    true },
1905                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  false },        // see below
1906         };
1907         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1908
1909         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1910         {
1911                 const CaseParams&       params          = cases[caseNdx];
1912
1913                 ComputeShaderSpec       spec;
1914                 vector<deInt64>         inputInts1      (numElements, 0);
1915                 vector<deInt64>         inputInts2      (numElements, 0);
1916                 vector<deInt64>         outputInts      (numElements, 0);
1917
1918
1919                 if (params.positive)
1920                 {
1921                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements, filterNonNegative);
1922                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterPositive);
1923                 }
1924                 else
1925                 {
1926                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements);
1927                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterNotZero);
1928                 }
1929
1930                 for (int ndx = 0; ndx < numElements; ++ndx)
1931                 {
1932                         deInt64 rem = inputInts1[ndx] % inputInts2[ndx];
1933                         if (rem == 0)
1934                         {
1935                                 outputInts[ndx] = 0;
1936                         }
1937                         else if ((inputInts1[ndx] >= 0) == (inputInts2[ndx] >= 0))
1938                         {
1939                                 // They have the same sign
1940                                 outputInts[ndx] = rem;
1941                         }
1942                         else
1943                         {
1944                                 // They have opposite sign.  The remainder operation takes the
1945                                 // sign inputInts1[ndx] but OpSMod is supposed to take ths sign
1946                                 // of inputInts2[ndx].  Adding inputInts2[ndx] will ensure that
1947                                 // the result has the correct sign and that it is still
1948                                 // congruent to inputInts1[ndx] modulo inputInts2[ndx]
1949                                 //
1950                                 // See also http://mathforum.org/library/drmath/view/52343.html
1951                                 outputInts[ndx] = rem + inputInts2[ndx];
1952                         }
1953                 }
1954
1955                 spec.assembly =
1956                         "OpCapability Int64\n"
1957
1958                         + string(getComputeAsmShaderPreamble()) +
1959
1960                         "OpName %main           \"main\"\n"
1961                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1962
1963                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1964
1965                         "OpDecorate %buf BufferBlock\n"
1966                         "OpDecorate %indata1 DescriptorSet 0\n"
1967                         "OpDecorate %indata1 Binding 0\n"
1968                         "OpDecorate %indata2 DescriptorSet 0\n"
1969                         "OpDecorate %indata2 Binding 1\n"
1970                         "OpDecorate %outdata DescriptorSet 0\n"
1971                         "OpDecorate %outdata Binding 2\n"
1972                         "OpDecorate %i64arr ArrayStride 8\n"
1973                         "OpMemberDecorate %buf 0 Offset 0\n"
1974
1975                         + string(getComputeAsmCommonTypes())
1976                         + string(getComputeAsmCommonInt64Types()) +
1977
1978                         "%buf        = OpTypeStruct %i64arr\n"
1979                         "%bufptr     = OpTypePointer Uniform %buf\n"
1980                         "%indata1    = OpVariable %bufptr Uniform\n"
1981                         "%indata2    = OpVariable %bufptr Uniform\n"
1982                         "%outdata    = OpVariable %bufptr Uniform\n"
1983
1984                         "%id        = OpVariable %uvec3ptr Input\n"
1985                         "%zero      = OpConstant %i64 0\n"
1986
1987                         "%main      = OpFunction %void None %voidf\n"
1988                         "%label     = OpLabel\n"
1989                         "%idval     = OpLoad %uvec3 %id\n"
1990                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1991                         "%inloc1    = OpAccessChain %i64ptr %indata1 %zero %x\n"
1992                         "%inval1    = OpLoad %i64 %inloc1\n"
1993                         "%inloc2    = OpAccessChain %i64ptr %indata2 %zero %x\n"
1994                         "%inval2    = OpLoad %i64 %inloc2\n"
1995                         "%rem       = OpSMod %i64 %inval1 %inval2\n"
1996                         "%outloc    = OpAccessChain %i64ptr %outdata %zero %x\n"
1997                         "             OpStore %outloc %rem\n"
1998                         "             OpReturn\n"
1999                         "             OpFunctionEnd\n";
2000
2001                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts1)));
2002                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts2)));
2003                 spec.outputs.push_back  (BufferSp(new Int64Buffer(outputInts)));
2004                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
2005                 spec.failResult                 = params.failResult;
2006                 spec.failMessage                = params.failMessage;
2007
2008                 spec.requestedVulkanFeatures.coreFeatures.shaderInt64 = VK_TRUE;
2009
2010                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
2011         }
2012
2013         return group.release();
2014 }
2015
2016 // Copy contents in the input buffer to the output buffer.
2017 tcu::TestCaseGroup* createOpCopyMemoryGroup (tcu::TestContext& testCtx)
2018 {
2019         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opcopymemory", "Test the OpCopyMemory instruction"));
2020         de::Random                                              rnd                             (deStringHash(group->getName()));
2021         const int                                               numElements             = 100;
2022
2023         // 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.
2024         ComputeShaderSpec                               spec1;
2025         vector<Vec4>                                    inputFloats1    (numElements);
2026         vector<Vec4>                                    outputFloats1   (numElements);
2027
2028         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats1[0], numElements * 4);
2029
2030         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2031         floorAll(inputFloats1);
2032
2033         for (size_t ndx = 0; ndx < numElements; ++ndx)
2034                 outputFloats1[ndx] = inputFloats1[ndx] + Vec4(0.f, 0.5f, 1.5f, 2.5f);
2035
2036         spec1.assembly =
2037                 string(getComputeAsmShaderPreamble()) +
2038
2039                 "OpName %main           \"main\"\n"
2040                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2041
2042                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2043                 "OpDecorate %vec4arr ArrayStride 16\n"
2044
2045                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2046
2047                 "%vec4       = OpTypeVector %f32 4\n"
2048                 "%vec4ptr_u  = OpTypePointer Uniform %vec4\n"
2049                 "%vec4ptr_f  = OpTypePointer Function %vec4\n"
2050                 "%vec4arr    = OpTypeRuntimeArray %vec4\n"
2051                 "%buf        = OpTypeStruct %vec4arr\n"
2052                 "%bufptr     = OpTypePointer Uniform %buf\n"
2053                 "%indata     = OpVariable %bufptr Uniform\n"
2054                 "%outdata    = OpVariable %bufptr Uniform\n"
2055
2056                 "%id         = OpVariable %uvec3ptr Input\n"
2057                 "%zero       = OpConstant %i32 0\n"
2058                 "%c_f_0      = OpConstant %f32 0.\n"
2059                 "%c_f_0_5    = OpConstant %f32 0.5\n"
2060                 "%c_f_1_5    = OpConstant %f32 1.5\n"
2061                 "%c_f_2_5    = OpConstant %f32 2.5\n"
2062                 "%c_vec4     = OpConstantComposite %vec4 %c_f_0 %c_f_0_5 %c_f_1_5 %c_f_2_5\n"
2063
2064                 "%main       = OpFunction %void None %voidf\n"
2065                 "%label      = OpLabel\n"
2066                 "%v_vec4     = OpVariable %vec4ptr_f Function\n"
2067                 "%idval      = OpLoad %uvec3 %id\n"
2068                 "%x          = OpCompositeExtract %u32 %idval 0\n"
2069                 "%inloc      = OpAccessChain %vec4ptr_u %indata %zero %x\n"
2070                 "%outloc     = OpAccessChain %vec4ptr_u %outdata %zero %x\n"
2071                 "              OpCopyMemory %v_vec4 %inloc\n"
2072                 "%v_vec4_val = OpLoad %vec4 %v_vec4\n"
2073                 "%add        = OpFAdd %vec4 %v_vec4_val %c_vec4\n"
2074                 "              OpStore %outloc %add\n"
2075                 "              OpReturn\n"
2076                 "              OpFunctionEnd\n";
2077
2078         spec1.inputs.push_back(BufferSp(new Vec4Buffer(inputFloats1)));
2079         spec1.outputs.push_back(BufferSp(new Vec4Buffer(outputFloats1)));
2080         spec1.numWorkGroups = IVec3(numElements, 1, 1);
2081
2082         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector", "OpCopyMemory elements of vector type", spec1));
2083
2084         // The following case copies a float[100] variable from the input buffer to the output buffer.
2085         ComputeShaderSpec                               spec2;
2086         vector<float>                                   inputFloats2    (numElements);
2087         vector<float>                                   outputFloats2   (numElements);
2088
2089         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats2[0], numElements);
2090
2091         for (size_t ndx = 0; ndx < numElements; ++ndx)
2092                 outputFloats2[ndx] = inputFloats2[ndx];
2093
2094         spec2.assembly =
2095                 string(getComputeAsmShaderPreamble()) +
2096
2097                 "OpName %main           \"main\"\n"
2098                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2099
2100                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2101                 "OpDecorate %f32arr100 ArrayStride 4\n"
2102
2103                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2104
2105                 "%hundred        = OpConstant %u32 100\n"
2106                 "%f32arr100      = OpTypeArray %f32 %hundred\n"
2107                 "%f32arr100ptr_f = OpTypePointer Function %f32arr100\n"
2108                 "%f32arr100ptr_u = OpTypePointer Uniform %f32arr100\n"
2109                 "%buf            = OpTypeStruct %f32arr100\n"
2110                 "%bufptr         = OpTypePointer Uniform %buf\n"
2111                 "%indata         = OpVariable %bufptr Uniform\n"
2112                 "%outdata        = OpVariable %bufptr Uniform\n"
2113
2114                 "%id             = OpVariable %uvec3ptr Input\n"
2115                 "%zero           = OpConstant %i32 0\n"
2116
2117                 "%main           = OpFunction %void None %voidf\n"
2118                 "%label          = OpLabel\n"
2119                 "%var            = OpVariable %f32arr100ptr_f Function\n"
2120                 "%inarr          = OpAccessChain %f32arr100ptr_u %indata %zero\n"
2121                 "%outarr         = OpAccessChain %f32arr100ptr_u %outdata %zero\n"
2122                 "                  OpCopyMemory %var %inarr\n"
2123                 "                  OpCopyMemory %outarr %var\n"
2124                 "                  OpReturn\n"
2125                 "                  OpFunctionEnd\n";
2126
2127         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
2128         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
2129         spec2.numWorkGroups = IVec3(1, 1, 1);
2130
2131         group->addChild(new SpvAsmComputeShaderCase(testCtx, "array", "OpCopyMemory elements of array type", spec2));
2132
2133         // The following case copies a struct{vec4, vec4, vec4, vec4} variable from the input buffer to the output buffer.
2134         ComputeShaderSpec                               spec3;
2135         vector<float>                                   inputFloats3    (16);
2136         vector<float>                                   outputFloats3   (16);
2137
2138         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats3[0], 16);
2139
2140         for (size_t ndx = 0; ndx < 16; ++ndx)
2141                 outputFloats3[ndx] = inputFloats3[ndx];
2142
2143         spec3.assembly =
2144                 string(getComputeAsmShaderPreamble()) +
2145
2146                 "OpName %main           \"main\"\n"
2147                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2148
2149                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2150                 //"OpMemberDecorate %buf 0 Offset 0\n"  - exists in getComputeAsmInputOutputBufferTraits
2151                 "OpMemberDecorate %buf 1 Offset 16\n"
2152                 "OpMemberDecorate %buf 2 Offset 32\n"
2153                 "OpMemberDecorate %buf 3 Offset 48\n"
2154
2155                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2156
2157                 "%vec4      = OpTypeVector %f32 4\n"
2158                 "%buf       = OpTypeStruct %vec4 %vec4 %vec4 %vec4\n"
2159                 "%bufptr    = OpTypePointer Uniform %buf\n"
2160                 "%indata    = OpVariable %bufptr Uniform\n"
2161                 "%outdata   = OpVariable %bufptr Uniform\n"
2162                 "%vec4stptr = OpTypePointer Function %buf\n"
2163
2164                 "%id        = OpVariable %uvec3ptr Input\n"
2165                 "%zero      = OpConstant %i32 0\n"
2166
2167                 "%main      = OpFunction %void None %voidf\n"
2168                 "%label     = OpLabel\n"
2169                 "%var       = OpVariable %vec4stptr Function\n"
2170                 "             OpCopyMemory %var %indata\n"
2171                 "             OpCopyMemory %outdata %var\n"
2172                 "             OpReturn\n"
2173                 "             OpFunctionEnd\n";
2174
2175         spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
2176         spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
2177         spec3.numWorkGroups = IVec3(1, 1, 1);
2178
2179         group->addChild(new SpvAsmComputeShaderCase(testCtx, "struct", "OpCopyMemory elements of struct type", spec3));
2180
2181         // The following case negates multiple float variables from the input buffer and stores the results to the output buffer.
2182         ComputeShaderSpec                               spec4;
2183         vector<float>                                   inputFloats4    (numElements);
2184         vector<float>                                   outputFloats4   (numElements);
2185
2186         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats4[0], numElements);
2187
2188         for (size_t ndx = 0; ndx < numElements; ++ndx)
2189                 outputFloats4[ndx] = -inputFloats4[ndx];
2190
2191         spec4.assembly =
2192                 string(getComputeAsmShaderPreamble()) +
2193
2194                 "OpName %main           \"main\"\n"
2195                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2196
2197                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2198
2199                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2200
2201                 "%f32ptr_f  = OpTypePointer Function %f32\n"
2202                 "%id        = OpVariable %uvec3ptr Input\n"
2203                 "%zero      = OpConstant %i32 0\n"
2204
2205                 "%main      = OpFunction %void None %voidf\n"
2206                 "%label     = OpLabel\n"
2207                 "%var       = OpVariable %f32ptr_f Function\n"
2208                 "%idval     = OpLoad %uvec3 %id\n"
2209                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2210                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
2211                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
2212                 "             OpCopyMemory %var %inloc\n"
2213                 "%val       = OpLoad %f32 %var\n"
2214                 "%neg       = OpFNegate %f32 %val\n"
2215                 "             OpStore %outloc %neg\n"
2216                 "             OpReturn\n"
2217                 "             OpFunctionEnd\n";
2218
2219         spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
2220         spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
2221         spec4.numWorkGroups = IVec3(numElements, 1, 1);
2222
2223         group->addChild(new SpvAsmComputeShaderCase(testCtx, "float", "OpCopyMemory elements of float type", spec4));
2224
2225         return group.release();
2226 }
2227
2228 tcu::TestCaseGroup* createOpCopyObjectGroup (tcu::TestContext& testCtx)
2229 {
2230         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opcopyobject", "Test the OpCopyObject instruction"));
2231         ComputeShaderSpec                               spec;
2232         de::Random                                              rnd                             (deStringHash(group->getName()));
2233         const int                                               numElements             = 100;
2234         vector<float>                                   inputFloats             (numElements, 0);
2235         vector<float>                                   outputFloats    (numElements, 0);
2236
2237         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
2238
2239         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2240         floorAll(inputFloats);
2241
2242         for (size_t ndx = 0; ndx < numElements; ++ndx)
2243                 outputFloats[ndx] = inputFloats[ndx] + 7.5f;
2244
2245         spec.assembly =
2246                 string(getComputeAsmShaderPreamble()) +
2247
2248                 "OpName %main           \"main\"\n"
2249                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2250
2251                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2252
2253                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2254
2255                 "%fmat     = OpTypeMatrix %fvec3 3\n"
2256                 "%three    = OpConstant %u32 3\n"
2257                 "%farr     = OpTypeArray %f32 %three\n"
2258                 "%fst      = OpTypeStruct %f32 %f32\n"
2259
2260                 + string(getComputeAsmInputOutputBuffer()) +
2261
2262                 "%id            = OpVariable %uvec3ptr Input\n"
2263                 "%zero          = OpConstant %i32 0\n"
2264                 "%c_f           = OpConstant %f32 1.5\n"
2265                 "%c_fvec3       = OpConstantComposite %fvec3 %c_f %c_f %c_f\n"
2266                 "%c_fmat        = OpConstantComposite %fmat %c_fvec3 %c_fvec3 %c_fvec3\n"
2267                 "%c_farr        = OpConstantComposite %farr %c_f %c_f %c_f\n"
2268                 "%c_fst         = OpConstantComposite %fst %c_f %c_f\n"
2269
2270                 "%main          = OpFunction %void None %voidf\n"
2271                 "%label         = OpLabel\n"
2272                 "%c_f_copy      = OpCopyObject %f32   %c_f\n"
2273                 "%c_fvec3_copy  = OpCopyObject %fvec3 %c_fvec3\n"
2274                 "%c_fmat_copy   = OpCopyObject %fmat  %c_fmat\n"
2275                 "%c_farr_copy   = OpCopyObject %farr  %c_farr\n"
2276                 "%c_fst_copy    = OpCopyObject %fst   %c_fst\n"
2277                 "%fvec3_elem    = OpCompositeExtract %f32 %c_fvec3_copy 0\n"
2278                 "%fmat_elem     = OpCompositeExtract %f32 %c_fmat_copy 1 2\n"
2279                 "%farr_elem     = OpCompositeExtract %f32 %c_farr_copy 2\n"
2280                 "%fst_elem      = OpCompositeExtract %f32 %c_fst_copy 1\n"
2281                 // Add up. 1.5 * 5 = 7.5.
2282                 "%add1          = OpFAdd %f32 %c_f_copy %fvec3_elem\n"
2283                 "%add2          = OpFAdd %f32 %add1     %fmat_elem\n"
2284                 "%add3          = OpFAdd %f32 %add2     %farr_elem\n"
2285                 "%add4          = OpFAdd %f32 %add3     %fst_elem\n"
2286
2287                 "%idval         = OpLoad %uvec3 %id\n"
2288                 "%x             = OpCompositeExtract %u32 %idval 0\n"
2289                 "%inloc         = OpAccessChain %f32ptr %indata %zero %x\n"
2290                 "%outloc        = OpAccessChain %f32ptr %outdata %zero %x\n"
2291                 "%inval         = OpLoad %f32 %inloc\n"
2292                 "%add           = OpFAdd %f32 %add4 %inval\n"
2293                 "                 OpStore %outloc %add\n"
2294                 "                 OpReturn\n"
2295                 "                 OpFunctionEnd\n";
2296         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2297         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2298         spec.numWorkGroups = IVec3(numElements, 1, 1);
2299
2300         group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "OpCopyObject on different types", spec));
2301
2302         return group.release();
2303 }
2304 // Assembly code used for testing OpUnreachable is based on GLSL source code:
2305 //
2306 // #version 430
2307 //
2308 // layout(std140, set = 0, binding = 0) readonly buffer Input {
2309 //   float elements[];
2310 // } input_data;
2311 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
2312 //   float elements[];
2313 // } output_data;
2314 //
2315 // void not_called_func() {
2316 //   // place OpUnreachable here
2317 // }
2318 //
2319 // uint modulo4(uint val) {
2320 //   switch (val % uint(4)) {
2321 //     case 0:  return 3;
2322 //     case 1:  return 2;
2323 //     case 2:  return 1;
2324 //     case 3:  return 0;
2325 //     default: return 100; // place OpUnreachable here
2326 //   }
2327 // }
2328 //
2329 // uint const5() {
2330 //   return 5;
2331 //   // place OpUnreachable here
2332 // }
2333 //
2334 // void main() {
2335 //   uint x = gl_GlobalInvocationID.x;
2336 //   if (const5() > modulo4(1000)) {
2337 //     output_data.elements[x] = -input_data.elements[x];
2338 //   } else {
2339 //     // place OpUnreachable here
2340 //     output_data.elements[x] = input_data.elements[x];
2341 //   }
2342 // }
2343
2344 tcu::TestCaseGroup* createOpUnreachableGroup (tcu::TestContext& testCtx)
2345 {
2346         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opunreachable", "Test the OpUnreachable instruction"));
2347         ComputeShaderSpec                               spec;
2348         de::Random                                              rnd                             (deStringHash(group->getName()));
2349         const int                                               numElements             = 100;
2350         vector<float>                                   positiveFloats  (numElements, 0);
2351         vector<float>                                   negativeFloats  (numElements, 0);
2352
2353         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
2354
2355         for (size_t ndx = 0; ndx < numElements; ++ndx)
2356                 negativeFloats[ndx] = -positiveFloats[ndx];
2357
2358         spec.assembly =
2359                 string(getComputeAsmShaderPreamble()) +
2360
2361                 "OpSource GLSL 430\n"
2362                 "OpName %main            \"main\"\n"
2363                 "OpName %func_not_called_func \"not_called_func(\"\n"
2364                 "OpName %func_modulo4         \"modulo4(u1;\"\n"
2365                 "OpName %func_const5          \"const5(\"\n"
2366                 "OpName %id                   \"gl_GlobalInvocationID\"\n"
2367
2368                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2369
2370                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2371
2372                 "%u32ptr    = OpTypePointer Function %u32\n"
2373                 "%uintfuint = OpTypeFunction %u32 %u32ptr\n"
2374                 "%unitf     = OpTypeFunction %u32\n"
2375
2376                 "%id        = OpVariable %uvec3ptr Input\n"
2377                 "%zero      = OpConstant %u32 0\n"
2378                 "%one       = OpConstant %u32 1\n"
2379                 "%two       = OpConstant %u32 2\n"
2380                 "%three     = OpConstant %u32 3\n"
2381                 "%four      = OpConstant %u32 4\n"
2382                 "%five      = OpConstant %u32 5\n"
2383                 "%hundred   = OpConstant %u32 100\n"
2384                 "%thousand  = OpConstant %u32 1000\n"
2385
2386                 + string(getComputeAsmInputOutputBuffer()) +
2387
2388                 // Main()
2389                 "%main   = OpFunction %void None %voidf\n"
2390                 "%main_entry  = OpLabel\n"
2391                 "%v_thousand  = OpVariable %u32ptr Function %thousand\n"
2392                 "%idval       = OpLoad %uvec3 %id\n"
2393                 "%x           = OpCompositeExtract %u32 %idval 0\n"
2394                 "%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
2395                 "%inval       = OpLoad %f32 %inloc\n"
2396                 "%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
2397                 "%ret_const5  = OpFunctionCall %u32 %func_const5\n"
2398                 "%ret_modulo4 = OpFunctionCall %u32 %func_modulo4 %v_thousand\n"
2399                 "%cmp_gt      = OpUGreaterThan %bool %ret_const5 %ret_modulo4\n"
2400                 "               OpSelectionMerge %if_end None\n"
2401                 "               OpBranchConditional %cmp_gt %if_true %if_false\n"
2402                 "%if_true     = OpLabel\n"
2403                 "%negate      = OpFNegate %f32 %inval\n"
2404                 "               OpStore %outloc %negate\n"
2405                 "               OpBranch %if_end\n"
2406                 "%if_false    = OpLabel\n"
2407                 "               OpUnreachable\n" // Unreachable else branch for if statement
2408                 "%if_end      = OpLabel\n"
2409                 "               OpReturn\n"
2410                 "               OpFunctionEnd\n"
2411
2412                 // not_called_function()
2413                 "%func_not_called_func  = OpFunction %void None %voidf\n"
2414                 "%not_called_func_entry = OpLabel\n"
2415                 "                         OpUnreachable\n" // Unreachable entry block in not called static function
2416                 "                         OpFunctionEnd\n"
2417
2418                 // modulo4()
2419                 "%func_modulo4  = OpFunction %u32 None %uintfuint\n"
2420                 "%valptr        = OpFunctionParameter %u32ptr\n"
2421                 "%modulo4_entry = OpLabel\n"
2422                 "%val           = OpLoad %u32 %valptr\n"
2423                 "%modulo        = OpUMod %u32 %val %four\n"
2424                 "                 OpSelectionMerge %switch_merge None\n"
2425                 "                 OpSwitch %modulo %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
2426                 "%case0         = OpLabel\n"
2427                 "                 OpReturnValue %three\n"
2428                 "%case1         = OpLabel\n"
2429                 "                 OpReturnValue %two\n"
2430                 "%case2         = OpLabel\n"
2431                 "                 OpReturnValue %one\n"
2432                 "%case3         = OpLabel\n"
2433                 "                 OpReturnValue %zero\n"
2434                 "%default       = OpLabel\n"
2435                 "                 OpUnreachable\n" // Unreachable default case for switch statement
2436                 "%switch_merge  = OpLabel\n"
2437                 "                 OpUnreachable\n" // Unreachable merge block for switch statement
2438                 "                 OpFunctionEnd\n"
2439
2440                 // const5()
2441                 "%func_const5  = OpFunction %u32 None %unitf\n"
2442                 "%const5_entry = OpLabel\n"
2443                 "                OpReturnValue %five\n"
2444                 "%unreachable  = OpLabel\n"
2445                 "                OpUnreachable\n" // Unreachable block in function
2446                 "                OpFunctionEnd\n";
2447         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
2448         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
2449         spec.numWorkGroups = IVec3(numElements, 1, 1);
2450
2451         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpUnreachable appearing at different places", spec));
2452
2453         return group.release();
2454 }
2455
2456 // Assembly code used for testing decoration group is based on GLSL source code:
2457 //
2458 // #version 430
2459 //
2460 // layout(std140, set = 0, binding = 0) readonly buffer Input0 {
2461 //   float elements[];
2462 // } input_data0;
2463 // layout(std140, set = 0, binding = 1) readonly buffer Input1 {
2464 //   float elements[];
2465 // } input_data1;
2466 // layout(std140, set = 0, binding = 2) readonly buffer Input2 {
2467 //   float elements[];
2468 // } input_data2;
2469 // layout(std140, set = 0, binding = 3) readonly buffer Input3 {
2470 //   float elements[];
2471 // } input_data3;
2472 // layout(std140, set = 0, binding = 4) readonly buffer Input4 {
2473 //   float elements[];
2474 // } input_data4;
2475 // layout(std140, set = 0, binding = 5) writeonly buffer Output {
2476 //   float elements[];
2477 // } output_data;
2478 //
2479 // void main() {
2480 //   uint x = gl_GlobalInvocationID.x;
2481 //   output_data.elements[x] = input_data0.elements[x] + input_data1.elements[x] + input_data2.elements[x] + input_data3.elements[x] + input_data4.elements[x];
2482 // }
2483 tcu::TestCaseGroup* createDecorationGroupGroup (tcu::TestContext& testCtx)
2484 {
2485         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "decoration_group", "Test the OpDecorationGroup & OpGroupDecorate instruction"));
2486         ComputeShaderSpec                               spec;
2487         de::Random                                              rnd                             (deStringHash(group->getName()));
2488         const int                                               numElements             = 100;
2489         vector<float>                                   inputFloats0    (numElements, 0);
2490         vector<float>                                   inputFloats1    (numElements, 0);
2491         vector<float>                                   inputFloats2    (numElements, 0);
2492         vector<float>                                   inputFloats3    (numElements, 0);
2493         vector<float>                                   inputFloats4    (numElements, 0);
2494         vector<float>                                   outputFloats    (numElements, 0);
2495
2496         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats0[0], numElements);
2497         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats1[0], numElements);
2498         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats2[0], numElements);
2499         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats3[0], numElements);
2500         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats4[0], numElements);
2501
2502         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2503         floorAll(inputFloats0);
2504         floorAll(inputFloats1);
2505         floorAll(inputFloats2);
2506         floorAll(inputFloats3);
2507         floorAll(inputFloats4);
2508
2509         for (size_t ndx = 0; ndx < numElements; ++ndx)
2510                 outputFloats[ndx] = inputFloats0[ndx] + inputFloats1[ndx] + inputFloats2[ndx] + inputFloats3[ndx] + inputFloats4[ndx];
2511
2512         spec.assembly =
2513                 string(getComputeAsmShaderPreamble()) +
2514
2515                 "OpSource GLSL 430\n"
2516                 "OpName %main \"main\"\n"
2517                 "OpName %id \"gl_GlobalInvocationID\"\n"
2518
2519                 // Not using group decoration on variable.
2520                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2521                 // Not using group decoration on type.
2522                 "OpDecorate %f32arr ArrayStride 4\n"
2523
2524                 "OpDecorate %groups BufferBlock\n"
2525                 "OpDecorate %groupm Offset 0\n"
2526                 "%groups = OpDecorationGroup\n"
2527                 "%groupm = OpDecorationGroup\n"
2528
2529                 // Group decoration on multiple structs.
2530                 "OpGroupDecorate %groups %outbuf %inbuf0 %inbuf1 %inbuf2 %inbuf3 %inbuf4\n"
2531                 // Group decoration on multiple struct members.
2532                 "OpGroupMemberDecorate %groupm %outbuf 0 %inbuf0 0 %inbuf1 0 %inbuf2 0 %inbuf3 0 %inbuf4 0\n"
2533
2534                 "OpDecorate %group1 DescriptorSet 0\n"
2535                 "OpDecorate %group3 DescriptorSet 0\n"
2536                 "OpDecorate %group3 NonWritable\n"
2537                 "OpDecorate %group3 Restrict\n"
2538                 "%group0 = OpDecorationGroup\n"
2539                 "%group1 = OpDecorationGroup\n"
2540                 "%group3 = OpDecorationGroup\n"
2541
2542                 // Applying the same decoration group multiple times.
2543                 "OpGroupDecorate %group1 %outdata\n"
2544                 "OpGroupDecorate %group1 %outdata\n"
2545                 "OpGroupDecorate %group1 %outdata\n"
2546                 "OpDecorate %outdata DescriptorSet 0\n"
2547                 "OpDecorate %outdata Binding 5\n"
2548                 // Applying decoration group containing nothing.
2549                 "OpGroupDecorate %group0 %indata0\n"
2550                 "OpDecorate %indata0 DescriptorSet 0\n"
2551                 "OpDecorate %indata0 Binding 0\n"
2552                 // Applying decoration group containing one decoration.
2553                 "OpGroupDecorate %group1 %indata1\n"
2554                 "OpDecorate %indata1 Binding 1\n"
2555                 // Applying decoration group containing multiple decorations.
2556                 "OpGroupDecorate %group3 %indata2 %indata3\n"
2557                 "OpDecorate %indata2 Binding 2\n"
2558                 "OpDecorate %indata3 Binding 3\n"
2559                 // Applying multiple decoration groups (with overlapping).
2560                 "OpGroupDecorate %group0 %indata4\n"
2561                 "OpGroupDecorate %group1 %indata4\n"
2562                 "OpGroupDecorate %group3 %indata4\n"
2563                 "OpDecorate %indata4 Binding 4\n"
2564
2565                 + string(getComputeAsmCommonTypes()) +
2566
2567                 "%id   = OpVariable %uvec3ptr Input\n"
2568                 "%zero = OpConstant %i32 0\n"
2569
2570                 "%outbuf    = OpTypeStruct %f32arr\n"
2571                 "%outbufptr = OpTypePointer Uniform %outbuf\n"
2572                 "%outdata   = OpVariable %outbufptr Uniform\n"
2573                 "%inbuf0    = OpTypeStruct %f32arr\n"
2574                 "%inbuf0ptr = OpTypePointer Uniform %inbuf0\n"
2575                 "%indata0   = OpVariable %inbuf0ptr Uniform\n"
2576                 "%inbuf1    = OpTypeStruct %f32arr\n"
2577                 "%inbuf1ptr = OpTypePointer Uniform %inbuf1\n"
2578                 "%indata1   = OpVariable %inbuf1ptr Uniform\n"
2579                 "%inbuf2    = OpTypeStruct %f32arr\n"
2580                 "%inbuf2ptr = OpTypePointer Uniform %inbuf2\n"
2581                 "%indata2   = OpVariable %inbuf2ptr Uniform\n"
2582                 "%inbuf3    = OpTypeStruct %f32arr\n"
2583                 "%inbuf3ptr = OpTypePointer Uniform %inbuf3\n"
2584                 "%indata3   = OpVariable %inbuf3ptr Uniform\n"
2585                 "%inbuf4    = OpTypeStruct %f32arr\n"
2586                 "%inbufptr  = OpTypePointer Uniform %inbuf4\n"
2587                 "%indata4   = OpVariable %inbufptr Uniform\n"
2588
2589                 "%main   = OpFunction %void None %voidf\n"
2590                 "%label  = OpLabel\n"
2591                 "%idval  = OpLoad %uvec3 %id\n"
2592                 "%x      = OpCompositeExtract %u32 %idval 0\n"
2593                 "%inloc0 = OpAccessChain %f32ptr %indata0 %zero %x\n"
2594                 "%inloc1 = OpAccessChain %f32ptr %indata1 %zero %x\n"
2595                 "%inloc2 = OpAccessChain %f32ptr %indata2 %zero %x\n"
2596                 "%inloc3 = OpAccessChain %f32ptr %indata3 %zero %x\n"
2597                 "%inloc4 = OpAccessChain %f32ptr %indata4 %zero %x\n"
2598                 "%outloc = OpAccessChain %f32ptr %outdata %zero %x\n"
2599                 "%inval0 = OpLoad %f32 %inloc0\n"
2600                 "%inval1 = OpLoad %f32 %inloc1\n"
2601                 "%inval2 = OpLoad %f32 %inloc2\n"
2602                 "%inval3 = OpLoad %f32 %inloc3\n"
2603                 "%inval4 = OpLoad %f32 %inloc4\n"
2604                 "%add0   = OpFAdd %f32 %inval0 %inval1\n"
2605                 "%add1   = OpFAdd %f32 %add0 %inval2\n"
2606                 "%add2   = OpFAdd %f32 %add1 %inval3\n"
2607                 "%add    = OpFAdd %f32 %add2 %inval4\n"
2608                 "          OpStore %outloc %add\n"
2609                 "          OpReturn\n"
2610                 "          OpFunctionEnd\n";
2611         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats0)));
2612         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
2613         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
2614         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
2615         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
2616         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2617         spec.numWorkGroups = IVec3(numElements, 1, 1);
2618
2619         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "decoration group cases", spec));
2620
2621         return group.release();
2622 }
2623
2624 struct SpecConstantTwoIntCase
2625 {
2626         const char*             caseName;
2627         const char*             scDefinition0;
2628         const char*             scDefinition1;
2629         const char*             scResultType;
2630         const char*             scOperation;
2631         deInt32                 scActualValue0;
2632         deInt32                 scActualValue1;
2633         const char*             resultOperation;
2634         vector<deInt32> expectedOutput;
2635         deInt32                 scActualValueLength;
2636
2637                                         SpecConstantTwoIntCase (const char* name,
2638                                                                                         const char* definition0,
2639                                                                                         const char* definition1,
2640                                                                                         const char* resultType,
2641                                                                                         const char* operation,
2642                                                                                         deInt32 value0,
2643                                                                                         deInt32 value1,
2644                                                                                         const char* resultOp,
2645                                                                                         const vector<deInt32>& output,
2646                                                                                         const deInt32   valueLength = sizeof(deInt32))
2647                                                 : caseName                              (name)
2648                                                 , scDefinition0                 (definition0)
2649                                                 , scDefinition1                 (definition1)
2650                                                 , scResultType                  (resultType)
2651                                                 , scOperation                   (operation)
2652                                                 , scActualValue0                (value0)
2653                                                 , scActualValue1                (value1)
2654                                                 , resultOperation               (resultOp)
2655                                                 , expectedOutput                (output)
2656                                                 , scActualValueLength   (valueLength)
2657                                                 {}
2658 };
2659
2660 tcu::TestCaseGroup* createSpecConstantGroup (tcu::TestContext& testCtx)
2661 {
2662         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
2663         vector<SpecConstantTwoIntCase>  cases;
2664         de::Random                                              rnd                             (deStringHash(group->getName()));
2665         const int                                               numElements             = 100;
2666         const deInt32                                   p1AsFloat16             = 0x3c00; // +1(fp16) == 0 01111 0000000000 == 0011 1100 0000 0000
2667         vector<deInt32>                                 inputInts               (numElements, 0);
2668         vector<deInt32>                                 outputInts1             (numElements, 0);
2669         vector<deInt32>                                 outputInts2             (numElements, 0);
2670         vector<deInt32>                                 outputInts3             (numElements, 0);
2671         vector<deInt32>                                 outputInts4             (numElements, 0);
2672         const StringTemplate                    shaderTemplate  (
2673                 "${CAPABILITIES:opt}"
2674                 + string(getComputeAsmShaderPreamble()) +
2675
2676                 "OpName %main           \"main\"\n"
2677                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2678
2679                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2680                 "OpDecorate %sc_0  SpecId 0\n"
2681                 "OpDecorate %sc_1  SpecId 1\n"
2682                 "OpDecorate %i32arr ArrayStride 4\n"
2683
2684                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2685
2686                 "${OPTYPE_DEFINITIONS:opt}"
2687                 "%buf     = OpTypeStruct %i32arr\n"
2688                 "%bufptr  = OpTypePointer Uniform %buf\n"
2689                 "%indata    = OpVariable %bufptr Uniform\n"
2690                 "%outdata   = OpVariable %bufptr Uniform\n"
2691
2692                 "%id        = OpVariable %uvec3ptr Input\n"
2693                 "%zero      = OpConstant %i32 0\n"
2694
2695                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
2696                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
2697                 "%sc_final  = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n"
2698
2699                 "%main      = OpFunction %void None %voidf\n"
2700                 "%label     = OpLabel\n"
2701                 "${TYPE_CONVERT:opt}"
2702                 "%idval     = OpLoad %uvec3 %id\n"
2703                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2704                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
2705                 "%inval     = OpLoad %i32 %inloc\n"
2706                 "%final     = ${GEN_RESULT}\n"
2707                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2708                 "             OpStore %outloc %final\n"
2709                 "             OpReturn\n"
2710                 "             OpFunctionEnd\n");
2711
2712         fillRandomScalars(rnd, -65536, 65536, &inputInts[0], numElements);
2713
2714         for (size_t ndx = 0; ndx < numElements; ++ndx)
2715         {
2716                 outputInts1[ndx] = inputInts[ndx] + 42;
2717                 outputInts2[ndx] = inputInts[ndx];
2718                 outputInts3[ndx] = inputInts[ndx] - 11200;
2719                 outputInts4[ndx] = inputInts[ndx] + 1;
2720         }
2721
2722         const char addScToInput[]               = "OpIAdd %i32 %inval %sc_final";
2723         const char addSc32ToInput[]             = "OpIAdd %i32 %inval %sc_final32";
2724         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_final %inval %zero";
2725         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_final %zero %inval";
2726
2727         cases.push_back(SpecConstantTwoIntCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                     62,             -20,    addScToInput,           outputInts1));
2728         cases.push_back(SpecConstantTwoIntCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                     100,    58,             addScToInput,           outputInts1));
2729         cases.push_back(SpecConstantTwoIntCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                     -2,             -21,    addScToInput,           outputInts1));
2730         cases.push_back(SpecConstantTwoIntCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                     -126,   -3,             addScToInput,           outputInts1));
2731         cases.push_back(SpecConstantTwoIntCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                     126,    3,              addScToInput,           outputInts1));
2732         cases.push_back(SpecConstantTwoIntCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
2733         cases.push_back(SpecConstantTwoIntCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
2734         cases.push_back(SpecConstantTwoIntCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                     342,    50,             addScToInput,           outputInts1));
2735         cases.push_back(SpecConstantTwoIntCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                     42,             63,             addScToInput,           outputInts1));
2736         cases.push_back(SpecConstantTwoIntCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                     34,             8,              addScToInput,           outputInts1));
2737         cases.push_back(SpecConstantTwoIntCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                     18,             56,             addScToInput,           outputInts1));
2738         cases.push_back(SpecConstantTwoIntCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
2739         cases.push_back(SpecConstantTwoIntCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
2740         cases.push_back(SpecConstantTwoIntCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                     21,             1,              addScToInput,           outputInts1));
2741         cases.push_back(SpecConstantTwoIntCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                     -20,    -10,    selectTrueUsingSc,      outputInts2));
2742         cases.push_back(SpecConstantTwoIntCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                     10,             20,             selectTrueUsingSc,      outputInts2));
2743         cases.push_back(SpecConstantTwoIntCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
2744         cases.push_back(SpecConstantTwoIntCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                     10,             5,              selectTrueUsingSc,      outputInts2));
2745         cases.push_back(SpecConstantTwoIntCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                     -10,    -10,    selectTrueUsingSc,      outputInts2));
2746         cases.push_back(SpecConstantTwoIntCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                     50,             100,    selectTrueUsingSc,      outputInts2));
2747         cases.push_back(SpecConstantTwoIntCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
2748         cases.push_back(SpecConstantTwoIntCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                     10,             10,             selectTrueUsingSc,      outputInts2));
2749         cases.push_back(SpecConstantTwoIntCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                     42,             24,             selectFalseUsingSc,     outputInts2));
2750         cases.push_back(SpecConstantTwoIntCase("inotequal",                             " %i32 0",              " %i32 0",              "%bool",        "INotEqual            %sc_0 %sc_1",                     42,             24,             selectTrueUsingSc,      outputInts2));
2751         cases.push_back(SpecConstantTwoIntCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
2752         cases.push_back(SpecConstantTwoIntCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
2753         cases.push_back(SpecConstantTwoIntCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
2754         cases.push_back(SpecConstantTwoIntCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
2755         cases.push_back(SpecConstantTwoIntCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                           -42,    0,              addScToInput,           outputInts1));
2756         cases.push_back(SpecConstantTwoIntCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                           -43,    0,              addScToInput,           outputInts1));
2757         cases.push_back(SpecConstantTwoIntCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                           1,              0,              selectFalseUsingSc,     outputInts2));
2758         cases.push_back(SpecConstantTwoIntCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %zero",       1,              42,             addScToInput,           outputInts1));
2759         cases.push_back(SpecConstantTwoIntCase("sconvert",                              " %i32 0",              " %i32 0",              "%i16",         "SConvert             %sc_0",                           -11200, 0,              addSc32ToInput,         outputInts3));
2760         // -969998336 stored as 32-bit two's complement is the binary representation of -11200 as IEEE-754 Float
2761         cases.push_back(SpecConstantTwoIntCase("fconvert",                              " %f32 0",              " %f32 0",              "%f64",         "FConvert             %sc_0",                           -969998336, 0,  addSc32ToInput,         outputInts3));
2762         cases.push_back(SpecConstantTwoIntCase("fconvert16",                    " %f16 0",              " %f16 0",              "%f32",         "FConvert             %sc_0",                           p1AsFloat16, 0, addSc32ToInput,         outputInts4, sizeof(deFloat16)));
2763
2764         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
2765         {
2766                 map<string, string>             specializations;
2767                 ComputeShaderSpec               spec;
2768
2769                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
2770                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
2771                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
2772                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
2773                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
2774
2775                 // Special SPIR-V code for SConvert-case
2776                 if (strcmp(cases[caseNdx].caseName, "sconvert") == 0)
2777                 {
2778                         spec.requestedVulkanFeatures.coreFeatures.shaderInt16   = VK_TRUE;
2779                         specializations["CAPABILITIES"]                                                 = "OpCapability Int16\n";                                                       // Adds 16-bit integer capability
2780                         specializations["OPTYPE_DEFINITIONS"]                                   = "%i16 = OpTypeInt 16 1\n";                                            // Adds 16-bit integer type
2781                         specializations["TYPE_CONVERT"]                                                 = "%sc_final32 = OpSConvert %i32 %sc_final\n";          // Converts 16-bit integer to 32-bit integer
2782                 }
2783
2784                 // Special SPIR-V code for FConvert-case
2785                 if (strcmp(cases[caseNdx].caseName, "fconvert") == 0)
2786                 {
2787                         spec.requestedVulkanFeatures.coreFeatures.shaderFloat64 = VK_TRUE;
2788                         specializations["CAPABILITIES"]                                                 = "OpCapability Float64\n";                                                     // Adds 64-bit float capability
2789                         specializations["OPTYPE_DEFINITIONS"]                                   = "%f64 = OpTypeFloat 64\n";                                            // Adds 64-bit float type
2790                         specializations["TYPE_CONVERT"]                                                 = "%sc_final32 = OpConvertFToS %i32 %sc_final\n";       // Converts 64-bit float to 32-bit integer
2791                 }
2792
2793                 // Special SPIR-V code for FConvert-case for 16-bit floats
2794                 if (strcmp(cases[caseNdx].caseName, "fconvert16") == 0)
2795                 {
2796                         spec.extensions.push_back("VK_KHR_shader_float16_int8");
2797                         spec.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
2798                         specializations["CAPABILITIES"]                 = "OpCapability Float16\n";                                                     // Adds 16-bit float capability
2799                         specializations["OPTYPE_DEFINITIONS"]   = "%f16 = OpTypeFloat 16\n";                                            // Adds 16-bit float type
2800                         specializations["TYPE_CONVERT"]                 = "%sc_final32 = OpConvertFToS %i32 %sc_final\n";       // Converts 16-bit float to 32-bit integer
2801                 }
2802
2803                 spec.assembly = shaderTemplate.specialize(specializations);
2804                 spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
2805                 spec.outputs.push_back(BufferSp(new Int32Buffer(cases[caseNdx].expectedOutput)));
2806                 spec.numWorkGroups = IVec3(numElements, 1, 1);
2807                 spec.specConstants.append(&cases[caseNdx].scActualValue0, cases[caseNdx].scActualValueLength);
2808                 spec.specConstants.append(&cases[caseNdx].scActualValue1, cases[caseNdx].scActualValueLength);
2809
2810                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].caseName, cases[caseNdx].caseName, spec));
2811         }
2812
2813         ComputeShaderSpec                               spec;
2814
2815         spec.assembly =
2816                 string(getComputeAsmShaderPreamble()) +
2817
2818                 "OpName %main           \"main\"\n"
2819                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2820
2821                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2822                 "OpDecorate %sc_0  SpecId 0\n"
2823                 "OpDecorate %sc_1  SpecId 1\n"
2824                 "OpDecorate %sc_2  SpecId 2\n"
2825                 "OpDecorate %i32arr ArrayStride 4\n"
2826
2827                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2828
2829                 "%ivec3       = OpTypeVector %i32 3\n"
2830                 "%buf         = OpTypeStruct %i32arr\n"
2831                 "%bufptr      = OpTypePointer Uniform %buf\n"
2832                 "%indata      = OpVariable %bufptr Uniform\n"
2833                 "%outdata     = OpVariable %bufptr Uniform\n"
2834
2835                 "%id          = OpVariable %uvec3ptr Input\n"
2836                 "%zero        = OpConstant %i32 0\n"
2837                 "%ivec3_0     = OpConstantComposite %ivec3 %zero %zero %zero\n"
2838                 "%vec3_undef  = OpUndef %ivec3\n"
2839
2840                 "%sc_0        = OpSpecConstant %i32 0\n"
2841                 "%sc_1        = OpSpecConstant %i32 0\n"
2842                 "%sc_2        = OpSpecConstant %i32 0\n"
2843                 "%sc_vec3_0   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_0        %ivec3_0     0\n"                                                 // (sc_0, 0, 0)
2844                 "%sc_vec3_1   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_1        %ivec3_0     1\n"                                                 // (0, sc_1, 0)
2845                 "%sc_vec3_2   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_2        %ivec3_0     2\n"                                                 // (0, 0, sc_2)
2846                 "%sc_vec3_0_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0   %vec3_undef  0          0xFFFFFFFF 2\n"   // (sc_0, ???,  0)
2847                 "%sc_vec3_1_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_1   %vec3_undef  0xFFFFFFFF 1          0\n"   // (???,  sc_1, 0)
2848                 "%sc_vec3_2_s = OpSpecConstantOp %ivec3 VectorShuffle    %vec3_undef  %sc_vec3_2   5          0xFFFFFFFF 5\n"   // (sc_2, ???,  sc_2)
2849                 "%sc_vec3_01  = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0_s %sc_vec3_1_s 1 0 4\n"                                             // (0,    sc_0, sc_1)
2850                 "%sc_vec3_012 = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_01  %sc_vec3_2_s 5 1 2\n"                                             // (sc_2, sc_0, sc_1)
2851                 "%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              0\n"                                                 // sc_2
2852                 "%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              1\n"                                                 // sc_0
2853                 "%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              2\n"                                                 // sc_1
2854                 "%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"                                                              // (sc_2 - sc_0)
2855                 "%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n"                                                              // (sc_2 - sc_0) * sc_1
2856
2857                 "%main      = OpFunction %void None %voidf\n"
2858                 "%label     = OpLabel\n"
2859                 "%idval     = OpLoad %uvec3 %id\n"
2860                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2861                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
2862                 "%inval     = OpLoad %i32 %inloc\n"
2863                 "%final     = OpIAdd %i32 %inval %sc_final\n"
2864                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2865                 "             OpStore %outloc %final\n"
2866                 "             OpReturn\n"
2867                 "             OpFunctionEnd\n";
2868         spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
2869         spec.outputs.push_back(BufferSp(new Int32Buffer(outputInts3)));
2870         spec.numWorkGroups = IVec3(numElements, 1, 1);
2871         spec.specConstants.append<deInt32>(123);
2872         spec.specConstants.append<deInt32>(56);
2873         spec.specConstants.append<deInt32>(-77);
2874
2875         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector_related", "VectorShuffle, CompositeExtract, & CompositeInsert", spec));
2876
2877         return group.release();
2878 }
2879
2880 void createOpPhiVartypeTests (de::MovePtr<tcu::TestCaseGroup>& group, tcu::TestContext& testCtx)
2881 {
2882         ComputeShaderSpec       specInt;
2883         ComputeShaderSpec       specFloat;
2884         ComputeShaderSpec       specFloat16;
2885         ComputeShaderSpec       specVec3;
2886         ComputeShaderSpec       specMat4;
2887         ComputeShaderSpec       specArray;
2888         ComputeShaderSpec       specStruct;
2889         de::Random                      rnd                             (deStringHash(group->getName()));
2890         const int                       numElements             = 100;
2891         vector<float>           inputFloats             (numElements, 0);
2892         vector<float>           outputFloats    (numElements, 0);
2893         vector<deFloat16>       inputFloats16   (numElements, 0);
2894         vector<deFloat16>       outputFloats16  (numElements, 0);
2895
2896         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
2897
2898         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2899         floorAll(inputFloats);
2900
2901         for (size_t ndx = 0; ndx < numElements; ++ndx)
2902         {
2903                 // Just check if the value is positive or not
2904                 outputFloats[ndx] = (inputFloats[ndx] > 0) ? 1.0f : -1.0f;
2905         }
2906
2907         for (size_t ndx = 0; ndx < numElements; ++ndx)
2908         {
2909                 inputFloats16[ndx] = tcu::Float16(inputFloats[ndx]).bits();
2910                 outputFloats16[ndx] = tcu::Float16(outputFloats[ndx]).bits();
2911         }
2912
2913         // All of the tests are of the form:
2914         //
2915         // testtype r
2916         //
2917         // if (inputdata > 0)
2918         //   r = 1
2919         // else
2920         //   r = -1
2921         //
2922         // return (float)r
2923
2924         specFloat.assembly =
2925                 string(getComputeAsmShaderPreamble()) +
2926
2927                 "OpSource GLSL 430\n"
2928                 "OpName %main \"main\"\n"
2929                 "OpName %id \"gl_GlobalInvocationID\"\n"
2930
2931                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2932
2933                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2934
2935                 "%id = OpVariable %uvec3ptr Input\n"
2936                 "%zero       = OpConstant %i32 0\n"
2937                 "%float_0    = OpConstant %f32 0.0\n"
2938                 "%float_1    = OpConstant %f32 1.0\n"
2939                 "%float_n1   = OpConstant %f32 -1.0\n"
2940
2941                 "%main     = OpFunction %void None %voidf\n"
2942                 "%entry    = OpLabel\n"
2943                 "%idval    = OpLoad %uvec3 %id\n"
2944                 "%x        = OpCompositeExtract %u32 %idval 0\n"
2945                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
2946                 "%inval    = OpLoad %f32 %inloc\n"
2947
2948                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
2949                 "            OpSelectionMerge %cm None\n"
2950                 "            OpBranchConditional %comp %tb %fb\n"
2951                 "%tb       = OpLabel\n"
2952                 "            OpBranch %cm\n"
2953                 "%fb       = OpLabel\n"
2954                 "            OpBranch %cm\n"
2955                 "%cm       = OpLabel\n"
2956                 "%res      = OpPhi %f32 %float_1 %tb %float_n1 %fb\n"
2957
2958                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
2959                 "            OpStore %outloc %res\n"
2960                 "            OpReturn\n"
2961
2962                 "            OpFunctionEnd\n";
2963         specFloat.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2964         specFloat.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2965         specFloat.numWorkGroups = IVec3(numElements, 1, 1);
2966
2967         specFloat16.assembly =
2968                 "OpCapability Shader\n"
2969                 "OpCapability StorageUniformBufferBlock16\n"
2970                 "OpExtension \"SPV_KHR_16bit_storage\"\n"
2971                 "OpMemoryModel Logical GLSL450\n"
2972                 "OpEntryPoint GLCompute %main \"main\" %id\n"
2973                 "OpExecutionMode %main LocalSize 1 1 1\n"
2974
2975                 "OpSource GLSL 430\n"
2976                 "OpName %main \"main\"\n"
2977                 "OpName %id \"gl_GlobalInvocationID\"\n"
2978
2979                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2980
2981                 "OpDecorate %buf BufferBlock\n"
2982                 "OpDecorate %indata DescriptorSet 0\n"
2983                 "OpDecorate %indata Binding 0\n"
2984                 "OpDecorate %outdata DescriptorSet 0\n"
2985                 "OpDecorate %outdata Binding 1\n"
2986                 "OpDecorate %f16arr ArrayStride 2\n"
2987                 "OpMemberDecorate %buf 0 Offset 0\n"
2988
2989                 "%f16      = OpTypeFloat 16\n"
2990                 "%f16ptr   = OpTypePointer Uniform %f16\n"
2991                 "%f16arr   = OpTypeRuntimeArray %f16\n"
2992
2993                 + string(getComputeAsmCommonTypes()) +
2994
2995                 "%buf      = OpTypeStruct %f16arr\n"
2996                 "%bufptr   = OpTypePointer Uniform %buf\n"
2997                 "%indata   = OpVariable %bufptr Uniform\n"
2998                 "%outdata  = OpVariable %bufptr Uniform\n"
2999
3000                 "%id       = OpVariable %uvec3ptr Input\n"
3001                 "%zero     = OpConstant %i32 0\n"
3002                 "%float_0  = OpConstant %f16 0.0\n"
3003                 "%float_1  = OpConstant %f16 1.0\n"
3004                 "%float_n1 = OpConstant %f16 -1.0\n"
3005
3006                 "%main     = OpFunction %void None %voidf\n"
3007                 "%entry    = OpLabel\n"
3008                 "%idval    = OpLoad %uvec3 %id\n"
3009                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3010                 "%inloc    = OpAccessChain %f16ptr %indata %zero %x\n"
3011                 "%inval    = OpLoad %f16 %inloc\n"
3012
3013                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3014                 "            OpSelectionMerge %cm None\n"
3015                 "            OpBranchConditional %comp %tb %fb\n"
3016                 "%tb       = OpLabel\n"
3017                 "            OpBranch %cm\n"
3018                 "%fb       = OpLabel\n"
3019                 "            OpBranch %cm\n"
3020                 "%cm       = OpLabel\n"
3021                 "%res      = OpPhi %f16 %float_1 %tb %float_n1 %fb\n"
3022
3023                 "%outloc   = OpAccessChain %f16ptr %outdata %zero %x\n"
3024                 "            OpStore %outloc %res\n"
3025                 "            OpReturn\n"
3026
3027                 "            OpFunctionEnd\n";
3028         specFloat16.inputs.push_back(BufferSp(new Float16Buffer(inputFloats16)));
3029         specFloat16.outputs.push_back(BufferSp(new Float16Buffer(outputFloats16)));
3030         specFloat16.numWorkGroups = IVec3(numElements, 1, 1);
3031         specFloat16.requestedVulkanFeatures.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
3032         specFloat16.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
3033
3034         specMat4.assembly =
3035                 string(getComputeAsmShaderPreamble()) +
3036
3037                 "OpSource GLSL 430\n"
3038                 "OpName %main \"main\"\n"
3039                 "OpName %id \"gl_GlobalInvocationID\"\n"
3040
3041                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3042
3043                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3044
3045                 "%id = OpVariable %uvec3ptr Input\n"
3046                 "%v4f32      = OpTypeVector %f32 4\n"
3047                 "%mat4v4f32  = OpTypeMatrix %v4f32 4\n"
3048                 "%zero       = OpConstant %i32 0\n"
3049                 "%float_0    = OpConstant %f32 0.0\n"
3050                 "%float_1    = OpConstant %f32 1.0\n"
3051                 "%float_n1   = OpConstant %f32 -1.0\n"
3052                 "%m11        = OpConstantComposite %v4f32 %float_1 %float_0 %float_0 %float_0\n"
3053                 "%m12        = OpConstantComposite %v4f32 %float_0 %float_1 %float_0 %float_0\n"
3054                 "%m13        = OpConstantComposite %v4f32 %float_0 %float_0 %float_1 %float_0\n"
3055                 "%m14        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_1\n"
3056                 "%m1         = OpConstantComposite %mat4v4f32 %m11 %m12 %m13 %m14\n"
3057                 "%m21        = OpConstantComposite %v4f32 %float_n1 %float_0 %float_0 %float_0\n"
3058                 "%m22        = OpConstantComposite %v4f32 %float_0 %float_n1 %float_0 %float_0\n"
3059                 "%m23        = OpConstantComposite %v4f32 %float_0 %float_0 %float_n1 %float_0\n"
3060                 "%m24        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_n1\n"
3061                 "%m2         = OpConstantComposite %mat4v4f32 %m21 %m22 %m23 %m24\n"
3062
3063                 "%main     = OpFunction %void None %voidf\n"
3064                 "%entry    = OpLabel\n"
3065                 "%idval    = OpLoad %uvec3 %id\n"
3066                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3067                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3068                 "%inval    = OpLoad %f32 %inloc\n"
3069
3070                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3071                 "            OpSelectionMerge %cm None\n"
3072                 "            OpBranchConditional %comp %tb %fb\n"
3073                 "%tb       = OpLabel\n"
3074                 "            OpBranch %cm\n"
3075                 "%fb       = OpLabel\n"
3076                 "            OpBranch %cm\n"
3077                 "%cm       = OpLabel\n"
3078                 "%mres     = OpPhi %mat4v4f32 %m1 %tb %m2 %fb\n"
3079                 "%res      = OpCompositeExtract %f32 %mres 2 2\n"
3080
3081                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3082                 "            OpStore %outloc %res\n"
3083                 "            OpReturn\n"
3084
3085                 "            OpFunctionEnd\n";
3086         specMat4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3087         specMat4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3088         specMat4.numWorkGroups = IVec3(numElements, 1, 1);
3089
3090         specVec3.assembly =
3091                 string(getComputeAsmShaderPreamble()) +
3092
3093                 "OpSource GLSL 430\n"
3094                 "OpName %main \"main\"\n"
3095                 "OpName %id \"gl_GlobalInvocationID\"\n"
3096
3097                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3098
3099                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3100
3101                 "%id = OpVariable %uvec3ptr Input\n"
3102                 "%zero       = OpConstant %i32 0\n"
3103                 "%float_0    = OpConstant %f32 0.0\n"
3104                 "%float_1    = OpConstant %f32 1.0\n"
3105                 "%float_n1   = OpConstant %f32 -1.0\n"
3106                 "%v1         = OpConstantComposite %fvec3 %float_1 %float_1 %float_1\n"
3107                 "%v2         = OpConstantComposite %fvec3 %float_n1 %float_n1 %float_n1\n"
3108
3109                 "%main     = OpFunction %void None %voidf\n"
3110                 "%entry    = OpLabel\n"
3111                 "%idval    = OpLoad %uvec3 %id\n"
3112                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3113                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3114                 "%inval    = OpLoad %f32 %inloc\n"
3115
3116                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3117                 "            OpSelectionMerge %cm None\n"
3118                 "            OpBranchConditional %comp %tb %fb\n"
3119                 "%tb       = OpLabel\n"
3120                 "            OpBranch %cm\n"
3121                 "%fb       = OpLabel\n"
3122                 "            OpBranch %cm\n"
3123                 "%cm       = OpLabel\n"
3124                 "%vres     = OpPhi %fvec3 %v1 %tb %v2 %fb\n"
3125                 "%res      = OpCompositeExtract %f32 %vres 2\n"
3126
3127                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3128                 "            OpStore %outloc %res\n"
3129                 "            OpReturn\n"
3130
3131                 "            OpFunctionEnd\n";
3132         specVec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3133         specVec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3134         specVec3.numWorkGroups = IVec3(numElements, 1, 1);
3135
3136         specInt.assembly =
3137                 string(getComputeAsmShaderPreamble()) +
3138
3139                 "OpSource GLSL 430\n"
3140                 "OpName %main \"main\"\n"
3141                 "OpName %id \"gl_GlobalInvocationID\"\n"
3142
3143                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3144
3145                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3146
3147                 "%id = OpVariable %uvec3ptr Input\n"
3148                 "%zero       = OpConstant %i32 0\n"
3149                 "%float_0    = OpConstant %f32 0.0\n"
3150                 "%i1         = OpConstant %i32 1\n"
3151                 "%i2         = OpConstant %i32 -1\n"
3152
3153                 "%main     = OpFunction %void None %voidf\n"
3154                 "%entry    = OpLabel\n"
3155                 "%idval    = OpLoad %uvec3 %id\n"
3156                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3157                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3158                 "%inval    = OpLoad %f32 %inloc\n"
3159
3160                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3161                 "            OpSelectionMerge %cm None\n"
3162                 "            OpBranchConditional %comp %tb %fb\n"
3163                 "%tb       = OpLabel\n"
3164                 "            OpBranch %cm\n"
3165                 "%fb       = OpLabel\n"
3166                 "            OpBranch %cm\n"
3167                 "%cm       = OpLabel\n"
3168                 "%ires     = OpPhi %i32 %i1 %tb %i2 %fb\n"
3169                 "%res      = OpConvertSToF %f32 %ires\n"
3170
3171                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3172                 "            OpStore %outloc %res\n"
3173                 "            OpReturn\n"
3174
3175                 "            OpFunctionEnd\n";
3176         specInt.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3177         specInt.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3178         specInt.numWorkGroups = IVec3(numElements, 1, 1);
3179
3180         specArray.assembly =
3181                 string(getComputeAsmShaderPreamble()) +
3182
3183                 "OpSource GLSL 430\n"
3184                 "OpName %main \"main\"\n"
3185                 "OpName %id \"gl_GlobalInvocationID\"\n"
3186
3187                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3188
3189                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3190
3191                 "%id = OpVariable %uvec3ptr Input\n"
3192                 "%zero       = OpConstant %i32 0\n"
3193                 "%u7         = OpConstant %u32 7\n"
3194                 "%float_0    = OpConstant %f32 0.0\n"
3195                 "%float_1    = OpConstant %f32 1.0\n"
3196                 "%float_n1   = OpConstant %f32 -1.0\n"
3197                 "%f32a7      = OpTypeArray %f32 %u7\n"
3198                 "%a1         = OpConstantComposite %f32a7 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1\n"
3199                 "%a2         = OpConstantComposite %f32a7 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1\n"
3200                 "%main     = OpFunction %void None %voidf\n"
3201                 "%entry    = OpLabel\n"
3202                 "%idval    = OpLoad %uvec3 %id\n"
3203                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3204                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3205                 "%inval    = OpLoad %f32 %inloc\n"
3206
3207                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3208                 "            OpSelectionMerge %cm None\n"
3209                 "            OpBranchConditional %comp %tb %fb\n"
3210                 "%tb       = OpLabel\n"
3211                 "            OpBranch %cm\n"
3212                 "%fb       = OpLabel\n"
3213                 "            OpBranch %cm\n"
3214                 "%cm       = OpLabel\n"
3215                 "%ares     = OpPhi %f32a7 %a1 %tb %a2 %fb\n"
3216                 "%res      = OpCompositeExtract %f32 %ares 5\n"
3217
3218                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3219                 "            OpStore %outloc %res\n"
3220                 "            OpReturn\n"
3221
3222                 "            OpFunctionEnd\n";
3223         specArray.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3224         specArray.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3225         specArray.numWorkGroups = IVec3(numElements, 1, 1);
3226
3227         specStruct.assembly =
3228                 string(getComputeAsmShaderPreamble()) +
3229
3230                 "OpSource GLSL 430\n"
3231                 "OpName %main \"main\"\n"
3232                 "OpName %id \"gl_GlobalInvocationID\"\n"
3233
3234                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3235
3236                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3237
3238                 "%id = OpVariable %uvec3ptr Input\n"
3239                 "%zero       = OpConstant %i32 0\n"
3240                 "%float_0    = OpConstant %f32 0.0\n"
3241                 "%float_1    = OpConstant %f32 1.0\n"
3242                 "%float_n1   = OpConstant %f32 -1.0\n"
3243
3244                 "%v2f32      = OpTypeVector %f32 2\n"
3245                 "%Data2      = OpTypeStruct %f32 %v2f32\n"
3246                 "%Data       = OpTypeStruct %Data2 %f32\n"
3247
3248                 "%in1a       = OpConstantComposite %v2f32 %float_1 %float_1\n"
3249                 "%in1b       = OpConstantComposite %Data2 %float_1 %in1a\n"
3250                 "%s1         = OpConstantComposite %Data %in1b %float_1\n"
3251                 "%in2a       = OpConstantComposite %v2f32 %float_n1 %float_n1\n"
3252                 "%in2b       = OpConstantComposite %Data2 %float_n1 %in2a\n"
3253                 "%s2         = OpConstantComposite %Data %in2b %float_n1\n"
3254
3255                 "%main     = OpFunction %void None %voidf\n"
3256                 "%entry    = OpLabel\n"
3257                 "%idval    = OpLoad %uvec3 %id\n"
3258                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3259                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3260                 "%inval    = OpLoad %f32 %inloc\n"
3261
3262                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3263                 "            OpSelectionMerge %cm None\n"
3264                 "            OpBranchConditional %comp %tb %fb\n"
3265                 "%tb       = OpLabel\n"
3266                 "            OpBranch %cm\n"
3267                 "%fb       = OpLabel\n"
3268                 "            OpBranch %cm\n"
3269                 "%cm       = OpLabel\n"
3270                 "%sres     = OpPhi %Data %s1 %tb %s2 %fb\n"
3271                 "%res      = OpCompositeExtract %f32 %sres 0 0\n"
3272
3273                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3274                 "            OpStore %outloc %res\n"
3275                 "            OpReturn\n"
3276
3277                 "            OpFunctionEnd\n";
3278         specStruct.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3279         specStruct.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3280         specStruct.numWorkGroups = IVec3(numElements, 1, 1);
3281
3282         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_int", "OpPhi with int variables", specInt));
3283         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_float", "OpPhi with float variables", specFloat));
3284         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_float16", "OpPhi with 16bit float variables", specFloat16));
3285         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_vec3", "OpPhi with vec3 variables", specVec3));
3286         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_mat4", "OpPhi with mat4 variables", specMat4));
3287         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_array", "OpPhi with array variables", specArray));
3288         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_struct", "OpPhi with struct variables", specStruct));
3289 }
3290
3291 string generateConstantDefinitions (int count)
3292 {
3293         std::ostringstream      r;
3294         for (int i = 0; i < count; i++)
3295                 r << "%cf" << (i * 10 + 5) << " = OpConstant %f32 " <<(i * 10 + 5) << ".0\n";
3296         r << "\n";
3297         return r.str();
3298 }
3299
3300 string generateSwitchCases (int count)
3301 {
3302         std::ostringstream      r;
3303         for (int i = 0; i < count; i++)
3304                 r << " " << i << " %case" << i;
3305         r << "\n";
3306         return r.str();
3307 }
3308
3309 string generateSwitchTargets (int count)
3310 {
3311         std::ostringstream      r;
3312         for (int i = 0; i < count; i++)
3313                 r << "%case" << i << " = OpLabel\n            OpBranch %phi\n";
3314         r << "\n";
3315         return r.str();
3316 }
3317
3318 string generateOpPhiParams (int count)
3319 {
3320         std::ostringstream      r;
3321         for (int i = 0; i < count; i++)
3322                 r << " %cf" << (i * 10 + 5) << " %case" << i;
3323         r << "\n";
3324         return r.str();
3325 }
3326
3327 string generateIntWidth (int value)
3328 {
3329         std::ostringstream      r;
3330         r << value;
3331         return r.str();
3332 }
3333
3334 // Expand input string by injecting "ABC" between the input
3335 // string characters. The acc/add/treshold parameters are used
3336 // to skip some of the injections to make the result less
3337 // uniform (and a lot shorter).
3338 string expandOpPhiCase5 (const string& s, int &acc, int add, int treshold)
3339 {
3340         std::ostringstream      res;
3341         const char*                     p = s.c_str();
3342
3343         while (*p)
3344         {
3345                 res << *p;
3346                 acc += add;
3347                 if (acc > treshold)
3348                 {
3349                         acc -= treshold;
3350                         res << "ABC";
3351                 }
3352                 p++;
3353         }
3354         return res.str();
3355 }
3356
3357 // Calculate expected result based on the code string
3358 float calcOpPhiCase5 (float val, const string& s)
3359 {
3360         const char*             p               = s.c_str();
3361         float                   x[8];
3362         bool                    b[8];
3363         const float             tv[8]   = { 0.5f, 1.5f, 3.5f, 7.5f, 15.5f, 31.5f, 63.5f, 127.5f };
3364         const float             v               = deFloatAbs(val);
3365         float                   res             = 0;
3366         int                             depth   = -1;
3367         int                             skip    = 0;
3368
3369         for (int i = 7; i >= 0; --i)
3370                 x[i] = std::fmod((float)v, (float)(2 << i));
3371         for (int i = 7; i >= 0; --i)
3372                 b[i] = x[i] > tv[i];
3373
3374         while (*p)
3375         {
3376                 if (*p == 'A')
3377                 {
3378                         depth++;
3379                         if (skip == 0 && b[depth])
3380                         {
3381                                 res++;
3382                         }
3383                         else
3384                                 skip++;
3385                 }
3386                 if (*p == 'B')
3387                 {
3388                         if (skip)
3389                                 skip--;
3390                         if (b[depth] || skip)
3391                                 skip++;
3392                 }
3393                 if (*p == 'C')
3394                 {
3395                         depth--;
3396                         if (skip)
3397                                 skip--;
3398                 }
3399                 p++;
3400         }
3401         return res;
3402 }
3403
3404 // In the code string, the letters represent the following:
3405 //
3406 // A:
3407 //     if (certain bit is set)
3408 //     {
3409 //       result++;
3410 //
3411 // B:
3412 //     } else {
3413 //
3414 // C:
3415 //     }
3416 //
3417 // examples:
3418 // AABCBC leads to if(){r++;if(){r++;}else{}}else{}
3419 // ABABCC leads to if(){r++;}else{if(){r++;}else{}}
3420 // ABCABC leads to if(){r++;}else{}if(){r++;}else{}
3421 //
3422 // Code generation gets a bit complicated due to the else-branches,
3423 // which do not generate new values. Thus, the generator needs to
3424 // keep track of the previous variable change seen by the else
3425 // branch.
3426 string generateOpPhiCase5 (const string& s)
3427 {
3428         std::stack<int>                         idStack;
3429         std::stack<std::string>         value;
3430         std::stack<std::string>         valueLabel;
3431         std::stack<std::string>         mergeLeft;
3432         std::stack<std::string>         mergeRight;
3433         std::ostringstream                      res;
3434         const char*                                     p                       = s.c_str();
3435         int                                                     depth           = -1;
3436         int                                                     currId          = 0;
3437         int                                                     iter            = 0;
3438
3439         idStack.push(-1);
3440         value.push("%f32_0");
3441         valueLabel.push("%f32_0 %entry");
3442
3443         while (*p)
3444         {
3445                 if (*p == 'A')
3446                 {
3447                         depth++;
3448                         currId = iter;
3449                         idStack.push(currId);
3450                         res << "\tOpSelectionMerge %m" << currId << " None\n";
3451                         res << "\tOpBranchConditional %b" << depth << " %t" << currId << " %f" << currId << "\n";
3452                         res << "%t" << currId << " = OpLabel\n";
3453                         res << "%rt" << currId << " = OpFAdd %f32 " << value.top() << " %f32_1\n";
3454                         std::ostringstream tag;
3455                         tag << "%rt" << currId;
3456                         value.push(tag.str());
3457                         tag << " %t" << currId;
3458                         valueLabel.push(tag.str());
3459                 }
3460
3461                 if (*p == 'B')
3462                 {
3463                         mergeLeft.push(valueLabel.top());
3464                         value.pop();
3465                         valueLabel.pop();
3466                         res << "\tOpBranch %m" << currId << "\n";
3467                         res << "%f" << currId << " = OpLabel\n";
3468                         std::ostringstream tag;
3469                         tag << value.top() << " %f" << currId;
3470                         valueLabel.pop();
3471                         valueLabel.push(tag.str());
3472                 }
3473
3474                 if (*p == 'C')
3475                 {
3476                         mergeRight.push(valueLabel.top());
3477                         res << "\tOpBranch %m" << currId << "\n";
3478                         res << "%m" << currId << " = OpLabel\n";
3479                         if (*(p + 1) == 0)
3480                                 res << "%res"; // last result goes to %res
3481                         else
3482                                 res << "%rm" << currId;
3483                         res << " = OpPhi %f32  " << mergeLeft.top() << "  " << mergeRight.top() << "\n";
3484                         std::ostringstream tag;
3485                         tag << "%rm" << currId;
3486                         value.pop();
3487                         value.push(tag.str());
3488                         tag << " %m" << currId;
3489                         valueLabel.pop();
3490                         valueLabel.push(tag.str());
3491                         mergeLeft.pop();
3492                         mergeRight.pop();
3493                         depth--;
3494                         idStack.pop();
3495                         currId = idStack.top();
3496                 }
3497                 p++;
3498                 iter++;
3499         }
3500         return res.str();
3501 }
3502
3503 tcu::TestCaseGroup* createOpPhiGroup (tcu::TestContext& testCtx)
3504 {
3505         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
3506         ComputeShaderSpec                               spec1;
3507         ComputeShaderSpec                               spec2;
3508         ComputeShaderSpec                               spec3;
3509         ComputeShaderSpec                               spec4;
3510         ComputeShaderSpec                               spec5;
3511         de::Random                                              rnd                             (deStringHash(group->getName()));
3512         const int                                               numElements             = 100;
3513         vector<float>                                   inputFloats             (numElements, 0);
3514         vector<float>                                   outputFloats1   (numElements, 0);
3515         vector<float>                                   outputFloats2   (numElements, 0);
3516         vector<float>                                   outputFloats3   (numElements, 0);
3517         vector<float>                                   outputFloats4   (numElements, 0);
3518         vector<float>                                   outputFloats5   (numElements, 0);
3519         std::string                                             codestring              = "ABC";
3520         const int                                               test4Width              = 1024;
3521
3522         // Build case 5 code string. Each iteration makes the hierarchy more complicated.
3523         // 9 iterations with (7, 24) parameters makes the hierarchy 8 deep with about 1500 lines of
3524         // shader code.
3525         for (int i = 0, acc = 0; i < 9; i++)
3526                 codestring = expandOpPhiCase5(codestring, acc, 7, 24);
3527
3528         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
3529
3530         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3531         floorAll(inputFloats);
3532
3533         for (size_t ndx = 0; ndx < numElements; ++ndx)
3534         {
3535                 switch (ndx % 3)
3536                 {
3537                         case 0:         outputFloats1[ndx] = inputFloats[ndx] + 5.5f;   break;
3538                         case 1:         outputFloats1[ndx] = inputFloats[ndx] + 20.5f;  break;
3539                         case 2:         outputFloats1[ndx] = inputFloats[ndx] + 1.75f;  break;
3540                         default:        break;
3541                 }
3542                 outputFloats2[ndx] = inputFloats[ndx] + 6.5f * 3;
3543                 outputFloats3[ndx] = 8.5f - inputFloats[ndx];
3544
3545                 int index4 = (int)deFloor(deAbs((float)ndx * inputFloats[ndx]));
3546                 outputFloats4[ndx] = (float)(index4 % test4Width) * 10.0f + 5.0f;
3547
3548                 outputFloats5[ndx] = calcOpPhiCase5(inputFloats[ndx], codestring);
3549         }
3550
3551         spec1.assembly =
3552                 string(getComputeAsmShaderPreamble()) +
3553
3554                 "OpSource GLSL 430\n"
3555                 "OpName %main \"main\"\n"
3556                 "OpName %id \"gl_GlobalInvocationID\"\n"
3557
3558                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3559
3560                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3561
3562                 "%id = OpVariable %uvec3ptr Input\n"
3563                 "%zero       = OpConstant %i32 0\n"
3564                 "%three      = OpConstant %u32 3\n"
3565                 "%constf5p5  = OpConstant %f32 5.5\n"
3566                 "%constf20p5 = OpConstant %f32 20.5\n"
3567                 "%constf1p75 = OpConstant %f32 1.75\n"
3568                 "%constf8p5  = OpConstant %f32 8.5\n"
3569                 "%constf6p5  = OpConstant %f32 6.5\n"
3570
3571                 "%main     = OpFunction %void None %voidf\n"
3572                 "%entry    = OpLabel\n"
3573                 "%idval    = OpLoad %uvec3 %id\n"
3574                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3575                 "%selector = OpUMod %u32 %x %three\n"
3576                 "            OpSelectionMerge %phi None\n"
3577                 "            OpSwitch %selector %default 0 %case0 1 %case1 2 %case2\n"
3578
3579                 // Case 1 before OpPhi.
3580                 "%case1    = OpLabel\n"
3581                 "            OpBranch %phi\n"
3582
3583                 "%default  = OpLabel\n"
3584                 "            OpUnreachable\n"
3585
3586                 "%phi      = OpLabel\n"
3587                 "%operand  = OpPhi %f32   %constf1p75 %case2   %constf20p5 %case1   %constf5p5 %case0\n" // not in the order of blocks
3588                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3589                 "%inval    = OpLoad %f32 %inloc\n"
3590                 "%add      = OpFAdd %f32 %inval %operand\n"
3591                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3592                 "            OpStore %outloc %add\n"
3593                 "            OpReturn\n"
3594
3595                 // Case 0 after OpPhi.
3596                 "%case0    = OpLabel\n"
3597                 "            OpBranch %phi\n"
3598
3599
3600                 // Case 2 after OpPhi.
3601                 "%case2    = OpLabel\n"
3602                 "            OpBranch %phi\n"
3603
3604                 "            OpFunctionEnd\n";
3605         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3606         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
3607         spec1.numWorkGroups = IVec3(numElements, 1, 1);
3608
3609         group->addChild(new SpvAsmComputeShaderCase(testCtx, "block", "out-of-order and unreachable blocks for OpPhi", spec1));
3610
3611         spec2.assembly =
3612                 string(getComputeAsmShaderPreamble()) +
3613
3614                 "OpName %main \"main\"\n"
3615                 "OpName %id \"gl_GlobalInvocationID\"\n"
3616
3617                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3618
3619                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3620
3621                 "%id         = OpVariable %uvec3ptr Input\n"
3622                 "%zero       = OpConstant %i32 0\n"
3623                 "%one        = OpConstant %i32 1\n"
3624                 "%three      = OpConstant %i32 3\n"
3625                 "%constf6p5  = OpConstant %f32 6.5\n"
3626
3627                 "%main       = OpFunction %void None %voidf\n"
3628                 "%entry      = OpLabel\n"
3629                 "%idval      = OpLoad %uvec3 %id\n"
3630                 "%x          = OpCompositeExtract %u32 %idval 0\n"
3631                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3632                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3633                 "%inval      = OpLoad %f32 %inloc\n"
3634                 "              OpBranch %phi\n"
3635
3636                 "%phi        = OpLabel\n"
3637                 "%step       = OpPhi %i32 %zero  %entry %step_next  %phi\n"
3638                 "%accum      = OpPhi %f32 %inval %entry %accum_next %phi\n"
3639                 "%step_next  = OpIAdd %i32 %step %one\n"
3640                 "%accum_next = OpFAdd %f32 %accum %constf6p5\n"
3641                 "%still_loop = OpSLessThan %bool %step %three\n"
3642                 "              OpLoopMerge %exit %phi None\n"
3643                 "              OpBranchConditional %still_loop %phi %exit\n"
3644
3645                 "%exit       = OpLabel\n"
3646                 "              OpStore %outloc %accum\n"
3647                 "              OpReturn\n"
3648                 "              OpFunctionEnd\n";
3649         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3650         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
3651         spec2.numWorkGroups = IVec3(numElements, 1, 1);
3652
3653         group->addChild(new SpvAsmComputeShaderCase(testCtx, "induction", "The usual way induction variables are handled in LLVM IR", spec2));
3654
3655         spec3.assembly =
3656                 string(getComputeAsmShaderPreamble()) +
3657
3658                 "OpName %main \"main\"\n"
3659                 "OpName %id \"gl_GlobalInvocationID\"\n"
3660
3661                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3662
3663                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3664
3665                 "%f32ptr_f   = OpTypePointer Function %f32\n"
3666                 "%id         = OpVariable %uvec3ptr Input\n"
3667                 "%true       = OpConstantTrue %bool\n"
3668                 "%false      = OpConstantFalse %bool\n"
3669                 "%zero       = OpConstant %i32 0\n"
3670                 "%constf8p5  = OpConstant %f32 8.5\n"
3671
3672                 "%main       = OpFunction %void None %voidf\n"
3673                 "%entry      = OpLabel\n"
3674                 "%b          = OpVariable %f32ptr_f Function %constf8p5\n"
3675                 "%idval      = OpLoad %uvec3 %id\n"
3676                 "%x          = OpCompositeExtract %u32 %idval 0\n"
3677                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3678                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3679                 "%a_init     = OpLoad %f32 %inloc\n"
3680                 "%b_init     = OpLoad %f32 %b\n"
3681                 "              OpBranch %phi\n"
3682
3683                 "%phi        = OpLabel\n"
3684                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
3685                 "%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
3686                 "%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
3687                 "              OpLoopMerge %exit %phi None\n"
3688                 "              OpBranchConditional %still_loop %phi %exit\n"
3689
3690                 "%exit       = OpLabel\n"
3691                 "%sub        = OpFSub %f32 %a_next %b_next\n"
3692                 "              OpStore %outloc %sub\n"
3693                 "              OpReturn\n"
3694                 "              OpFunctionEnd\n";
3695         spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3696         spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
3697         spec3.numWorkGroups = IVec3(numElements, 1, 1);
3698
3699         group->addChild(new SpvAsmComputeShaderCase(testCtx, "swap", "Swap the values of two variables using OpPhi", spec3));
3700
3701         spec4.assembly =
3702                 "OpCapability Shader\n"
3703                 "%ext = OpExtInstImport \"GLSL.std.450\"\n"
3704                 "OpMemoryModel Logical GLSL450\n"
3705                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3706                 "OpExecutionMode %main LocalSize 1 1 1\n"
3707
3708                 "OpSource GLSL 430\n"
3709                 "OpName %main \"main\"\n"
3710                 "OpName %id \"gl_GlobalInvocationID\"\n"
3711
3712                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3713
3714                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3715
3716                 "%id       = OpVariable %uvec3ptr Input\n"
3717                 "%zero     = OpConstant %i32 0\n"
3718                 "%cimod    = OpConstant %u32 " + generateIntWidth(test4Width) + "\n"
3719
3720                 + generateConstantDefinitions(test4Width) +
3721
3722                 "%main     = OpFunction %void None %voidf\n"
3723                 "%entry    = OpLabel\n"
3724                 "%idval    = OpLoad %uvec3 %id\n"
3725                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3726                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3727                 "%inval    = OpLoad %f32 %inloc\n"
3728                 "%xf       = OpConvertUToF %f32 %x\n"
3729                 "%xm       = OpFMul %f32 %xf %inval\n"
3730                 "%xa       = OpExtInst %f32 %ext FAbs %xm\n"
3731                 "%xi       = OpConvertFToU %u32 %xa\n"
3732                 "%selector = OpUMod %u32 %xi %cimod\n"
3733                 "            OpSelectionMerge %phi None\n"
3734                 "            OpSwitch %selector %default "
3735
3736                 + generateSwitchCases(test4Width) +
3737
3738                 "%default  = OpLabel\n"
3739                 "            OpUnreachable\n"
3740
3741                 + generateSwitchTargets(test4Width) +
3742
3743                 "%phi      = OpLabel\n"
3744                 "%result   = OpPhi %f32"
3745
3746                 + generateOpPhiParams(test4Width) +
3747
3748                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3749                 "            OpStore %outloc %result\n"
3750                 "            OpReturn\n"
3751
3752                 "            OpFunctionEnd\n";
3753         spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3754         spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
3755         spec4.numWorkGroups = IVec3(numElements, 1, 1);
3756
3757         group->addChild(new SpvAsmComputeShaderCase(testCtx, "wide", "OpPhi with a lot of parameters", spec4));
3758
3759         spec5.assembly =
3760                 "OpCapability Shader\n"
3761                 "%ext      = OpExtInstImport \"GLSL.std.450\"\n"
3762                 "OpMemoryModel Logical GLSL450\n"
3763                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3764                 "OpExecutionMode %main LocalSize 1 1 1\n"
3765                 "%code     = OpString \"" + codestring + "\"\n"
3766
3767                 "OpSource GLSL 430\n"
3768                 "OpName %main \"main\"\n"
3769                 "OpName %id \"gl_GlobalInvocationID\"\n"
3770
3771                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3772
3773                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3774
3775                 "%id       = OpVariable %uvec3ptr Input\n"
3776                 "%zero     = OpConstant %i32 0\n"
3777                 "%f32_0    = OpConstant %f32 0.0\n"
3778                 "%f32_0_5  = OpConstant %f32 0.5\n"
3779                 "%f32_1    = OpConstant %f32 1.0\n"
3780                 "%f32_1_5  = OpConstant %f32 1.5\n"
3781                 "%f32_2    = OpConstant %f32 2.0\n"
3782                 "%f32_3_5  = OpConstant %f32 3.5\n"
3783                 "%f32_4    = OpConstant %f32 4.0\n"
3784                 "%f32_7_5  = OpConstant %f32 7.5\n"
3785                 "%f32_8    = OpConstant %f32 8.0\n"
3786                 "%f32_15_5 = OpConstant %f32 15.5\n"
3787                 "%f32_16   = OpConstant %f32 16.0\n"
3788                 "%f32_31_5 = OpConstant %f32 31.5\n"
3789                 "%f32_32   = OpConstant %f32 32.0\n"
3790                 "%f32_63_5 = OpConstant %f32 63.5\n"
3791                 "%f32_64   = OpConstant %f32 64.0\n"
3792                 "%f32_127_5 = OpConstant %f32 127.5\n"
3793                 "%f32_128  = OpConstant %f32 128.0\n"
3794                 "%f32_256  = OpConstant %f32 256.0\n"
3795
3796                 "%main     = OpFunction %void None %voidf\n"
3797                 "%entry    = OpLabel\n"
3798                 "%idval    = OpLoad %uvec3 %id\n"
3799                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3800                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3801                 "%inval    = OpLoad %f32 %inloc\n"
3802
3803                 "%xabs     = OpExtInst %f32 %ext FAbs %inval\n"
3804                 "%x8       = OpFMod %f32 %xabs %f32_256\n"
3805                 "%x7       = OpFMod %f32 %xabs %f32_128\n"
3806                 "%x6       = OpFMod %f32 %xabs %f32_64\n"
3807                 "%x5       = OpFMod %f32 %xabs %f32_32\n"
3808                 "%x4       = OpFMod %f32 %xabs %f32_16\n"
3809                 "%x3       = OpFMod %f32 %xabs %f32_8\n"
3810                 "%x2       = OpFMod %f32 %xabs %f32_4\n"
3811                 "%x1       = OpFMod %f32 %xabs %f32_2\n"
3812
3813                 "%b7       = OpFOrdGreaterThanEqual %bool %x8 %f32_127_5\n"
3814                 "%b6       = OpFOrdGreaterThanEqual %bool %x7 %f32_63_5\n"
3815                 "%b5       = OpFOrdGreaterThanEqual %bool %x6 %f32_31_5\n"
3816                 "%b4       = OpFOrdGreaterThanEqual %bool %x5 %f32_15_5\n"
3817                 "%b3       = OpFOrdGreaterThanEqual %bool %x4 %f32_7_5\n"
3818                 "%b2       = OpFOrdGreaterThanEqual %bool %x3 %f32_3_5\n"
3819                 "%b1       = OpFOrdGreaterThanEqual %bool %x2 %f32_1_5\n"
3820                 "%b0       = OpFOrdGreaterThanEqual %bool %x1 %f32_0_5\n"
3821
3822                 + generateOpPhiCase5(codestring) +
3823
3824                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3825                 "            OpStore %outloc %res\n"
3826                 "            OpReturn\n"
3827
3828                 "            OpFunctionEnd\n";
3829         spec5.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3830         spec5.outputs.push_back(BufferSp(new Float32Buffer(outputFloats5)));
3831         spec5.numWorkGroups = IVec3(numElements, 1, 1);
3832
3833         group->addChild(new SpvAsmComputeShaderCase(testCtx, "nested", "Stress OpPhi with a lot of nesting", spec5));
3834
3835         createOpPhiVartypeTests(group, testCtx);
3836
3837         return group.release();
3838 }
3839
3840 // Assembly code used for testing block order is based on GLSL source code:
3841 //
3842 // #version 430
3843 //
3844 // layout(std140, set = 0, binding = 0) readonly buffer Input {
3845 //   float elements[];
3846 // } input_data;
3847 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
3848 //   float elements[];
3849 // } output_data;
3850 //
3851 // void main() {
3852 //   uint x = gl_GlobalInvocationID.x;
3853 //   output_data.elements[x] = input_data.elements[x];
3854 //   if (x > uint(50)) {
3855 //     switch (x % uint(3)) {
3856 //       case 0: output_data.elements[x] += 1.5f; break;
3857 //       case 1: output_data.elements[x] += 42.f; break;
3858 //       case 2: output_data.elements[x] -= 27.f; break;
3859 //       default: break;
3860 //     }
3861 //   } else {
3862 //     output_data.elements[x] = -input_data.elements[x];
3863 //   }
3864 // }
3865 tcu::TestCaseGroup* createBlockOrderGroup (tcu::TestContext& testCtx)
3866 {
3867         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "block_order", "Test block orders"));
3868         ComputeShaderSpec                               spec;
3869         de::Random                                              rnd                             (deStringHash(group->getName()));
3870         const int                                               numElements             = 100;
3871         vector<float>                                   inputFloats             (numElements, 0);
3872         vector<float>                                   outputFloats    (numElements, 0);
3873
3874         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
3875
3876         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3877         floorAll(inputFloats);
3878
3879         for (size_t ndx = 0; ndx <= 50; ++ndx)
3880                 outputFloats[ndx] = -inputFloats[ndx];
3881
3882         for (size_t ndx = 51; ndx < numElements; ++ndx)
3883         {
3884                 switch (ndx % 3)
3885                 {
3886                         case 0:         outputFloats[ndx] = inputFloats[ndx] + 1.5f; break;
3887                         case 1:         outputFloats[ndx] = inputFloats[ndx] + 42.f; break;
3888                         case 2:         outputFloats[ndx] = inputFloats[ndx] - 27.f; break;
3889                         default:        break;
3890                 }
3891         }
3892
3893         spec.assembly =
3894                 string(getComputeAsmShaderPreamble()) +
3895
3896                 "OpSource GLSL 430\n"
3897                 "OpName %main \"main\"\n"
3898                 "OpName %id \"gl_GlobalInvocationID\"\n"
3899
3900                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3901
3902                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
3903
3904                 "%u32ptr       = OpTypePointer Function %u32\n"
3905                 "%u32ptr_input = OpTypePointer Input %u32\n"
3906
3907                 + string(getComputeAsmInputOutputBuffer()) +
3908
3909                 "%id        = OpVariable %uvec3ptr Input\n"
3910                 "%zero      = OpConstant %i32 0\n"
3911                 "%const3    = OpConstant %u32 3\n"
3912                 "%const50   = OpConstant %u32 50\n"
3913                 "%constf1p5 = OpConstant %f32 1.5\n"
3914                 "%constf27  = OpConstant %f32 27.0\n"
3915                 "%constf42  = OpConstant %f32 42.0\n"
3916
3917                 "%main = OpFunction %void None %voidf\n"
3918
3919                 // entry block.
3920                 "%entry    = OpLabel\n"
3921
3922                 // Create a temporary variable to hold the value of gl_GlobalInvocationID.x.
3923                 "%xvar     = OpVariable %u32ptr Function\n"
3924                 "%xptr     = OpAccessChain %u32ptr_input %id %zero\n"
3925                 "%x        = OpLoad %u32 %xptr\n"
3926                 "            OpStore %xvar %x\n"
3927
3928                 "%cmp      = OpUGreaterThan %bool %x %const50\n"
3929                 "            OpSelectionMerge %if_merge None\n"
3930                 "            OpBranchConditional %cmp %if_true %if_false\n"
3931
3932                 // False branch for if-statement: placed in the middle of switch cases and before true branch.
3933                 "%if_false = OpLabel\n"
3934                 "%x_f      = OpLoad %u32 %xvar\n"
3935                 "%inloc_f  = OpAccessChain %f32ptr %indata %zero %x_f\n"
3936                 "%inval_f  = OpLoad %f32 %inloc_f\n"
3937                 "%negate   = OpFNegate %f32 %inval_f\n"
3938                 "%outloc_f = OpAccessChain %f32ptr %outdata %zero %x_f\n"
3939                 "            OpStore %outloc_f %negate\n"
3940                 "            OpBranch %if_merge\n"
3941
3942                 // Merge block for if-statement: placed in the middle of true and false branch.
3943                 "%if_merge = OpLabel\n"
3944                 "            OpReturn\n"
3945
3946                 // True branch for if-statement: placed in the middle of swtich cases and after the false branch.
3947                 "%if_true  = OpLabel\n"
3948                 "%xval_t   = OpLoad %u32 %xvar\n"
3949                 "%mod      = OpUMod %u32 %xval_t %const3\n"
3950                 "            OpSelectionMerge %switch_merge None\n"
3951                 "            OpSwitch %mod %default 0 %case0 1 %case1 2 %case2\n"
3952
3953                 // Merge block for switch-statement: placed before the case
3954                 // bodies.  But it must follow OpSwitch which dominates it.
3955                 "%switch_merge = OpLabel\n"
3956                 "                OpBranch %if_merge\n"
3957
3958                 // Case 1 for switch-statement: placed before case 0.
3959                 // It must follow the OpSwitch that dominates it.
3960                 "%case1    = OpLabel\n"
3961                 "%x_1      = OpLoad %u32 %xvar\n"
3962                 "%inloc_1  = OpAccessChain %f32ptr %indata %zero %x_1\n"
3963                 "%inval_1  = OpLoad %f32 %inloc_1\n"
3964                 "%addf42   = OpFAdd %f32 %inval_1 %constf42\n"
3965                 "%outloc_1 = OpAccessChain %f32ptr %outdata %zero %x_1\n"
3966                 "            OpStore %outloc_1 %addf42\n"
3967                 "            OpBranch %switch_merge\n"
3968
3969                 // Case 2 for switch-statement.
3970                 "%case2    = OpLabel\n"
3971                 "%x_2      = OpLoad %u32 %xvar\n"
3972                 "%inloc_2  = OpAccessChain %f32ptr %indata %zero %x_2\n"
3973                 "%inval_2  = OpLoad %f32 %inloc_2\n"
3974                 "%subf27   = OpFSub %f32 %inval_2 %constf27\n"
3975                 "%outloc_2 = OpAccessChain %f32ptr %outdata %zero %x_2\n"
3976                 "            OpStore %outloc_2 %subf27\n"
3977                 "            OpBranch %switch_merge\n"
3978
3979                 // Default case for switch-statement: placed in the middle of normal cases.
3980                 "%default = OpLabel\n"
3981                 "           OpBranch %switch_merge\n"
3982
3983                 // Case 0 for switch-statement: out of order.
3984                 "%case0    = OpLabel\n"
3985                 "%x_0      = OpLoad %u32 %xvar\n"
3986                 "%inloc_0  = OpAccessChain %f32ptr %indata %zero %x_0\n"
3987                 "%inval_0  = OpLoad %f32 %inloc_0\n"
3988                 "%addf1p5  = OpFAdd %f32 %inval_0 %constf1p5\n"
3989                 "%outloc_0 = OpAccessChain %f32ptr %outdata %zero %x_0\n"
3990                 "            OpStore %outloc_0 %addf1p5\n"
3991                 "            OpBranch %switch_merge\n"
3992
3993                 "            OpFunctionEnd\n";
3994         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3995         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3996         spec.numWorkGroups = IVec3(numElements, 1, 1);
3997
3998         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "various out-of-order blocks", spec));
3999
4000         return group.release();
4001 }
4002
4003 tcu::TestCaseGroup* createMultipleShaderGroup (tcu::TestContext& testCtx)
4004 {
4005         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "multiple_shaders", "Test multiple shaders in the same module"));
4006         ComputeShaderSpec                               spec1;
4007         ComputeShaderSpec                               spec2;
4008         de::Random                                              rnd                             (deStringHash(group->getName()));
4009         const int                                               numElements             = 100;
4010         vector<float>                                   inputFloats             (numElements, 0);
4011         vector<float>                                   outputFloats1   (numElements, 0);
4012         vector<float>                                   outputFloats2   (numElements, 0);
4013         fillRandomScalars(rnd, -500.f, 500.f, &inputFloats[0], numElements);
4014
4015         for (size_t ndx = 0; ndx < numElements; ++ndx)
4016         {
4017                 outputFloats1[ndx] = inputFloats[ndx] + inputFloats[ndx];
4018                 outputFloats2[ndx] = -inputFloats[ndx];
4019         }
4020
4021         const string assembly(
4022                 "OpCapability Shader\n"
4023                 "OpMemoryModel Logical GLSL450\n"
4024                 "OpEntryPoint GLCompute %comp_main1 \"entrypoint1\" %id\n"
4025                 "OpEntryPoint GLCompute %comp_main2 \"entrypoint2\" %id\n"
4026                 // A module cannot have two OpEntryPoint instructions with the same Execution Model and the same Name string.
4027                 "OpEntryPoint Vertex    %vert_main  \"entrypoint2\" %vert_builtins %vertexIndex %instanceIndex\n"
4028                 "OpExecutionMode %comp_main1 LocalSize 1 1 1\n"
4029                 "OpExecutionMode %comp_main2 LocalSize 1 1 1\n"
4030
4031                 "OpName %comp_main1              \"entrypoint1\"\n"
4032                 "OpName %comp_main2              \"entrypoint2\"\n"
4033                 "OpName %vert_main               \"entrypoint2\"\n"
4034                 "OpName %id                      \"gl_GlobalInvocationID\"\n"
4035                 "OpName %vert_builtin_st         \"gl_PerVertex\"\n"
4036                 "OpName %vertexIndex             \"gl_VertexIndex\"\n"
4037                 "OpName %instanceIndex           \"gl_InstanceIndex\"\n"
4038                 "OpMemberName %vert_builtin_st 0 \"gl_Position\"\n"
4039                 "OpMemberName %vert_builtin_st 1 \"gl_PointSize\"\n"
4040                 "OpMemberName %vert_builtin_st 2 \"gl_ClipDistance\"\n"
4041
4042                 "OpDecorate %id                      BuiltIn GlobalInvocationId\n"
4043                 "OpDecorate %vertexIndex             BuiltIn VertexIndex\n"
4044                 "OpDecorate %instanceIndex           BuiltIn InstanceIndex\n"
4045                 "OpDecorate %vert_builtin_st         Block\n"
4046                 "OpMemberDecorate %vert_builtin_st 0 BuiltIn Position\n"
4047                 "OpMemberDecorate %vert_builtin_st 1 BuiltIn PointSize\n"
4048                 "OpMemberDecorate %vert_builtin_st 2 BuiltIn ClipDistance\n"
4049
4050                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4051
4052                 "%zero       = OpConstant %i32 0\n"
4053                 "%one        = OpConstant %u32 1\n"
4054                 "%c_f32_1    = OpConstant %f32 1\n"
4055
4056                 "%i32inputptr         = OpTypePointer Input %i32\n"
4057                 "%vec4                = OpTypeVector %f32 4\n"
4058                 "%vec4ptr             = OpTypePointer Output %vec4\n"
4059                 "%f32arr1             = OpTypeArray %f32 %one\n"
4060                 "%vert_builtin_st     = OpTypeStruct %vec4 %f32 %f32arr1\n"
4061                 "%vert_builtin_st_ptr = OpTypePointer Output %vert_builtin_st\n"
4062                 "%vert_builtins       = OpVariable %vert_builtin_st_ptr Output\n"
4063
4064                 "%id         = OpVariable %uvec3ptr Input\n"
4065                 "%vertexIndex = OpVariable %i32inputptr Input\n"
4066                 "%instanceIndex = OpVariable %i32inputptr Input\n"
4067                 "%c_vec4_1   = OpConstantComposite %vec4 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
4068
4069                 // gl_Position = vec4(1.);
4070                 "%vert_main  = OpFunction %void None %voidf\n"
4071                 "%vert_entry = OpLabel\n"
4072                 "%position   = OpAccessChain %vec4ptr %vert_builtins %zero\n"
4073                 "              OpStore %position %c_vec4_1\n"
4074                 "              OpReturn\n"
4075                 "              OpFunctionEnd\n"
4076
4077                 // Double inputs.
4078                 "%comp_main1  = OpFunction %void None %voidf\n"
4079                 "%comp1_entry = OpLabel\n"
4080                 "%idval1      = OpLoad %uvec3 %id\n"
4081                 "%x1          = OpCompositeExtract %u32 %idval1 0\n"
4082                 "%inloc1      = OpAccessChain %f32ptr %indata %zero %x1\n"
4083                 "%inval1      = OpLoad %f32 %inloc1\n"
4084                 "%add         = OpFAdd %f32 %inval1 %inval1\n"
4085                 "%outloc1     = OpAccessChain %f32ptr %outdata %zero %x1\n"
4086                 "               OpStore %outloc1 %add\n"
4087                 "               OpReturn\n"
4088                 "               OpFunctionEnd\n"
4089
4090                 // Negate inputs.
4091                 "%comp_main2  = OpFunction %void None %voidf\n"
4092                 "%comp2_entry = OpLabel\n"
4093                 "%idval2      = OpLoad %uvec3 %id\n"
4094                 "%x2          = OpCompositeExtract %u32 %idval2 0\n"
4095                 "%inloc2      = OpAccessChain %f32ptr %indata %zero %x2\n"
4096                 "%inval2      = OpLoad %f32 %inloc2\n"
4097                 "%neg         = OpFNegate %f32 %inval2\n"
4098                 "%outloc2     = OpAccessChain %f32ptr %outdata %zero %x2\n"
4099                 "               OpStore %outloc2 %neg\n"
4100                 "               OpReturn\n"
4101                 "               OpFunctionEnd\n");
4102
4103         spec1.assembly = assembly;
4104         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4105         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
4106         spec1.numWorkGroups = IVec3(numElements, 1, 1);
4107         spec1.entryPoint = "entrypoint1";
4108
4109         spec2.assembly = assembly;
4110         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4111         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
4112         spec2.numWorkGroups = IVec3(numElements, 1, 1);
4113         spec2.entryPoint = "entrypoint2";
4114
4115         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader1", "multiple shaders in the same module", spec1));
4116         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader2", "multiple shaders in the same module", spec2));
4117
4118         return group.release();
4119 }
4120
4121 inline std::string makeLongUTF8String (size_t num4ByteChars)
4122 {
4123         // An example of a longest valid UTF-8 character.  Be explicit about the
4124         // character type because Microsoft compilers can otherwise interpret the
4125         // character string as being over wide (16-bit) characters. Ideally, we
4126         // would just use a C++11 UTF-8 string literal, but we want to support older
4127         // Microsoft compilers.
4128         const std::basic_string<char> earthAfrica("\xF0\x9F\x8C\x8D");
4129         std::string longString;
4130         longString.reserve(num4ByteChars * 4);
4131         for (size_t count = 0; count < num4ByteChars; count++)
4132         {
4133                 longString += earthAfrica;
4134         }
4135         return longString;
4136 }
4137
4138 tcu::TestCaseGroup* createOpSourceGroup (tcu::TestContext& testCtx)
4139 {
4140         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsource", "Tests the OpSource & OpSourceContinued instruction"));
4141         vector<CaseParameter>                   cases;
4142         de::Random                                              rnd                             (deStringHash(group->getName()));
4143         const int                                               numElements             = 100;
4144         vector<float>                                   positiveFloats  (numElements, 0);
4145         vector<float>                                   negativeFloats  (numElements, 0);
4146         const StringTemplate                    shaderTemplate  (
4147                 "OpCapability Shader\n"
4148                 "OpMemoryModel Logical GLSL450\n"
4149
4150                 "OpEntryPoint GLCompute %main \"main\" %id\n"
4151                 "OpExecutionMode %main LocalSize 1 1 1\n"
4152
4153                 "${SOURCE}\n"
4154
4155                 "OpName %main           \"main\"\n"
4156                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4157
4158                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4159
4160                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4161
4162                 "%id        = OpVariable %uvec3ptr Input\n"
4163                 "%zero      = OpConstant %i32 0\n"
4164
4165                 "%main      = OpFunction %void None %voidf\n"
4166                 "%label     = OpLabel\n"
4167                 "%idval     = OpLoad %uvec3 %id\n"
4168                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4169                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4170                 "%inval     = OpLoad %f32 %inloc\n"
4171                 "%neg       = OpFNegate %f32 %inval\n"
4172                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4173                 "             OpStore %outloc %neg\n"
4174                 "             OpReturn\n"
4175                 "             OpFunctionEnd\n");
4176
4177         cases.push_back(CaseParameter("unknown_source",                                                 "OpSource Unknown 0"));
4178         cases.push_back(CaseParameter("wrong_source",                                                   "OpSource OpenCL_C 210"));
4179         cases.push_back(CaseParameter("normal_filename",                                                "%fname = OpString \"filename\"\n"
4180                                                                                                                                                         "OpSource GLSL 430 %fname"));
4181         cases.push_back(CaseParameter("empty_filename",                                                 "%fname = OpString \"\"\n"
4182                                                                                                                                                         "OpSource GLSL 430 %fname"));
4183         cases.push_back(CaseParameter("normal_source_code",                                             "%fname = OpString \"filename\"\n"
4184                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\""));
4185         cases.push_back(CaseParameter("empty_source_code",                                              "%fname = OpString \"filename\"\n"
4186                                                                                                                                                         "OpSource GLSL 430 %fname \"\""));
4187         cases.push_back(CaseParameter("long_source_code",                                               "%fname = OpString \"filename\"\n"
4188                                                                                                                                                         "OpSource GLSL 430 %fname \"" + makeLongUTF8String(65530) + "ccc\"")); // word count: 65535
4189         cases.push_back(CaseParameter("utf8_source_code",                                               "%fname = OpString \"filename\"\n"
4190                                                                                                                                                         "OpSource GLSL 430 %fname \"\xE2\x98\x82\xE2\x98\x85\"")); // umbrella & black star symbol
4191         cases.push_back(CaseParameter("normal_sourcecontinued",                                 "%fname = OpString \"filename\"\n"
4192                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvo\"\n"
4193                                                                                                                                                         "OpSourceContinued \"id main() {}\""));
4194         cases.push_back(CaseParameter("empty_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
4195                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4196                                                                                                                                                         "OpSourceContinued \"\""));
4197         cases.push_back(CaseParameter("long_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
4198                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4199                                                                                                                                                         "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\"")); // word count: 65535
4200         cases.push_back(CaseParameter("utf8_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
4201                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4202                                                                                                                                                         "OpSourceContinued \"\xE2\x98\x8E\xE2\x9A\x91\"")); // white telephone & black flag symbol
4203         cases.push_back(CaseParameter("multi_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
4204                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\n\"\n"
4205                                                                                                                                                         "OpSourceContinued \"void\"\n"
4206                                                                                                                                                         "OpSourceContinued \"main()\"\n"
4207                                                                                                                                                         "OpSourceContinued \"{}\""));
4208         cases.push_back(CaseParameter("empty_source_before_sourcecontinued",    "%fname = OpString \"filename\"\n"
4209                                                                                                                                                         "OpSource GLSL 430 %fname \"\"\n"
4210                                                                                                                                                         "OpSourceContinued \"#version 430\nvoid main() {}\""));
4211
4212         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4213
4214         for (size_t ndx = 0; ndx < numElements; ++ndx)
4215                 negativeFloats[ndx] = -positiveFloats[ndx];
4216
4217         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4218         {
4219                 map<string, string>             specializations;
4220                 ComputeShaderSpec               spec;
4221
4222                 specializations["SOURCE"] = cases[caseNdx].param;
4223                 spec.assembly = shaderTemplate.specialize(specializations);
4224                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4225                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4226                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4227
4228                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4229         }
4230
4231         return group.release();
4232 }
4233
4234 tcu::TestCaseGroup* createOpSourceExtensionGroup (tcu::TestContext& testCtx)
4235 {
4236         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsourceextension", "Tests the OpSource instruction"));
4237         vector<CaseParameter>                   cases;
4238         de::Random                                              rnd                             (deStringHash(group->getName()));
4239         const int                                               numElements             = 100;
4240         vector<float>                                   inputFloats             (numElements, 0);
4241         vector<float>                                   outputFloats    (numElements, 0);
4242         const StringTemplate                    shaderTemplate  (
4243                 string(getComputeAsmShaderPreamble()) +
4244
4245                 "OpSourceExtension \"${EXTENSION}\"\n"
4246
4247                 "OpName %main           \"main\"\n"
4248                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4249
4250                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4251
4252                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4253
4254                 "%id        = OpVariable %uvec3ptr Input\n"
4255                 "%zero      = OpConstant %i32 0\n"
4256
4257                 "%main      = OpFunction %void None %voidf\n"
4258                 "%label     = OpLabel\n"
4259                 "%idval     = OpLoad %uvec3 %id\n"
4260                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4261                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4262                 "%inval     = OpLoad %f32 %inloc\n"
4263                 "%neg       = OpFNegate %f32 %inval\n"
4264                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4265                 "             OpStore %outloc %neg\n"
4266                 "             OpReturn\n"
4267                 "             OpFunctionEnd\n");
4268
4269         cases.push_back(CaseParameter("empty_extension",        ""));
4270         cases.push_back(CaseParameter("real_extension",         "GL_ARB_texture_rectangle"));
4271         cases.push_back(CaseParameter("fake_extension",         "GL_ARB_im_the_ultimate_extension"));
4272         cases.push_back(CaseParameter("utf8_extension",         "GL_ARB_\xE2\x98\x82\xE2\x98\x85"));
4273         cases.push_back(CaseParameter("long_extension",         makeLongUTF8String(65533) + "ccc")); // word count: 65535
4274
4275         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
4276
4277         for (size_t ndx = 0; ndx < numElements; ++ndx)
4278                 outputFloats[ndx] = -inputFloats[ndx];
4279
4280         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4281         {
4282                 map<string, string>             specializations;
4283                 ComputeShaderSpec               spec;
4284
4285                 specializations["EXTENSION"] = cases[caseNdx].param;
4286                 spec.assembly = shaderTemplate.specialize(specializations);
4287                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4288                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
4289                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4290
4291                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4292         }
4293
4294         return group.release();
4295 }
4296
4297 // Checks that a compute shader can generate a constant null value of various types, without exercising a computation on it.
4298 tcu::TestCaseGroup* createOpConstantNullGroup (tcu::TestContext& testCtx)
4299 {
4300         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnull", "Tests the OpConstantNull instruction"));
4301         vector<CaseParameter>                   cases;
4302         de::Random                                              rnd                             (deStringHash(group->getName()));
4303         const int                                               numElements             = 100;
4304         vector<float>                                   positiveFloats  (numElements, 0);
4305         vector<float>                                   negativeFloats  (numElements, 0);
4306         const StringTemplate                    shaderTemplate  (
4307                 string(getComputeAsmShaderPreamble()) +
4308
4309                 "OpSource GLSL 430\n"
4310                 "OpName %main           \"main\"\n"
4311                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4312
4313                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4314
4315                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4316                 "%uvec2     = OpTypeVector %u32 2\n"
4317                 "%bvec3     = OpTypeVector %bool 3\n"
4318                 "%fvec4     = OpTypeVector %f32 4\n"
4319                 "%fmat33    = OpTypeMatrix %fvec3 3\n"
4320                 "%const100  = OpConstant %u32 100\n"
4321                 "%uarr100   = OpTypeArray %i32 %const100\n"
4322                 "%struct    = OpTypeStruct %f32 %i32 %u32\n"
4323                 "%pointer   = OpTypePointer Function %i32\n"
4324                 + string(getComputeAsmInputOutputBuffer()) +
4325
4326                 "%null      = OpConstantNull ${TYPE}\n"
4327
4328                 "%id        = OpVariable %uvec3ptr Input\n"
4329                 "%zero      = OpConstant %i32 0\n"
4330
4331                 "%main      = OpFunction %void None %voidf\n"
4332                 "%label     = OpLabel\n"
4333                 "%idval     = OpLoad %uvec3 %id\n"
4334                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4335                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4336                 "%inval     = OpLoad %f32 %inloc\n"
4337                 "%neg       = OpFNegate %f32 %inval\n"
4338                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4339                 "             OpStore %outloc %neg\n"
4340                 "             OpReturn\n"
4341                 "             OpFunctionEnd\n");
4342
4343         cases.push_back(CaseParameter("bool",                   "%bool"));
4344         cases.push_back(CaseParameter("sint32",                 "%i32"));
4345         cases.push_back(CaseParameter("uint32",                 "%u32"));
4346         cases.push_back(CaseParameter("float32",                "%f32"));
4347         cases.push_back(CaseParameter("vec4float32",    "%fvec4"));
4348         cases.push_back(CaseParameter("vec3bool",               "%bvec3"));
4349         cases.push_back(CaseParameter("vec2uint32",             "%uvec2"));
4350         cases.push_back(CaseParameter("matrix",                 "%fmat33"));
4351         cases.push_back(CaseParameter("array",                  "%uarr100"));
4352         cases.push_back(CaseParameter("struct",                 "%struct"));
4353         cases.push_back(CaseParameter("pointer",                "%pointer"));
4354
4355         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4356
4357         for (size_t ndx = 0; ndx < numElements; ++ndx)
4358                 negativeFloats[ndx] = -positiveFloats[ndx];
4359
4360         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4361         {
4362                 map<string, string>             specializations;
4363                 ComputeShaderSpec               spec;
4364
4365                 specializations["TYPE"] = cases[caseNdx].param;
4366                 spec.assembly = shaderTemplate.specialize(specializations);
4367                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4368                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4369                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4370
4371                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4372         }
4373
4374         return group.release();
4375 }
4376
4377 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
4378 tcu::TestCaseGroup* createOpConstantCompositeGroup (tcu::TestContext& testCtx)
4379 {
4380         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "Tests the OpConstantComposite instruction"));
4381         vector<CaseParameter>                   cases;
4382         de::Random                                              rnd                             (deStringHash(group->getName()));
4383         const int                                               numElements             = 100;
4384         vector<float>                                   positiveFloats  (numElements, 0);
4385         vector<float>                                   negativeFloats  (numElements, 0);
4386         const StringTemplate                    shaderTemplate  (
4387                 string(getComputeAsmShaderPreamble()) +
4388
4389                 "OpSource GLSL 430\n"
4390                 "OpName %main           \"main\"\n"
4391                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4392
4393                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4394
4395                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4396
4397                 "%id        = OpVariable %uvec3ptr Input\n"
4398                 "%zero      = OpConstant %i32 0\n"
4399
4400                 "${CONSTANT}\n"
4401
4402                 "%main      = OpFunction %void None %voidf\n"
4403                 "%label     = OpLabel\n"
4404                 "%idval     = OpLoad %uvec3 %id\n"
4405                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4406                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4407                 "%inval     = OpLoad %f32 %inloc\n"
4408                 "%neg       = OpFNegate %f32 %inval\n"
4409                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4410                 "             OpStore %outloc %neg\n"
4411                 "             OpReturn\n"
4412                 "             OpFunctionEnd\n");
4413
4414         cases.push_back(CaseParameter("vector",                 "%five = OpConstant %u32 5\n"
4415                                                                                                         "%const = OpConstantComposite %uvec3 %five %zero %five"));
4416         cases.push_back(CaseParameter("matrix",                 "%m3fvec3 = OpTypeMatrix %fvec3 3\n"
4417                                                                                                         "%ten = OpConstant %f32 10.\n"
4418                                                                                                         "%fzero = OpConstant %f32 0.\n"
4419                                                                                                         "%vec = OpConstantComposite %fvec3 %ten %fzero %ten\n"
4420                                                                                                         "%mat = OpConstantComposite %m3fvec3 %vec %vec %vec"));
4421         cases.push_back(CaseParameter("struct",                 "%m2vec3 = OpTypeMatrix %fvec3 2\n"
4422                                                                                                         "%struct = OpTypeStruct %i32 %f32 %fvec3 %m2vec3\n"
4423                                                                                                         "%fzero = OpConstant %f32 0.\n"
4424                                                                                                         "%one = OpConstant %f32 1.\n"
4425                                                                                                         "%point5 = OpConstant %f32 0.5\n"
4426                                                                                                         "%vec = OpConstantComposite %fvec3 %one %one %fzero\n"
4427                                                                                                         "%mat = OpConstantComposite %m2vec3 %vec %vec\n"
4428                                                                                                         "%const = OpConstantComposite %struct %zero %point5 %vec %mat"));
4429         cases.push_back(CaseParameter("nested_struct",  "%st1 = OpTypeStruct %u32 %f32\n"
4430                                                                                                         "%st2 = OpTypeStruct %i32 %i32\n"
4431                                                                                                         "%struct = OpTypeStruct %st1 %st2\n"
4432                                                                                                         "%point5 = OpConstant %f32 0.5\n"
4433                                                                                                         "%one = OpConstant %u32 1\n"
4434                                                                                                         "%ten = OpConstant %i32 10\n"
4435                                                                                                         "%st1val = OpConstantComposite %st1 %one %point5\n"
4436                                                                                                         "%st2val = OpConstantComposite %st2 %ten %ten\n"
4437                                                                                                         "%const = OpConstantComposite %struct %st1val %st2val"));
4438
4439         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4440
4441         for (size_t ndx = 0; ndx < numElements; ++ndx)
4442                 negativeFloats[ndx] = -positiveFloats[ndx];
4443
4444         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4445         {
4446                 map<string, string>             specializations;
4447                 ComputeShaderSpec               spec;
4448
4449                 specializations["CONSTANT"] = cases[caseNdx].param;
4450                 spec.assembly = shaderTemplate.specialize(specializations);
4451                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4452                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4453                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4454
4455                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4456         }
4457
4458         return group.release();
4459 }
4460
4461 // Creates a floating point number with the given exponent, and significand
4462 // bits set. It can only create normalized numbers. Only the least significant
4463 // 24 bits of the significand will be examined. The final bit of the
4464 // significand will also be ignored. This allows alignment to be written
4465 // similarly to C99 hex-floats.
4466 // For example if you wanted to write 0x1.7f34p-12 you would call
4467 // constructNormalizedFloat(-12, 0x7f3400)
4468 float constructNormalizedFloat (deInt32 exponent, deUint32 significand)
4469 {
4470         float f = 1.0f;
4471
4472         for (deInt32 idx = 0; idx < 23; ++idx)
4473         {
4474                 f += ((significand & 0x800000) == 0) ? 0.f : std::ldexp(1.0f, -(idx + 1));
4475                 significand <<= 1;
4476         }
4477
4478         return std::ldexp(f, exponent);
4479 }
4480
4481 // Compare instruction for the OpQuantizeF16 compute exact case.
4482 // Returns true if the output is what is expected from the test case.
4483 bool compareOpQuantizeF16ComputeExactCase (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
4484 {
4485         if (outputAllocs.size() != 1)
4486                 return false;
4487
4488         // Only size is needed because we cannot compare Nans.
4489         size_t byteSize = expectedOutputs[0].getByteSize();
4490
4491         const float*    outputAsFloat   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
4492
4493         if (byteSize != 4*sizeof(float)) {
4494                 return false;
4495         }
4496
4497         if (*outputAsFloat != constructNormalizedFloat(8, 0x304000) &&
4498                 *outputAsFloat != constructNormalizedFloat(8, 0x300000)) {
4499                 return false;
4500         }
4501         outputAsFloat++;
4502
4503         if (*outputAsFloat != -constructNormalizedFloat(-7, 0x600000) &&
4504                 *outputAsFloat != -constructNormalizedFloat(-7, 0x604000)) {
4505                 return false;
4506         }
4507         outputAsFloat++;
4508
4509         if (*outputAsFloat != constructNormalizedFloat(2, 0x01C000) &&
4510                 *outputAsFloat != constructNormalizedFloat(2, 0x020000)) {
4511                 return false;
4512         }
4513         outputAsFloat++;
4514
4515         if (*outputAsFloat != constructNormalizedFloat(1, 0xFFC000) &&
4516                 *outputAsFloat != constructNormalizedFloat(2, 0x000000)) {
4517                 return false;
4518         }
4519
4520         return true;
4521 }
4522
4523 // Checks that every output from a test-case is a float NaN.
4524 bool compareNan (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
4525 {
4526         if (outputAllocs.size() != 1)
4527                 return false;
4528
4529         // Only size is needed because we cannot compare Nans.
4530         size_t byteSize = expectedOutputs[0].getByteSize();
4531
4532         const float* const      output_as_float = static_cast<const float*>(outputAllocs[0]->getHostPtr());
4533
4534         for (size_t idx = 0; idx < byteSize / sizeof(float); ++idx)
4535         {
4536                 if (!deFloatIsNaN(output_as_float[idx]))
4537                 {
4538                         return false;
4539                 }
4540         }
4541
4542         return true;
4543 }
4544
4545 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
4546 tcu::TestCaseGroup* createOpQuantizeToF16Group (tcu::TestContext& testCtx)
4547 {
4548         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opquantize", "Tests the OpQuantizeToF16 instruction"));
4549
4550         const std::string shader (
4551                 string(getComputeAsmShaderPreamble()) +
4552
4553                 "OpSource GLSL 430\n"
4554                 "OpName %main           \"main\"\n"
4555                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4556
4557                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4558
4559                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4560
4561                 "%id        = OpVariable %uvec3ptr Input\n"
4562                 "%zero      = OpConstant %i32 0\n"
4563
4564                 "%main      = OpFunction %void None %voidf\n"
4565                 "%label     = OpLabel\n"
4566                 "%idval     = OpLoad %uvec3 %id\n"
4567                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4568                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4569                 "%inval     = OpLoad %f32 %inloc\n"
4570                 "%quant     = OpQuantizeToF16 %f32 %inval\n"
4571                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4572                 "             OpStore %outloc %quant\n"
4573                 "             OpReturn\n"
4574                 "             OpFunctionEnd\n");
4575
4576         {
4577                 ComputeShaderSpec       spec;
4578                 const deUint32          numElements             = 100;
4579                 vector<float>           infinities;
4580                 vector<float>           results;
4581
4582                 infinities.reserve(numElements);
4583                 results.reserve(numElements);
4584
4585                 for (size_t idx = 0; idx < numElements; ++idx)
4586                 {
4587                         switch(idx % 4)
4588                         {
4589                                 case 0:
4590                                         infinities.push_back(std::numeric_limits<float>::infinity());
4591                                         results.push_back(std::numeric_limits<float>::infinity());
4592                                         break;
4593                                 case 1:
4594                                         infinities.push_back(-std::numeric_limits<float>::infinity());
4595                                         results.push_back(-std::numeric_limits<float>::infinity());
4596                                         break;
4597                                 case 2:
4598                                         infinities.push_back(std::ldexp(1.0f, 16));
4599                                         results.push_back(std::numeric_limits<float>::infinity());
4600                                         break;
4601                                 case 3:
4602                                         infinities.push_back(std::ldexp(-1.0f, 32));
4603                                         results.push_back(-std::numeric_limits<float>::infinity());
4604                                         break;
4605                         }
4606                 }
4607
4608                 spec.assembly = shader;
4609                 spec.inputs.push_back(BufferSp(new Float32Buffer(infinities)));
4610                 spec.outputs.push_back(BufferSp(new Float32Buffer(results)));
4611                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4612
4613                 group->addChild(new SpvAsmComputeShaderCase(
4614                         testCtx, "infinities", "Check that infinities propagated and created", spec));
4615         }
4616
4617         {
4618                 ComputeShaderSpec       spec;
4619                 vector<float>           nans;
4620                 const deUint32          numElements             = 100;
4621
4622                 nans.reserve(numElements);
4623
4624                 for (size_t idx = 0; idx < numElements; ++idx)
4625                 {
4626                         if (idx % 2 == 0)
4627                         {
4628                                 nans.push_back(std::numeric_limits<float>::quiet_NaN());
4629                         }
4630                         else
4631                         {
4632                                 nans.push_back(-std::numeric_limits<float>::quiet_NaN());
4633                         }
4634                 }
4635
4636                 spec.assembly = shader;
4637                 spec.inputs.push_back(BufferSp(new Float32Buffer(nans)));
4638                 spec.outputs.push_back(BufferSp(new Float32Buffer(nans)));
4639                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4640                 spec.verifyIO = &compareNan;
4641
4642                 group->addChild(new SpvAsmComputeShaderCase(
4643                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
4644         }
4645
4646         {
4647                 ComputeShaderSpec       spec;
4648                 vector<float>           small;
4649                 vector<float>           zeros;
4650                 const deUint32          numElements             = 100;
4651
4652                 small.reserve(numElements);
4653                 zeros.reserve(numElements);
4654
4655                 for (size_t idx = 0; idx < numElements; ++idx)
4656                 {
4657                         switch(idx % 6)
4658                         {
4659                                 case 0:
4660                                         small.push_back(0.f);
4661                                         zeros.push_back(0.f);
4662                                         break;
4663                                 case 1:
4664                                         small.push_back(-0.f);
4665                                         zeros.push_back(-0.f);
4666                                         break;
4667                                 case 2:
4668                                         small.push_back(std::ldexp(1.0f, -16));
4669                                         zeros.push_back(0.f);
4670                                         break;
4671                                 case 3:
4672                                         small.push_back(std::ldexp(-1.0f, -32));
4673                                         zeros.push_back(-0.f);
4674                                         break;
4675                                 case 4:
4676                                         small.push_back(std::ldexp(1.0f, -127));
4677                                         zeros.push_back(0.f);
4678                                         break;
4679                                 case 5:
4680                                         small.push_back(-std::ldexp(1.0f, -128));
4681                                         zeros.push_back(-0.f);
4682                                         break;
4683                         }
4684                 }
4685
4686                 spec.assembly = shader;
4687                 spec.inputs.push_back(BufferSp(new Float32Buffer(small)));
4688                 spec.outputs.push_back(BufferSp(new Float32Buffer(zeros)));
4689                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4690
4691                 group->addChild(new SpvAsmComputeShaderCase(
4692                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
4693         }
4694
4695         {
4696                 ComputeShaderSpec       spec;
4697                 vector<float>           exact;
4698                 const deUint32          numElements             = 200;
4699
4700                 exact.reserve(numElements);
4701
4702                 for (size_t idx = 0; idx < numElements; ++idx)
4703                         exact.push_back(static_cast<float>(static_cast<int>(idx) - 100));
4704
4705                 spec.assembly = shader;
4706                 spec.inputs.push_back(BufferSp(new Float32Buffer(exact)));
4707                 spec.outputs.push_back(BufferSp(new Float32Buffer(exact)));
4708                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4709
4710                 group->addChild(new SpvAsmComputeShaderCase(
4711                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
4712         }
4713
4714         {
4715                 ComputeShaderSpec       spec;
4716                 vector<float>           inputs;
4717                 const deUint32          numElements             = 4;
4718
4719                 inputs.push_back(constructNormalizedFloat(8,    0x300300));
4720                 inputs.push_back(-constructNormalizedFloat(-7,  0x600800));
4721                 inputs.push_back(constructNormalizedFloat(2,    0x01E000));
4722                 inputs.push_back(constructNormalizedFloat(1,    0xFFE000));
4723
4724                 spec.assembly = shader;
4725                 spec.verifyIO = &compareOpQuantizeF16ComputeExactCase;
4726                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4727                 spec.outputs.push_back(BufferSp(new Float32Buffer(inputs)));
4728                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4729
4730                 group->addChild(new SpvAsmComputeShaderCase(
4731                         testCtx, "rounded", "Check that are rounded when needed", spec));
4732         }
4733
4734         return group.release();
4735 }
4736
4737 tcu::TestCaseGroup* createSpecConstantOpQuantizeToF16Group (tcu::TestContext& testCtx)
4738 {
4739         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opspecconstantop_opquantize", "Tests the OpQuantizeToF16 opcode for the OpSpecConstantOp instruction"));
4740
4741         const std::string shader (
4742                 string(getComputeAsmShaderPreamble()) +
4743
4744                 "OpName %main           \"main\"\n"
4745                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4746
4747                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4748
4749                 "OpDecorate %sc_0  SpecId 0\n"
4750                 "OpDecorate %sc_1  SpecId 1\n"
4751                 "OpDecorate %sc_2  SpecId 2\n"
4752                 "OpDecorate %sc_3  SpecId 3\n"
4753                 "OpDecorate %sc_4  SpecId 4\n"
4754                 "OpDecorate %sc_5  SpecId 5\n"
4755
4756                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4757
4758                 "%id        = OpVariable %uvec3ptr Input\n"
4759                 "%zero      = OpConstant %i32 0\n"
4760                 "%c_u32_6   = OpConstant %u32 6\n"
4761
4762                 "%sc_0      = OpSpecConstant %f32 0.\n"
4763                 "%sc_1      = OpSpecConstant %f32 0.\n"
4764                 "%sc_2      = OpSpecConstant %f32 0.\n"
4765                 "%sc_3      = OpSpecConstant %f32 0.\n"
4766                 "%sc_4      = OpSpecConstant %f32 0.\n"
4767                 "%sc_5      = OpSpecConstant %f32 0.\n"
4768
4769                 "%sc_0_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_0\n"
4770                 "%sc_1_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_1\n"
4771                 "%sc_2_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_2\n"
4772                 "%sc_3_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_3\n"
4773                 "%sc_4_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_4\n"
4774                 "%sc_5_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_5\n"
4775
4776                 "%main      = OpFunction %void None %voidf\n"
4777                 "%label     = OpLabel\n"
4778                 "%idval     = OpLoad %uvec3 %id\n"
4779                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4780                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4781                 "%selector  = OpUMod %u32 %x %c_u32_6\n"
4782                 "            OpSelectionMerge %exit None\n"
4783                 "            OpSwitch %selector %exit 0 %case0 1 %case1 2 %case2 3 %case3 4 %case4 5 %case5\n"
4784
4785                 "%case0     = OpLabel\n"
4786                 "             OpStore %outloc %sc_0_quant\n"
4787                 "             OpBranch %exit\n"
4788
4789                 "%case1     = OpLabel\n"
4790                 "             OpStore %outloc %sc_1_quant\n"
4791                 "             OpBranch %exit\n"
4792
4793                 "%case2     = OpLabel\n"
4794                 "             OpStore %outloc %sc_2_quant\n"
4795                 "             OpBranch %exit\n"
4796
4797                 "%case3     = OpLabel\n"
4798                 "             OpStore %outloc %sc_3_quant\n"
4799                 "             OpBranch %exit\n"
4800
4801                 "%case4     = OpLabel\n"
4802                 "             OpStore %outloc %sc_4_quant\n"
4803                 "             OpBranch %exit\n"
4804
4805                 "%case5     = OpLabel\n"
4806                 "             OpStore %outloc %sc_5_quant\n"
4807                 "             OpBranch %exit\n"
4808
4809                 "%exit      = OpLabel\n"
4810                 "             OpReturn\n"
4811
4812                 "             OpFunctionEnd\n");
4813
4814         {
4815                 ComputeShaderSpec       spec;
4816                 const deUint8           numCases        = 4;
4817                 vector<float>           inputs          (numCases, 0.f);
4818                 vector<float>           outputs;
4819
4820                 spec.assembly           = shader;
4821                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4822
4823                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::numeric_limits<float>::infinity()));
4824                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-std::numeric_limits<float>::infinity()));
4825                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, 16)));
4826                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(-1.0f, 32)));
4827
4828                 outputs.push_back(std::numeric_limits<float>::infinity());
4829                 outputs.push_back(-std::numeric_limits<float>::infinity());
4830                 outputs.push_back(std::numeric_limits<float>::infinity());
4831                 outputs.push_back(-std::numeric_limits<float>::infinity());
4832
4833                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4834                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4835
4836                 group->addChild(new SpvAsmComputeShaderCase(
4837                         testCtx, "infinities", "Check that infinities propagated and created", spec));
4838         }
4839
4840         {
4841                 ComputeShaderSpec       spec;
4842                 const deUint8           numCases        = 2;
4843                 vector<float>           inputs          (numCases, 0.f);
4844                 vector<float>           outputs;
4845
4846                 spec.assembly           = shader;
4847                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4848                 spec.verifyIO           = &compareNan;
4849
4850                 outputs.push_back(std::numeric_limits<float>::quiet_NaN());
4851                 outputs.push_back(-std::numeric_limits<float>::quiet_NaN());
4852
4853                 for (deUint8 idx = 0; idx < numCases; ++idx)
4854                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(outputs[idx]));
4855
4856                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4857                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4858
4859                 group->addChild(new SpvAsmComputeShaderCase(
4860                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
4861         }
4862
4863         {
4864                 ComputeShaderSpec       spec;
4865                 const deUint8           numCases        = 6;
4866                 vector<float>           inputs          (numCases, 0.f);
4867                 vector<float>           outputs;
4868
4869                 spec.assembly           = shader;
4870                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4871
4872                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(0.f));
4873                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-0.f));
4874                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, -16)));
4875                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(-1.0f, -32)));
4876                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, -127)));
4877                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-std::ldexp(1.0f, -128)));
4878
4879                 outputs.push_back(0.f);
4880                 outputs.push_back(-0.f);
4881                 outputs.push_back(0.f);
4882                 outputs.push_back(-0.f);
4883                 outputs.push_back(0.f);
4884                 outputs.push_back(-0.f);
4885
4886                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4887                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4888
4889                 group->addChild(new SpvAsmComputeShaderCase(
4890                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
4891         }
4892
4893         {
4894                 ComputeShaderSpec       spec;
4895                 const deUint8           numCases        = 6;
4896                 vector<float>           inputs          (numCases, 0.f);
4897                 vector<float>           outputs;
4898
4899                 spec.assembly           = shader;
4900                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4901
4902                 for (deUint8 idx = 0; idx < 6; ++idx)
4903                 {
4904                         const float f = static_cast<float>(idx * 10 - 30) / 4.f;
4905                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(f));
4906                         outputs.push_back(f);
4907                 }
4908
4909                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4910                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4911
4912                 group->addChild(new SpvAsmComputeShaderCase(
4913                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
4914         }
4915
4916         {
4917                 ComputeShaderSpec       spec;
4918                 const deUint8           numCases        = 4;
4919                 vector<float>           inputs          (numCases, 0.f);
4920                 vector<float>           outputs;
4921
4922                 spec.assembly           = shader;
4923                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4924                 spec.verifyIO           = &compareOpQuantizeF16ComputeExactCase;
4925
4926                 outputs.push_back(constructNormalizedFloat(8, 0x300300));
4927                 outputs.push_back(-constructNormalizedFloat(-7, 0x600800));
4928                 outputs.push_back(constructNormalizedFloat(2, 0x01E000));
4929                 outputs.push_back(constructNormalizedFloat(1, 0xFFE000));
4930
4931                 for (deUint8 idx = 0; idx < numCases; ++idx)
4932                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(outputs[idx]));
4933
4934                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4935                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4936
4937                 group->addChild(new SpvAsmComputeShaderCase(
4938                         testCtx, "rounded", "Check that are rounded when needed", spec));
4939         }
4940
4941         return group.release();
4942 }
4943
4944 // Checks that constant null/composite values can be used in computation.
4945 tcu::TestCaseGroup* createOpConstantUsageGroup (tcu::TestContext& testCtx)
4946 {
4947         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnullcomposite", "Spotcheck the OpConstantNull & OpConstantComposite instruction"));
4948         ComputeShaderSpec                               spec;
4949         de::Random                                              rnd                             (deStringHash(group->getName()));
4950         const int                                               numElements             = 100;
4951         vector<float>                                   positiveFloats  (numElements, 0);
4952         vector<float>                                   negativeFloats  (numElements, 0);
4953
4954         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4955
4956         for (size_t ndx = 0; ndx < numElements; ++ndx)
4957                 negativeFloats[ndx] = -positiveFloats[ndx];
4958
4959         spec.assembly =
4960                 "OpCapability Shader\n"
4961                 "%std450 = OpExtInstImport \"GLSL.std.450\"\n"
4962                 "OpMemoryModel Logical GLSL450\n"
4963                 "OpEntryPoint GLCompute %main \"main\" %id\n"
4964                 "OpExecutionMode %main LocalSize 1 1 1\n"
4965
4966                 "OpSource GLSL 430\n"
4967                 "OpName %main           \"main\"\n"
4968                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4969
4970                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4971
4972                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4973
4974                 "%fmat      = OpTypeMatrix %fvec3 3\n"
4975                 "%ten       = OpConstant %u32 10\n"
4976                 "%f32arr10  = OpTypeArray %f32 %ten\n"
4977                 "%fst       = OpTypeStruct %f32 %f32\n"
4978
4979                 + string(getComputeAsmInputOutputBuffer()) +
4980
4981                 "%id        = OpVariable %uvec3ptr Input\n"
4982                 "%zero      = OpConstant %i32 0\n"
4983
4984                 // Create a bunch of null values
4985                 "%unull     = OpConstantNull %u32\n"
4986                 "%fnull     = OpConstantNull %f32\n"
4987                 "%vnull     = OpConstantNull %fvec3\n"
4988                 "%mnull     = OpConstantNull %fmat\n"
4989                 "%anull     = OpConstantNull %f32arr10\n"
4990                 "%snull     = OpConstantComposite %fst %fnull %fnull\n"
4991
4992                 "%main      = OpFunction %void None %voidf\n"
4993                 "%label     = OpLabel\n"
4994                 "%idval     = OpLoad %uvec3 %id\n"
4995                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4996                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4997                 "%inval     = OpLoad %f32 %inloc\n"
4998                 "%neg       = OpFNegate %f32 %inval\n"
4999
5000                 // Get the abs() of (a certain element of) those null values
5001                 "%unull_cov = OpConvertUToF %f32 %unull\n"
5002                 "%unull_abs = OpExtInst %f32 %std450 FAbs %unull_cov\n"
5003                 "%fnull_abs = OpExtInst %f32 %std450 FAbs %fnull\n"
5004                 "%vnull_0   = OpCompositeExtract %f32 %vnull 0\n"
5005                 "%vnull_abs = OpExtInst %f32 %std450 FAbs %vnull_0\n"
5006                 "%mnull_12  = OpCompositeExtract %f32 %mnull 1 2\n"
5007                 "%mnull_abs = OpExtInst %f32 %std450 FAbs %mnull_12\n"
5008                 "%anull_3   = OpCompositeExtract %f32 %anull 3\n"
5009                 "%anull_abs = OpExtInst %f32 %std450 FAbs %anull_3\n"
5010                 "%snull_1   = OpCompositeExtract %f32 %snull 1\n"
5011                 "%snull_abs = OpExtInst %f32 %std450 FAbs %snull_1\n"
5012
5013                 // Add them all
5014                 "%add1      = OpFAdd %f32 %neg  %unull_abs\n"
5015                 "%add2      = OpFAdd %f32 %add1 %fnull_abs\n"
5016                 "%add3      = OpFAdd %f32 %add2 %vnull_abs\n"
5017                 "%add4      = OpFAdd %f32 %add3 %mnull_abs\n"
5018                 "%add5      = OpFAdd %f32 %add4 %anull_abs\n"
5019                 "%final     = OpFAdd %f32 %add5 %snull_abs\n"
5020
5021                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5022                 "             OpStore %outloc %final\n" // write to output
5023                 "             OpReturn\n"
5024                 "             OpFunctionEnd\n";
5025         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
5026         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
5027         spec.numWorkGroups = IVec3(numElements, 1, 1);
5028
5029         group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "Check that values constructed via OpConstantNull & OpConstantComposite can be used", spec));
5030
5031         return group.release();
5032 }
5033
5034 // Assembly code used for testing loop control is based on GLSL source code:
5035 // #version 430
5036 //
5037 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5038 //   float elements[];
5039 // } input_data;
5040 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5041 //   float elements[];
5042 // } output_data;
5043 //
5044 // void main() {
5045 //   uint x = gl_GlobalInvocationID.x;
5046 //   output_data.elements[x] = input_data.elements[x];
5047 //   for (uint i = 0; i < 4; ++i)
5048 //     output_data.elements[x] += 1.f;
5049 // }
5050 tcu::TestCaseGroup* createLoopControlGroup (tcu::TestContext& testCtx)
5051 {
5052         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "loop_control", "Tests loop control cases"));
5053         vector<CaseParameter>                   cases;
5054         de::Random                                              rnd                             (deStringHash(group->getName()));
5055         const int                                               numElements             = 100;
5056         vector<float>                                   inputFloats             (numElements, 0);
5057         vector<float>                                   outputFloats    (numElements, 0);
5058         const StringTemplate                    shaderTemplate  (
5059                 string(getComputeAsmShaderPreamble()) +
5060
5061                 "OpSource GLSL 430\n"
5062                 "OpName %main \"main\"\n"
5063                 "OpName %id \"gl_GlobalInvocationID\"\n"
5064
5065                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5066
5067                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5068
5069                 "%u32ptr      = OpTypePointer Function %u32\n"
5070
5071                 "%id          = OpVariable %uvec3ptr Input\n"
5072                 "%zero        = OpConstant %i32 0\n"
5073                 "%uzero       = OpConstant %u32 0\n"
5074                 "%one         = OpConstant %i32 1\n"
5075                 "%constf1     = OpConstant %f32 1.0\n"
5076                 "%four        = OpConstant %u32 4\n"
5077
5078                 "%main        = OpFunction %void None %voidf\n"
5079                 "%entry       = OpLabel\n"
5080                 "%i           = OpVariable %u32ptr Function\n"
5081                 "               OpStore %i %uzero\n"
5082
5083                 "%idval       = OpLoad %uvec3 %id\n"
5084                 "%x           = OpCompositeExtract %u32 %idval 0\n"
5085                 "%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
5086                 "%inval       = OpLoad %f32 %inloc\n"
5087                 "%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
5088                 "               OpStore %outloc %inval\n"
5089                 "               OpBranch %loop_entry\n"
5090
5091                 "%loop_entry  = OpLabel\n"
5092                 "%i_val       = OpLoad %u32 %i\n"
5093                 "%cmp_lt      = OpULessThan %bool %i_val %four\n"
5094                 "               OpLoopMerge %loop_merge %loop_body ${CONTROL}\n"
5095                 "               OpBranchConditional %cmp_lt %loop_body %loop_merge\n"
5096                 "%loop_body   = OpLabel\n"
5097                 "%outval      = OpLoad %f32 %outloc\n"
5098                 "%addf1       = OpFAdd %f32 %outval %constf1\n"
5099                 "               OpStore %outloc %addf1\n"
5100                 "%new_i       = OpIAdd %u32 %i_val %one\n"
5101                 "               OpStore %i %new_i\n"
5102                 "               OpBranch %loop_entry\n"
5103                 "%loop_merge  = OpLabel\n"
5104                 "               OpReturn\n"
5105                 "               OpFunctionEnd\n");
5106
5107         cases.push_back(CaseParameter("none",                           "None"));
5108         cases.push_back(CaseParameter("unroll",                         "Unroll"));
5109         cases.push_back(CaseParameter("dont_unroll",            "DontUnroll"));
5110         cases.push_back(CaseParameter("unroll_dont_unroll",     "Unroll|DontUnroll"));
5111
5112         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5113
5114         for (size_t ndx = 0; ndx < numElements; ++ndx)
5115                 outputFloats[ndx] = inputFloats[ndx] + 4.f;
5116
5117         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5118         {
5119                 map<string, string>             specializations;
5120                 ComputeShaderSpec               spec;
5121
5122                 specializations["CONTROL"] = cases[caseNdx].param;
5123                 spec.assembly = shaderTemplate.specialize(specializations);
5124                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5125                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5126                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5127
5128                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5129         }
5130
5131         group->addChild(new SpvAsmLoopControlDependencyLengthCase(testCtx, "dependency_length", "dependency_length"));
5132         group->addChild(new SpvAsmLoopControlDependencyInfiniteCase(testCtx, "dependency_infinite", "dependency_infinite"));
5133
5134         return group.release();
5135 }
5136
5137 // Assembly code used for testing selection control is based on GLSL source code:
5138 // #version 430
5139 //
5140 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5141 //   float elements[];
5142 // } input_data;
5143 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5144 //   float elements[];
5145 // } output_data;
5146 //
5147 // void main() {
5148 //   uint x = gl_GlobalInvocationID.x;
5149 //   float val = input_data.elements[x];
5150 //   if (val > 10.f)
5151 //     output_data.elements[x] = val + 1.f;
5152 //   else
5153 //     output_data.elements[x] = val - 1.f;
5154 // }
5155 tcu::TestCaseGroup* createSelectionControlGroup (tcu::TestContext& testCtx)
5156 {
5157         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "selection_control", "Tests selection control cases"));
5158         vector<CaseParameter>                   cases;
5159         de::Random                                              rnd                             (deStringHash(group->getName()));
5160         const int                                               numElements             = 100;
5161         vector<float>                                   inputFloats             (numElements, 0);
5162         vector<float>                                   outputFloats    (numElements, 0);
5163         const StringTemplate                    shaderTemplate  (
5164                 string(getComputeAsmShaderPreamble()) +
5165
5166                 "OpSource GLSL 430\n"
5167                 "OpName %main \"main\"\n"
5168                 "OpName %id \"gl_GlobalInvocationID\"\n"
5169
5170                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5171
5172                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5173
5174                 "%id       = OpVariable %uvec3ptr Input\n"
5175                 "%zero     = OpConstant %i32 0\n"
5176                 "%constf1  = OpConstant %f32 1.0\n"
5177                 "%constf10 = OpConstant %f32 10.0\n"
5178
5179                 "%main     = OpFunction %void None %voidf\n"
5180                 "%entry    = OpLabel\n"
5181                 "%idval    = OpLoad %uvec3 %id\n"
5182                 "%x        = OpCompositeExtract %u32 %idval 0\n"
5183                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
5184                 "%inval    = OpLoad %f32 %inloc\n"
5185                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
5186                 "%cmp_gt   = OpFOrdGreaterThan %bool %inval %constf10\n"
5187
5188                 "            OpSelectionMerge %if_end ${CONTROL}\n"
5189                 "            OpBranchConditional %cmp_gt %if_true %if_false\n"
5190                 "%if_true  = OpLabel\n"
5191                 "%addf1    = OpFAdd %f32 %inval %constf1\n"
5192                 "            OpStore %outloc %addf1\n"
5193                 "            OpBranch %if_end\n"
5194                 "%if_false = OpLabel\n"
5195                 "%subf1    = OpFSub %f32 %inval %constf1\n"
5196                 "            OpStore %outloc %subf1\n"
5197                 "            OpBranch %if_end\n"
5198                 "%if_end   = OpLabel\n"
5199                 "            OpReturn\n"
5200                 "            OpFunctionEnd\n");
5201
5202         cases.push_back(CaseParameter("none",                                   "None"));
5203         cases.push_back(CaseParameter("flatten",                                "Flatten"));
5204         cases.push_back(CaseParameter("dont_flatten",                   "DontFlatten"));
5205         cases.push_back(CaseParameter("flatten_dont_flatten",   "DontFlatten|Flatten"));
5206
5207         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5208
5209         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
5210         floorAll(inputFloats);
5211
5212         for (size_t ndx = 0; ndx < numElements; ++ndx)
5213                 outputFloats[ndx] = inputFloats[ndx] + (inputFloats[ndx] > 10.f ? 1.f : -1.f);
5214
5215         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5216         {
5217                 map<string, string>             specializations;
5218                 ComputeShaderSpec               spec;
5219
5220                 specializations["CONTROL"] = cases[caseNdx].param;
5221                 spec.assembly = shaderTemplate.specialize(specializations);
5222                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5223                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5224                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5225
5226                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5227         }
5228
5229         return group.release();
5230 }
5231
5232 tcu::TestCaseGroup* createOpNameGroup(tcu::TestContext& testCtx)
5233 {
5234         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opname", "Tests OpName cases"));
5235         de::MovePtr<tcu::TestCaseGroup> entryMainGroup  (new tcu::TestCaseGroup(testCtx, "entry_main", "OpName tests with entry main"));
5236         de::MovePtr<tcu::TestCaseGroup> entryNotGroup   (new tcu::TestCaseGroup(testCtx, "entry_rdc", "OpName tests with entry rdc"));
5237         vector<CaseParameter>                   cases;
5238         vector<string>                                  testFunc;
5239         de::Random                                              rnd                             (deStringHash(group->getName()));
5240         const int                                               numElements             = 100;
5241         vector<float>                                   inputFloats             (numElements, 0);
5242         vector<float>                                   outputFloats    (numElements, 0);
5243
5244         fillRandomScalars(rnd, -100.0f, 100.0f, &inputFloats[0], numElements);
5245
5246         for(size_t ndx = 0; ndx < numElements; ++ndx)
5247                 outputFloats[ndx] = -inputFloats[ndx];
5248
5249         const StringTemplate shaderTemplate (
5250                 "OpCapability Shader\n"
5251                 "OpMemoryModel Logical GLSL450\n"
5252                 "OpEntryPoint GLCompute %main \"${ENTRY}\" %id\n"
5253                 "OpExecutionMode %main LocalSize 1 1 1\n"
5254
5255                 "OpName %${FUNC_ID} \"${NAME}\"\n"
5256
5257                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5258
5259                 + string(getComputeAsmInputOutputBufferTraits())
5260
5261                 + string(getComputeAsmCommonTypes())
5262
5263                 + string(getComputeAsmInputOutputBuffer()) +
5264
5265                 "%id        = OpVariable %uvec3ptr Input\n"
5266                 "%zero      = OpConstant %i32 0\n"
5267
5268                 "%func      = OpFunction %void None %voidf\n"
5269                 "%5         = OpLabel\n"
5270                 "             OpReturn\n"
5271                 "             OpFunctionEnd\n"
5272
5273                 "%main      = OpFunction %void None %voidf\n"
5274                 "%entry     = OpLabel\n"
5275                 "%7         = OpFunctionCall %void %func\n"
5276
5277                 "%idval     = OpLoad %uvec3 %id\n"
5278                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5279
5280                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5281                 "%inval     = OpLoad %f32 %inloc\n"
5282                 "%neg       = OpFNegate %f32 %inval\n"
5283                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5284                 "             OpStore %outloc %neg\n"
5285
5286
5287                 "             OpReturn\n"
5288                 "             OpFunctionEnd\n");
5289
5290         cases.push_back(CaseParameter("_is_main", "main"));
5291         cases.push_back(CaseParameter("_is_not_main", "not_main"));
5292
5293         testFunc.push_back("main");
5294         testFunc.push_back("func");
5295
5296         for(size_t fNdx = 0; fNdx < testFunc.size(); ++fNdx)
5297         {
5298                 for(size_t ndx = 0; ndx < cases.size(); ++ndx)
5299                 {
5300                         map<string, string>     specializations;
5301                         ComputeShaderSpec       spec;
5302
5303                         specializations["ENTRY"] = "main";
5304                         specializations["FUNC_ID"] = testFunc[fNdx];
5305                         specializations["NAME"] = cases[ndx].param;
5306                         spec.assembly = shaderTemplate.specialize(specializations);
5307                         spec.numWorkGroups = IVec3(numElements, 1, 1);
5308                         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5309                         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5310
5311                         entryMainGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (testFunc[fNdx] + cases[ndx].name).c_str(), cases[ndx].name, spec));
5312                 }
5313         }
5314
5315         cases.push_back(CaseParameter("_is_entry", "rdc"));
5316
5317         for(size_t fNdx = 0; fNdx < testFunc.size(); ++fNdx)
5318         {
5319                 for(size_t ndx = 0; ndx < cases.size(); ++ndx)
5320                 {
5321                         map<string, string>     specializations;
5322                         ComputeShaderSpec       spec;
5323
5324                         specializations["ENTRY"] = "rdc";
5325                         specializations["FUNC_ID"] = testFunc[fNdx];
5326                         specializations["NAME"] = cases[ndx].param;
5327                         spec.assembly = shaderTemplate.specialize(specializations);
5328                         spec.numWorkGroups = IVec3(numElements, 1, 1);
5329                         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5330                         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5331                         spec.entryPoint = "rdc";
5332
5333                         entryNotGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (testFunc[fNdx] + cases[ndx].name).c_str(), cases[ndx].name, spec));
5334                 }
5335         }
5336
5337         group->addChild(entryMainGroup.release());
5338         group->addChild(entryNotGroup.release());
5339
5340         return group.release();
5341 }
5342
5343 // Assembly code used for testing function control is based on GLSL source code:
5344 //
5345 // #version 430
5346 //
5347 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5348 //   float elements[];
5349 // } input_data;
5350 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5351 //   float elements[];
5352 // } output_data;
5353 //
5354 // float const10() { return 10.f; }
5355 //
5356 // void main() {
5357 //   uint x = gl_GlobalInvocationID.x;
5358 //   output_data.elements[x] = input_data.elements[x] + const10();
5359 // }
5360 tcu::TestCaseGroup* createFunctionControlGroup (tcu::TestContext& testCtx)
5361 {
5362         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "function_control", "Tests function control cases"));
5363         vector<CaseParameter>                   cases;
5364         de::Random                                              rnd                             (deStringHash(group->getName()));
5365         const int                                               numElements             = 100;
5366         vector<float>                                   inputFloats             (numElements, 0);
5367         vector<float>                                   outputFloats    (numElements, 0);
5368         const StringTemplate                    shaderTemplate  (
5369                 string(getComputeAsmShaderPreamble()) +
5370
5371                 "OpSource GLSL 430\n"
5372                 "OpName %main \"main\"\n"
5373                 "OpName %func_const10 \"const10(\"\n"
5374                 "OpName %id \"gl_GlobalInvocationID\"\n"
5375
5376                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5377
5378                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5379
5380                 "%f32f = OpTypeFunction %f32\n"
5381                 "%id = OpVariable %uvec3ptr Input\n"
5382                 "%zero = OpConstant %i32 0\n"
5383                 "%constf10 = OpConstant %f32 10.0\n"
5384
5385                 "%main         = OpFunction %void None %voidf\n"
5386                 "%entry        = OpLabel\n"
5387                 "%idval        = OpLoad %uvec3 %id\n"
5388                 "%x            = OpCompositeExtract %u32 %idval 0\n"
5389                 "%inloc        = OpAccessChain %f32ptr %indata %zero %x\n"
5390                 "%inval        = OpLoad %f32 %inloc\n"
5391                 "%ret_10       = OpFunctionCall %f32 %func_const10\n"
5392                 "%fadd         = OpFAdd %f32 %inval %ret_10\n"
5393                 "%outloc       = OpAccessChain %f32ptr %outdata %zero %x\n"
5394                 "                OpStore %outloc %fadd\n"
5395                 "                OpReturn\n"
5396                 "                OpFunctionEnd\n"
5397
5398                 "%func_const10 = OpFunction %f32 ${CONTROL} %f32f\n"
5399                 "%label        = OpLabel\n"
5400                 "                OpReturnValue %constf10\n"
5401                 "                OpFunctionEnd\n");
5402
5403         cases.push_back(CaseParameter("none",                                           "None"));
5404         cases.push_back(CaseParameter("inline",                                         "Inline"));
5405         cases.push_back(CaseParameter("dont_inline",                            "DontInline"));
5406         cases.push_back(CaseParameter("pure",                                           "Pure"));
5407         cases.push_back(CaseParameter("const",                                          "Const"));
5408         cases.push_back(CaseParameter("inline_pure",                            "Inline|Pure"));
5409         cases.push_back(CaseParameter("const_dont_inline",                      "Const|DontInline"));
5410         cases.push_back(CaseParameter("inline_dont_inline",                     "Inline|DontInline"));
5411         cases.push_back(CaseParameter("pure_inline_dont_inline",        "Pure|Inline|DontInline"));
5412
5413         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5414
5415         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
5416         floorAll(inputFloats);
5417
5418         for (size_t ndx = 0; ndx < numElements; ++ndx)
5419                 outputFloats[ndx] = inputFloats[ndx] + 10.f;
5420
5421         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5422         {
5423                 map<string, string>             specializations;
5424                 ComputeShaderSpec               spec;
5425
5426                 specializations["CONTROL"] = cases[caseNdx].param;
5427                 spec.assembly = shaderTemplate.specialize(specializations);
5428                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5429                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5430                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5431
5432                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5433         }
5434
5435         return group.release();
5436 }
5437
5438 tcu::TestCaseGroup* createMemoryAccessGroup (tcu::TestContext& testCtx)
5439 {
5440         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "memory_access", "Tests memory access cases"));
5441         vector<CaseParameter>                   cases;
5442         de::Random                                              rnd                             (deStringHash(group->getName()));
5443         const int                                               numElements             = 100;
5444         vector<float>                                   inputFloats             (numElements, 0);
5445         vector<float>                                   outputFloats    (numElements, 0);
5446         const StringTemplate                    shaderTemplate  (
5447                 string(getComputeAsmShaderPreamble()) +
5448
5449                 "OpSource GLSL 430\n"
5450                 "OpName %main           \"main\"\n"
5451                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5452
5453                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5454
5455                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5456
5457                 "%f32ptr_f  = OpTypePointer Function %f32\n"
5458
5459                 "%id        = OpVariable %uvec3ptr Input\n"
5460                 "%zero      = OpConstant %i32 0\n"
5461                 "%four      = OpConstant %i32 4\n"
5462
5463                 "%main      = OpFunction %void None %voidf\n"
5464                 "%label     = OpLabel\n"
5465                 "%copy      = OpVariable %f32ptr_f Function\n"
5466                 "%idval     = OpLoad %uvec3 %id ${ACCESS}\n"
5467                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5468                 "%inloc     = OpAccessChain %f32ptr %indata  %zero %x\n"
5469                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5470                 "             OpCopyMemory %copy %inloc ${ACCESS}\n"
5471                 "%val1      = OpLoad %f32 %copy\n"
5472                 "%val2      = OpLoad %f32 %inloc\n"
5473                 "%add       = OpFAdd %f32 %val1 %val2\n"
5474                 "             OpStore %outloc %add ${ACCESS}\n"
5475                 "             OpReturn\n"
5476                 "             OpFunctionEnd\n");
5477
5478         cases.push_back(CaseParameter("null",                                   ""));
5479         cases.push_back(CaseParameter("none",                                   "None"));
5480         cases.push_back(CaseParameter("volatile",                               "Volatile"));
5481         cases.push_back(CaseParameter("aligned",                                "Aligned 4"));
5482         cases.push_back(CaseParameter("nontemporal",                    "Nontemporal"));
5483         cases.push_back(CaseParameter("aligned_nontemporal",    "Aligned|Nontemporal 4"));
5484         cases.push_back(CaseParameter("aligned_volatile",               "Volatile|Aligned 4"));
5485
5486         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5487
5488         for (size_t ndx = 0; ndx < numElements; ++ndx)
5489                 outputFloats[ndx] = inputFloats[ndx] + inputFloats[ndx];
5490
5491         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5492         {
5493                 map<string, string>             specializations;
5494                 ComputeShaderSpec               spec;
5495
5496                 specializations["ACCESS"] = cases[caseNdx].param;
5497                 spec.assembly = shaderTemplate.specialize(specializations);
5498                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5499                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5500                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5501
5502                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5503         }
5504
5505         return group.release();
5506 }
5507
5508 // Checks that we can get undefined values for various types, without exercising a computation with it.
5509 tcu::TestCaseGroup* createOpUndefGroup (tcu::TestContext& testCtx)
5510 {
5511         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opundef", "Tests the OpUndef instruction"));
5512         vector<CaseParameter>                   cases;
5513         de::Random                                              rnd                             (deStringHash(group->getName()));
5514         const int                                               numElements             = 100;
5515         vector<float>                                   positiveFloats  (numElements, 0);
5516         vector<float>                                   negativeFloats  (numElements, 0);
5517         const StringTemplate                    shaderTemplate  (
5518                 string(getComputeAsmShaderPreamble()) +
5519
5520                 "OpSource GLSL 430\n"
5521                 "OpName %main           \"main\"\n"
5522                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5523
5524                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5525
5526                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
5527                 "%uvec2     = OpTypeVector %u32 2\n"
5528                 "%fvec4     = OpTypeVector %f32 4\n"
5529                 "%fmat33    = OpTypeMatrix %fvec3 3\n"
5530                 "%image     = OpTypeImage %f32 2D 0 0 0 1 Unknown\n"
5531                 "%sampler   = OpTypeSampler\n"
5532                 "%simage    = OpTypeSampledImage %image\n"
5533                 "%const100  = OpConstant %u32 100\n"
5534                 "%uarr100   = OpTypeArray %i32 %const100\n"
5535                 "%struct    = OpTypeStruct %f32 %i32 %u32\n"
5536                 "%pointer   = OpTypePointer Function %i32\n"
5537                 + string(getComputeAsmInputOutputBuffer()) +
5538
5539                 "%id        = OpVariable %uvec3ptr Input\n"
5540                 "%zero      = OpConstant %i32 0\n"
5541
5542                 "%main      = OpFunction %void None %voidf\n"
5543                 "%label     = OpLabel\n"
5544
5545                 "%undef     = OpUndef ${TYPE}\n"
5546
5547                 "%idval     = OpLoad %uvec3 %id\n"
5548                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5549
5550                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5551                 "%inval     = OpLoad %f32 %inloc\n"
5552                 "%neg       = OpFNegate %f32 %inval\n"
5553                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5554                 "             OpStore %outloc %neg\n"
5555                 "             OpReturn\n"
5556                 "             OpFunctionEnd\n");
5557
5558         cases.push_back(CaseParameter("bool",                   "%bool"));
5559         cases.push_back(CaseParameter("sint32",                 "%i32"));
5560         cases.push_back(CaseParameter("uint32",                 "%u32"));
5561         cases.push_back(CaseParameter("float32",                "%f32"));
5562         cases.push_back(CaseParameter("vec4float32",    "%fvec4"));
5563         cases.push_back(CaseParameter("vec2uint32",             "%uvec2"));
5564         cases.push_back(CaseParameter("matrix",                 "%fmat33"));
5565         cases.push_back(CaseParameter("image",                  "%image"));
5566         cases.push_back(CaseParameter("sampler",                "%sampler"));
5567         cases.push_back(CaseParameter("sampledimage",   "%simage"));
5568         cases.push_back(CaseParameter("array",                  "%uarr100"));
5569         cases.push_back(CaseParameter("runtimearray",   "%f32arr"));
5570         cases.push_back(CaseParameter("struct",                 "%struct"));
5571         cases.push_back(CaseParameter("pointer",                "%pointer"));
5572
5573         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
5574
5575         for (size_t ndx = 0; ndx < numElements; ++ndx)
5576                 negativeFloats[ndx] = -positiveFloats[ndx];
5577
5578         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5579         {
5580                 map<string, string>             specializations;
5581                 ComputeShaderSpec               spec;
5582
5583                 specializations["TYPE"] = cases[caseNdx].param;
5584                 spec.assembly = shaderTemplate.specialize(specializations);
5585                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
5586                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
5587                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5588
5589                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5590         }
5591
5592                 return group.release();
5593 }
5594
5595 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
5596 tcu::TestCaseGroup* createFloat16OpConstantCompositeGroup (tcu::TestContext& testCtx)
5597 {
5598         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "Tests the OpConstantComposite instruction"));
5599         vector<CaseParameter>                   cases;
5600         de::Random                                              rnd                             (deStringHash(group->getName()));
5601         const int                                               numElements             = 100;
5602         vector<float>                                   positiveFloats  (numElements, 0);
5603         vector<float>                                   negativeFloats  (numElements, 0);
5604         const StringTemplate                    shaderTemplate  (
5605                 "OpCapability Shader\n"
5606                 "OpCapability Float16\n"
5607                 "OpMemoryModel Logical GLSL450\n"
5608                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5609                 "OpExecutionMode %main LocalSize 1 1 1\n"
5610                 "OpSource GLSL 430\n"
5611                 "OpName %main           \"main\"\n"
5612                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5613
5614                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5615
5616                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5617
5618                 "%id        = OpVariable %uvec3ptr Input\n"
5619                 "%zero      = OpConstant %i32 0\n"
5620                 "%f16       = OpTypeFloat 16\n"
5621                 "%c_f16_0   = OpConstant %f16 0.0\n"
5622                 "%c_f16_0_5 = OpConstant %f16 0.5\n"
5623                 "%c_f16_1   = OpConstant %f16 1.0\n"
5624                 "%v2f16     = OpTypeVector %f16 2\n"
5625                 "%v3f16     = OpTypeVector %f16 3\n"
5626                 "%v4f16     = OpTypeVector %f16 4\n"
5627
5628                 "${CONSTANT}\n"
5629
5630                 "%main      = OpFunction %void None %voidf\n"
5631                 "%label     = OpLabel\n"
5632                 "%idval     = OpLoad %uvec3 %id\n"
5633                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5634                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5635                 "%inval     = OpLoad %f32 %inloc\n"
5636                 "%neg       = OpFNegate %f32 %inval\n"
5637                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5638                 "             OpStore %outloc %neg\n"
5639                 "             OpReturn\n"
5640                 "             OpFunctionEnd\n");
5641
5642
5643         cases.push_back(CaseParameter("vector",                 "%const = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"));
5644         cases.push_back(CaseParameter("matrix",                 "%m3v3f16 = OpTypeMatrix %v3f16 3\n"
5645                                                                                                         "%vec = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"
5646                                                                                                         "%mat = OpConstantComposite %m3v3f16 %vec %vec %vec"));
5647         cases.push_back(CaseParameter("struct",                 "%m2v3f16 = OpTypeMatrix %v3f16 2\n"
5648                                                                                                         "%struct = OpTypeStruct %i32 %f16 %v3f16 %m2v3f16\n"
5649                                                                                                         "%vec = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"
5650                                                                                                         "%mat = OpConstantComposite %m2v3f16 %vec %vec\n"
5651                                                                                                         "%const = OpConstantComposite %struct %zero %c_f16_0_5 %vec %mat\n"));
5652         cases.push_back(CaseParameter("nested_struct",  "%st1 = OpTypeStruct %i32 %f16\n"
5653                                                                                                         "%st2 = OpTypeStruct %i32 %i32\n"
5654                                                                                                         "%struct = OpTypeStruct %st1 %st2\n"
5655                                                                                                         "%st1val = OpConstantComposite %st1 %zero %c_f16_0_5\n"
5656                                                                                                         "%st2val = OpConstantComposite %st2 %zero %zero\n"
5657                                                                                                         "%const = OpConstantComposite %struct %st1val %st2val"));
5658
5659         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
5660
5661         for (size_t ndx = 0; ndx < numElements; ++ndx)
5662                 negativeFloats[ndx] = -positiveFloats[ndx];
5663
5664         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5665         {
5666                 map<string, string>             specializations;
5667                 ComputeShaderSpec               spec;
5668
5669                 specializations["CONSTANT"] = cases[caseNdx].param;
5670                 spec.assembly = shaderTemplate.specialize(specializations);
5671                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
5672                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
5673                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5674                 spec.extensions.push_back("VK_KHR_16bit_storage");
5675
5676                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5677         }
5678
5679         return group.release();
5680 }
5681
5682 // IEEE-754 floating point numbers:
5683 // +--------+------+----------+-------------+
5684 // | binary | sign | exponent | significand |
5685 // +--------+------+----------+-------------+
5686 // | 16-bit |  1   |    5     |     10      |
5687 // +--------+------+----------+-------------+
5688 // | 32-bit |  1   |    8     |     23      |
5689 // +--------+------+----------+-------------+
5690 //
5691 // 16-bit floats:
5692 //
5693 // 0   000 00   00 0000 0001 (0x0001: 2e-24:         minimum positive denormalized)
5694 // 0   000 00   11 1111 1111 (0x03ff: 2e-14 - 2e-24: maximum positive denormalized)
5695 // 0   000 01   00 0000 0000 (0x0400: 2e-14:         minimum positive normalized)
5696 //
5697 // 0   000 00   00 0000 0000 (0x0000: +0)
5698 // 0   111 11   00 0000 0000 (0x7c00: +Inf)
5699 // 0   000 00   11 1111 0000 (0x03f0: +Denorm)
5700 // 0   000 01   00 0000 0001 (0x0401: +Norm)
5701 // 0   111 11   00 0000 1111 (0x7c0f: +SNaN)
5702 // 0   111 11   11 1111 0000 (0x7ff0: +QNaN)
5703
5704 // Generate and return 16-bit floats and their corresponding 32-bit values.
5705 //
5706 // The first 14 number pairs are manually picked, while the rest are randomly generated.
5707 // Expected count to be at least 14 (numPicks).
5708 vector<deFloat16> getFloat16s (de::Random& rnd, deUint32 count)
5709 {
5710         vector<deFloat16>       float16;
5711
5712         float16.reserve(count);
5713
5714         // Zero
5715         float16.push_back(deUint16(0x0000));
5716         float16.push_back(deUint16(0x8000));
5717         // Infinity
5718         float16.push_back(deUint16(0x7c00));
5719         float16.push_back(deUint16(0xfc00));
5720         // SNaN
5721         float16.push_back(deUint16(0x7c0f));
5722         float16.push_back(deUint16(0xfc0f));
5723         // QNaN
5724         float16.push_back(deUint16(0x7ff0));
5725         float16.push_back(deUint16(0xfff0));
5726
5727         // Denormalized
5728         float16.push_back(deUint16(0x03f0));
5729         float16.push_back(deUint16(0x83f0));
5730         // Normalized
5731         float16.push_back(deUint16(0x0401));
5732         float16.push_back(deUint16(0x8401));
5733         // Some normal number
5734         float16.push_back(deUint16(0x14cb));
5735         float16.push_back(deUint16(0x94cb));
5736
5737         const deUint32          numPicks        = static_cast<deUint32>(float16.size());
5738
5739         DE_ASSERT(count >= numPicks);
5740         count -= numPicks;
5741
5742         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
5743                 float16.push_back(rnd.getUint16());
5744
5745         return float16;
5746 }
5747
5748 const vector<deFloat16> squarize(const vector<deFloat16>& inData, const deUint32 argNo)
5749 {
5750         const size_t            inDataLength    = inData.size();
5751         vector<deFloat16>       result;
5752
5753         result.reserve(inDataLength * inDataLength);
5754
5755         if (argNo == 0)
5756         {
5757                 for (size_t numIdx = 0; numIdx < inDataLength; ++numIdx)
5758                         result.insert(result.end(), inData.begin(), inData.end());
5759         }
5760
5761         if (argNo == 1)
5762         {
5763                 for (size_t numIdx = 0; numIdx < inDataLength; ++numIdx)
5764                 {
5765                         const vector<deFloat16> tmp(inDataLength, inData[numIdx]);
5766
5767                         result.insert(result.end(), tmp.begin(), tmp.end());
5768                 }
5769         }
5770
5771         return result;
5772 }
5773
5774 const vector<deFloat16> squarizeVector(const vector<deFloat16>& inData, const deUint32 argNo)
5775 {
5776         vector<deFloat16>       vec;
5777         vector<deFloat16>       result;
5778
5779         // Create vectors. vec will contain each possible pair from inData
5780         {
5781                 const size_t    inDataLength    = inData.size();
5782
5783                 DE_ASSERT(inDataLength <= 64);
5784
5785                 vec.reserve(2 * inDataLength * inDataLength);
5786
5787                 for (size_t numIdxX = 0; numIdxX < inDataLength; ++numIdxX)
5788                 for (size_t numIdxY = 0; numIdxY < inDataLength; ++numIdxY)
5789                 {
5790                         vec.push_back(inData[numIdxX]);
5791                         vec.push_back(inData[numIdxY]);
5792                 }
5793         }
5794
5795         // Create vector pairs. result will contain each possible pair from vec
5796         {
5797                 const size_t    coordsPerVector = 2;
5798                 const size_t    vectorsCount    = vec.size() / coordsPerVector;
5799
5800                 result.reserve(coordsPerVector * vectorsCount * vectorsCount);
5801
5802                 if (argNo == 0)
5803                 {
5804                         for (size_t numIdxX = 0; numIdxX < vectorsCount; ++numIdxX)
5805                         for (size_t numIdxY = 0; numIdxY < vectorsCount; ++numIdxY)
5806                         {
5807                                 for (size_t coordNdx = 0; coordNdx < coordsPerVector; ++coordNdx)
5808                                         result.push_back(vec[coordsPerVector * numIdxY + coordNdx]);
5809                         }
5810                 }
5811
5812                 if (argNo == 1)
5813                 {
5814                         for (size_t numIdxX = 0; numIdxX < vectorsCount; ++numIdxX)
5815                         for (size_t numIdxY = 0; numIdxY < vectorsCount; ++numIdxY)
5816                         {
5817                                 for (size_t coordNdx = 0; coordNdx < coordsPerVector; ++coordNdx)
5818                                         result.push_back(vec[coordsPerVector * numIdxX + coordNdx]);
5819                         }
5820                 }
5821         }
5822
5823         return result;
5824 }
5825
5826 struct fp16isNan                        { bool operator()(const tcu::Float16 in1, const tcu::Float16)           { return in1.isNaN(); } };
5827 struct fp16isInf                        { bool operator()(const tcu::Float16 in1, const tcu::Float16)           { return in1.isInf(); } };
5828 struct fp16isEqual                      { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() == in2.asFloat(); } };
5829 struct fp16isUnequal            { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() != in2.asFloat(); } };
5830 struct fp16isLess                       { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() <  in2.asFloat(); } };
5831 struct fp16isGreater            { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() >  in2.asFloat(); } };
5832 struct fp16isLessOrEqual        { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() <= in2.asFloat(); } };
5833 struct fp16isGreaterOrEqual     { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() >= in2.asFloat(); } };
5834
5835 template <class TestedLogicalFunction, bool onlyTestFunc, bool unationModeAnd, bool nanSupported>
5836 bool compareFP16Logical (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
5837 {
5838         if (inputs.size() != 2 || outputAllocs.size() != 1)
5839                 return false;
5840
5841         vector<deUint8> input1Bytes;
5842         vector<deUint8> input2Bytes;
5843
5844         inputs[0].getBytes(input1Bytes);
5845         inputs[1].getBytes(input2Bytes);
5846
5847         const deUint32                  denormModesCount                        = 2;
5848         const deFloat16                 float16one                                      = tcu::Float16(1.0f).bits();
5849         const deFloat16                 float16zero                                     = tcu::Float16(0.0f).bits();
5850         const tcu::Float16              zero                                            = tcu::Float16::zero(1);
5851         const deFloat16* const  outputAsFP16                            = static_cast<deFloat16*>(outputAllocs[0]->getHostPtr());
5852         const deFloat16* const  input1AsFP16                            = reinterpret_cast<deFloat16* const>(&input1Bytes.front());
5853         const deFloat16* const  input2AsFP16                            = reinterpret_cast<deFloat16* const>(&input2Bytes.front());
5854         deUint32                                successfulRuns                          = denormModesCount;
5855         std::string                             results[denormModesCount];
5856         TestedLogicalFunction   testedLogicalFunction;
5857
5858         for (deUint32 denormMode = 0; denormMode < denormModesCount; denormMode++)
5859         {
5860                 const bool flushToZero = (denormMode == 1);
5861
5862                 for (size_t idx = 0; idx < input1Bytes.size() / sizeof(deFloat16); ++idx)
5863                 {
5864                         const tcu::Float16      f1pre                   = tcu::Float16(input1AsFP16[idx]);
5865                         const tcu::Float16      f2pre                   = tcu::Float16(input2AsFP16[idx]);
5866                         const tcu::Float16      f1                              = (flushToZero && f1pre.isDenorm()) ? zero : f1pre;
5867                         const tcu::Float16      f2                              = (flushToZero && f2pre.isDenorm()) ? zero : f2pre;
5868                         deFloat16                       expectedOutput  = float16zero;
5869
5870                         if (onlyTestFunc)
5871                         {
5872                                 if (testedLogicalFunction(f1, f2))
5873                                         expectedOutput = float16one;
5874                         }
5875                         else
5876                         {
5877                                 const bool      f1nan   = f1.isNaN();
5878                                 const bool      f2nan   = f2.isNaN();
5879
5880                                 // Skip NaN floats if not supported by implementation
5881                                 if (!nanSupported && (f1nan || f2nan))
5882                                         continue;
5883
5884                                 if (unationModeAnd)
5885                                 {
5886                                         const bool      ordered         = !f1nan && !f2nan;
5887
5888                                         if (ordered && testedLogicalFunction(f1, f2))
5889                                                 expectedOutput = float16one;
5890                                 }
5891                                 else
5892                                 {
5893                                         const bool      unordered       = f1nan || f2nan;
5894
5895                                         if (unordered || testedLogicalFunction(f1, f2))
5896                                                 expectedOutput = float16one;
5897                                 }
5898                         }
5899
5900                         if (outputAsFP16[idx] != expectedOutput)
5901                         {
5902                                 std::ostringstream str;
5903
5904                                 str << "ERROR: Sub-case #" << idx
5905                                         << " flushToZero:" << flushToZero
5906                                         << std::hex
5907                                         << " failed, inputs: 0x" << f1.bits()
5908                                         << ";0x" << f2.bits()
5909                                         << " output: 0x" << outputAsFP16[idx]
5910                                         << " expected output: 0x" << expectedOutput;
5911
5912                                 results[denormMode] = str.str();
5913
5914                                 successfulRuns--;
5915
5916                                 break;
5917                         }
5918                 }
5919         }
5920
5921         if (successfulRuns == 0)
5922                 for (deUint32 denormMode = 0; denormMode < denormModesCount; denormMode++)
5923                         log << TestLog::Message << results[denormMode] << TestLog::EndMessage;
5924
5925         return successfulRuns > 0;
5926 }
5927
5928 } // anonymous
5929
5930 tcu::TestCaseGroup* createOpSourceTests (tcu::TestContext& testCtx)
5931 {
5932         struct NameCodePair { string name, code; };
5933         RGBA                                                    defaultColors[4];
5934         de::MovePtr<tcu::TestCaseGroup> opSourceTests                   (new tcu::TestCaseGroup(testCtx, "opsource", "OpSource instruction"));
5935         const std::string                               opsourceGLSLWithFile    = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile ";
5936         map<string, string>                             fragments                               = passthruFragments();
5937         const NameCodePair                              tests[]                                 =
5938         {
5939                 {"unknown", "OpSource Unknown 321"},
5940                 {"essl", "OpSource ESSL 310"},
5941                 {"glsl", "OpSource GLSL 450"},
5942                 {"opencl_cpp", "OpSource OpenCL_CPP 120"},
5943                 {"opencl_c", "OpSource OpenCL_C 120"},
5944                 {"multiple", "OpSource GLSL 450\nOpSource GLSL 450"},
5945                 {"file", opsourceGLSLWithFile},
5946                 {"source", opsourceGLSLWithFile + "\"void main(){}\""},
5947                 // Longest possible source string: SPIR-V limits instructions to 65535
5948                 // words, of which the first 4 are opsourceGLSLWithFile; the rest will
5949                 // contain 65530 UTF8 characters (one word each) plus one last word
5950                 // containing 3 ASCII characters and \0.
5951                 {"longsource", opsourceGLSLWithFile + '"' + makeLongUTF8String(65530) + "ccc" + '"'}
5952         };
5953
5954         getDefaultColors(defaultColors);
5955         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
5956         {
5957                 fragments["debug"] = tests[testNdx].code;
5958                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
5959         }
5960
5961         return opSourceTests.release();
5962 }
5963
5964 tcu::TestCaseGroup* createOpSourceContinuedTests (tcu::TestContext& testCtx)
5965 {
5966         struct NameCodePair { string name, code; };
5967         RGBA                                                            defaultColors[4];
5968         de::MovePtr<tcu::TestCaseGroup>         opSourceTests           (new tcu::TestCaseGroup(testCtx, "opsourcecontinued", "OpSourceContinued instruction"));
5969         map<string, string>                                     fragments                       = passthruFragments();
5970         const std::string                                       opsource                        = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile \"void main(){}\"\n";
5971         const NameCodePair                                      tests[]                         =
5972         {
5973                 {"empty", opsource + "OpSourceContinued \"\""},
5974                 {"short", opsource + "OpSourceContinued \"abcde\""},
5975                 {"multiple", opsource + "OpSourceContinued \"abcde\"\nOpSourceContinued \"fghij\""},
5976                 // Longest possible source string: SPIR-V limits instructions to 65535
5977                 // words, of which the first one is OpSourceContinued/length; the rest
5978                 // will contain 65533 UTF8 characters (one word each) plus one last word
5979                 // containing 3 ASCII characters and \0.
5980                 {"long", opsource + "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\""}
5981         };
5982
5983         getDefaultColors(defaultColors);
5984         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
5985         {
5986                 fragments["debug"] = tests[testNdx].code;
5987                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
5988         }
5989
5990         return opSourceTests.release();
5991 }
5992 tcu::TestCaseGroup* createOpNoLineTests(tcu::TestContext& testCtx)
5993 {
5994         RGBA                                                             defaultColors[4];
5995         de::MovePtr<tcu::TestCaseGroup>          opLineTests             (new tcu::TestCaseGroup(testCtx, "opnoline", "OpNoLine instruction"));
5996         map<string, string>                                      fragments;
5997         getDefaultColors(defaultColors);
5998         fragments["debug"]                      =
5999                 "%name = OpString \"name\"\n";
6000
6001         fragments["pre_main"]   =
6002                 "OpNoLine\n"
6003                 "OpNoLine\n"
6004                 "OpLine %name 1 1\n"
6005                 "OpNoLine\n"
6006                 "OpLine %name 1 1\n"
6007                 "OpLine %name 1 1\n"
6008                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6009                 "OpNoLine\n"
6010                 "OpLine %name 1 1\n"
6011                 "OpNoLine\n"
6012                 "OpLine %name 1 1\n"
6013                 "OpLine %name 1 1\n"
6014                 "%second_param1 = OpFunctionParameter %v4f32\n"
6015                 "OpNoLine\n"
6016                 "OpNoLine\n"
6017                 "%label_secondfunction = OpLabel\n"
6018                 "OpNoLine\n"
6019                 "OpReturnValue %second_param1\n"
6020                 "OpFunctionEnd\n"
6021                 "OpNoLine\n"
6022                 "OpNoLine\n";
6023
6024         fragments["testfun"]            =
6025                 // A %test_code function that returns its argument unchanged.
6026                 "OpNoLine\n"
6027                 "OpNoLine\n"
6028                 "OpLine %name 1 1\n"
6029                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6030                 "OpNoLine\n"
6031                 "%param1 = OpFunctionParameter %v4f32\n"
6032                 "OpNoLine\n"
6033                 "OpNoLine\n"
6034                 "%label_testfun = OpLabel\n"
6035                 "OpNoLine\n"
6036                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6037                 "OpReturnValue %val1\n"
6038                 "OpFunctionEnd\n"
6039                 "OpLine %name 1 1\n"
6040                 "OpNoLine\n";
6041
6042         createTestsForAllStages("opnoline", defaultColors, defaultColors, fragments, opLineTests.get());
6043
6044         return opLineTests.release();
6045 }
6046
6047 tcu::TestCaseGroup* createOpModuleProcessedTests(tcu::TestContext& testCtx)
6048 {
6049         RGBA                                                            defaultColors[4];
6050         de::MovePtr<tcu::TestCaseGroup>         opModuleProcessedTests                  (new tcu::TestCaseGroup(testCtx, "opmoduleprocessed", "OpModuleProcessed instruction"));
6051         map<string, string>                                     fragments;
6052         std::vector<std::string>                        noExtensions;
6053         GraphicsResources                                       resources;
6054
6055         getDefaultColors(defaultColors);
6056         resources.verifyBinary = veryfiBinaryShader;
6057         resources.spirvVersion = SPIRV_VERSION_1_3;
6058
6059         fragments["moduleprocessed"]                                                    =
6060                 "OpModuleProcessed \"VULKAN CTS\"\n"
6061                 "OpModuleProcessed \"Negative values\"\n"
6062                 "OpModuleProcessed \"Date: 2017/09/21\"\n";
6063
6064         fragments["pre_main"]   =
6065                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6066                 "%second_param1 = OpFunctionParameter %v4f32\n"
6067                 "%label_secondfunction = OpLabel\n"
6068                 "OpReturnValue %second_param1\n"
6069                 "OpFunctionEnd\n";
6070
6071         fragments["testfun"]            =
6072                 // A %test_code function that returns its argument unchanged.
6073                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6074                 "%param1 = OpFunctionParameter %v4f32\n"
6075                 "%label_testfun = OpLabel\n"
6076                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6077                 "OpReturnValue %val1\n"
6078                 "OpFunctionEnd\n";
6079
6080         createTestsForAllStages ("opmoduleprocessed", defaultColors, defaultColors, fragments, resources, noExtensions, opModuleProcessedTests.get());
6081
6082         return opModuleProcessedTests.release();
6083 }
6084
6085
6086 tcu::TestCaseGroup* createOpLineTests(tcu::TestContext& testCtx)
6087 {
6088         RGBA                                                                                                    defaultColors[4];
6089         de::MovePtr<tcu::TestCaseGroup>                                                 opLineTests                     (new tcu::TestCaseGroup(testCtx, "opline", "OpLine instruction"));
6090         map<string, string>                                                                             fragments;
6091         std::vector<std::pair<std::string, std::string> >               problemStrings;
6092
6093         problemStrings.push_back(std::make_pair<std::string, std::string>("empty_name", ""));
6094         problemStrings.push_back(std::make_pair<std::string, std::string>("short_name", "short_name"));
6095         problemStrings.push_back(std::make_pair<std::string, std::string>("long_name", makeLongUTF8String(65530) + "ccc"));
6096         getDefaultColors(defaultColors);
6097
6098         fragments["debug"]                      =
6099                 "%other_name = OpString \"other_name\"\n";
6100
6101         fragments["pre_main"]   =
6102                 "OpLine %file_name 32 0\n"
6103                 "OpLine %file_name 32 32\n"
6104                 "OpLine %file_name 32 40\n"
6105                 "OpLine %other_name 32 40\n"
6106                 "OpLine %other_name 0 100\n"
6107                 "OpLine %other_name 0 4294967295\n"
6108                 "OpLine %other_name 4294967295 0\n"
6109                 "OpLine %other_name 32 40\n"
6110                 "OpLine %file_name 0 0\n"
6111                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6112                 "OpLine %file_name 1 0\n"
6113                 "%second_param1 = OpFunctionParameter %v4f32\n"
6114                 "OpLine %file_name 1 3\n"
6115                 "OpLine %file_name 1 2\n"
6116                 "%label_secondfunction = OpLabel\n"
6117                 "OpLine %file_name 0 2\n"
6118                 "OpReturnValue %second_param1\n"
6119                 "OpFunctionEnd\n"
6120                 "OpLine %file_name 0 2\n"
6121                 "OpLine %file_name 0 2\n";
6122
6123         fragments["testfun"]            =
6124                 // A %test_code function that returns its argument unchanged.
6125                 "OpLine %file_name 1 0\n"
6126                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6127                 "OpLine %file_name 16 330\n"
6128                 "%param1 = OpFunctionParameter %v4f32\n"
6129                 "OpLine %file_name 14 442\n"
6130                 "%label_testfun = OpLabel\n"
6131                 "OpLine %file_name 11 1024\n"
6132                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6133                 "OpLine %file_name 2 97\n"
6134                 "OpReturnValue %val1\n"
6135                 "OpFunctionEnd\n"
6136                 "OpLine %file_name 5 32\n";
6137
6138         for (size_t i = 0; i < problemStrings.size(); ++i)
6139         {
6140                 map<string, string> testFragments = fragments;
6141                 testFragments["debug"] += "%file_name = OpString \"" + problemStrings[i].second + "\"\n";
6142                 createTestsForAllStages(string("opline") + "_" + problemStrings[i].first, defaultColors, defaultColors, testFragments, opLineTests.get());
6143         }
6144
6145         return opLineTests.release();
6146 }
6147
6148 tcu::TestCaseGroup* createOpConstantNullTests(tcu::TestContext& testCtx)
6149 {
6150         de::MovePtr<tcu::TestCaseGroup> opConstantNullTests             (new tcu::TestCaseGroup(testCtx, "opconstantnull", "OpConstantNull instruction"));
6151         RGBA                                                    colors[4];
6152
6153
6154         const char                                              functionStart[] =
6155                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6156                 "%param1 = OpFunctionParameter %v4f32\n"
6157                 "%lbl    = OpLabel\n";
6158
6159         const char                                              functionEnd[]   =
6160                 "OpReturnValue %transformed_param\n"
6161                 "OpFunctionEnd\n";
6162
6163         struct NameConstantsCode
6164         {
6165                 string name;
6166                 string constants;
6167                 string code;
6168         };
6169
6170         NameConstantsCode tests[] =
6171         {
6172                 {
6173                         "vec4",
6174                         "%cnull = OpConstantNull %v4f32\n",
6175                         "%transformed_param = OpFAdd %v4f32 %param1 %cnull\n"
6176                 },
6177                 {
6178                         "float",
6179                         "%cnull = OpConstantNull %f32\n",
6180                         "%vp = OpVariable %fp_v4f32 Function\n"
6181                         "%v  = OpLoad %v4f32 %vp\n"
6182                         "%v0 = OpVectorInsertDynamic %v4f32 %v %cnull %c_i32_0\n"
6183                         "%v1 = OpVectorInsertDynamic %v4f32 %v0 %cnull %c_i32_1\n"
6184                         "%v2 = OpVectorInsertDynamic %v4f32 %v1 %cnull %c_i32_2\n"
6185                         "%v3 = OpVectorInsertDynamic %v4f32 %v2 %cnull %c_i32_3\n"
6186                         "%transformed_param = OpFAdd %v4f32 %param1 %v3\n"
6187                 },
6188                 {
6189                         "bool",
6190                         "%cnull             = OpConstantNull %bool\n",
6191                         "%v                 = OpVariable %fp_v4f32 Function\n"
6192                         "                     OpStore %v %param1\n"
6193                         "                     OpSelectionMerge %false_label None\n"
6194                         "                     OpBranchConditional %cnull %true_label %false_label\n"
6195                         "%true_label        = OpLabel\n"
6196                         "                     OpStore %v %c_v4f32_0_5_0_5_0_5_0_5\n"
6197                         "                     OpBranch %false_label\n"
6198                         "%false_label       = OpLabel\n"
6199                         "%transformed_param = OpLoad %v4f32 %v\n"
6200                 },
6201                 {
6202                         "i32",
6203                         "%cnull             = OpConstantNull %i32\n",
6204                         "%v                 = OpVariable %fp_v4f32 Function %c_v4f32_0_5_0_5_0_5_0_5\n"
6205                         "%b                 = OpIEqual %bool %cnull %c_i32_0\n"
6206                         "                     OpSelectionMerge %false_label None\n"
6207                         "                     OpBranchConditional %b %true_label %false_label\n"
6208                         "%true_label        = OpLabel\n"
6209                         "                     OpStore %v %param1\n"
6210                         "                     OpBranch %false_label\n"
6211                         "%false_label       = OpLabel\n"
6212                         "%transformed_param = OpLoad %v4f32 %v\n"
6213                 },
6214                 {
6215                         "struct",
6216                         "%stype             = OpTypeStruct %f32 %v4f32\n"
6217                         "%fp_stype          = OpTypePointer Function %stype\n"
6218                         "%cnull             = OpConstantNull %stype\n",
6219                         "%v                 = OpVariable %fp_stype Function %cnull\n"
6220                         "%f                 = OpAccessChain %fp_v4f32 %v %c_i32_1\n"
6221                         "%f_val             = OpLoad %v4f32 %f\n"
6222                         "%transformed_param = OpFAdd %v4f32 %param1 %f_val\n"
6223                 },
6224                 {
6225                         "array",
6226                         "%a4_v4f32          = OpTypeArray %v4f32 %c_u32_4\n"
6227                         "%fp_a4_v4f32       = OpTypePointer Function %a4_v4f32\n"
6228                         "%cnull             = OpConstantNull %a4_v4f32\n",
6229                         "%v                 = OpVariable %fp_a4_v4f32 Function %cnull\n"
6230                         "%f                 = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
6231                         "%f1                = OpAccessChain %fp_v4f32 %v %c_u32_1\n"
6232                         "%f2                = OpAccessChain %fp_v4f32 %v %c_u32_2\n"
6233                         "%f3                = OpAccessChain %fp_v4f32 %v %c_u32_3\n"
6234                         "%f_val             = OpLoad %v4f32 %f\n"
6235                         "%f1_val            = OpLoad %v4f32 %f1\n"
6236                         "%f2_val            = OpLoad %v4f32 %f2\n"
6237                         "%f3_val            = OpLoad %v4f32 %f3\n"
6238                         "%t0                = OpFAdd %v4f32 %param1 %f_val\n"
6239                         "%t1                = OpFAdd %v4f32 %t0 %f1_val\n"
6240                         "%t2                = OpFAdd %v4f32 %t1 %f2_val\n"
6241                         "%transformed_param = OpFAdd %v4f32 %t2 %f3_val\n"
6242                 },
6243                 {
6244                         "matrix",
6245                         "%mat4x4_f32        = OpTypeMatrix %v4f32 4\n"
6246                         "%cnull             = OpConstantNull %mat4x4_f32\n",
6247                         // Our null matrix * any vector should result in a zero vector.
6248                         "%v                 = OpVectorTimesMatrix %v4f32 %param1 %cnull\n"
6249                         "%transformed_param = OpFAdd %v4f32 %param1 %v\n"
6250                 }
6251         };
6252
6253         getHalfColorsFullAlpha(colors);
6254
6255         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
6256         {
6257                 map<string, string> fragments;
6258                 fragments["pre_main"] = tests[testNdx].constants;
6259                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
6260                 createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, opConstantNullTests.get());
6261         }
6262         return opConstantNullTests.release();
6263 }
6264 tcu::TestCaseGroup* createOpConstantCompositeTests(tcu::TestContext& testCtx)
6265 {
6266         de::MovePtr<tcu::TestCaseGroup> opConstantCompositeTests                (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "OpConstantComposite instruction"));
6267         RGBA                                                    inputColors[4];
6268         RGBA                                                    outputColors[4];
6269
6270
6271         const char                                              functionStart[]  =
6272                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6273                 "%param1 = OpFunctionParameter %v4f32\n"
6274                 "%lbl    = OpLabel\n";
6275
6276         const char                                              functionEnd[]           =
6277                 "OpReturnValue %transformed_param\n"
6278                 "OpFunctionEnd\n";
6279
6280         struct NameConstantsCode
6281         {
6282                 string name;
6283                 string constants;
6284                 string code;
6285         };
6286
6287         NameConstantsCode tests[] =
6288         {
6289                 {
6290                         "vec4",
6291
6292                         "%cval              = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0\n",
6293                         "%transformed_param = OpFAdd %v4f32 %param1 %cval\n"
6294                 },
6295                 {
6296                         "struct",
6297
6298                         "%stype             = OpTypeStruct %v4f32 %f32\n"
6299                         "%fp_stype          = OpTypePointer Function %stype\n"
6300                         "%f32_n_1           = OpConstant %f32 -1.0\n"
6301                         "%f32_1_5           = OpConstant %f32 !0x3fc00000\n" // +1.5
6302                         "%cvec              = OpConstantComposite %v4f32 %f32_1_5 %f32_1_5 %f32_1_5 %c_f32_1\n"
6303                         "%cval              = OpConstantComposite %stype %cvec %f32_n_1\n",
6304
6305                         "%v                 = OpVariable %fp_stype Function %cval\n"
6306                         "%vec_ptr           = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
6307                         "%f32_ptr           = OpAccessChain %fp_f32 %v %c_u32_1\n"
6308                         "%vec_val           = OpLoad %v4f32 %vec_ptr\n"
6309                         "%f32_val           = OpLoad %f32 %f32_ptr\n"
6310                         "%tmp1              = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_1 %f32_val\n" // vec4(-1)
6311                         "%tmp2              = OpFAdd %v4f32 %tmp1 %param1\n" // param1 + vec4(-1)
6312                         "%transformed_param = OpFAdd %v4f32 %tmp2 %vec_val\n" // param1 + vec4(-1) + vec4(1.5, 1.5, 1.5, 1.0)
6313                 },
6314                 {
6315                         // [1|0|0|0.5] [x] = x + 0.5
6316                         // [0|1|0|0.5] [y] = y + 0.5
6317                         // [0|0|1|0.5] [z] = z + 0.5
6318                         // [0|0|0|1  ] [1] = 1
6319                         "matrix",
6320
6321                         "%mat4x4_f32          = OpTypeMatrix %v4f32 4\n"
6322                         "%v4f32_1_0_0_0       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_0 %c_f32_0 %c_f32_0\n"
6323                         "%v4f32_0_1_0_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_1 %c_f32_0 %c_f32_0\n"
6324                         "%v4f32_0_0_1_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_1 %c_f32_0\n"
6325                         "%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"
6326                         "%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",
6327
6328                         "%transformed_param   = OpMatrixTimesVector %v4f32 %cval %param1\n"
6329                 },
6330                 {
6331                         "array",
6332
6333                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
6334                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
6335                         "%f32_n_1             = OpConstant %f32 -1.0\n"
6336                         "%f32_1_5             = OpConstant %f32 !0x3fc00000\n" // +1.5
6337                         "%carr                = OpConstantComposite %a4f32 %c_f32_0 %f32_n_1 %f32_1_5 %c_f32_0\n",
6338
6339                         "%v                   = OpVariable %fp_a4f32 Function %carr\n"
6340                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_0\n"
6341                         "%f1                  = OpAccessChain %fp_f32 %v %c_u32_1\n"
6342                         "%f2                  = OpAccessChain %fp_f32 %v %c_u32_2\n"
6343                         "%f3                  = OpAccessChain %fp_f32 %v %c_u32_3\n"
6344                         "%f_val               = OpLoad %f32 %f\n"
6345                         "%f1_val              = OpLoad %f32 %f1\n"
6346                         "%f2_val              = OpLoad %f32 %f2\n"
6347                         "%f3_val              = OpLoad %f32 %f3\n"
6348                         "%ftot1               = OpFAdd %f32 %f_val %f1_val\n"
6349                         "%ftot2               = OpFAdd %f32 %ftot1 %f2_val\n"
6350                         "%ftot3               = OpFAdd %f32 %ftot2 %f3_val\n"  // 0 - 1 + 1.5 + 0
6351                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %ftot3\n"
6352                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
6353                 },
6354                 {
6355                         //
6356                         // [
6357                         //   {
6358                         //      0.0,
6359                         //      [ 1.0, 1.0, 1.0, 1.0]
6360                         //   },
6361                         //   {
6362                         //      1.0,
6363                         //      [ 0.0, 0.5, 0.0, 0.0]
6364                         //   }, //     ^^^
6365                         //   {
6366                         //      0.0,
6367                         //      [ 1.0, 1.0, 1.0, 1.0]
6368                         //   }
6369                         // ]
6370                         "array_of_struct_of_array",
6371
6372                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
6373                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
6374                         "%stype               = OpTypeStruct %f32 %a4f32\n"
6375                         "%a3stype             = OpTypeArray %stype %c_u32_3\n"
6376                         "%fp_a3stype          = OpTypePointer Function %a3stype\n"
6377                         "%ca4f32_0            = OpConstantComposite %a4f32 %c_f32_0 %c_f32_0_5 %c_f32_0 %c_f32_0\n"
6378                         "%ca4f32_1            = OpConstantComposite %a4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
6379                         "%cstype1             = OpConstantComposite %stype %c_f32_0 %ca4f32_1\n"
6380                         "%cstype2             = OpConstantComposite %stype %c_f32_1 %ca4f32_0\n"
6381                         "%carr                = OpConstantComposite %a3stype %cstype1 %cstype2 %cstype1",
6382
6383                         "%v                   = OpVariable %fp_a3stype Function %carr\n"
6384                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_1 %c_u32_1 %c_u32_1\n"
6385                         "%f_l                 = OpLoad %f32 %f\n"
6386                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %f_l\n"
6387                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
6388                 }
6389         };
6390
6391         getHalfColorsFullAlpha(inputColors);
6392         outputColors[0] = RGBA(255, 255, 255, 255);
6393         outputColors[1] = RGBA(255, 127, 127, 255);
6394         outputColors[2] = RGBA(127, 255, 127, 255);
6395         outputColors[3] = RGBA(127, 127, 255, 255);
6396
6397         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
6398         {
6399                 map<string, string> fragments;
6400                 fragments["pre_main"] = tests[testNdx].constants;
6401                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
6402                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, opConstantCompositeTests.get());
6403         }
6404         return opConstantCompositeTests.release();
6405 }
6406
6407 tcu::TestCaseGroup* createSelectionBlockOrderTests(tcu::TestContext& testCtx)
6408 {
6409         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "selection_block_order", "Out-of-order blocks for selection"));
6410         RGBA                                                    inputColors[4];
6411         RGBA                                                    outputColors[4];
6412         map<string, string>                             fragments;
6413
6414         // vec4 test_code(vec4 param) {
6415         //   vec4 result = param;
6416         //   for (int i = 0; i < 4; ++i) {
6417         //     if (i == 0) result[i] = 0.;
6418         //     else        result[i] = 1. - result[i];
6419         //   }
6420         //   return result;
6421         // }
6422         const char                                              function[]                      =
6423                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6424                 "%param1    = OpFunctionParameter %v4f32\n"
6425                 "%lbl       = OpLabel\n"
6426                 "%iptr      = OpVariable %fp_i32 Function\n"
6427                 "%result    = OpVariable %fp_v4f32 Function\n"
6428                 "             OpStore %iptr %c_i32_0\n"
6429                 "             OpStore %result %param1\n"
6430                 "             OpBranch %loop\n"
6431
6432                 // Loop entry block.
6433                 "%loop      = OpLabel\n"
6434                 "%ival      = OpLoad %i32 %iptr\n"
6435                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6436                 "             OpLoopMerge %exit %if_entry None\n"
6437                 "             OpBranchConditional %lt_4 %if_entry %exit\n"
6438
6439                 // Merge block for loop.
6440                 "%exit      = OpLabel\n"
6441                 "%ret       = OpLoad %v4f32 %result\n"
6442                 "             OpReturnValue %ret\n"
6443
6444                 // If-statement entry block.
6445                 "%if_entry  = OpLabel\n"
6446                 "%loc       = OpAccessChain %fp_f32 %result %ival\n"
6447                 "%eq_0      = OpIEqual %bool %ival %c_i32_0\n"
6448                 "             OpSelectionMerge %if_exit None\n"
6449                 "             OpBranchConditional %eq_0 %if_true %if_false\n"
6450
6451                 // False branch for if-statement.
6452                 "%if_false  = OpLabel\n"
6453                 "%val       = OpLoad %f32 %loc\n"
6454                 "%sub       = OpFSub %f32 %c_f32_1 %val\n"
6455                 "             OpStore %loc %sub\n"
6456                 "             OpBranch %if_exit\n"
6457
6458                 // Merge block for if-statement.
6459                 "%if_exit   = OpLabel\n"
6460                 "%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
6461                 "             OpStore %iptr %ival_next\n"
6462                 "             OpBranch %loop\n"
6463
6464                 // True branch for if-statement.
6465                 "%if_true   = OpLabel\n"
6466                 "             OpStore %loc %c_f32_0\n"
6467                 "             OpBranch %if_exit\n"
6468
6469                 "             OpFunctionEnd\n";
6470
6471         fragments["testfun"]    = function;
6472
6473         inputColors[0]                  = RGBA(127, 127, 127, 0);
6474         inputColors[1]                  = RGBA(127, 0,   0,   0);
6475         inputColors[2]                  = RGBA(0,   127, 0,   0);
6476         inputColors[3]                  = RGBA(0,   0,   127, 0);
6477
6478         outputColors[0]                 = RGBA(0, 128, 128, 255);
6479         outputColors[1]                 = RGBA(0, 255, 255, 255);
6480         outputColors[2]                 = RGBA(0, 128, 255, 255);
6481         outputColors[3]                 = RGBA(0, 255, 128, 255);
6482
6483         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
6484
6485         return group.release();
6486 }
6487
6488 tcu::TestCaseGroup* createSwitchBlockOrderTests(tcu::TestContext& testCtx)
6489 {
6490         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "switch_block_order", "Out-of-order blocks for switch"));
6491         RGBA                                                    inputColors[4];
6492         RGBA                                                    outputColors[4];
6493         map<string, string>                             fragments;
6494
6495         const char                                              typesAndConstants[]     =
6496                 "%c_f32_p2  = OpConstant %f32 0.2\n"
6497                 "%c_f32_p4  = OpConstant %f32 0.4\n"
6498                 "%c_f32_p6  = OpConstant %f32 0.6\n"
6499                 "%c_f32_p8  = OpConstant %f32 0.8\n";
6500
6501         // vec4 test_code(vec4 param) {
6502         //   vec4 result = param;
6503         //   for (int i = 0; i < 4; ++i) {
6504         //     switch (i) {
6505         //       case 0: result[i] += .2; break;
6506         //       case 1: result[i] += .6; break;
6507         //       case 2: result[i] += .4; break;
6508         //       case 3: result[i] += .8; break;
6509         //       default: break; // unreachable
6510         //     }
6511         //   }
6512         //   return result;
6513         // }
6514         const char                                              function[]                      =
6515                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6516                 "%param1    = OpFunctionParameter %v4f32\n"
6517                 "%lbl       = OpLabel\n"
6518                 "%iptr      = OpVariable %fp_i32 Function\n"
6519                 "%result    = OpVariable %fp_v4f32 Function\n"
6520                 "             OpStore %iptr %c_i32_0\n"
6521                 "             OpStore %result %param1\n"
6522                 "             OpBranch %loop\n"
6523
6524                 // Loop entry block.
6525                 "%loop      = OpLabel\n"
6526                 "%ival      = OpLoad %i32 %iptr\n"
6527                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6528                 "             OpLoopMerge %exit %switch_exit None\n"
6529                 "             OpBranchConditional %lt_4 %switch_entry %exit\n"
6530
6531                 // Merge block for loop.
6532                 "%exit      = OpLabel\n"
6533                 "%ret       = OpLoad %v4f32 %result\n"
6534                 "             OpReturnValue %ret\n"
6535
6536                 // Switch-statement entry block.
6537                 "%switch_entry   = OpLabel\n"
6538                 "%loc            = OpAccessChain %fp_f32 %result %ival\n"
6539                 "%val            = OpLoad %f32 %loc\n"
6540                 "                  OpSelectionMerge %switch_exit None\n"
6541                 "                  OpSwitch %ival %switch_default 0 %case0 1 %case1 2 %case2 3 %case3\n"
6542
6543                 "%case2          = OpLabel\n"
6544                 "%addp4          = OpFAdd %f32 %val %c_f32_p4\n"
6545                 "                  OpStore %loc %addp4\n"
6546                 "                  OpBranch %switch_exit\n"
6547
6548                 "%switch_default = OpLabel\n"
6549                 "                  OpUnreachable\n"
6550
6551                 "%case3          = OpLabel\n"
6552                 "%addp8          = OpFAdd %f32 %val %c_f32_p8\n"
6553                 "                  OpStore %loc %addp8\n"
6554                 "                  OpBranch %switch_exit\n"
6555
6556                 "%case0          = OpLabel\n"
6557                 "%addp2          = OpFAdd %f32 %val %c_f32_p2\n"
6558                 "                  OpStore %loc %addp2\n"
6559                 "                  OpBranch %switch_exit\n"
6560
6561                 // Merge block for switch-statement.
6562                 "%switch_exit    = OpLabel\n"
6563                 "%ival_next      = OpIAdd %i32 %ival %c_i32_1\n"
6564                 "                  OpStore %iptr %ival_next\n"
6565                 "                  OpBranch %loop\n"
6566
6567                 "%case1          = OpLabel\n"
6568                 "%addp6          = OpFAdd %f32 %val %c_f32_p6\n"
6569                 "                  OpStore %loc %addp6\n"
6570                 "                  OpBranch %switch_exit\n"
6571
6572                 "                  OpFunctionEnd\n";
6573
6574         fragments["pre_main"]   = typesAndConstants;
6575         fragments["testfun"]    = function;
6576
6577         inputColors[0]                  = RGBA(127, 27,  127, 51);
6578         inputColors[1]                  = RGBA(127, 0,   0,   51);
6579         inputColors[2]                  = RGBA(0,   27,  0,   51);
6580         inputColors[3]                  = RGBA(0,   0,   127, 51);
6581
6582         outputColors[0]                 = RGBA(178, 180, 229, 255);
6583         outputColors[1]                 = RGBA(178, 153, 102, 255);
6584         outputColors[2]                 = RGBA(51,  180, 102, 255);
6585         outputColors[3]                 = RGBA(51,  153, 229, 255);
6586
6587         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
6588
6589         return group.release();
6590 }
6591
6592 tcu::TestCaseGroup* createDecorationGroupTests(tcu::TestContext& testCtx)
6593 {
6594         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "decoration_group", "Decoration group tests"));
6595         RGBA                                                    inputColors[4];
6596         RGBA                                                    outputColors[4];
6597         map<string, string>                             fragments;
6598
6599         const char                                              decorations[]           =
6600                 "OpDecorate %array_group         ArrayStride 4\n"
6601                 "OpDecorate %struct_member_group Offset 0\n"
6602                 "%array_group         = OpDecorationGroup\n"
6603                 "%struct_member_group = OpDecorationGroup\n"
6604
6605                 "OpDecorate %group1 RelaxedPrecision\n"
6606                 "OpDecorate %group3 RelaxedPrecision\n"
6607                 "OpDecorate %group3 Invariant\n"
6608                 "OpDecorate %group3 Restrict\n"
6609                 "%group0 = OpDecorationGroup\n"
6610                 "%group1 = OpDecorationGroup\n"
6611                 "%group3 = OpDecorationGroup\n";
6612
6613         const char                                              typesAndConstants[]     =
6614                 "%a3f32     = OpTypeArray %f32 %c_u32_3\n"
6615                 "%struct1   = OpTypeStruct %a3f32\n"
6616                 "%struct2   = OpTypeStruct %a3f32\n"
6617                 "%fp_struct1 = OpTypePointer Function %struct1\n"
6618                 "%fp_struct2 = OpTypePointer Function %struct2\n"
6619                 "%c_f32_2    = OpConstant %f32 2.\n"
6620                 "%c_f32_n2   = OpConstant %f32 -2.\n"
6621
6622                 "%c_a3f32_1 = OpConstantComposite %a3f32 %c_f32_1 %c_f32_2 %c_f32_1\n"
6623                 "%c_a3f32_2 = OpConstantComposite %a3f32 %c_f32_n1 %c_f32_n2 %c_f32_n1\n"
6624                 "%c_struct1 = OpConstantComposite %struct1 %c_a3f32_1\n"
6625                 "%c_struct2 = OpConstantComposite %struct2 %c_a3f32_2\n";
6626
6627         const char                                              function[]                      =
6628                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6629                 "%param     = OpFunctionParameter %v4f32\n"
6630                 "%entry     = OpLabel\n"
6631                 "%result    = OpVariable %fp_v4f32 Function\n"
6632                 "%v_struct1 = OpVariable %fp_struct1 Function\n"
6633                 "%v_struct2 = OpVariable %fp_struct2 Function\n"
6634                 "             OpStore %result %param\n"
6635                 "             OpStore %v_struct1 %c_struct1\n"
6636                 "             OpStore %v_struct2 %c_struct2\n"
6637                 "%ptr1      = OpAccessChain %fp_f32 %v_struct1 %c_i32_0 %c_i32_2\n"
6638                 "%val1      = OpLoad %f32 %ptr1\n"
6639                 "%ptr2      = OpAccessChain %fp_f32 %v_struct2 %c_i32_0 %c_i32_2\n"
6640                 "%val2      = OpLoad %f32 %ptr2\n"
6641                 "%addvalues = OpFAdd %f32 %val1 %val2\n"
6642                 "%ptr       = OpAccessChain %fp_f32 %result %c_i32_1\n"
6643                 "%val       = OpLoad %f32 %ptr\n"
6644                 "%addresult = OpFAdd %f32 %addvalues %val\n"
6645                 "             OpStore %ptr %addresult\n"
6646                 "%ret       = OpLoad %v4f32 %result\n"
6647                 "             OpReturnValue %ret\n"
6648                 "             OpFunctionEnd\n";
6649
6650         struct CaseNameDecoration
6651         {
6652                 string name;
6653                 string decoration;
6654         };
6655
6656         CaseNameDecoration tests[] =
6657         {
6658                 {
6659                         "same_decoration_group_on_multiple_types",
6660                         "OpGroupMemberDecorate %struct_member_group %struct1 0 %struct2 0\n"
6661                 },
6662                 {
6663                         "empty_decoration_group",
6664                         "OpGroupDecorate %group0      %a3f32\n"
6665                         "OpGroupDecorate %group0      %result\n"
6666                 },
6667                 {
6668                         "one_element_decoration_group",
6669                         "OpGroupDecorate %array_group %a3f32\n"
6670                 },
6671                 {
6672                         "multiple_elements_decoration_group",
6673                         "OpGroupDecorate %group3      %v_struct1\n"
6674                 },
6675                 {
6676                         "multiple_decoration_groups_on_same_variable",
6677                         "OpGroupDecorate %group0      %v_struct2\n"
6678                         "OpGroupDecorate %group1      %v_struct2\n"
6679                         "OpGroupDecorate %group3      %v_struct2\n"
6680                 },
6681                 {
6682                         "same_decoration_group_multiple_times",
6683                         "OpGroupDecorate %group1      %addvalues\n"
6684                         "OpGroupDecorate %group1      %addvalues\n"
6685                         "OpGroupDecorate %group1      %addvalues\n"
6686                 },
6687
6688         };
6689
6690         getHalfColorsFullAlpha(inputColors);
6691         getHalfColorsFullAlpha(outputColors);
6692
6693         for (size_t idx = 0; idx < (sizeof(tests) / sizeof(tests[0])); ++idx)
6694         {
6695                 fragments["decoration"] = decorations + tests[idx].decoration;
6696                 fragments["pre_main"]   = typesAndConstants;
6697                 fragments["testfun"]    = function;
6698
6699                 createTestsForAllStages(tests[idx].name, inputColors, outputColors, fragments, group.get());
6700         }
6701
6702         return group.release();
6703 }
6704
6705 struct SpecConstantTwoIntGraphicsCase
6706 {
6707         const char*             caseName;
6708         const char*             scDefinition0;
6709         const char*             scDefinition1;
6710         const char*             scResultType;
6711         const char*             scOperation;
6712         deInt32                 scActualValue0;
6713         deInt32                 scActualValue1;
6714         const char*             resultOperation;
6715         RGBA                    expectedColors[4];
6716         deInt32                 scActualValueLength;
6717
6718                                         SpecConstantTwoIntGraphicsCase (const char*             name,
6719                                                                                                         const char*             definition0,
6720                                                                                                         const char*             definition1,
6721                                                                                                         const char*             resultType,
6722                                                                                                         const char*             operation,
6723                                                                                                         const deInt32   value0,
6724                                                                                                         const deInt32   value1,
6725                                                                                                         const char*             resultOp,
6726                                                                                                         const RGBA              (&output)[4],
6727                                                                                                         const deInt32   valueLength = sizeof(deInt32))
6728                                                 : caseName                              (name)
6729                                                 , scDefinition0                 (definition0)
6730                                                 , scDefinition1                 (definition1)
6731                                                 , scResultType                  (resultType)
6732                                                 , scOperation                   (operation)
6733                                                 , scActualValue0                (value0)
6734                                                 , scActualValue1                (value1)
6735                                                 , resultOperation               (resultOp)
6736                                                 , scActualValueLength   (valueLength)
6737         {
6738                 expectedColors[0] = output[0];
6739                 expectedColors[1] = output[1];
6740                 expectedColors[2] = output[2];
6741                 expectedColors[3] = output[3];
6742         }
6743 };
6744
6745 tcu::TestCaseGroup* createSpecConstantTests (tcu::TestContext& testCtx)
6746 {
6747         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
6748         vector<SpecConstantTwoIntGraphicsCase>  cases;
6749         RGBA                                                    inputColors[4];
6750         RGBA                                                    outputColors0[4];
6751         RGBA                                                    outputColors1[4];
6752         RGBA                                                    outputColors2[4];
6753
6754         const deInt32                                   m1AsFloat16                     = 0xbc00; // -1(fp16) == 1 01111 0000000000 == 1011 1100 0000 0000
6755
6756         const char      decorations1[]                  =
6757                 "OpDecorate %sc_0  SpecId 0\n"
6758                 "OpDecorate %sc_1  SpecId 1\n";
6759
6760         const char      typesAndConstants1[]    =
6761                 "${OPTYPE_DEFINITIONS:opt}"
6762                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
6763                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
6764                 "%sc_op     = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n";
6765
6766         const char      function1[]                             =
6767                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6768                 "%param     = OpFunctionParameter %v4f32\n"
6769                 "%label     = OpLabel\n"
6770                 "%result    = OpVariable %fp_v4f32 Function\n"
6771                 "${TYPE_CONVERT:opt}"
6772                 "             OpStore %result %param\n"
6773                 "%gen       = ${GEN_RESULT}\n"
6774                 "%index     = OpIAdd %i32 %gen %c_i32_1\n"
6775                 "%loc       = OpAccessChain %fp_f32 %result %index\n"
6776                 "%val       = OpLoad %f32 %loc\n"
6777                 "%add       = OpFAdd %f32 %val %c_f32_0_5\n"
6778                 "             OpStore %loc %add\n"
6779                 "%ret       = OpLoad %v4f32 %result\n"
6780                 "             OpReturnValue %ret\n"
6781                 "             OpFunctionEnd\n";
6782
6783         inputColors[0] = RGBA(127, 127, 127, 255);
6784         inputColors[1] = RGBA(127, 0,   0,   255);
6785         inputColors[2] = RGBA(0,   127, 0,   255);
6786         inputColors[3] = RGBA(0,   0,   127, 255);
6787
6788         // Derived from inputColors[x] by adding 128 to inputColors[x][0].
6789         outputColors0[0] = RGBA(255, 127, 127, 255);
6790         outputColors0[1] = RGBA(255, 0,   0,   255);
6791         outputColors0[2] = RGBA(128, 127, 0,   255);
6792         outputColors0[3] = RGBA(128, 0,   127, 255);
6793
6794         // Derived from inputColors[x] by adding 128 to inputColors[x][1].
6795         outputColors1[0] = RGBA(127, 255, 127, 255);
6796         outputColors1[1] = RGBA(127, 128, 0,   255);
6797         outputColors1[2] = RGBA(0,   255, 0,   255);
6798         outputColors1[3] = RGBA(0,   128, 127, 255);
6799
6800         // Derived from inputColors[x] by adding 128 to inputColors[x][2].
6801         outputColors2[0] = RGBA(127, 127, 255, 255);
6802         outputColors2[1] = RGBA(127, 0,   128, 255);
6803         outputColors2[2] = RGBA(0,   127, 128, 255);
6804         outputColors2[3] = RGBA(0,   0,   255, 255);
6805
6806         const char addZeroToSc[]                = "OpIAdd %i32 %c_i32_0 %sc_op";
6807         const char addZeroToSc32[]              = "OpIAdd %i32 %c_i32_0 %sc_op32";
6808         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_op %c_i32_1 %c_i32_0";
6809         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_op %c_i32_0 %c_i32_1";
6810
6811         cases.push_back(SpecConstantTwoIntGraphicsCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                             19,             -20,    addZeroToSc,            outputColors0));
6812         cases.push_back(SpecConstantTwoIntGraphicsCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                             19,             20,             addZeroToSc,            outputColors0));
6813         cases.push_back(SpecConstantTwoIntGraphicsCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                             -1,             -1,             addZeroToSc,            outputColors2));
6814         cases.push_back(SpecConstantTwoIntGraphicsCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                             -126,   126,    addZeroToSc,            outputColors0));
6815         cases.push_back(SpecConstantTwoIntGraphicsCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                             126,    126,    addZeroToSc,            outputColors2));
6816         cases.push_back(SpecConstantTwoIntGraphicsCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
6817         cases.push_back(SpecConstantTwoIntGraphicsCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
6818         cases.push_back(SpecConstantTwoIntGraphicsCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                             1001,   500,    addZeroToSc,            outputColors2));
6819         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                             0x33,   0x0d,   addZeroToSc,            outputColors2));
6820         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                             0,              1,              addZeroToSc,            outputColors2));
6821         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                             0x2e,   0x2f,   addZeroToSc,            outputColors2));
6822         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                             2,              1,              addZeroToSc,            outputColors2));
6823         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                             -4,             2,              addZeroToSc,            outputColors0));
6824         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                             1,              0,              addZeroToSc,            outputColors2));
6825         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                             -20,    -10,    selectTrueUsingSc,      outputColors2));
6826         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                             10,             20,             selectTrueUsingSc,      outputColors2));
6827         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
6828         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                             10,             5,              selectTrueUsingSc,      outputColors2));
6829         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                             -10,    -10,    selectTrueUsingSc,      outputColors2));
6830         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                             50,             100,    selectTrueUsingSc,      outputColors2));
6831         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
6832         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                             10,             10,             selectTrueUsingSc,      outputColors2));
6833         cases.push_back(SpecConstantTwoIntGraphicsCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                             42,             24,             selectFalseUsingSc,     outputColors2));
6834         cases.push_back(SpecConstantTwoIntGraphicsCase("inotequal",                             " %i32 0",              " %i32 0",              "%bool",        "INotEqual            %sc_0 %sc_1",                             42,             24,             selectTrueUsingSc,      outputColors2));
6835         cases.push_back(SpecConstantTwoIntGraphicsCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
6836         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
6837         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
6838         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
6839         cases.push_back(SpecConstantTwoIntGraphicsCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                                   -1,             0,              addZeroToSc,            outputColors2));
6840         cases.push_back(SpecConstantTwoIntGraphicsCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                                   -2,             0,              addZeroToSc,            outputColors2));
6841         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                                   1,              0,              selectFalseUsingSc,     outputColors2));
6842         cases.push_back(SpecConstantTwoIntGraphicsCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %c_i32_0",    1,              1,              addZeroToSc,            outputColors2));
6843         cases.push_back(SpecConstantTwoIntGraphicsCase("sconvert",                              " %i32 0",              " %i32 0",              "%i16",         "SConvert             %sc_0",                                   -1,             0,              addZeroToSc32,          outputColors0));
6844         // -1082130432 stored as 32-bit two's complement is the binary representation of -1 as IEEE-754 Float
6845         cases.push_back(SpecConstantTwoIntGraphicsCase("fconvert",                              " %f32 0",              " %f32 0",              "%f64",         "FConvert             %sc_0",                                   -1082130432, 0, addZeroToSc32,          outputColors0));
6846         cases.push_back(SpecConstantTwoIntGraphicsCase("fconvert16",                    " %f16 0",              " %f16 0",              "%f32",         "FConvert             %sc_0",                                   m1AsFloat16, 0, addZeroToSc32,          outputColors0, sizeof(deFloat16)));
6847         // \todo[2015-12-1 antiagainst] OpQuantizeToF16
6848
6849         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
6850         {
6851                 map<string, string>                     specializations;
6852                 map<string, string>                     fragments;
6853                 SpecConstants                           specConstants;
6854                 vector<string>                          features;
6855                 PushConstants                           noPushConstants;
6856                 GraphicsResources                       noResources;
6857                 GraphicsInterfaces                      noInterfaces;
6858                 std::vector<std::string>        noExtensions;
6859
6860                 // Special SPIR-V code for SConvert-case
6861                 if (strcmp(cases[caseNdx].caseName, "sconvert") == 0)
6862                 {
6863                         features.push_back("shaderInt16");
6864                         fragments["capability"]                                 = "OpCapability Int16\n";                                       // Adds 16-bit integer capability
6865                         specializations["OPTYPE_DEFINITIONS"]   = "%i16 = OpTypeInt 16 1\n";                            // Adds 16-bit integer type
6866                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpSConvert %i32 %sc_op\n";        // Converts 16-bit integer to 32-bit integer
6867                 }
6868
6869                 // Special SPIR-V code for FConvert-case
6870                 if (strcmp(cases[caseNdx].caseName, "fconvert") == 0)
6871                 {
6872                         features.push_back("shaderFloat64");
6873                         fragments["capability"]                                 = "OpCapability Float64\n";                                     // Adds 64-bit float capability
6874                         specializations["OPTYPE_DEFINITIONS"]   = "%f64 = OpTypeFloat 64\n";                            // Adds 64-bit float type
6875                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpConvertFToS %i32 %sc_op\n";     // Converts 64-bit float to 32-bit integer
6876                 }
6877
6878                 // Special SPIR-V code for FConvert-case for 16-bit floats
6879                 if (strcmp(cases[caseNdx].caseName, "fconvert16") == 0)
6880                 {
6881                         fragments["capability"]                                 = "OpCapability Float16\n";                                     // Adds 16-bit float capability
6882                         specializations["OPTYPE_DEFINITIONS"]   = "%f16 = OpTypeFloat 16\n";                            // Adds 16-bit float type
6883                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpConvertFToS %i32 %sc_op\n";     // Converts 16-bit float to 32-bit integer
6884                 }
6885
6886                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
6887                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
6888                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
6889                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
6890                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
6891
6892                 fragments["decoration"]                         = tcu::StringTemplate(decorations1).specialize(specializations);
6893                 fragments["pre_main"]                           = tcu::StringTemplate(typesAndConstants1).specialize(specializations);
6894                 fragments["testfun"]                            = tcu::StringTemplate(function1).specialize(specializations);
6895
6896                 specConstants.append(&cases[caseNdx].scActualValue0, cases[caseNdx].scActualValueLength);
6897                 specConstants.append(&cases[caseNdx].scActualValue1, cases[caseNdx].scActualValueLength);
6898
6899                 createTestsForAllStages(
6900                         cases[caseNdx].caseName, inputColors, cases[caseNdx].expectedColors, fragments, specConstants,
6901                         noPushConstants, noResources, noInterfaces, noExtensions, features, VulkanFeatures(), group.get());
6902         }
6903
6904         const char      decorations2[]                  =
6905                 "OpDecorate %sc_0  SpecId 0\n"
6906                 "OpDecorate %sc_1  SpecId 1\n"
6907                 "OpDecorate %sc_2  SpecId 2\n";
6908
6909         const char      typesAndConstants2[]    =
6910                 "%vec3_0      = OpConstantComposite %v3i32 %c_i32_0 %c_i32_0 %c_i32_0\n"
6911                 "%vec3_undef  = OpUndef %v3i32\n"
6912
6913                 "%sc_0        = OpSpecConstant %i32 0\n"
6914                 "%sc_1        = OpSpecConstant %i32 0\n"
6915                 "%sc_2        = OpSpecConstant %i32 0\n"
6916                 "%sc_vec3_0   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_0        %vec3_0      0\n"                                                 // (sc_0, 0,    0)
6917                 "%sc_vec3_1   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_1        %vec3_0      1\n"                                                 // (0,    sc_1, 0)
6918                 "%sc_vec3_2   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_2        %vec3_0      2\n"                                                 // (0,    0,    sc_2)
6919                 "%sc_vec3_0_s = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_0   %vec3_undef  0          0xFFFFFFFF 2\n"   // (sc_0, ???,  0)
6920                 "%sc_vec3_1_s = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_1   %vec3_undef  0xFFFFFFFF 1          0\n"   // (???,  sc_1, 0)
6921                 "%sc_vec3_2_s = OpSpecConstantOp %v3i32 VectorShuffle    %vec3_undef  %sc_vec3_2   5          0xFFFFFFFF 5\n"   // (sc_2, ???,  sc_2)
6922                 "%sc_vec3_01  = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_0_s %sc_vec3_1_s 1 0 4\n"                                             // (0,    sc_0, sc_1)
6923                 "%sc_vec3_012 = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_01  %sc_vec3_2_s 5 1 2\n"                                             // (sc_2, sc_0, sc_1)
6924                 "%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              0\n"                                                 // sc_2
6925                 "%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              1\n"                                                 // sc_0
6926                 "%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              2\n"                                                 // sc_1
6927                 "%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"                                                              // (sc_2 - sc_0)
6928                 "%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n";                                                             // (sc_2 - sc_0) * sc_1
6929
6930         const char      function2[]                             =
6931                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6932                 "%param     = OpFunctionParameter %v4f32\n"
6933                 "%label     = OpLabel\n"
6934                 "%result    = OpVariable %fp_v4f32 Function\n"
6935                 "             OpStore %result %param\n"
6936                 "%loc       = OpAccessChain %fp_f32 %result %sc_final\n"
6937                 "%val       = OpLoad %f32 %loc\n"
6938                 "%add       = OpFAdd %f32 %val %c_f32_0_5\n"
6939                 "             OpStore %loc %add\n"
6940                 "%ret       = OpLoad %v4f32 %result\n"
6941                 "             OpReturnValue %ret\n"
6942                 "             OpFunctionEnd\n";
6943
6944         map<string, string>     fragments;
6945         SpecConstants           specConstants;
6946
6947         fragments["decoration"] = decorations2;
6948         fragments["pre_main"]   = typesAndConstants2;
6949         fragments["testfun"]    = function2;
6950
6951         specConstants.append<deInt32>(56789);
6952         specConstants.append<deInt32>(-2);
6953         specConstants.append<deInt32>(56788);
6954
6955         createTestsForAllStages("vector_related", inputColors, outputColors2, fragments, specConstants, group.get());
6956
6957         return group.release();
6958 }
6959
6960 tcu::TestCaseGroup* createOpPhiTests(tcu::TestContext& testCtx)
6961 {
6962         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
6963         RGBA                                                    inputColors[4];
6964         RGBA                                                    outputColors1[4];
6965         RGBA                                                    outputColors2[4];
6966         RGBA                                                    outputColors3[4];
6967         RGBA                                                    outputColors4[4];
6968         map<string, string>                             fragments1;
6969         map<string, string>                             fragments2;
6970         map<string, string>                             fragments3;
6971         map<string, string>                             fragments4;
6972         std::vector<std::string>                extensions4;
6973         GraphicsResources                               resources4;
6974         VulkanFeatures                                  vulkanFeatures4;
6975
6976         const char      typesAndConstants1[]    =
6977                 "%c_f32_p2  = OpConstant %f32 0.2\n"
6978                 "%c_f32_p4  = OpConstant %f32 0.4\n"
6979                 "%c_f32_p5  = OpConstant %f32 0.5\n"
6980                 "%c_f32_p8  = OpConstant %f32 0.8\n";
6981
6982         // vec4 test_code(vec4 param) {
6983         //   vec4 result = param;
6984         //   for (int i = 0; i < 4; ++i) {
6985         //     float operand;
6986         //     switch (i) {
6987         //       case 0: operand = .2; break;
6988         //       case 1: operand = .5; break;
6989         //       case 2: operand = .4; break;
6990         //       case 3: operand = .0; break;
6991         //       default: break; // unreachable
6992         //     }
6993         //     result[i] += operand;
6994         //   }
6995         //   return result;
6996         // }
6997         const char      function1[]                             =
6998                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6999                 "%param1    = OpFunctionParameter %v4f32\n"
7000                 "%lbl       = OpLabel\n"
7001                 "%iptr      = OpVariable %fp_i32 Function\n"
7002                 "%result    = OpVariable %fp_v4f32 Function\n"
7003                 "             OpStore %iptr %c_i32_0\n"
7004                 "             OpStore %result %param1\n"
7005                 "             OpBranch %loop\n"
7006
7007                 "%loop      = OpLabel\n"
7008                 "%ival      = OpLoad %i32 %iptr\n"
7009                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
7010                 "             OpLoopMerge %exit %phi None\n"
7011                 "             OpBranchConditional %lt_4 %entry %exit\n"
7012
7013                 "%entry     = OpLabel\n"
7014                 "%loc       = OpAccessChain %fp_f32 %result %ival\n"
7015                 "%val       = OpLoad %f32 %loc\n"
7016                 "             OpSelectionMerge %phi None\n"
7017                 "             OpSwitch %ival %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
7018
7019                 "%case0     = OpLabel\n"
7020                 "             OpBranch %phi\n"
7021                 "%case1     = OpLabel\n"
7022                 "             OpBranch %phi\n"
7023                 "%case2     = OpLabel\n"
7024                 "             OpBranch %phi\n"
7025                 "%case3     = OpLabel\n"
7026                 "             OpBranch %phi\n"
7027
7028                 "%default   = OpLabel\n"
7029                 "             OpUnreachable\n"
7030
7031                 "%phi       = OpLabel\n"
7032                 "%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
7033                 "%add       = OpFAdd %f32 %val %operand\n"
7034                 "             OpStore %loc %add\n"
7035                 "%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
7036                 "             OpStore %iptr %ival_next\n"
7037                 "             OpBranch %loop\n"
7038
7039                 "%exit      = OpLabel\n"
7040                 "%ret       = OpLoad %v4f32 %result\n"
7041                 "             OpReturnValue %ret\n"
7042
7043                 "             OpFunctionEnd\n";
7044
7045         fragments1["pre_main"]  = typesAndConstants1;
7046         fragments1["testfun"]   = function1;
7047
7048         getHalfColorsFullAlpha(inputColors);
7049
7050         outputColors1[0]                = RGBA(178, 255, 229, 255);
7051         outputColors1[1]                = RGBA(178, 127, 102, 255);
7052         outputColors1[2]                = RGBA(51,  255, 102, 255);
7053         outputColors1[3]                = RGBA(51,  127, 229, 255);
7054
7055         createTestsForAllStages("out_of_order", inputColors, outputColors1, fragments1, group.get());
7056
7057         const char      typesAndConstants2[]    =
7058                 "%c_f32_p2  = OpConstant %f32 0.2\n";
7059
7060         // Add .4 to the second element of the given parameter.
7061         const char      function2[]                             =
7062                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7063                 "%param     = OpFunctionParameter %v4f32\n"
7064                 "%entry     = OpLabel\n"
7065                 "%result    = OpVariable %fp_v4f32 Function\n"
7066                 "             OpStore %result %param\n"
7067                 "%loc       = OpAccessChain %fp_f32 %result %c_i32_1\n"
7068                 "%val       = OpLoad %f32 %loc\n"
7069                 "             OpBranch %phi\n"
7070
7071                 "%phi        = OpLabel\n"
7072                 "%step       = OpPhi %i32 %c_i32_0  %entry %step_next  %phi\n"
7073                 "%accum      = OpPhi %f32 %val      %entry %accum_next %phi\n"
7074                 "%step_next  = OpIAdd %i32 %step  %c_i32_1\n"
7075                 "%accum_next = OpFAdd %f32 %accum %c_f32_p2\n"
7076                 "%still_loop = OpSLessThan %bool %step %c_i32_2\n"
7077                 "              OpLoopMerge %exit %phi None\n"
7078                 "              OpBranchConditional %still_loop %phi %exit\n"
7079
7080                 "%exit       = OpLabel\n"
7081                 "              OpStore %loc %accum\n"
7082                 "%ret        = OpLoad %v4f32 %result\n"
7083                 "              OpReturnValue %ret\n"
7084
7085                 "              OpFunctionEnd\n";
7086
7087         fragments2["pre_main"]  = typesAndConstants2;
7088         fragments2["testfun"]   = function2;
7089
7090         outputColors2[0]                        = RGBA(127, 229, 127, 255);
7091         outputColors2[1]                        = RGBA(127, 102, 0,   255);
7092         outputColors2[2]                        = RGBA(0,   229, 0,   255);
7093         outputColors2[3]                        = RGBA(0,   102, 127, 255);
7094
7095         createTestsForAllStages("induction", inputColors, outputColors2, fragments2, group.get());
7096
7097         const char      typesAndConstants3[]    =
7098                 "%true      = OpConstantTrue %bool\n"
7099                 "%false     = OpConstantFalse %bool\n"
7100                 "%c_f32_p2  = OpConstant %f32 0.2\n";
7101
7102         // Swap the second and the third element of the given parameter.
7103         const char      function3[]                             =
7104                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7105                 "%param     = OpFunctionParameter %v4f32\n"
7106                 "%entry     = OpLabel\n"
7107                 "%result    = OpVariable %fp_v4f32 Function\n"
7108                 "             OpStore %result %param\n"
7109                 "%a_loc     = OpAccessChain %fp_f32 %result %c_i32_1\n"
7110                 "%a_init    = OpLoad %f32 %a_loc\n"
7111                 "%b_loc     = OpAccessChain %fp_f32 %result %c_i32_2\n"
7112                 "%b_init    = OpLoad %f32 %b_loc\n"
7113                 "             OpBranch %phi\n"
7114
7115                 "%phi        = OpLabel\n"
7116                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
7117                 "%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
7118                 "%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
7119                 "              OpLoopMerge %exit %phi None\n"
7120                 "              OpBranchConditional %still_loop %phi %exit\n"
7121
7122                 "%exit       = OpLabel\n"
7123                 "              OpStore %a_loc %a_next\n"
7124                 "              OpStore %b_loc %b_next\n"
7125                 "%ret        = OpLoad %v4f32 %result\n"
7126                 "              OpReturnValue %ret\n"
7127
7128                 "              OpFunctionEnd\n";
7129
7130         fragments3["pre_main"]  = typesAndConstants3;
7131         fragments3["testfun"]   = function3;
7132
7133         outputColors3[0]                        = RGBA(127, 127, 127, 255);
7134         outputColors3[1]                        = RGBA(127, 0,   0,   255);
7135         outputColors3[2]                        = RGBA(0,   0,   127, 255);
7136         outputColors3[3]                        = RGBA(0,   127, 0,   255);
7137
7138         createTestsForAllStages("swap", inputColors, outputColors3, fragments3, group.get());
7139
7140         const char      typesAndConstants4[]    =
7141                 "%f16        = OpTypeFloat 16\n"
7142                 "%v4f16      = OpTypeVector %f16 4\n"
7143                 "%fp_f16     = OpTypePointer Function %f16\n"
7144                 "%fp_v4f16   = OpTypePointer Function %v4f16\n"
7145                 "%true       = OpConstantTrue %bool\n"
7146                 "%false      = OpConstantFalse %bool\n"
7147                 "%c_f32_p2   = OpConstant %f32 0.2\n";
7148
7149         // Swap the second and the third element of the given parameter.
7150         const char      function4[]                             =
7151                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7152                 "%param      = OpFunctionParameter %v4f32\n"
7153                 "%entry      = OpLabel\n"
7154                 "%result     = OpVariable %fp_v4f16 Function\n"
7155                 "%param16    = OpFConvert %v4f16 %param\n"
7156                 "              OpStore %result %param16\n"
7157                 "%a_loc      = OpAccessChain %fp_f16 %result %c_i32_1\n"
7158                 "%a_init     = OpLoad %f16 %a_loc\n"
7159                 "%b_loc      = OpAccessChain %fp_f16 %result %c_i32_2\n"
7160                 "%b_init     = OpLoad %f16 %b_loc\n"
7161                 "              OpBranch %phi\n"
7162
7163                 "%phi        = OpLabel\n"
7164                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
7165                 "%a_next     = OpPhi %f16  %a_init %entry %b_next %phi\n"
7166                 "%b_next     = OpPhi %f16  %b_init %entry %a_next %phi\n"
7167                 "              OpLoopMerge %exit %phi None\n"
7168                 "              OpBranchConditional %still_loop %phi %exit\n"
7169
7170                 "%exit       = OpLabel\n"
7171                 "              OpStore %a_loc %a_next\n"
7172                 "              OpStore %b_loc %b_next\n"
7173                 "%ret16      = OpLoad %v4f16 %result\n"
7174                 "%ret        = OpFConvert %v4f32 %ret16\n"
7175                 "              OpReturnValue %ret\n"
7176
7177                 "              OpFunctionEnd\n";
7178
7179         fragments4["pre_main"]          = typesAndConstants4;
7180         fragments4["testfun"]           = function4;
7181         fragments4["capability"]        = "OpCapability StorageUniformBufferBlock16\n";
7182         fragments4["extension"]         = "OpExtension \"SPV_KHR_16bit_storage\"";
7183
7184         extensions4.push_back("VK_KHR_16bit_storage");
7185         extensions4.push_back("VK_KHR_shader_float16_int8");
7186
7187         vulkanFeatures4.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
7188         vulkanFeatures4.extFloat16Int8  = EXTFLOAT16INT8FEATURES_FLOAT16;
7189
7190         outputColors4[0]                        = RGBA(127, 127, 127, 255);
7191         outputColors4[1]                        = RGBA(127, 0,   0,   255);
7192         outputColors4[2]                        = RGBA(0,   0,   127, 255);
7193         outputColors4[3]                        = RGBA(0,   127, 0,   255);
7194
7195         createTestsForAllStages("swap16", inputColors, outputColors4, fragments4, resources4, extensions4, group.get(), vulkanFeatures4);
7196
7197         return group.release();
7198 }
7199
7200 tcu::TestCaseGroup* createNoContractionTests(tcu::TestContext& testCtx)
7201 {
7202         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
7203         RGBA                                                    inputColors[4];
7204         RGBA                                                    outputColors[4];
7205
7206         // With NoContraction, (1 + 2^-23) * (1 - 2^-23) - 1 should be conducted as a multiplication and an addition separately.
7207         // For the multiplication, the result is 1 - 2^-46, which is out of the precision range for 32-bit float. (32-bit float
7208         // only have 23-bit fraction.) So it will be rounded to 1. Or 0x1.fffffc. Then the final result is 0 or -0x1p-24.
7209         // On the contrary, the result will be 2^-46, which is a normalized number perfectly representable as 32-bit float.
7210         const char                                              constantsAndTypes[]      =
7211                 "%c_vec4_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_0 %c_f32_1\n"
7212                 "%c_vec4_1       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
7213                 "%c_f32_1pl2_23  = OpConstant %f32 0x1.000002p+0\n" // 1 + 2^-23
7214                 "%c_f32_1mi2_23  = OpConstant %f32 0x1.fffffcp-1\n" // 1 - 2^-23
7215                 "%c_f32_n1pn24   = OpConstant %f32 -0x1p-24\n";
7216
7217         const char                                              function[]       =
7218                 "%test_code      = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7219                 "%param          = OpFunctionParameter %v4f32\n"
7220                 "%label          = OpLabel\n"
7221                 "%var1           = OpVariable %fp_f32 Function %c_f32_1pl2_23\n"
7222                 "%var2           = OpVariable %fp_f32 Function\n"
7223                 "%red            = OpCompositeExtract %f32 %param 0\n"
7224                 "%plus_red       = OpFAdd %f32 %c_f32_1mi2_23 %red\n"
7225                 "                  OpStore %var2 %plus_red\n"
7226                 "%val1           = OpLoad %f32 %var1\n"
7227                 "%val2           = OpLoad %f32 %var2\n"
7228                 "%mul            = OpFMul %f32 %val1 %val2\n"
7229                 "%add            = OpFAdd %f32 %mul %c_f32_n1\n"
7230                 "%is0            = OpFOrdEqual %bool %add %c_f32_0\n"
7231                 "%isn1n24         = OpFOrdEqual %bool %add %c_f32_n1pn24\n"
7232                 "%success        = OpLogicalOr %bool %is0 %isn1n24\n"
7233                 "%v4success      = OpCompositeConstruct %v4bool %success %success %success %success\n"
7234                 "%ret            = OpSelect %v4f32 %v4success %c_vec4_0 %c_vec4_1\n"
7235                 "                  OpReturnValue %ret\n"
7236                 "                  OpFunctionEnd\n";
7237
7238         struct CaseNameDecoration
7239         {
7240                 string name;
7241                 string decoration;
7242         };
7243
7244
7245         CaseNameDecoration tests[] = {
7246                 {"multiplication",      "OpDecorate %mul NoContraction"},
7247                 {"addition",            "OpDecorate %add NoContraction"},
7248                 {"both",                        "OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"},
7249         };
7250
7251         getHalfColorsFullAlpha(inputColors);
7252
7253         for (deUint8 idx = 0; idx < 4; ++idx)
7254         {
7255                 inputColors[idx].setRed(0);
7256                 outputColors[idx] = RGBA(0, 0, 0, 255);
7257         }
7258
7259         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(CaseNameDecoration); ++testNdx)
7260         {
7261                 map<string, string> fragments;
7262
7263                 fragments["decoration"] = tests[testNdx].decoration;
7264                 fragments["pre_main"] = constantsAndTypes;
7265                 fragments["testfun"] = function;
7266
7267                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, group.get());
7268         }
7269
7270         return group.release();
7271 }
7272
7273 tcu::TestCaseGroup* createMemoryAccessTests(tcu::TestContext& testCtx)
7274 {
7275         de::MovePtr<tcu::TestCaseGroup> memoryAccessTests (new tcu::TestCaseGroup(testCtx, "opmemoryaccess", "Memory Semantics"));
7276         RGBA                                                    colors[4];
7277
7278         const char                                              constantsAndTypes[]      =
7279                 "%c_a2f32_1         = OpConstantComposite %a2f32 %c_f32_1 %c_f32_1\n"
7280                 "%fp_a2f32          = OpTypePointer Function %a2f32\n"
7281                 "%stype             = OpTypeStruct  %v4f32 %a2f32 %f32\n"
7282                 "%fp_stype          = OpTypePointer Function %stype\n";
7283
7284         const char                                              function[]       =
7285                 "%test_code         = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7286                 "%param1            = OpFunctionParameter %v4f32\n"
7287                 "%lbl               = OpLabel\n"
7288                 "%v1                = OpVariable %fp_v4f32 Function\n"
7289                 "%v2                = OpVariable %fp_a2f32 Function\n"
7290                 "%v3                = OpVariable %fp_f32 Function\n"
7291                 "%v                 = OpVariable %fp_stype Function\n"
7292                 "%vv                = OpVariable %fp_stype Function\n"
7293                 "%vvv               = OpVariable %fp_f32 Function\n"
7294
7295                 "                     OpStore %v1 %c_v4f32_1_1_1_1\n"
7296                 "                     OpStore %v2 %c_a2f32_1\n"
7297                 "                     OpStore %v3 %c_f32_1\n"
7298
7299                 "%p_v4f32          = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
7300                 "%p_a2f32          = OpAccessChain %fp_a2f32 %v %c_u32_1\n"
7301                 "%p_f32            = OpAccessChain %fp_f32 %v %c_u32_2\n"
7302                 "%v1_v             = OpLoad %v4f32 %v1 ${access_type}\n"
7303                 "%v2_v             = OpLoad %a2f32 %v2 ${access_type}\n"
7304                 "%v3_v             = OpLoad %f32 %v3 ${access_type}\n"
7305
7306                 "                    OpStore %p_v4f32 %v1_v ${access_type}\n"
7307                 "                    OpStore %p_a2f32 %v2_v ${access_type}\n"
7308                 "                    OpStore %p_f32 %v3_v ${access_type}\n"
7309
7310                 "                    OpCopyMemory %vv %v ${access_type}\n"
7311                 "                    OpCopyMemory %vvv %p_f32 ${access_type}\n"
7312
7313                 "%p_f32_2          = OpAccessChain %fp_f32 %vv %c_u32_2\n"
7314                 "%v_f32_2          = OpLoad %f32 %p_f32_2\n"
7315                 "%v_f32_3          = OpLoad %f32 %vvv\n"
7316
7317                 "%ret1             = OpVectorTimesScalar %v4f32 %param1 %v_f32_2\n"
7318                 "%ret2             = OpVectorTimesScalar %v4f32 %ret1 %v_f32_3\n"
7319                 "                    OpReturnValue %ret2\n"
7320                 "                    OpFunctionEnd\n";
7321
7322         struct NameMemoryAccess
7323         {
7324                 string name;
7325                 string accessType;
7326         };
7327
7328
7329         NameMemoryAccess tests[] =
7330         {
7331                 { "none", "" },
7332                 { "volatile", "Volatile" },
7333                 { "aligned",  "Aligned 1" },
7334                 { "volatile_aligned",  "Volatile|Aligned 1" },
7335                 { "nontemporal_aligned",  "Nontemporal|Aligned 1" },
7336                 { "volatile_nontemporal",  "Volatile|Nontemporal" },
7337                 { "volatile_nontermporal_aligned",  "Volatile|Nontemporal|Aligned 1" },
7338         };
7339
7340         getHalfColorsFullAlpha(colors);
7341
7342         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameMemoryAccess); ++testNdx)
7343         {
7344                 map<string, string> fragments;
7345                 map<string, string> memoryAccess;
7346                 memoryAccess["access_type"] = tests[testNdx].accessType;
7347
7348                 fragments["pre_main"] = constantsAndTypes;
7349                 fragments["testfun"] = tcu::StringTemplate(function).specialize(memoryAccess);
7350                 createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, memoryAccessTests.get());
7351         }
7352         return memoryAccessTests.release();
7353 }
7354 tcu::TestCaseGroup* createOpUndefTests(tcu::TestContext& testCtx)
7355 {
7356         de::MovePtr<tcu::TestCaseGroup>         opUndefTests             (new tcu::TestCaseGroup(testCtx, "opundef", "Test OpUndef"));
7357         RGBA                                                            defaultColors[4];
7358         map<string, string>                                     fragments;
7359         getDefaultColors(defaultColors);
7360
7361         // First, simple cases that don't do anything with the OpUndef result.
7362         struct NameCodePair { string name, decl, type; };
7363         const NameCodePair tests[] =
7364         {
7365                 {"bool", "", "%bool"},
7366                 {"vec2uint32", "", "%v2u32"},
7367                 {"image", "%type = OpTypeImage %f32 2D 0 0 0 1 Unknown", "%type"},
7368                 {"sampler", "%type = OpTypeSampler", "%type"},
7369                 {"sampledimage", "%img = OpTypeImage %f32 2D 0 0 0 1 Unknown\n" "%type = OpTypeSampledImage %img", "%type"},
7370                 {"pointer", "", "%fp_i32"},
7371                 {"runtimearray", "%type = OpTypeRuntimeArray %f32", "%type"},
7372                 {"array", "%c_u32_100 = OpConstant %u32 100\n" "%type = OpTypeArray %i32 %c_u32_100", "%type"},
7373                 {"struct", "%type = OpTypeStruct %f32 %i32 %u32", "%type"}};
7374         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
7375         {
7376                 fragments["undef_type"] = tests[testNdx].type;
7377                 fragments["testfun"] = StringTemplate(
7378                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7379                         "%param1 = OpFunctionParameter %v4f32\n"
7380                         "%label_testfun = OpLabel\n"
7381                         "%undef = OpUndef ${undef_type}\n"
7382                         "OpReturnValue %param1\n"
7383                         "OpFunctionEnd\n").specialize(fragments);
7384                 fragments["pre_main"] = tests[testNdx].decl;
7385                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opUndefTests.get());
7386         }
7387         fragments.clear();
7388
7389         fragments["testfun"] =
7390                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7391                 "%param1 = OpFunctionParameter %v4f32\n"
7392                 "%label_testfun = OpLabel\n"
7393                 "%undef = OpUndef %f32\n"
7394                 "%zero = OpFMul %f32 %undef %c_f32_0\n"
7395                 "%is_nan = OpIsNan %bool %zero\n" //OpUndef may result in NaN which may turn %zero into Nan.
7396                 "%actually_zero = OpSelect %f32 %is_nan %c_f32_0 %zero\n"
7397                 "%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7398                 "%b = OpFAdd %f32 %a %actually_zero\n"
7399                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %b %c_i32_0\n"
7400                 "OpReturnValue %ret\n"
7401                 "OpFunctionEnd\n";
7402
7403         createTestsForAllStages("float32", defaultColors, defaultColors, fragments, opUndefTests.get());
7404
7405         fragments["testfun"] =
7406                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7407                 "%param1 = OpFunctionParameter %v4f32\n"
7408                 "%label_testfun = OpLabel\n"
7409                 "%undef = OpUndef %i32\n"
7410                 "%zero = OpIMul %i32 %undef %c_i32_0\n"
7411                 "%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
7412                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
7413                 "OpReturnValue %ret\n"
7414                 "OpFunctionEnd\n";
7415
7416         createTestsForAllStages("sint32", defaultColors, defaultColors, fragments, opUndefTests.get());
7417
7418         fragments["testfun"] =
7419                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7420                 "%param1 = OpFunctionParameter %v4f32\n"
7421                 "%label_testfun = OpLabel\n"
7422                 "%undef = OpUndef %u32\n"
7423                 "%zero = OpIMul %u32 %undef %c_i32_0\n"
7424                 "%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
7425                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
7426                 "OpReturnValue %ret\n"
7427                 "OpFunctionEnd\n";
7428
7429         createTestsForAllStages("uint32", defaultColors, defaultColors, fragments, opUndefTests.get());
7430
7431         fragments["testfun"] =
7432                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7433                 "%param1 = OpFunctionParameter %v4f32\n"
7434                 "%label_testfun = OpLabel\n"
7435                 "%undef = OpUndef %v4f32\n"
7436                 "%vzero = OpVectorTimesScalar %v4f32 %undef %c_f32_0\n"
7437                 "%zero_0 = OpVectorExtractDynamic %f32 %vzero %c_i32_0\n"
7438                 "%zero_1 = OpVectorExtractDynamic %f32 %vzero %c_i32_1\n"
7439                 "%zero_2 = OpVectorExtractDynamic %f32 %vzero %c_i32_2\n"
7440                 "%zero_3 = OpVectorExtractDynamic %f32 %vzero %c_i32_3\n"
7441                 "%is_nan_0 = OpIsNan %bool %zero_0\n"
7442                 "%is_nan_1 = OpIsNan %bool %zero_1\n"
7443                 "%is_nan_2 = OpIsNan %bool %zero_2\n"
7444                 "%is_nan_3 = OpIsNan %bool %zero_3\n"
7445                 "%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
7446                 "%actually_zero_1 = OpSelect %f32 %is_nan_1 %c_f32_0 %zero_1\n"
7447                 "%actually_zero_2 = OpSelect %f32 %is_nan_2 %c_f32_0 %zero_2\n"
7448                 "%actually_zero_3 = OpSelect %f32 %is_nan_3 %c_f32_0 %zero_3\n"
7449                 "%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7450                 "%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
7451                 "%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
7452                 "%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
7453                 "%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
7454                 "%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
7455                 "%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
7456                 "%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
7457                 "%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
7458                 "%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
7459                 "%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
7460                 "%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
7461                 "OpReturnValue %ret\n"
7462                 "OpFunctionEnd\n";
7463
7464         createTestsForAllStages("vec4float32", defaultColors, defaultColors, fragments, opUndefTests.get());
7465
7466         fragments["pre_main"] =
7467                 "%m2x2f32 = OpTypeMatrix %v2f32 2\n";
7468         fragments["testfun"] =
7469                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7470                 "%param1 = OpFunctionParameter %v4f32\n"
7471                 "%label_testfun = OpLabel\n"
7472                 "%undef = OpUndef %m2x2f32\n"
7473                 "%mzero = OpMatrixTimesScalar %m2x2f32 %undef %c_f32_0\n"
7474                 "%zero_0 = OpCompositeExtract %f32 %mzero 0 0\n"
7475                 "%zero_1 = OpCompositeExtract %f32 %mzero 0 1\n"
7476                 "%zero_2 = OpCompositeExtract %f32 %mzero 1 0\n"
7477                 "%zero_3 = OpCompositeExtract %f32 %mzero 1 1\n"
7478                 "%is_nan_0 = OpIsNan %bool %zero_0\n"
7479                 "%is_nan_1 = OpIsNan %bool %zero_1\n"
7480                 "%is_nan_2 = OpIsNan %bool %zero_2\n"
7481                 "%is_nan_3 = OpIsNan %bool %zero_3\n"
7482                 "%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
7483                 "%actually_zero_1 = OpSelect %f32 %is_nan_1 %c_f32_0 %zero_1\n"
7484                 "%actually_zero_2 = OpSelect %f32 %is_nan_2 %c_f32_0 %zero_2\n"
7485                 "%actually_zero_3 = OpSelect %f32 %is_nan_3 %c_f32_0 %zero_3\n"
7486                 "%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7487                 "%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
7488                 "%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
7489                 "%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
7490                 "%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
7491                 "%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
7492                 "%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
7493                 "%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
7494                 "%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
7495                 "%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
7496                 "%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
7497                 "%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
7498                 "OpReturnValue %ret\n"
7499                 "OpFunctionEnd\n";
7500
7501         createTestsForAllStages("matrix", defaultColors, defaultColors, fragments, opUndefTests.get());
7502
7503         return opUndefTests.release();
7504 }
7505
7506 void createOpQuantizeSingleOptionTests(tcu::TestCaseGroup* testCtx)
7507 {
7508         const RGBA              inputColors[4]          =
7509         {
7510                 RGBA(0,         0,              0,              255),
7511                 RGBA(0,         0,              255,    255),
7512                 RGBA(0,         255,    0,              255),
7513                 RGBA(0,         255,    255,    255)
7514         };
7515
7516         const RGBA              expectedColors[4]       =
7517         {
7518                 RGBA(255,        0,              0,              255),
7519                 RGBA(255,        0,              0,              255),
7520                 RGBA(255,        0,              0,              255),
7521                 RGBA(255,        0,              0,              255)
7522         };
7523
7524         const struct SingleFP16Possibility
7525         {
7526                 const char* name;
7527                 const char* constant;  // Value to assign to %test_constant.
7528                 float           valueAsFloat;
7529                 const char* condition; // Must assign to %cond an expression that evaluates to true after %c = OpQuantizeToF16(%test_constant + 0).
7530         }                               tests[]                         =
7531         {
7532                 {
7533                         "negative",
7534                         "-0x1.3p1\n",
7535                         -constructNormalizedFloat(1, 0x300000),
7536                         "%cond = OpFOrdEqual %bool %c %test_constant\n"
7537                 }, // -19
7538                 {
7539                         "positive",
7540                         "0x1.0p7\n",
7541                         constructNormalizedFloat(7, 0x000000),
7542                         "%cond = OpFOrdEqual %bool %c %test_constant\n"
7543                 },  // +128
7544                 // SPIR-V requires that OpQuantizeToF16 flushes
7545                 // any numbers that would end up denormalized in F16 to zero.
7546                 {
7547                         "denorm",
7548                         "0x0.0006p-126\n",
7549                         std::ldexp(1.5f, -140),
7550                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7551                 },  // denorm
7552                 {
7553                         "negative_denorm",
7554                         "-0x0.0006p-126\n",
7555                         -std::ldexp(1.5f, -140),
7556                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7557                 }, // -denorm
7558                 {
7559                         "too_small",
7560                         "0x1.0p-16\n",
7561                         std::ldexp(1.0f, -16),
7562                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7563                 },     // too small positive
7564                 {
7565                         "negative_too_small",
7566                         "-0x1.0p-32\n",
7567                         -std::ldexp(1.0f, -32),
7568                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7569                 },      // too small negative
7570                 {
7571                         "negative_inf",
7572                         "-0x1.0p128\n",
7573                         -std::ldexp(1.0f, 128),
7574
7575                         "%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
7576                         "%inf = OpIsInf %bool %c\n"
7577                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7578                 },     // -inf to -inf
7579                 {
7580                         "inf",
7581                         "0x1.0p128\n",
7582                         std::ldexp(1.0f, 128),
7583
7584                         "%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
7585                         "%inf = OpIsInf %bool %c\n"
7586                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7587                 },     // +inf to +inf
7588                 {
7589                         "round_to_negative_inf",
7590                         "-0x1.0p32\n",
7591                         -std::ldexp(1.0f, 32),
7592
7593                         "%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
7594                         "%inf = OpIsInf %bool %c\n"
7595                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7596                 },     // round to -inf
7597                 {
7598                         "round_to_inf",
7599                         "0x1.0p16\n",
7600                         std::ldexp(1.0f, 16),
7601
7602                         "%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
7603                         "%inf = OpIsInf %bool %c\n"
7604                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7605                 },     // round to +inf
7606                 {
7607                         "nan",
7608                         "0x1.1p128\n",
7609                         std::numeric_limits<float>::quiet_NaN(),
7610
7611                         // Test for any NaN value, as NaNs are not preserved
7612                         "%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
7613                         "%cond = OpIsNan %bool %direct_quant\n"
7614                 }, // nan
7615                 {
7616                         "negative_nan",
7617                         "-0x1.0001p128\n",
7618                         std::numeric_limits<float>::quiet_NaN(),
7619
7620                         // Test for any NaN value, as NaNs are not preserved
7621                         "%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
7622                         "%cond = OpIsNan %bool %direct_quant\n"
7623                 } // -nan
7624         };
7625         const char*             constants                       =
7626                 "%test_constant = OpConstant %f32 ";  // The value will be test.constant.
7627
7628         StringTemplate  function                        (
7629                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7630                 "%param1        = OpFunctionParameter %v4f32\n"
7631                 "%label_testfun = OpLabel\n"
7632                 "%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7633                 "%b             = OpFAdd %f32 %test_constant %a\n"
7634                 "%c             = OpQuantizeToF16 %f32 %b\n"
7635                 "${condition}\n"
7636                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
7637                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
7638                 "                 OpReturnValue %retval\n"
7639                 "OpFunctionEnd\n"
7640         );
7641
7642         const char*             specDecorations         = "OpDecorate %test_constant SpecId 0\n";
7643         const char*             specConstants           =
7644                         "%test_constant = OpSpecConstant %f32 0.\n"
7645                         "%c             = OpSpecConstantOp %f32 QuantizeToF16 %test_constant\n";
7646
7647         StringTemplate  specConstantFunction(
7648                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7649                 "%param1        = OpFunctionParameter %v4f32\n"
7650                 "%label_testfun = OpLabel\n"
7651                 "${condition}\n"
7652                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
7653                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
7654                 "                 OpReturnValue %retval\n"
7655                 "OpFunctionEnd\n"
7656         );
7657
7658         for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
7659         {
7660                 map<string, string>                                                             codeSpecialization;
7661                 map<string, string>                                                             fragments;
7662                 codeSpecialization["condition"]                                 = tests[idx].condition;
7663                 fragments["testfun"]                                                    = function.specialize(codeSpecialization);
7664                 fragments["pre_main"]                                                   = string(constants) + tests[idx].constant + "\n";
7665                 createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
7666         }
7667
7668         for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
7669         {
7670                 map<string, string>                                                             codeSpecialization;
7671                 map<string, string>                                                             fragments;
7672                 SpecConstants                                                                   passConstants;
7673
7674                 codeSpecialization["condition"]                                 = tests[idx].condition;
7675                 fragments["testfun"]                                                    = specConstantFunction.specialize(codeSpecialization);
7676                 fragments["decoration"]                                                 = specDecorations;
7677                 fragments["pre_main"]                                                   = specConstants;
7678
7679                 passConstants.append<float>(tests[idx].valueAsFloat);
7680
7681                 createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
7682         }
7683 }
7684
7685 void createOpQuantizeTwoPossibilityTests(tcu::TestCaseGroup* testCtx)
7686 {
7687         RGBA inputColors[4] =  {
7688                 RGBA(0,         0,              0,              255),
7689                 RGBA(0,         0,              255,    255),
7690                 RGBA(0,         255,    0,              255),
7691                 RGBA(0,         255,    255,    255)
7692         };
7693
7694         RGBA expectedColors[4] =
7695         {
7696                 RGBA(255,        0,              0,              255),
7697                 RGBA(255,        0,              0,              255),
7698                 RGBA(255,        0,              0,              255),
7699                 RGBA(255,        0,              0,              255)
7700         };
7701
7702         struct DualFP16Possibility
7703         {
7704                 const char* name;
7705                 const char* input;
7706                 float           inputAsFloat;
7707                 const char* possibleOutput1;
7708                 const char* possibleOutput2;
7709         } tests[] = {
7710                 {
7711                         "positive_round_up_or_round_down",
7712                         "0x1.3003p8",
7713                         constructNormalizedFloat(8, 0x300300),
7714                         "0x1.304p8",
7715                         "0x1.3p8"
7716                 },
7717                 {
7718                         "negative_round_up_or_round_down",
7719                         "-0x1.6008p-7",
7720                         -constructNormalizedFloat(-7, 0x600800),
7721                         "-0x1.6p-7",
7722                         "-0x1.604p-7"
7723                 },
7724                 {
7725                         "carry_bit",
7726                         "0x1.01ep2",
7727                         constructNormalizedFloat(2, 0x01e000),
7728                         "0x1.01cp2",
7729                         "0x1.02p2"
7730                 },
7731                 {
7732                         "carry_to_exponent",
7733                         "0x1.ffep1",
7734                         constructNormalizedFloat(1, 0xffe000),
7735                         "0x1.ffcp1",
7736                         "0x1.0p2"
7737                 },
7738         };
7739         StringTemplate constants (
7740                 "%input_const = OpConstant %f32 ${input}\n"
7741                 "%possible_solution1 = OpConstant %f32 ${output1}\n"
7742                 "%possible_solution2 = OpConstant %f32 ${output2}\n"
7743                 );
7744
7745         StringTemplate specConstants (
7746                 "%input_const = OpSpecConstant %f32 0.\n"
7747                 "%possible_solution1 = OpConstant %f32 ${output1}\n"
7748                 "%possible_solution2 = OpConstant %f32 ${output2}\n"
7749         );
7750
7751         const char* specDecorations = "OpDecorate %input_const  SpecId 0\n";
7752
7753         const char* function  =
7754                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7755                 "%param1        = OpFunctionParameter %v4f32\n"
7756                 "%label_testfun = OpLabel\n"
7757                 "%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7758                 // For the purposes of this test we assume that 0.f will always get
7759                 // faithfully passed through the pipeline stages.
7760                 "%b             = OpFAdd %f32 %input_const %a\n"
7761                 "%c             = OpQuantizeToF16 %f32 %b\n"
7762                 "%eq_1          = OpFOrdEqual %bool %c %possible_solution1\n"
7763                 "%eq_2          = OpFOrdEqual %bool %c %possible_solution2\n"
7764                 "%cond          = OpLogicalOr %bool %eq_1 %eq_2\n"
7765                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
7766                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1"
7767                 "                 OpReturnValue %retval\n"
7768                 "OpFunctionEnd\n";
7769
7770         for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
7771                 map<string, string>                                                                     fragments;
7772                 map<string, string>                                                                     constantSpecialization;
7773
7774                 constantSpecialization["input"]                                         = tests[idx].input;
7775                 constantSpecialization["output1"]                                       = tests[idx].possibleOutput1;
7776                 constantSpecialization["output2"]                                       = tests[idx].possibleOutput2;
7777                 fragments["testfun"]                                                            = function;
7778                 fragments["pre_main"]                                                           = constants.specialize(constantSpecialization);
7779                 createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
7780         }
7781
7782         for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
7783                 map<string, string>                                                                     fragments;
7784                 map<string, string>                                                                     constantSpecialization;
7785                 SpecConstants                                                                           passConstants;
7786
7787                 constantSpecialization["output1"]                                       = tests[idx].possibleOutput1;
7788                 constantSpecialization["output2"]                                       = tests[idx].possibleOutput2;
7789                 fragments["testfun"]                                                            = function;
7790                 fragments["decoration"]                                                         = specDecorations;
7791                 fragments["pre_main"]                                                           = specConstants.specialize(constantSpecialization);
7792
7793                 passConstants.append<float>(tests[idx].inputAsFloat);
7794
7795                 createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
7796         }
7797 }
7798
7799 tcu::TestCaseGroup* createOpQuantizeTests(tcu::TestContext& testCtx)
7800 {
7801         de::MovePtr<tcu::TestCaseGroup> opQuantizeTests (new tcu::TestCaseGroup(testCtx, "opquantize", "Test OpQuantizeToF16"));
7802         createOpQuantizeSingleOptionTests(opQuantizeTests.get());
7803         createOpQuantizeTwoPossibilityTests(opQuantizeTests.get());
7804         return opQuantizeTests.release();
7805 }
7806
7807 struct ShaderPermutation
7808 {
7809         deUint8 vertexPermutation;
7810         deUint8 geometryPermutation;
7811         deUint8 tesscPermutation;
7812         deUint8 tessePermutation;
7813         deUint8 fragmentPermutation;
7814 };
7815
7816 ShaderPermutation getShaderPermutation(deUint8 inputValue)
7817 {
7818         ShaderPermutation       permutation =
7819         {
7820                 static_cast<deUint8>(inputValue & 0x10? 1u: 0u),
7821                 static_cast<deUint8>(inputValue & 0x08? 1u: 0u),
7822                 static_cast<deUint8>(inputValue & 0x04? 1u: 0u),
7823                 static_cast<deUint8>(inputValue & 0x02? 1u: 0u),
7824                 static_cast<deUint8>(inputValue & 0x01? 1u: 0u)
7825         };
7826         return permutation;
7827 }
7828
7829 tcu::TestCaseGroup* createModuleTests(tcu::TestContext& testCtx)
7830 {
7831         RGBA                                                            defaultColors[4];
7832         RGBA                                                            invertedColors[4];
7833         de::MovePtr<tcu::TestCaseGroup>         moduleTests                     (new tcu::TestCaseGroup(testCtx, "module", "Multiple entry points into shaders"));
7834
7835         const ShaderElement                                     combinedPipeline[]      =
7836         {
7837                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
7838                 ShaderElement("module", "main", VK_SHADER_STAGE_GEOMETRY_BIT),
7839                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
7840                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
7841                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
7842         };
7843
7844         getDefaultColors(defaultColors);
7845         getInvertedDefaultColors(invertedColors);
7846         addFunctionCaseWithPrograms<InstanceContext>(
7847                         moduleTests.get(), "same_module", "", createCombinedModule, runAndVerifyDefaultPipeline,
7848                         createInstanceContext(combinedPipeline, map<string, string>()));
7849
7850         const char* numbers[] =
7851         {
7852                 "1", "2"
7853         };
7854
7855         for (deInt8 idx = 0; idx < 32; ++idx)
7856         {
7857                 ShaderPermutation                       permutation             = getShaderPermutation(idx);
7858                 string                                          name                    = string("vert") + numbers[permutation.vertexPermutation] + "_geom" + numbers[permutation.geometryPermutation] + "_tessc" + numbers[permutation.tesscPermutation] + "_tesse" + numbers[permutation.tessePermutation] + "_frag" + numbers[permutation.fragmentPermutation];
7859                 const ShaderElement                     pipeline[]              =
7860                 {
7861                         ShaderElement("vert",   string("vert") +        numbers[permutation.vertexPermutation],         VK_SHADER_STAGE_VERTEX_BIT),
7862                         ShaderElement("geom",   string("geom") +        numbers[permutation.geometryPermutation],       VK_SHADER_STAGE_GEOMETRY_BIT),
7863                         ShaderElement("tessc",  string("tessc") +       numbers[permutation.tesscPermutation],          VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
7864                         ShaderElement("tesse",  string("tesse") +       numbers[permutation.tessePermutation],          VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
7865                         ShaderElement("frag",   string("frag") +        numbers[permutation.fragmentPermutation],       VK_SHADER_STAGE_FRAGMENT_BIT)
7866                 };
7867
7868                 // If there are an even number of swaps, then it should be no-op.
7869                 // If there are an odd number, the color should be flipped.
7870                 if ((permutation.vertexPermutation + permutation.geometryPermutation + permutation.tesscPermutation + permutation.tessePermutation + permutation.fragmentPermutation) % 2 == 0)
7871                 {
7872                         addFunctionCaseWithPrograms<InstanceContext>(
7873                                         moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline,
7874                                         createInstanceContext(pipeline, defaultColors, defaultColors, map<string, string>()));
7875                 }
7876                 else
7877                 {
7878                         addFunctionCaseWithPrograms<InstanceContext>(
7879                                         moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline,
7880                                         createInstanceContext(pipeline, defaultColors, invertedColors, map<string, string>()));
7881                 }
7882         }
7883         return moduleTests.release();
7884 }
7885
7886 tcu::TestCaseGroup* createLoopTests(tcu::TestContext& testCtx)
7887 {
7888         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "loop", "Looping control flow"));
7889         RGBA defaultColors[4];
7890         getDefaultColors(defaultColors);
7891         map<string, string> fragments;
7892         fragments["pre_main"] =
7893                 "%c_f32_5 = OpConstant %f32 5.\n";
7894
7895         // A loop with a single block. The Continue Target is the loop block
7896         // itself. In SPIR-V terms, the "loop construct" contains no blocks at all
7897         // -- the "continue construct" forms the entire loop.
7898         fragments["testfun"] =
7899                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7900                 "%param1 = OpFunctionParameter %v4f32\n"
7901
7902                 "%entry = OpLabel\n"
7903                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7904                 "OpBranch %loop\n"
7905
7906                 ";adds and subtracts 1.0 to %val in alternate iterations\n"
7907                 "%loop = OpLabel\n"
7908                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
7909                 "%delta = OpPhi %f32 %c_f32_1 %entry %minus_delta %loop\n"
7910                 "%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
7911                 "%val = OpFAdd %f32 %val1 %delta\n"
7912                 "%minus_delta = OpFSub %f32 %c_f32_0 %delta\n"
7913                 "%count__ = OpISub %i32 %count %c_i32_1\n"
7914                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
7915                 "OpLoopMerge %exit %loop None\n"
7916                 "OpBranchConditional %again %loop %exit\n"
7917
7918                 "%exit = OpLabel\n"
7919                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
7920                 "OpReturnValue %result\n"
7921
7922                 "OpFunctionEnd\n";
7923
7924         createTestsForAllStages("single_block", defaultColors, defaultColors, fragments, testGroup.get());
7925
7926         // Body comprised of multiple basic blocks.
7927         const StringTemplate multiBlock(
7928                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7929                 "%param1 = OpFunctionParameter %v4f32\n"
7930
7931                 "%entry = OpLabel\n"
7932                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7933                 "OpBranch %loop\n"
7934
7935                 ";adds and subtracts 1.0 to %val in alternate iterations\n"
7936                 "%loop = OpLabel\n"
7937                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %gather\n"
7938                 "%delta = OpPhi %f32 %c_f32_1 %entry %delta_next %gather\n"
7939                 "%val1 = OpPhi %f32 %val0 %entry %val %gather\n"
7940                 // There are several possibilities for the Continue Target below.  Each
7941                 // will be specialized into a separate test case.
7942                 "OpLoopMerge %exit ${continue_target} None\n"
7943                 "OpBranch %if\n"
7944
7945                 "%if = OpLabel\n"
7946                 ";delta_next = (delta > 0) ? -1 : 1;\n"
7947                 "%gt0 = OpFOrdGreaterThan %bool %delta %c_f32_0\n"
7948                 "OpSelectionMerge %gather DontFlatten\n"
7949                 "OpBranchConditional %gt0 %even %odd ;tells us if %count is even or odd\n"
7950
7951                 "%odd = OpLabel\n"
7952                 "OpBranch %gather\n"
7953
7954                 "%even = OpLabel\n"
7955                 "OpBranch %gather\n"
7956
7957                 "%gather = OpLabel\n"
7958                 "%delta_next = OpPhi %f32 %c_f32_n1 %even %c_f32_1 %odd\n"
7959                 "%val = OpFAdd %f32 %val1 %delta\n"
7960                 "%count__ = OpISub %i32 %count %c_i32_1\n"
7961                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
7962                 "OpBranchConditional %again %loop %exit\n"
7963
7964                 "%exit = OpLabel\n"
7965                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
7966                 "OpReturnValue %result\n"
7967
7968                 "OpFunctionEnd\n");
7969
7970         map<string, string> continue_target;
7971
7972         // The Continue Target is the loop block itself.
7973         continue_target["continue_target"] = "%loop";
7974         fragments["testfun"] = multiBlock.specialize(continue_target);
7975         createTestsForAllStages("multi_block_continue_construct", defaultColors, defaultColors, fragments, testGroup.get());
7976
7977         // The Continue Target is at the end of the loop.
7978         continue_target["continue_target"] = "%gather";
7979         fragments["testfun"] = multiBlock.specialize(continue_target);
7980         createTestsForAllStages("multi_block_loop_construct", defaultColors, defaultColors, fragments, testGroup.get());
7981
7982         // A loop with continue statement.
7983         fragments["testfun"] =
7984                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7985                 "%param1 = OpFunctionParameter %v4f32\n"
7986
7987                 "%entry = OpLabel\n"
7988                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7989                 "OpBranch %loop\n"
7990
7991                 ";adds 4, 3, and 1 to %val0 (skips 2)\n"
7992                 "%loop = OpLabel\n"
7993                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
7994                 "%val1 = OpPhi %f32 %val0 %entry %val %continue\n"
7995                 "OpLoopMerge %exit %continue None\n"
7996                 "OpBranch %if\n"
7997
7998                 "%if = OpLabel\n"
7999                 ";skip if %count==2\n"
8000                 "%eq2 = OpIEqual %bool %count %c_i32_2\n"
8001                 "OpSelectionMerge %continue DontFlatten\n"
8002                 "OpBranchConditional %eq2 %continue %body\n"
8003
8004                 "%body = OpLabel\n"
8005                 "%fcount = OpConvertSToF %f32 %count\n"
8006                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8007                 "OpBranch %continue\n"
8008
8009                 "%continue = OpLabel\n"
8010                 "%val = OpPhi %f32 %val2 %body %val1 %if\n"
8011                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8012                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8013                 "OpBranchConditional %again %loop %exit\n"
8014
8015                 "%exit = OpLabel\n"
8016                 "%same = OpFSub %f32 %val %c_f32_8\n"
8017                 "%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8018                 "OpReturnValue %result\n"
8019                 "OpFunctionEnd\n";
8020         createTestsForAllStages("continue", defaultColors, defaultColors, fragments, testGroup.get());
8021
8022         // A loop with break.
8023         fragments["testfun"] =
8024                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8025                 "%param1 = OpFunctionParameter %v4f32\n"
8026
8027                 "%entry = OpLabel\n"
8028                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8029                 "%dot = OpDot %f32 %param1 %param1\n"
8030                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8031                 "%zero = OpConvertFToU %u32 %div\n"
8032                 "%two = OpIAdd %i32 %zero %c_i32_2\n"
8033                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8034                 "OpBranch %loop\n"
8035
8036                 ";adds 4 and 3 to %val0 (exits early)\n"
8037                 "%loop = OpLabel\n"
8038                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8039                 "%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
8040                 "OpLoopMerge %exit %continue None\n"
8041                 "OpBranch %if\n"
8042
8043                 "%if = OpLabel\n"
8044                 ";end loop if %count==%two\n"
8045                 "%above2 = OpSGreaterThan %bool %count %two\n"
8046                 "OpSelectionMerge %continue DontFlatten\n"
8047                 "OpBranchConditional %above2 %body %exit\n"
8048
8049                 "%body = OpLabel\n"
8050                 "%fcount = OpConvertSToF %f32 %count\n"
8051                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8052                 "OpBranch %continue\n"
8053
8054                 "%continue = OpLabel\n"
8055                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8056                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8057                 "OpBranchConditional %again %loop %exit\n"
8058
8059                 "%exit = OpLabel\n"
8060                 "%val_post = OpPhi %f32 %val2 %continue %val1 %if\n"
8061                 "%same = OpFSub %f32 %val_post %c_f32_7\n"
8062                 "%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8063                 "OpReturnValue %result\n"
8064                 "OpFunctionEnd\n";
8065         createTestsForAllStages("break", defaultColors, defaultColors, fragments, testGroup.get());
8066
8067         // A loop with return.
8068         fragments["testfun"] =
8069                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8070                 "%param1 = OpFunctionParameter %v4f32\n"
8071
8072                 "%entry = OpLabel\n"
8073                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8074                 "%dot = OpDot %f32 %param1 %param1\n"
8075                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8076                 "%zero = OpConvertFToU %u32 %div\n"
8077                 "%two = OpIAdd %i32 %zero %c_i32_2\n"
8078                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8079                 "OpBranch %loop\n"
8080
8081                 ";returns early without modifying %param1\n"
8082                 "%loop = OpLabel\n"
8083                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8084                 "%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
8085                 "OpLoopMerge %exit %continue None\n"
8086                 "OpBranch %if\n"
8087
8088                 "%if = OpLabel\n"
8089                 ";return if %count==%two\n"
8090                 "%above2 = OpSGreaterThan %bool %count %two\n"
8091                 "OpSelectionMerge %continue DontFlatten\n"
8092                 "OpBranchConditional %above2 %body %early_exit\n"
8093
8094                 "%early_exit = OpLabel\n"
8095                 "OpReturnValue %param1\n"
8096
8097                 "%body = OpLabel\n"
8098                 "%fcount = OpConvertSToF %f32 %count\n"
8099                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8100                 "OpBranch %continue\n"
8101
8102                 "%continue = OpLabel\n"
8103                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8104                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8105                 "OpBranchConditional %again %loop %exit\n"
8106
8107                 "%exit = OpLabel\n"
8108                 ";should never get here, so return an incorrect result\n"
8109                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val2 %c_i32_0\n"
8110                 "OpReturnValue %result\n"
8111                 "OpFunctionEnd\n";
8112         createTestsForAllStages("return", defaultColors, defaultColors, fragments, testGroup.get());
8113
8114         // Continue inside a switch block to break to enclosing loop's merge block.
8115         // Matches roughly the following GLSL code:
8116         // for (; keep_going; keep_going = false)
8117         // {
8118         //     switch (int(param1.x))
8119         //     {
8120         //         case 0: continue;
8121         //         case 1: continue;
8122         //         default: continue;
8123         //     }
8124         //     dead code: modify return value to invalid result.
8125         // }
8126         fragments["pre_main"] =
8127                 "%fp_bool = OpTypePointer Function %bool\n"
8128                 "%true = OpConstantTrue %bool\n"
8129                 "%false = OpConstantFalse %bool\n";
8130
8131         fragments["testfun"] =
8132                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8133                 "%param1 = OpFunctionParameter %v4f32\n"
8134
8135                 "%entry = OpLabel\n"
8136                 "%keep_going = OpVariable %fp_bool Function\n"
8137                 "%val_ptr = OpVariable %fp_f32 Function\n"
8138                 "%param1_x = OpCompositeExtract %f32 %param1 0\n"
8139                 "OpStore %keep_going %true\n"
8140                 "OpBranch %forloop_begin\n"
8141
8142                 "%forloop_begin = OpLabel\n"
8143                 "OpLoopMerge %forloop_merge %forloop_continue None\n"
8144                 "OpBranch %forloop\n"
8145
8146                 "%forloop = OpLabel\n"
8147                 "%for_condition = OpLoad %bool %keep_going\n"
8148                 "OpBranchConditional %for_condition %forloop_body %forloop_merge\n"
8149
8150                 "%forloop_body = OpLabel\n"
8151                 "OpStore %val_ptr %param1_x\n"
8152                 "%param1_x_int = OpConvertFToS %i32 %param1_x\n"
8153
8154                 "OpSelectionMerge %switch_merge None\n"
8155                 "OpSwitch %param1_x_int %default 0 %case_0 1 %case_1\n"
8156                 "%case_0 = OpLabel\n"
8157                 "OpBranch %forloop_continue\n"
8158                 "%case_1 = OpLabel\n"
8159                 "OpBranch %forloop_continue\n"
8160                 "%default = OpLabel\n"
8161                 "OpBranch %forloop_continue\n"
8162                 "%switch_merge = OpLabel\n"
8163                 ";should never get here, so change the return value to invalid result\n"
8164                 "OpStore %val_ptr %c_f32_1\n"
8165                 "OpBranch %forloop_continue\n"
8166
8167                 "%forloop_continue = OpLabel\n"
8168                 "OpStore %keep_going %false\n"
8169                 "OpBranch %forloop_begin\n"
8170                 "%forloop_merge = OpLabel\n"
8171
8172                 "%val = OpLoad %f32 %val_ptr\n"
8173                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8174                 "OpReturnValue %result\n"
8175                 "OpFunctionEnd\n";
8176         createTestsForAllStages("switch_continue", defaultColors, defaultColors, fragments, testGroup.get());
8177
8178         return testGroup.release();
8179 }
8180
8181 // A collection of tests putting OpControlBarrier in places GLSL forbids but SPIR-V allows.
8182 tcu::TestCaseGroup* createBarrierTests(tcu::TestContext& testCtx)
8183 {
8184         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "barrier", "OpControlBarrier"));
8185         map<string, string> fragments;
8186
8187         // A barrier inside a function body.
8188         fragments["pre_main"] =
8189                 "%Workgroup = OpConstant %i32 2\n"
8190                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n";
8191         fragments["testfun"] =
8192                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8193                 "%param1 = OpFunctionParameter %v4f32\n"
8194                 "%label_testfun = OpLabel\n"
8195                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8196                 "OpReturnValue %param1\n"
8197                 "OpFunctionEnd\n";
8198         addTessCtrlTest(testGroup.get(), "in_function", fragments);
8199
8200         // Common setup code for the following tests.
8201         fragments["pre_main"] =
8202                 "%Workgroup = OpConstant %i32 2\n"
8203                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n"
8204                 "%c_f32_5 = OpConstant %f32 5.\n";
8205         const string setupPercentZero =  // Begins %test_code function with code that sets %zero to 0u but cannot be optimized away.
8206                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8207                 "%param1 = OpFunctionParameter %v4f32\n"
8208                 "%entry = OpLabel\n"
8209                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8210                 "%dot = OpDot %f32 %param1 %param1\n"
8211                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8212                 "%zero = OpConvertFToU %u32 %div\n";
8213
8214         // Barriers inside OpSwitch branches.
8215         fragments["testfun"] =
8216                 setupPercentZero +
8217                 "OpSelectionMerge %switch_exit None\n"
8218                 "OpSwitch %zero %switch_default 0 %case0 1 %case1 ;should always go to %case0\n"
8219
8220                 "%case1 = OpLabel\n"
8221                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8222                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8223                 "%wrong_branch_alert1 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8224                 "OpBranch %switch_exit\n"
8225
8226                 "%switch_default = OpLabel\n"
8227                 "%wrong_branch_alert2 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8228                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8229                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8230                 "OpBranch %switch_exit\n"
8231
8232                 "%case0 = OpLabel\n"
8233                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8234                 "OpBranch %switch_exit\n"
8235
8236                 "%switch_exit = OpLabel\n"
8237                 "%ret = OpPhi %v4f32 %param1 %case0 %wrong_branch_alert1 %case1 %wrong_branch_alert2 %switch_default\n"
8238                 "OpReturnValue %ret\n"
8239                 "OpFunctionEnd\n";
8240         addTessCtrlTest(testGroup.get(), "in_switch", fragments);
8241
8242         // Barriers inside if-then-else.
8243         fragments["testfun"] =
8244                 setupPercentZero +
8245                 "%eq0 = OpIEqual %bool %zero %c_u32_0\n"
8246                 "OpSelectionMerge %exit DontFlatten\n"
8247                 "OpBranchConditional %eq0 %then %else\n"
8248
8249                 "%else = OpLabel\n"
8250                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8251                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8252                 "%wrong_branch_alert = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8253                 "OpBranch %exit\n"
8254
8255                 "%then = OpLabel\n"
8256                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8257                 "OpBranch %exit\n"
8258
8259                 "%exit = OpLabel\n"
8260                 "%ret = OpPhi %v4f32 %param1 %then %wrong_branch_alert %else\n"
8261                 "OpReturnValue %ret\n"
8262                 "OpFunctionEnd\n";
8263         addTessCtrlTest(testGroup.get(), "in_if", fragments);
8264
8265         // A barrier after control-flow reconvergence, tempting the compiler to attempt something like this:
8266         // http://lists.llvm.org/pipermail/llvm-dev/2009-October/026317.html.
8267         fragments["testfun"] =
8268                 setupPercentZero +
8269                 "%thread_id = OpLoad %i32 %BP_gl_InvocationID\n"
8270                 "%thread0 = OpIEqual %bool %thread_id %c_i32_0\n"
8271                 "OpSelectionMerge %exit DontFlatten\n"
8272                 "OpBranchConditional %thread0 %then %else\n"
8273
8274                 "%else = OpLabel\n"
8275                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8276                 "OpBranch %exit\n"
8277
8278                 "%then = OpLabel\n"
8279                 "%val1 = OpVectorExtractDynamic %f32 %param1 %zero\n"
8280                 "OpBranch %exit\n"
8281
8282                 "%exit = OpLabel\n"
8283                 "%val = OpPhi %f32 %val0 %else %val1 %then\n"
8284                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8285                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %val %zero\n"
8286                 "OpReturnValue %ret\n"
8287                 "OpFunctionEnd\n";
8288         addTessCtrlTest(testGroup.get(), "after_divergent_if", fragments);
8289
8290         // A barrier inside a loop.
8291         fragments["pre_main"] =
8292                 "%Workgroup = OpConstant %i32 2\n"
8293                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n"
8294                 "%c_f32_10 = OpConstant %f32 10.\n";
8295         fragments["testfun"] =
8296                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8297                 "%param1 = OpFunctionParameter %v4f32\n"
8298                 "%entry = OpLabel\n"
8299                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8300                 "OpBranch %loop\n"
8301
8302                 ";adds 4, 3, 2, and 1 to %val0\n"
8303                 "%loop = OpLabel\n"
8304                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
8305                 "%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
8306                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8307                 "%fcount = OpConvertSToF %f32 %count\n"
8308                 "%val = OpFAdd %f32 %val1 %fcount\n"
8309                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8310                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8311                 "OpLoopMerge %exit %loop None\n"
8312                 "OpBranchConditional %again %loop %exit\n"
8313
8314                 "%exit = OpLabel\n"
8315                 "%same = OpFSub %f32 %val %c_f32_10\n"
8316                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8317                 "OpReturnValue %ret\n"
8318                 "OpFunctionEnd\n";
8319         addTessCtrlTest(testGroup.get(), "in_loop", fragments);
8320
8321         return testGroup.release();
8322 }
8323
8324 // Test for the OpFRem instruction.
8325 tcu::TestCaseGroup* createFRemTests(tcu::TestContext& testCtx)
8326 {
8327         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "frem", "OpFRem"));
8328         map<string, string>                                     fragments;
8329         RGBA                                                            inputColors[4];
8330         RGBA                                                            outputColors[4];
8331
8332         fragments["pre_main"]                            =
8333                 "%c_f32_3 = OpConstant %f32 3.0\n"
8334                 "%c_f32_n3 = OpConstant %f32 -3.0\n"
8335                 "%c_f32_4 = OpConstant %f32 4.0\n"
8336                 "%c_f32_p75 = OpConstant %f32 0.75\n"
8337                 "%c_v4f32_p75_p75_p75_p75 = OpConstantComposite %v4f32 %c_f32_p75 %c_f32_p75 %c_f32_p75 %c_f32_p75 \n"
8338                 "%c_v4f32_4_4_4_4 = OpConstantComposite %v4f32 %c_f32_4 %c_f32_4 %c_f32_4 %c_f32_4\n"
8339                 "%c_v4f32_3_n3_3_n3 = OpConstantComposite %v4f32 %c_f32_3 %c_f32_n3 %c_f32_3 %c_f32_n3\n";
8340
8341         // The test does the following.
8342         // vec4 result = (param1 * 8.0) - 4.0;
8343         // return (frem(result.x,3) + 0.75, frem(result.y, -3) + 0.75, 0, 1)
8344         fragments["testfun"]                             =
8345                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8346                 "%param1 = OpFunctionParameter %v4f32\n"
8347                 "%label_testfun = OpLabel\n"
8348                 "%v_times_8 = OpVectorTimesScalar %v4f32 %param1 %c_f32_8\n"
8349                 "%minus_4 = OpFSub %v4f32 %v_times_8 %c_v4f32_4_4_4_4\n"
8350                 "%frem = OpFRem %v4f32 %minus_4 %c_v4f32_3_n3_3_n3\n"
8351                 "%added = OpFAdd %v4f32 %frem %c_v4f32_p75_p75_p75_p75\n"
8352                 "%xyz_1 = OpVectorInsertDynamic %v4f32 %added %c_f32_1 %c_i32_3\n"
8353                 "%xy_0_1 = OpVectorInsertDynamic %v4f32 %xyz_1 %c_f32_0 %c_i32_2\n"
8354                 "OpReturnValue %xy_0_1\n"
8355                 "OpFunctionEnd\n";
8356
8357
8358         inputColors[0]          = RGBA(16,      16,             0, 255);
8359         inputColors[1]          = RGBA(232, 232,        0, 255);
8360         inputColors[2]          = RGBA(232, 16,         0, 255);
8361         inputColors[3]          = RGBA(16,      232,    0, 255);
8362
8363         outputColors[0]         = RGBA(64,      64,             0, 255);
8364         outputColors[1]         = RGBA(255, 255,        0, 255);
8365         outputColors[2]         = RGBA(255, 64,         0, 255);
8366         outputColors[3]         = RGBA(64,      255,    0, 255);
8367
8368         createTestsForAllStages("frem", inputColors, outputColors, fragments, testGroup.get());
8369         return testGroup.release();
8370 }
8371
8372 // Test for the OpSRem instruction.
8373 tcu::TestCaseGroup* createOpSRemGraphicsTests(tcu::TestContext& testCtx, qpTestResult negFailResult)
8374 {
8375         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "srem", "OpSRem"));
8376         map<string, string>                                     fragments;
8377
8378         fragments["pre_main"]                            =
8379                 "%c_f32_255 = OpConstant %f32 255.0\n"
8380                 "%c_i32_128 = OpConstant %i32 128\n"
8381                 "%c_i32_255 = OpConstant %i32 255\n"
8382                 "%c_v4f32_255 = OpConstantComposite %v4f32 %c_f32_255 %c_f32_255 %c_f32_255 %c_f32_255 \n"
8383                 "%c_v4f32_0_5 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 \n"
8384                 "%c_v4i32_128 = OpConstantComposite %v4i32 %c_i32_128 %c_i32_128 %c_i32_128 %c_i32_128 \n";
8385
8386         // The test does the following.
8387         // ivec4 ints = int(param1 * 255.0 + 0.5) - 128;
8388         // ivec4 result = ivec4(srem(ints.x, ints.y), srem(ints.y, ints.z), srem(ints.z, ints.x), 255);
8389         // return float(result + 128) / 255.0;
8390         fragments["testfun"]                             =
8391                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8392                 "%param1 = OpFunctionParameter %v4f32\n"
8393                 "%label_testfun = OpLabel\n"
8394                 "%div255 = OpFMul %v4f32 %param1 %c_v4f32_255\n"
8395                 "%add0_5 = OpFAdd %v4f32 %div255 %c_v4f32_0_5\n"
8396                 "%uints_in = OpConvertFToS %v4i32 %add0_5\n"
8397                 "%ints_in = OpISub %v4i32 %uints_in %c_v4i32_128\n"
8398                 "%x_in = OpCompositeExtract %i32 %ints_in 0\n"
8399                 "%y_in = OpCompositeExtract %i32 %ints_in 1\n"
8400                 "%z_in = OpCompositeExtract %i32 %ints_in 2\n"
8401                 "%x_out = OpSRem %i32 %x_in %y_in\n"
8402                 "%y_out = OpSRem %i32 %y_in %z_in\n"
8403                 "%z_out = OpSRem %i32 %z_in %x_in\n"
8404                 "%ints_out = OpCompositeConstruct %v4i32 %x_out %y_out %z_out %c_i32_255\n"
8405                 "%ints_offset = OpIAdd %v4i32 %ints_out %c_v4i32_128\n"
8406                 "%f_ints_offset = OpConvertSToF %v4f32 %ints_offset\n"
8407                 "%float_out = OpFDiv %v4f32 %f_ints_offset %c_v4f32_255\n"
8408                 "OpReturnValue %float_out\n"
8409                 "OpFunctionEnd\n";
8410
8411         const struct CaseParams
8412         {
8413                 const char*             name;
8414                 const char*             failMessageTemplate;    // customized status message
8415                 qpTestResult    failResult;                             // override status on failure
8416                 int                             operands[4][3];                 // four (x, y, z) vectors of operands
8417                 int                             results[4][3];                  // four (x, y, z) vectors of results
8418         } cases[] =
8419         {
8420                 {
8421                         "positive",
8422                         "${reason}",
8423                         QP_TEST_RESULT_FAIL,
8424                         { { 5, 12, 17 }, { 5, 5, 7 }, { 75, 8, 81 }, { 25, 60, 100 } },                 // operands
8425                         { { 5, 12,  2 }, { 0, 5, 2 }, {  3, 8,  6 }, { 25, 60,   0 } },                 // results
8426                 },
8427                 {
8428                         "all",
8429                         "Inconsistent results, but within specification: ${reason}",
8430                         negFailResult,                                                                                                                  // negative operands, not required by the spec
8431                         { { 5, 12, -17 }, { -5, -5, 7 }, { 75, 8, -81 }, { 25, -60, 100 } },    // operands
8432                         { { 5, 12,  -2 }, {  0, -5, 2 }, {  3, 8,  -6 }, { 25, -60,   0 } },    // results
8433                 },
8434         };
8435         // If either operand is negative the result is undefined. Some implementations may still return correct values.
8436
8437         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
8438         {
8439                 const CaseParams&       params                  = cases[caseNdx];
8440                 RGBA                            inputColors[4];
8441                 RGBA                            outputColors[4];
8442
8443                 for (int i = 0; i < 4; ++i)
8444                 {
8445                         inputColors [i] = RGBA(params.operands[i][0] + 128, params.operands[i][1] + 128, params.operands[i][2] + 128, 255);
8446                         outputColors[i] = RGBA(params.results [i][0] + 128, params.results [i][1] + 128, params.results [i][2] + 128, 255);
8447                 }
8448
8449                 createTestsForAllStages(params.name, inputColors, outputColors, fragments, testGroup.get(), params.failResult, params.failMessageTemplate);
8450         }
8451
8452         return testGroup.release();
8453 }
8454
8455 // Test for the OpSMod instruction.
8456 tcu::TestCaseGroup* createOpSModGraphicsTests(tcu::TestContext& testCtx, qpTestResult negFailResult)
8457 {
8458         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "smod", "OpSMod"));
8459         map<string, string>                                     fragments;
8460
8461         fragments["pre_main"]                            =
8462                 "%c_f32_255 = OpConstant %f32 255.0\n"
8463                 "%c_i32_128 = OpConstant %i32 128\n"
8464                 "%c_i32_255 = OpConstant %i32 255\n"
8465                 "%c_v4f32_255 = OpConstantComposite %v4f32 %c_f32_255 %c_f32_255 %c_f32_255 %c_f32_255 \n"
8466                 "%c_v4f32_0_5 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 \n"
8467                 "%c_v4i32_128 = OpConstantComposite %v4i32 %c_i32_128 %c_i32_128 %c_i32_128 %c_i32_128 \n";
8468
8469         // The test does the following.
8470         // ivec4 ints = int(param1 * 255.0 + 0.5) - 128;
8471         // ivec4 result = ivec4(smod(ints.x, ints.y), smod(ints.y, ints.z), smod(ints.z, ints.x), 255);
8472         // return float(result + 128) / 255.0;
8473         fragments["testfun"]                             =
8474                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8475                 "%param1 = OpFunctionParameter %v4f32\n"
8476                 "%label_testfun = OpLabel\n"
8477                 "%div255 = OpFMul %v4f32 %param1 %c_v4f32_255\n"
8478                 "%add0_5 = OpFAdd %v4f32 %div255 %c_v4f32_0_5\n"
8479                 "%uints_in = OpConvertFToS %v4i32 %add0_5\n"
8480                 "%ints_in = OpISub %v4i32 %uints_in %c_v4i32_128\n"
8481                 "%x_in = OpCompositeExtract %i32 %ints_in 0\n"
8482                 "%y_in = OpCompositeExtract %i32 %ints_in 1\n"
8483                 "%z_in = OpCompositeExtract %i32 %ints_in 2\n"
8484                 "%x_out = OpSMod %i32 %x_in %y_in\n"
8485                 "%y_out = OpSMod %i32 %y_in %z_in\n"
8486                 "%z_out = OpSMod %i32 %z_in %x_in\n"
8487                 "%ints_out = OpCompositeConstruct %v4i32 %x_out %y_out %z_out %c_i32_255\n"
8488                 "%ints_offset = OpIAdd %v4i32 %ints_out %c_v4i32_128\n"
8489                 "%f_ints_offset = OpConvertSToF %v4f32 %ints_offset\n"
8490                 "%float_out = OpFDiv %v4f32 %f_ints_offset %c_v4f32_255\n"
8491                 "OpReturnValue %float_out\n"
8492                 "OpFunctionEnd\n";
8493
8494         const struct CaseParams
8495         {
8496                 const char*             name;
8497                 const char*             failMessageTemplate;    // customized status message
8498                 qpTestResult    failResult;                             // override status on failure
8499                 int                             operands[4][3];                 // four (x, y, z) vectors of operands
8500                 int                             results[4][3];                  // four (x, y, z) vectors of results
8501         } cases[] =
8502         {
8503                 {
8504                         "positive",
8505                         "${reason}",
8506                         QP_TEST_RESULT_FAIL,
8507                         { { 5, 12, 17 }, { 5, 5, 7 }, { 75, 8, 81 }, { 25, 60, 100 } },                         // operands
8508                         { { 5, 12,  2 }, { 0, 5, 2 }, {  3, 8,  6 }, { 25, 60,   0 } },                         // results
8509                 },
8510                 {
8511                         "all",
8512                         "Inconsistent results, but within specification: ${reason}",
8513                         negFailResult,                                                                                                                          // negative operands, not required by the spec
8514                         { { 5, 12, -17 }, { -5, -5,  7 }, { 75,   8, -81 }, {  25, -60, 100 } },        // operands
8515                         { { 5, -5,   3 }, {  0,  2, -3 }, {  3, -73,  69 }, { -35,  40,   0 } },        // results
8516                 },
8517         };
8518         // If either operand is negative the result is undefined. Some implementations may still return correct values.
8519
8520         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
8521         {
8522                 const CaseParams&       params                  = cases[caseNdx];
8523                 RGBA                            inputColors[4];
8524                 RGBA                            outputColors[4];
8525
8526                 for (int i = 0; i < 4; ++i)
8527                 {
8528                         inputColors [i] = RGBA(params.operands[i][0] + 128, params.operands[i][1] + 128, params.operands[i][2] + 128, 255);
8529                         outputColors[i] = RGBA(params.results [i][0] + 128, params.results [i][1] + 128, params.results [i][2] + 128, 255);
8530                 }
8531
8532                 createTestsForAllStages(params.name, inputColors, outputColors, fragments, testGroup.get(), params.failResult, params.failMessageTemplate);
8533         }
8534         return testGroup.release();
8535 }
8536
8537 enum ConversionDataType
8538 {
8539         DATA_TYPE_SIGNED_8,
8540         DATA_TYPE_SIGNED_16,
8541         DATA_TYPE_SIGNED_32,
8542         DATA_TYPE_SIGNED_64,
8543         DATA_TYPE_UNSIGNED_8,
8544         DATA_TYPE_UNSIGNED_16,
8545         DATA_TYPE_UNSIGNED_32,
8546         DATA_TYPE_UNSIGNED_64,
8547         DATA_TYPE_FLOAT_16,
8548         DATA_TYPE_FLOAT_32,
8549         DATA_TYPE_FLOAT_64,
8550         DATA_TYPE_VEC2_SIGNED_16,
8551         DATA_TYPE_VEC2_SIGNED_32
8552 };
8553
8554 const string getBitWidthStr (ConversionDataType type)
8555 {
8556         switch (type)
8557         {
8558                 case DATA_TYPE_SIGNED_8:
8559                 case DATA_TYPE_UNSIGNED_8:
8560                         return "8";
8561
8562                 case DATA_TYPE_SIGNED_16:
8563                 case DATA_TYPE_UNSIGNED_16:
8564                 case DATA_TYPE_FLOAT_16:
8565                         return "16";
8566
8567                 case DATA_TYPE_SIGNED_32:
8568                 case DATA_TYPE_UNSIGNED_32:
8569                 case DATA_TYPE_FLOAT_32:
8570                 case DATA_TYPE_VEC2_SIGNED_16:
8571                         return "32";
8572
8573                 case DATA_TYPE_SIGNED_64:
8574                 case DATA_TYPE_UNSIGNED_64:
8575                 case DATA_TYPE_FLOAT_64:
8576                 case DATA_TYPE_VEC2_SIGNED_32:
8577                         return "64";
8578
8579                 default:
8580                         DE_ASSERT(false);
8581         }
8582         return "";
8583 }
8584
8585 const string getByteWidthStr (ConversionDataType type)
8586 {
8587         switch (type)
8588         {
8589                 case DATA_TYPE_SIGNED_8:
8590                 case DATA_TYPE_UNSIGNED_8:
8591                         return "1";
8592
8593                 case DATA_TYPE_SIGNED_16:
8594                 case DATA_TYPE_UNSIGNED_16:
8595                 case DATA_TYPE_FLOAT_16:
8596                         return "2";
8597
8598                 case DATA_TYPE_SIGNED_32:
8599                 case DATA_TYPE_UNSIGNED_32:
8600                 case DATA_TYPE_FLOAT_32:
8601                 case DATA_TYPE_VEC2_SIGNED_16:
8602                         return "4";
8603
8604                 case DATA_TYPE_SIGNED_64:
8605                 case DATA_TYPE_UNSIGNED_64:
8606                 case DATA_TYPE_FLOAT_64:
8607                 case DATA_TYPE_VEC2_SIGNED_32:
8608                         return "8";
8609
8610                 default:
8611                         DE_ASSERT(false);
8612         }
8613         return "";
8614 }
8615
8616 bool isSigned (ConversionDataType type)
8617 {
8618         switch (type)
8619         {
8620                 case DATA_TYPE_SIGNED_8:
8621                 case DATA_TYPE_SIGNED_16:
8622                 case DATA_TYPE_SIGNED_32:
8623                 case DATA_TYPE_SIGNED_64:
8624                 case DATA_TYPE_FLOAT_16:
8625                 case DATA_TYPE_FLOAT_32:
8626                 case DATA_TYPE_FLOAT_64:
8627                 case DATA_TYPE_VEC2_SIGNED_16:
8628                 case DATA_TYPE_VEC2_SIGNED_32:
8629                         return true;
8630
8631                 case DATA_TYPE_UNSIGNED_8:
8632                 case DATA_TYPE_UNSIGNED_16:
8633                 case DATA_TYPE_UNSIGNED_32:
8634                 case DATA_TYPE_UNSIGNED_64:
8635                         return false;
8636
8637                 default:
8638                         DE_ASSERT(false);
8639         }
8640         return false;
8641 }
8642
8643 bool isInt (ConversionDataType type)
8644 {
8645         switch (type)
8646         {
8647                 case DATA_TYPE_SIGNED_8:
8648                 case DATA_TYPE_SIGNED_16:
8649                 case DATA_TYPE_SIGNED_32:
8650                 case DATA_TYPE_SIGNED_64:
8651                 case DATA_TYPE_UNSIGNED_8:
8652                 case DATA_TYPE_UNSIGNED_16:
8653                 case DATA_TYPE_UNSIGNED_32:
8654                 case DATA_TYPE_UNSIGNED_64:
8655                         return true;
8656
8657                 case DATA_TYPE_FLOAT_16:
8658                 case DATA_TYPE_FLOAT_32:
8659                 case DATA_TYPE_FLOAT_64:
8660                 case DATA_TYPE_VEC2_SIGNED_16:
8661                 case DATA_TYPE_VEC2_SIGNED_32:
8662                         return false;
8663
8664                 default:
8665                         DE_ASSERT(false);
8666         }
8667         return false;
8668 }
8669
8670 bool isFloat (ConversionDataType type)
8671 {
8672         switch (type)
8673         {
8674                 case DATA_TYPE_SIGNED_8:
8675                 case DATA_TYPE_SIGNED_16:
8676                 case DATA_TYPE_SIGNED_32:
8677                 case DATA_TYPE_SIGNED_64:
8678                 case DATA_TYPE_UNSIGNED_8:
8679                 case DATA_TYPE_UNSIGNED_16:
8680                 case DATA_TYPE_UNSIGNED_32:
8681                 case DATA_TYPE_UNSIGNED_64:
8682                 case DATA_TYPE_VEC2_SIGNED_16:
8683                 case DATA_TYPE_VEC2_SIGNED_32:
8684                         return false;
8685
8686                 case DATA_TYPE_FLOAT_16:
8687                 case DATA_TYPE_FLOAT_32:
8688                 case DATA_TYPE_FLOAT_64:
8689                         return true;
8690
8691                 default:
8692                         DE_ASSERT(false);
8693         }
8694         return false;
8695 }
8696
8697 const string getTypeName (ConversionDataType type)
8698 {
8699         string prefix = isSigned(type) ? "" : "u";
8700
8701         if              (isInt(type))                                           return prefix + "int"   + getBitWidthStr(type);
8702         else if (isFloat(type))                                         return prefix + "float" + getBitWidthStr(type);
8703         else if (type == DATA_TYPE_VEC2_SIGNED_16)      return "i16vec2";
8704         else if (type == DATA_TYPE_VEC2_SIGNED_32)      return "i32vec2";
8705         else                                                                            DE_ASSERT(false);
8706
8707         return "";
8708 }
8709
8710 const string getTestName (ConversionDataType from, ConversionDataType to, const char* suffix)
8711 {
8712         const string fullSuffix(suffix == DE_NULL ? "" : string("_") + string(suffix));
8713
8714         return getTypeName(from) + "_to_" + getTypeName(to) + fullSuffix;
8715 }
8716
8717 const string getAsmTypeName (ConversionDataType type)
8718 {
8719         string prefix;
8720
8721         if              (isInt(type))                                           prefix = isSigned(type) ? "i" : "u";
8722         else if (isFloat(type))                                         prefix = "f";
8723         else if (type == DATA_TYPE_VEC2_SIGNED_16)      return "i16vec2";
8724         else if (type == DATA_TYPE_VEC2_SIGNED_32)      return "v2i32";
8725         else                                                                            DE_ASSERT(false);
8726
8727         return prefix + getBitWidthStr(type);
8728 }
8729
8730 template<typename T>
8731 BufferSp getSpecializedBuffer (deInt64 number)
8732 {
8733         return BufferSp(new Buffer<T>(vector<T>(1, (T)number)));
8734 }
8735
8736 BufferSp getBuffer (ConversionDataType type, deInt64 number)
8737 {
8738         switch (type)
8739         {
8740                 case DATA_TYPE_SIGNED_8:                return getSpecializedBuffer<deInt8>(number);
8741                 case DATA_TYPE_SIGNED_16:               return getSpecializedBuffer<deInt16>(number);
8742                 case DATA_TYPE_SIGNED_32:               return getSpecializedBuffer<deInt32>(number);
8743                 case DATA_TYPE_SIGNED_64:               return getSpecializedBuffer<deInt64>(number);
8744                 case DATA_TYPE_UNSIGNED_8:              return getSpecializedBuffer<deUint8>(number);
8745                 case DATA_TYPE_UNSIGNED_16:             return getSpecializedBuffer<deUint16>(number);
8746                 case DATA_TYPE_UNSIGNED_32:             return getSpecializedBuffer<deUint32>(number);
8747                 case DATA_TYPE_UNSIGNED_64:             return getSpecializedBuffer<deUint64>(number);
8748                 case DATA_TYPE_FLOAT_16:                return getSpecializedBuffer<deUint16>(number);
8749                 case DATA_TYPE_FLOAT_32:                return getSpecializedBuffer<deUint32>(number);
8750                 case DATA_TYPE_FLOAT_64:                return getSpecializedBuffer<deUint64>(number);
8751                 case DATA_TYPE_VEC2_SIGNED_16:  return getSpecializedBuffer<deUint32>(number);
8752                 case DATA_TYPE_VEC2_SIGNED_32:  return getSpecializedBuffer<deUint64>(number);
8753
8754                 default:                                                TCU_THROW(InternalError, "Unimplemented type passed");
8755         }
8756 }
8757
8758 bool usesInt8 (ConversionDataType from, ConversionDataType to)
8759 {
8760         return (from == DATA_TYPE_SIGNED_8 || to == DATA_TYPE_SIGNED_8 ||
8761                         from == DATA_TYPE_UNSIGNED_8 || to == DATA_TYPE_UNSIGNED_8);
8762 }
8763
8764 bool usesInt16 (ConversionDataType from, ConversionDataType to)
8765 {
8766         return (from == DATA_TYPE_SIGNED_16 || to == DATA_TYPE_SIGNED_16 ||
8767                         from == DATA_TYPE_UNSIGNED_16 || to == DATA_TYPE_UNSIGNED_16 ||
8768                         from == DATA_TYPE_VEC2_SIGNED_16 || to == DATA_TYPE_VEC2_SIGNED_16);
8769 }
8770
8771 bool usesInt32 (ConversionDataType from, ConversionDataType to)
8772 {
8773         return (from == DATA_TYPE_SIGNED_32 || to == DATA_TYPE_SIGNED_32 ||
8774                         from == DATA_TYPE_UNSIGNED_32 || to == DATA_TYPE_UNSIGNED_32 ||
8775                         from == DATA_TYPE_VEC2_SIGNED_32|| to == DATA_TYPE_VEC2_SIGNED_32);
8776 }
8777
8778 bool usesInt64 (ConversionDataType from, ConversionDataType to)
8779 {
8780         return (from == DATA_TYPE_SIGNED_64 || to == DATA_TYPE_SIGNED_64 ||
8781                         from == DATA_TYPE_UNSIGNED_64 || to == DATA_TYPE_UNSIGNED_64);
8782 }
8783
8784 bool usesFloat16 (ConversionDataType from, ConversionDataType to)
8785 {
8786         return (from == DATA_TYPE_FLOAT_16 || to == DATA_TYPE_FLOAT_16);
8787 }
8788
8789 bool usesFloat32 (ConversionDataType from, ConversionDataType to)
8790 {
8791         return (from == DATA_TYPE_FLOAT_32 || to == DATA_TYPE_FLOAT_32);
8792 }
8793
8794 bool usesFloat64 (ConversionDataType from, ConversionDataType to)
8795 {
8796         return (from == DATA_TYPE_FLOAT_64 || to == DATA_TYPE_FLOAT_64);
8797 }
8798
8799 void getVulkanFeaturesAndExtensions (ConversionDataType from, ConversionDataType to, VulkanFeatures& vulkanFeatures, vector<string>& extensions)
8800 {
8801         if (usesInt16(from, to) && !usesInt32(from, to))
8802                 vulkanFeatures.coreFeatures.shaderInt16 = DE_TRUE;
8803
8804         if (usesInt64(from, to))
8805                 vulkanFeatures.coreFeatures.shaderInt64 = DE_TRUE;
8806
8807         if (usesFloat64(from, to))
8808                 vulkanFeatures.coreFeatures.shaderFloat64 = DE_TRUE;
8809
8810         if (usesInt16(from, to) || usesFloat16(from, to))
8811         {
8812                 extensions.push_back("VK_KHR_16bit_storage");
8813                 vulkanFeatures.ext16BitStorage |= EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
8814         }
8815
8816         if (usesFloat16(from, to) || usesInt8(from, to))
8817         {
8818                 extensions.push_back("VK_KHR_shader_float16_int8");
8819
8820                 if (usesFloat16(from, to))
8821                 {
8822                         vulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_FLOAT16;
8823                 }
8824
8825                 if (usesInt8(from, to))
8826                 {
8827                         vulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_INT8;
8828
8829                         extensions.push_back("VK_KHR_8bit_storage");
8830                         vulkanFeatures.ext8BitStorage |= EXT8BITSTORAGEFEATURES_STORAGE_BUFFER;
8831                 }
8832         }
8833 }
8834
8835 struct ConvertCase
8836 {
8837         ConvertCase (const string& instruction, ConversionDataType from, ConversionDataType to, deInt64 number, bool separateOutput = false, deInt64 outputNumber = 0, const char* suffix = DE_NULL)
8838         : m_fromType            (from)
8839         , m_toType                      (to)
8840         , m_name                        (getTestName(from, to, suffix))
8841         , m_inputBuffer         (getBuffer(from, number))
8842         {
8843                 string caps;
8844                 string decl;
8845                 string exts;
8846
8847                 m_asmTypes["inputType"]         = getAsmTypeName(from);
8848                 m_asmTypes["outputType"]        = getAsmTypeName(to);
8849
8850                 if (separateOutput)
8851                         m_outputBuffer = getBuffer(to, outputNumber);
8852                 else
8853                         m_outputBuffer = getBuffer(to, number);
8854
8855                 if (usesInt8(from, to))
8856                 {
8857                         bool requiresInt8Capability = true;
8858                         if (instruction == "OpUConvert" || instruction == "OpSConvert")
8859                         {
8860                                 // Conversions between 8 and 32 bit are provided by SPV_KHR_8bit_storage. The rest requires explicit Int8
8861                                 if (usesInt32(from, to))
8862                                         requiresInt8Capability = false;
8863                         }
8864
8865                         caps += "OpCapability StorageBuffer8BitAccess\n";
8866                         if (requiresInt8Capability)
8867                                 caps += "OpCapability Int8\n";
8868
8869                         decl += "%i8         = OpTypeInt 8 1\n"
8870                                         "%u8         = OpTypeInt 8 0\n";
8871                         exts += "OpExtension \"SPV_KHR_8bit_storage\"\n";
8872                 }
8873
8874                 if (usesInt16(from, to))
8875                 {
8876                         bool requiresInt16Capability = true;
8877
8878                         if (instruction == "OpUConvert" || instruction == "OpSConvert" || instruction == "OpFConvert")
8879                         {
8880                                 // Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Int16
8881                                 if (usesInt32(from, to) || usesFloat32(from, to))
8882                                         requiresInt16Capability = false;
8883                         }
8884
8885                         decl += "%i16        = OpTypeInt 16 1\n"
8886                                         "%u16        = OpTypeInt 16 0\n"
8887                                         "%i16vec2    = OpTypeVector %i16 2\n";
8888
8889                         // Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Int16
8890                         if (requiresInt16Capability)
8891                                 caps += "OpCapability Int16\n";
8892                 }
8893
8894                 if (usesFloat16(from, to))
8895                 {
8896                         decl += "%f16        = OpTypeFloat 16\n";
8897
8898                         // Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Float16
8899                         if (!(usesInt32(from, to) || usesFloat32(from, to)))
8900                                 caps += "OpCapability Float16\n";
8901                 }
8902
8903                 if (usesInt16(from, to) || usesFloat16(from, to))
8904                 {
8905                         caps += "OpCapability StorageUniformBufferBlock16\n"
8906                                         "OpCapability StorageUniform16\n";
8907                         exts += "OpExtension \"SPV_KHR_16bit_storage\"\n";
8908                 }
8909
8910                 if (usesInt64(from, to))
8911                 {
8912                         caps += "OpCapability Int64\n";
8913                         decl += "%i64        = OpTypeInt 64 1\n"
8914                                         "%u64        = OpTypeInt 64 0\n";
8915                 }
8916
8917                 if (usesFloat64(from, to))
8918                 {
8919                         caps += "OpCapability Float64\n";
8920                         decl += "%f64        = OpTypeFloat 64\n";
8921                 }
8922
8923                 m_asmTypes["datatype_capabilities"]             = caps;
8924                 m_asmTypes["datatype_additional_decl"]  = decl;
8925                 m_asmTypes["datatype_extensions"]               = exts;
8926         }
8927
8928         ConversionDataType              m_fromType;
8929         ConversionDataType              m_toType;
8930         string                                  m_name;
8931         map<string, string>             m_asmTypes;
8932         BufferSp                                m_inputBuffer;
8933         BufferSp                                m_outputBuffer;
8934 };
8935
8936 const string getConvertCaseShaderStr (const string& instruction, const ConvertCase& convertCase)
8937 {
8938         map<string, string> params = convertCase.m_asmTypes;
8939
8940         params["instruction"]   = instruction;
8941         params["inDecorator"]   = getByteWidthStr(convertCase.m_fromType);
8942         params["outDecorator"]  = getByteWidthStr(convertCase.m_toType);
8943
8944         const StringTemplate shader (
8945                 "OpCapability Shader\n"
8946                 "${datatype_capabilities}"
8947                 "${datatype_extensions:opt}"
8948                 "OpMemoryModel Logical GLSL450\n"
8949                 "OpEntryPoint GLCompute %main \"main\"\n"
8950                 "OpExecutionMode %main LocalSize 1 1 1\n"
8951                 "OpSource GLSL 430\n"
8952                 "OpName %main           \"main\"\n"
8953                 // Decorators
8954                 "OpDecorate %indata DescriptorSet 0\n"
8955                 "OpDecorate %indata Binding 0\n"
8956                 "OpDecorate %outdata DescriptorSet 0\n"
8957                 "OpDecorate %outdata Binding 1\n"
8958                 "OpDecorate %in_buf BufferBlock\n"
8959                 "OpDecorate %out_buf BufferBlock\n"
8960                 "OpMemberDecorate %in_buf 0 Offset 0\n"
8961                 "OpMemberDecorate %out_buf 0 Offset 0\n"
8962                 // Base types
8963                 "%void       = OpTypeVoid\n"
8964                 "%voidf      = OpTypeFunction %void\n"
8965                 "%u32        = OpTypeInt 32 0\n"
8966                 "%i32        = OpTypeInt 32 1\n"
8967                 "%f32        = OpTypeFloat 32\n"
8968                 "%v2i32      = OpTypeVector %i32 2\n"
8969                 "${datatype_additional_decl}"
8970                 "%uvec3      = OpTypeVector %u32 3\n"
8971                 // Derived types
8972                 "%in_ptr     = OpTypePointer Uniform %${inputType}\n"
8973                 "%out_ptr    = OpTypePointer Uniform %${outputType}\n"
8974                 "%in_buf     = OpTypeStruct %${inputType}\n"
8975                 "%out_buf    = OpTypeStruct %${outputType}\n"
8976                 "%in_bufptr  = OpTypePointer Uniform %in_buf\n"
8977                 "%out_bufptr = OpTypePointer Uniform %out_buf\n"
8978                 "%indata     = OpVariable %in_bufptr Uniform\n"
8979                 "%outdata    = OpVariable %out_bufptr Uniform\n"
8980                 // Constants
8981                 "%zero       = OpConstant %i32 0\n"
8982                 // Main function
8983                 "%main       = OpFunction %void None %voidf\n"
8984                 "%label      = OpLabel\n"
8985                 "%inloc      = OpAccessChain %in_ptr %indata %zero\n"
8986                 "%outloc     = OpAccessChain %out_ptr %outdata %zero\n"
8987                 "%inval      = OpLoad %${inputType} %inloc\n"
8988                 "%conv       = ${instruction} %${outputType} %inval\n"
8989                 "              OpStore %outloc %conv\n"
8990                 "              OpReturn\n"
8991                 "              OpFunctionEnd\n"
8992         );
8993
8994         return shader.specialize(params);
8995 }
8996
8997 void createConvertCases (vector<ConvertCase>& testCases, const string& instruction)
8998 {
8999         if (instruction == "OpUConvert")
9000         {
9001                 // Convert unsigned int to unsigned int
9002                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_16,          42));
9003                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_32,          73));
9004                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_64,          121));
9005
9006                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_8,           33));
9007                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_32,          60653));
9008                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_64,          17991));
9009
9010                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_64,          904256275));
9011                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_16,          6275));
9012                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_8,           17));
9013
9014                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_32,          701256243));
9015                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_16,          4741));
9016                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_8,           65));
9017         }
9018         else if (instruction == "OpSConvert")
9019         {
9020                 // Sign extension int->int
9021                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_16,            -30));
9022                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_32,            55));
9023                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_64,            -3));
9024                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_32,            14669));
9025                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_64,            -3341));
9026                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_64,            973610259));
9027
9028                 // Truncate for int->int
9029                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_8,                     81));
9030                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_8,                     -93));
9031                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_8,                     3182748172687672ll,                                     true,   56));
9032                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_16,            12382));
9033                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_32,            -972812359));
9034                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_16,            -1067742499291926803ll,                         true,   -4371));
9035
9036                 // Sign extension for int->uint
9037                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_16,          56));
9038                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_32,          -47,                                                            true,   4294967249u));
9039                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_64,          -5,                                                                     true,   18446744073709551611ull));
9040                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_32,          14669));
9041                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_64,          -3341,                                                          true,   18446744073709548275ull));
9042                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_64,          973610259));
9043
9044                 // Truncate for int->uint
9045                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_8,           -25711,                                                         true,   145));
9046                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_8,           103));
9047                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_8,           -1067742499291926803ll,                         true,   61165));
9048                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_16,          12382));
9049                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_32,          -972812359,                                                     true,   3322154937u));
9050                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_16,          -1067742499291926803ll,                         true,   61165));
9051
9052                 // Sign extension for uint->int
9053                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_16,            71));
9054                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_32,            201,                                                            true,   -55));
9055                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_64,            188,                                                            true,   -68));
9056                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_32,            14669));
9057                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_64,            62195,                                                          true,   -3341));
9058                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_64,            973610259));
9059
9060                 // Truncate for uint->int
9061                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_8,                     67));
9062                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_8,                     133,                                                            true,   -123));
9063                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_8,                     836927654193256494ull,                          true,   46));
9064                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_16,            12382));
9065                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_32,            18446744072736739257ull,                        true,   -972812359));
9066                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_16,            17379001574417624813ull,                        true,   -4371));
9067
9068                 // Convert i16vec2 to i32vec2 and vice versa
9069                 // Unsigned values are used here to represent negative signed values and to allow defined shifting behaviour.
9070                 // The actual signed value -32123 is used here as uint16 value 33413 and uint32 value 4294935173
9071                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_VEC2_SIGNED_16,       DATA_TYPE_VEC2_SIGNED_32,       (33413u << 16)                  | 27593,        true,   (4294935173ull << 32)   | 27593));
9072                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_VEC2_SIGNED_32,       DATA_TYPE_VEC2_SIGNED_16,       (4294935173ull << 32)   | 27593,        true,   (33413u << 16)                  | 27593));
9073         }
9074         else if (instruction == "OpFConvert")
9075         {
9076                 // All hexadecimal values below represent 1234.0 as 16/32/64-bit IEEE 754 float
9077                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_FLOAT_64,                     0x449a4000,                                                     true,   0x4093480000000000));
9078                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_FLOAT_32,                     0x4093480000000000,                                     true,   0x449a4000));
9079
9080                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_FLOAT_16,                     0x449a4000,                                                     true,   0x64D2));
9081                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_FLOAT_32,                     0x64D2,                                                         true,   0x449a4000));
9082
9083                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_FLOAT_64,                     0x64D2,                                                         true,   0x4093480000000000));
9084                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_FLOAT_16,                     0x4093480000000000,                                     true,   0x64D2));
9085         }
9086         else if (instruction == "OpConvertFToU")
9087         {
9088                 // Normal numbers from uint8 range
9089                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x5020,                                                         true,   33,                                                                     "33"));
9090                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x42280000,                                                     true,   42,                                                                     "42"));
9091                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x4067800000000000ull,                          true,   188,                                                            "188"));
9092
9093                 // Maximum uint8 value
9094                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x5BF8,                                                         true,   255,                                                            "max"));
9095                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x437F0000,                                                     true,   255,                                                            "max"));
9096                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x406FE00000000000ull,                          true,   255,                                                            "max"));
9097
9098                 // +0
9099                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x0000,                                                         true,   0,                                                                      "p0"));
9100                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x00000000,                                                     true,   0,                                                                      "p0"));
9101                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x0000000000000000ull,                          true,   0,                                                                      "p0"));
9102
9103                 // -0
9104                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x8000,                                                         true,   0,                                                                      "m0"));
9105                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x80000000,                                                     true,   0,                                                                      "m0"));
9106                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x8000000000000000ull,                          true,   0,                                                                      "m0"));
9107
9108                 // All hexadecimal values below represent 1234.0 as 16/32/64-bit IEEE 754 float
9109                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x64D2,                                                         true,   1234,                                                           "1234"));
9110                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x64D2,                                                         true,   1234,                                                           "1234"));
9111                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x64D2,                                                         true,   1234,                                                           "1234"));
9112
9113                 // 0x7BFF = 0111 1011 1111 1111 = 0 11110 1111111111 = 65504
9114                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x7BFF,                                                         true,   65504,                                                          "max"));
9115                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x7BFF,                                                         true,   65504,                                                          "max"));
9116                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x7BFF,                                                         true,   65504,                                                          "max"));
9117
9118                 // +0
9119                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x0000,                                                         true,   0,                                                                      "p0"));
9120                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x0000,                                                         true,   0,                                                                      "p0"));
9121                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x0000,                                                         true,   0,                                                                      "p0"));
9122
9123                 // -0
9124                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x8000,                                                         true,   0,                                                                      "m0"));
9125                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x8000,                                                         true,   0,                                                                      "m0"));
9126                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x8000,                                                         true,   0,                                                                      "m0"));
9127
9128                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_16,          0x449a4000,                                                     true,   1234));
9129                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_32,          0x449a4000,                                                     true,   1234));
9130                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_64,          0x449a4000,                                                     true,   1234));
9131                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_16,          0x4093480000000000,                                     true,   1234));
9132                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_32,          0x4093480000000000,                                     true,   1234));
9133                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_64,          0x4093480000000000,                                     true,   1234));
9134         }
9135         else if (instruction == "OpConvertUToF")
9136         {
9137                 // Normal numbers from uint8 range
9138                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_16,                     116,                                                            true,   0x5740,                                                         "116"));
9139                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_32,                     232,                                                            true,   0x43680000,                                                     "232"));
9140                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_64,                     164,                                                            true,   0x4064800000000000ull,                          "164"));
9141
9142                 // Maximum uint8 value
9143                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_16,                     255,                                                            true,   0x5BF8,                                                         "max"));
9144                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_32,                     255,                                                            true,   0x437F0000,                                                     "max"));
9145                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_64,                     255,                                                            true,   0x406FE00000000000ull,                          "max"));
9146
9147                 // All hexadecimal values below represent 1234.0 as 32/64-bit IEEE 754 float
9148                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9149                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9150                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9151
9152                 // 0x7BFF = 0111 1011 1111 1111 = 0 11110 1111111111 = 65504
9153                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9154                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9155                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9156
9157                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9158                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9159                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9160                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9161                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9162                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9163         }
9164         else if (instruction == "OpConvertFToS")
9165         {
9166                 // Normal numbers from int8 range
9167                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0xC980,                                                         true,   -11,                                                            "m11"));
9168                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0xC2140000,                                                     true,   -37,                                                            "m37"));
9169                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0xC050800000000000ull,                          true,   -66,                                                            "m66"));
9170
9171                 // Minimum int8 value
9172                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0xD800,                                                         true,   -128,                                                           "min"));
9173                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0xC3000000,                                                     true,   -128,                                                           "min"));
9174                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0xC060000000000000ull,                          true,   -128,                                                           "min"));
9175
9176                 // Maximum int8 value
9177                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x57F0,                                                         true,   127,                                                            "max"));
9178                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x42FE0000,                                                     true,   127,                                                            "max"));
9179                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x405FC00000000000ull,                          true,   127,                                                            "max"));
9180
9181                 // +0
9182                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x0000,                                                         true,   0,                                                                      "p0"));
9183                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x00000000,                                                     true,   0,                                                                      "p0"));
9184                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x0000000000000000ull,                          true,   0,                                                                      "p0"));
9185
9186                 // -0
9187                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x8000,                                                         true,   0,                                                                      "m0"));
9188                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x80000000,                                                     true,   0,                                                                      "m0"));
9189                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x8000000000000000ull,                          true,   0,                                                                      "m0"));
9190
9191                 // All hexadecimal values below represent -1234.0 as 32/64-bit IEEE 754 float
9192                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9193                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9194                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9195
9196                 // 0xF800 = 1111 1000 0000 0000 = 1 11110 0000000000 = -32768
9197                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0xF800,                                                         true,   -32768,                                                         "min"));
9198                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0xF800,                                                         true,   -32768,                                                         "min"));
9199                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0xF800,                                                         true,   -32768,                                                         "min"));
9200
9201                 // 0x77FF = 0111 0111 1111 1111 = 0 11101 1111111111 = 32752
9202                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x77FF,                                                         true,   32752,                                                          "max"));
9203                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x77FF,                                                         true,   32752,                                                          "max"));
9204                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x77FF,                                                         true,   32752,                                                          "max"));
9205
9206                 // +0
9207                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x0000,                                                         true,   0,                                                                      "p0"));
9208                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x0000,                                                         true,   0,                                                                      "p0"));
9209                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x0000,                                                         true,   0,                                                                      "p0"));
9210
9211                 // -0
9212                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x8000,                                                         true,   0,                                                                      "m0"));
9213                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x8000,                                                         true,   0,                                                                      "m0"));
9214                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x8000,                                                         true,   0,                                                                      "m0"));
9215
9216                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0xc49a4000,                                                     true,   -1234));
9217                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_32,            0xc49a4000,                                                     true,   -1234));
9218                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_64,            0xc49a4000,                                                     true,   -1234));
9219                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_16,            0xc093480000000000,                                     true,   -1234));
9220                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_32,            0xc093480000000000,                                     true,   -1234));
9221                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_64,            0xc093480000000000,                                     true,   -1234));
9222         }
9223         else if (instruction == "OpConvertSToF")
9224         {
9225                 // Normal numbers from int8 range
9226                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     -12,                                                            true,   0xCA00,                                                         "m21"));
9227                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     -21,                                                            true,   0xC1A80000,                                                     "m21"));
9228                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     -99,                                                            true,   0xC058C00000000000ull,                          "m99"));
9229
9230                 // Minimum int8 value
9231                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     -128,                                                           true,   0xD800,                                                         "min"));
9232                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     -128,                                                           true,   0xC3000000,                                                     "min"));
9233                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     -128,                                                           true,   0xC060000000000000ull,                          "min"));
9234
9235                 // Maximum int8 value
9236                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     127,                                                            true,   0x57F0,                                                         "max"));
9237                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     127,                                                            true,   0x42FE0000,                                                     "max"));
9238                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     127,                                                            true,   0x405FC00000000000ull,                          "max"));
9239
9240                 // All hexadecimal values below represent 1234.0 as 32/64-bit IEEE 754 float
9241                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9242                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9243                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9244
9245                 // 0xF800 = 1111 1000 0000 0000 = 1 11110 0000000000 = -32768
9246                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9247                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9248                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9249
9250                 // 0x77FF = 0111 0111 1111 1111 = 0 11101 1111111111 = 32752
9251                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9252                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9253                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9254
9255                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9256                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9257                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9258                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9259                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9260                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9261         }
9262         else
9263                 DE_FATAL("Unknown instruction");
9264 }
9265
9266 const map<string, string> getConvertCaseFragments (string instruction, const ConvertCase& convertCase)
9267 {
9268         map<string, string> params = convertCase.m_asmTypes;
9269         map<string, string> fragments;
9270
9271         params["instruction"] = instruction;
9272         params["inDecorator"] = getByteWidthStr(convertCase.m_fromType);
9273
9274         const StringTemplate decoration (
9275                 "      OpDecorate %SSBOi DescriptorSet 0\n"
9276                 "      OpDecorate %SSBOo DescriptorSet 0\n"
9277                 "      OpDecorate %SSBOi Binding 0\n"
9278                 "      OpDecorate %SSBOo Binding 1\n"
9279                 "      OpDecorate %s_SSBOi Block\n"
9280                 "      OpDecorate %s_SSBOo Block\n"
9281                 "OpMemberDecorate %s_SSBOi 0 Offset 0\n"
9282                 "OpMemberDecorate %s_SSBOo 0 Offset 0\n");
9283
9284         const StringTemplate pre_main (
9285                 "${datatype_additional_decl:opt}"
9286                 "    %ptr_in = OpTypePointer StorageBuffer %${inputType}\n"
9287                 "   %ptr_out = OpTypePointer StorageBuffer %${outputType}\n"
9288                 "   %s_SSBOi = OpTypeStruct %${inputType}\n"
9289                 "   %s_SSBOo = OpTypeStruct %${outputType}\n"
9290                 " %ptr_SSBOi = OpTypePointer StorageBuffer %s_SSBOi\n"
9291                 " %ptr_SSBOo = OpTypePointer StorageBuffer %s_SSBOo\n"
9292                 "     %SSBOi = OpVariable %ptr_SSBOi StorageBuffer\n"
9293                 "     %SSBOo = OpVariable %ptr_SSBOo StorageBuffer\n");
9294
9295         const StringTemplate testfun (
9296                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9297                 "%param     = OpFunctionParameter %v4f32\n"
9298                 "%label     = OpLabel\n"
9299                 "%iLoc      = OpAccessChain %ptr_in %SSBOi %c_u32_0\n"
9300                 "%oLoc      = OpAccessChain %ptr_out %SSBOo %c_u32_0\n"
9301                 "%valIn     = OpLoad %${inputType} %iLoc\n"
9302                 "%valOut    = ${instruction} %${outputType} %valIn\n"
9303                 "             OpStore %oLoc %valOut\n"
9304                 "             OpReturnValue %param\n"
9305                 "             OpFunctionEnd\n");
9306
9307         params["datatype_extensions"] =
9308                 params["datatype_extensions"] +
9309                 "OpExtension \"SPV_KHR_storage_buffer_storage_class\"\n";
9310
9311         fragments["capability"] = params["datatype_capabilities"];
9312         fragments["extension"]  = params["datatype_extensions"];
9313         fragments["decoration"] = decoration.specialize(params);
9314         fragments["pre_main"]   = pre_main.specialize(params);
9315         fragments["testfun"]    = testfun.specialize(params);
9316
9317         return fragments;
9318 }
9319
9320 // Test for OpSConvert, OpUConvert, OpFConvert and OpConvert* in compute shaders
9321 tcu::TestCaseGroup* createConvertComputeTests (tcu::TestContext& testCtx, const string& instruction, const string& name)
9322 {
9323         de::MovePtr<tcu::TestCaseGroup>         group(new tcu::TestCaseGroup(testCtx, name.c_str(), instruction.c_str()));
9324         vector<ConvertCase>                                     testCases;
9325         createConvertCases(testCases, instruction);
9326
9327         for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
9328         {
9329                 ComputeShaderSpec spec;
9330                 spec.assembly                   = getConvertCaseShaderStr(instruction, *test);
9331                 spec.numWorkGroups              = IVec3(1, 1, 1);
9332                 spec.inputs.push_back   (test->m_inputBuffer);
9333                 spec.outputs.push_back  (test->m_outputBuffer);
9334
9335                 getVulkanFeaturesAndExtensions(test->m_fromType, test->m_toType, spec.requestedVulkanFeatures, spec.extensions);
9336
9337                 group->addChild(new SpvAsmComputeShaderCase(testCtx, test->m_name.c_str(), "", spec));
9338         }
9339         return group.release();
9340 }
9341
9342 // Test for OpSConvert, OpUConvert, OpFConvert and OpConvert* in graphics shaders
9343 tcu::TestCaseGroup* createConvertGraphicsTests (tcu::TestContext& testCtx, const string& instruction, const string& name)
9344 {
9345         de::MovePtr<tcu::TestCaseGroup>         group(new tcu::TestCaseGroup(testCtx, name.c_str(), instruction.c_str()));
9346         vector<ConvertCase>                                     testCases;
9347         createConvertCases(testCases, instruction);
9348
9349         for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
9350         {
9351                 map<string, string>     fragments               = getConvertCaseFragments(instruction, *test);
9352                 vector<string>          features;
9353                 VulkanFeatures          vulkanFeatures;
9354                 GraphicsResources       resources;
9355                 vector<string>          extensions;
9356                 SpecConstants           noSpecConstants;
9357                 PushConstants           noPushConstants;
9358                 GraphicsInterfaces      noInterfaces;
9359                 tcu::RGBA                       defaultColors[4];
9360
9361                 getDefaultColors                        (defaultColors);
9362                 resources.inputs.push_back      (Resource(test->m_inputBuffer, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9363                 resources.outputs.push_back     (Resource(test->m_outputBuffer, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9364                 extensions.push_back            ("VK_KHR_storage_buffer_storage_class");
9365
9366                 getVulkanFeaturesAndExtensions(test->m_fromType, test->m_toType, vulkanFeatures, extensions);
9367
9368                 createTestsForAllStages(
9369                         test->m_name, defaultColors, defaultColors, fragments, noSpecConstants,
9370                         noPushConstants, resources, noInterfaces, extensions, features, vulkanFeatures, group.get());
9371         }
9372         return group.release();
9373 }
9374
9375 // Constant-Creation Instructions: OpConstant, OpConstantComposite
9376 tcu::TestCaseGroup* createOpConstantFloat16Tests(tcu::TestContext& testCtx)
9377 {
9378         de::MovePtr<tcu::TestCaseGroup> opConstantCompositeTests                (new tcu::TestCaseGroup(testCtx, "opconstant", "OpConstant and OpConstantComposite instruction"));
9379         RGBA                                                    inputColors[4];
9380         RGBA                                                    outputColors[4];
9381         vector<string>                                  extensions;
9382         GraphicsResources                               resources;
9383         VulkanFeatures                                  features;
9384
9385         const char                                              functionStart[]  =
9386                 "%test_code             = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9387                 "%param1                = OpFunctionParameter %v4f32\n"
9388                 "%lbl                   = OpLabel\n";
9389
9390         const char                                              functionEnd[]           =
9391                 "%transformed_param_32  = OpFConvert %v4f32 %transformed_param\n"
9392                 "                         OpReturnValue %transformed_param_32\n"
9393                 "                         OpFunctionEnd\n";
9394
9395         struct NameConstantsCode
9396         {
9397                 string name;
9398                 string constants;
9399                 string code;
9400         };
9401
9402 #define FLOAT_16_COMMON_TYPES_AND_CONSTS \
9403                         "%f16                  = OpTypeFloat 16\n"                                                 \
9404                         "%c_f16_0              = OpConstant %f16 0.0\n"                                            \
9405                         "%c_f16_0_5            = OpConstant %f16 0.5\n"                                            \
9406                         "%c_f16_1              = OpConstant %f16 1.0\n"                                            \
9407                         "%v4f16                = OpTypeVector %f16 4\n"                                            \
9408                         "%fp_f16               = OpTypePointer Function %f16\n"                                    \
9409                         "%fp_v4f16             = OpTypePointer Function %v4f16\n"                                  \
9410                         "%c_v4f16_1_1_1_1      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_1\n" \
9411                         "%a4f16                = OpTypeArray %f16 %c_u32_4\n"                                      \
9412
9413         NameConstantsCode                               tests[] =
9414         {
9415                 {
9416                         "vec4",
9417
9418                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9419                         "%cval                 = OpConstantComposite %v4f16 %c_f16_0_5 %c_f16_0_5 %c_f16_0_5 %c_f16_0\n",
9420                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9421                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %cval\n"
9422                 },
9423                 {
9424                         "struct",
9425
9426                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9427                         "%stype                = OpTypeStruct %v4f16 %f16\n"
9428                         "%fp_stype             = OpTypePointer Function %stype\n"
9429                         "%f16_n_1              = OpConstant %f16 -1.0\n"
9430                         "%f16_1_5              = OpConstant %f16 !0x3e00\n" // +1.5
9431                         "%cvec                 = OpConstantComposite %v4f16 %f16_1_5 %f16_1_5 %f16_1_5 %c_f16_1\n"
9432                         "%cval                 = OpConstantComposite %stype %cvec %f16_n_1\n",
9433
9434                         "%v                    = OpVariable %fp_stype Function %cval\n"
9435                         "%vec_ptr              = OpAccessChain %fp_v4f16 %v %c_u32_0\n"
9436                         "%f16_ptr              = OpAccessChain %fp_f16 %v %c_u32_1\n"
9437                         "%vec_val              = OpLoad %v4f16 %vec_ptr\n"
9438                         "%f16_val              = OpLoad %f16 %f16_ptr\n"
9439                         "%tmp1                 = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_1 %f16_val\n" // vec4(-1)
9440                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9441                         "%tmp2                 = OpFAdd %v4f16 %tmp1 %param1_16\n" // param1 + vec4(-1)
9442                         "%transformed_param    = OpFAdd %v4f16 %tmp2 %vec_val\n" // param1 + vec4(-1) + vec4(1.5, 1.5, 1.5, 1.0)
9443                 },
9444                 {
9445                         // [1|0|0|0.5] [x] = x + 0.5
9446                         // [0|1|0|0.5] [y] = y + 0.5
9447                         // [0|0|1|0.5] [z] = z + 0.5
9448                         // [0|0|0|1  ] [1] = 1
9449                         "matrix",
9450
9451                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9452                         "%mat4x4_f16           = OpTypeMatrix %v4f16 4\n"
9453                         "%v4f16_1_0_0_0        = OpConstantComposite %v4f16 %c_f16_1 %c_f16_0 %c_f16_0 %c_f16_0\n"
9454                         "%v4f16_0_1_0_0        = OpConstantComposite %v4f16 %c_f16_0 %c_f16_1 %c_f16_0 %c_f16_0\n"
9455                         "%v4f16_0_0_1_0        = OpConstantComposite %v4f16 %c_f16_0 %c_f16_0 %c_f16_1 %c_f16_0\n"
9456                         "%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"
9457                         "%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",
9458
9459                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9460                         "%transformed_param    = OpMatrixTimesVector %v4f16 %cval %param1_16\n"
9461                 },
9462                 {
9463                         "array",
9464
9465                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9466                         "%c_v4f16_1_1_1_0      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_0\n"
9467                         "%fp_a4f16             = OpTypePointer Function %a4f16\n"
9468                         "%f16_n_1              = OpConstant %f16 -1.0\n"
9469                         "%f16_1_5              = OpConstant %f16 !0x3e00\n" // +1.5
9470                         "%carr                 = OpConstantComposite %a4f16 %c_f16_0 %f16_n_1 %f16_1_5 %c_f16_0\n",
9471
9472                         "%v                    = OpVariable %fp_a4f16 Function %carr\n"
9473                         "%f                    = OpAccessChain %fp_f16 %v %c_u32_0\n"
9474                         "%f1                   = OpAccessChain %fp_f16 %v %c_u32_1\n"
9475                         "%f2                   = OpAccessChain %fp_f16 %v %c_u32_2\n"
9476                         "%f3                   = OpAccessChain %fp_f16 %v %c_u32_3\n"
9477                         "%f_val                = OpLoad %f16 %f\n"
9478                         "%f1_val               = OpLoad %f16 %f1\n"
9479                         "%f2_val               = OpLoad %f16 %f2\n"
9480                         "%f3_val               = OpLoad %f16 %f3\n"
9481                         "%ftot1                = OpFAdd %f16 %f_val %f1_val\n"
9482                         "%ftot2                = OpFAdd %f16 %ftot1 %f2_val\n"
9483                         "%ftot3                = OpFAdd %f16 %ftot2 %f3_val\n"  // 0 - 1 + 1.5 + 0
9484                         "%add_vec              = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_0 %ftot3\n"
9485                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9486                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %add_vec\n"
9487                 },
9488                 {
9489                         //
9490                         // [
9491                         //   {
9492                         //      0.0,
9493                         //      [ 1.0, 1.0, 1.0, 1.0]
9494                         //   },
9495                         //   {
9496                         //      1.0,
9497                         //      [ 0.0, 0.5, 0.0, 0.0]
9498                         //   }, //     ^^^
9499                         //   {
9500                         //      0.0,
9501                         //      [ 1.0, 1.0, 1.0, 1.0]
9502                         //   }
9503                         // ]
9504                         "array_of_struct_of_array",
9505
9506                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9507                         "%c_v4f16_1_1_1_0      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_0\n"
9508                         "%fp_a4f16             = OpTypePointer Function %a4f16\n"
9509                         "%stype                = OpTypeStruct %f16 %a4f16\n"
9510                         "%a3stype              = OpTypeArray %stype %c_u32_3\n"
9511                         "%fp_a3stype           = OpTypePointer Function %a3stype\n"
9512                         "%ca4f16_0             = OpConstantComposite %a4f16 %c_f16_0 %c_f16_0_5 %c_f16_0 %c_f16_0\n"
9513                         "%ca4f16_1             = OpConstantComposite %a4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_1\n"
9514                         "%cstype1              = OpConstantComposite %stype %c_f16_0 %ca4f16_1\n"
9515                         "%cstype2              = OpConstantComposite %stype %c_f16_1 %ca4f16_0\n"
9516                         "%carr                 = OpConstantComposite %a3stype %cstype1 %cstype2 %cstype1",
9517
9518                         "%v                    = OpVariable %fp_a3stype Function %carr\n"
9519                         "%f                    = OpAccessChain %fp_f16 %v %c_u32_1 %c_u32_1 %c_u32_1\n"
9520                         "%f_l                  = OpLoad %f16 %f\n"
9521                         "%add_vec              = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_0 %f_l\n"
9522                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9523                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %add_vec\n"
9524                 }
9525         };
9526
9527         getHalfColorsFullAlpha(inputColors);
9528         outputColors[0] = RGBA(255, 255, 255, 255);
9529         outputColors[1] = RGBA(255, 127, 127, 255);
9530         outputColors[2] = RGBA(127, 255, 127, 255);
9531         outputColors[3] = RGBA(127, 127, 255, 255);
9532
9533         extensions.push_back("VK_KHR_16bit_storage");
9534         extensions.push_back("VK_KHR_shader_float16_int8");
9535
9536         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
9537         {
9538                 map<string, string> fragments;
9539
9540                 fragments["extension"]  = "OpExtension \"SPV_KHR_16bit_storage\"";
9541                 fragments["capability"] = "OpCapability Float16\n";
9542                 fragments["pre_main"]   = tests[testNdx].constants;
9543                 fragments["testfun"]    = string(functionStart) + tests[testNdx].code + functionEnd;
9544
9545                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, resources, extensions, opConstantCompositeTests.get(), features);
9546         }
9547         return opConstantCompositeTests.release();
9548 }
9549
9550 template<typename T>
9551 void finalizeTestsCreation (T&                                                  specResource,
9552                                                         const map<string, string>&      fragments,
9553                                                         tcu::TestContext&                       testCtx,
9554                                                         tcu::TestCaseGroup&                     testGroup,
9555                                                         const std::string&                      testName,
9556                                                         const VulkanFeatures&           vulkanFeatures,
9557                                                         const vector<string>&           extensions,
9558                                                         const IVec3&                            numWorkGroups);
9559
9560 template<>
9561 void finalizeTestsCreation (GraphicsResources&                  specResource,
9562                                                         const map<string, string>&      fragments,
9563                                                         tcu::TestContext&                       ,
9564                                                         tcu::TestCaseGroup&                     testGroup,
9565                                                         const std::string&                      testName,
9566                                                         const VulkanFeatures&           vulkanFeatures,
9567                                                         const vector<string>&           extensions,
9568                                                         const IVec3&                            )
9569 {
9570         RGBA defaultColors[4];
9571         getDefaultColors(defaultColors);
9572
9573         createTestsForAllStages(testName, defaultColors, defaultColors, fragments, specResource, extensions, &testGroup, vulkanFeatures);
9574 }
9575
9576 template<>
9577 void finalizeTestsCreation (ComputeShaderSpec&                  specResource,
9578                                                         const map<string, string>&      fragments,
9579                                                         tcu::TestContext&                       testCtx,
9580                                                         tcu::TestCaseGroup&                     testGroup,
9581                                                         const std::string&                      testName,
9582                                                         const VulkanFeatures&           vulkanFeatures,
9583                                                         const vector<string>&           extensions,
9584                                                         const IVec3&                            numWorkGroups)
9585 {
9586         specResource.numWorkGroups = numWorkGroups;
9587         specResource.requestedVulkanFeatures = vulkanFeatures;
9588         specResource.extensions = extensions;
9589
9590         specResource.assembly = makeComputeShaderAssembly(fragments);
9591
9592         testGroup.addChild(new SpvAsmComputeShaderCase(testCtx, testName.c_str(), "", specResource));
9593 }
9594
9595 template<class SpecResource>
9596 tcu::TestCaseGroup* createFloat16LogicalSet (tcu::TestContext& testCtx, const bool nanSupported)
9597 {
9598         const string                                            nan                                     = nanSupported ? "_nan" : "";
9599         const string                                            groupName                       = "logical" + nan;
9600         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Float 16 logical tests"));
9601
9602         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
9603         const StringTemplate                            capabilities            ("OpCapability ${cap}\n");
9604         const deUint32                                          numDataPoints           = 16;
9605         const vector<deFloat16>                         float16Data                     = getFloat16s(rnd, numDataPoints);
9606         const vector<deFloat16>                         float16Data1            = squarize(float16Data, 0);
9607         const vector<deFloat16>                         float16Data2            = squarize(float16Data, 1);
9608         const vector<deFloat16>                         float16DataVec1         = squarizeVector(float16Data, 0);
9609         const vector<deFloat16>                         float16DataVec2         = squarizeVector(float16Data, 1);
9610         const vector<deFloat16>                         float16OutDummy         (float16Data1.size(), 0);
9611         const vector<deFloat16>                         float16OutVecDummy      (float16DataVec1.size(), 0);
9612
9613         struct TestOp
9614         {
9615                 const char*             opCode;
9616                 VerifyIOFunc    verifyFuncNan;
9617                 VerifyIOFunc    verifyFuncNonNan;
9618                 const deUint32  argCount;
9619         };
9620
9621         const TestOp    testOps[]       =
9622         {
9623                 { "OpIsNan"                                             ,       compareFP16Logical<fp16isNan,                           true,  false, true>,    compareFP16Logical<fp16isNan,                           true,  false, false>,   1       },
9624                 { "OpIsInf"                                             ,       compareFP16Logical<fp16isInf,                           true,  false, true>,    compareFP16Logical<fp16isInf,                           true,  false, false>,   1       },
9625                 { "OpFOrdEqual"                                 ,       compareFP16Logical<fp16isEqual,                         false, true,  true>,    compareFP16Logical<fp16isEqual,                         false, true,  false>,   2       },
9626                 { "OpFUnordEqual"                               ,       compareFP16Logical<fp16isEqual,                         false, false, true>,    compareFP16Logical<fp16isEqual,                         false, false, false>,   2       },
9627                 { "OpFOrdNotEqual"                              ,       compareFP16Logical<fp16isUnequal,                       false, true,  true>,    compareFP16Logical<fp16isUnequal,                       false, true,  false>,   2       },
9628                 { "OpFUnordNotEqual"                    ,       compareFP16Logical<fp16isUnequal,                       false, false, true>,    compareFP16Logical<fp16isUnequal,                       false, false, false>,   2       },
9629                 { "OpFOrdLessThan"                              ,       compareFP16Logical<fp16isLess,                          false, true,  true>,    compareFP16Logical<fp16isLess,                          false, true,  false>,   2       },
9630                 { "OpFUnordLessThan"                    ,       compareFP16Logical<fp16isLess,                          false, false, true>,    compareFP16Logical<fp16isLess,                          false, false, false>,   2       },
9631                 { "OpFOrdGreaterThan"                   ,       compareFP16Logical<fp16isGreater,                       false, true,  true>,    compareFP16Logical<fp16isGreater,                       false, true,  false>,   2       },
9632                 { "OpFUnordGreaterThan"                 ,       compareFP16Logical<fp16isGreater,                       false, false, true>,    compareFP16Logical<fp16isGreater,                       false, false, false>,   2       },
9633                 { "OpFOrdLessThanEqual"                 ,       compareFP16Logical<fp16isLessOrEqual,           false, true,  true>,    compareFP16Logical<fp16isLessOrEqual,           false, true,  false>,   2       },
9634                 { "OpFUnordLessThanEqual"               ,       compareFP16Logical<fp16isLessOrEqual,           false, false, true>,    compareFP16Logical<fp16isLessOrEqual,           false, false, false>,   2       },
9635                 { "OpFOrdGreaterThanEqual"              ,       compareFP16Logical<fp16isGreaterOrEqual,        false, true,  true>,    compareFP16Logical<fp16isGreaterOrEqual,        false, true,  false>,   2       },
9636                 { "OpFUnordGreaterThanEqual"    ,       compareFP16Logical<fp16isGreaterOrEqual,        false, false, true>,    compareFP16Logical<fp16isGreaterOrEqual,        false, false, false>,   2       },
9637         };
9638
9639         { // scalar cases
9640                 const StringTemplate preMain
9641                 (
9642                         "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
9643                         "      %f16 = OpTypeFloat 16\n"
9644                         "  %c_f16_0 = OpConstant %f16 0.0\n"
9645                         "  %c_f16_1 = OpConstant %f16 1.0\n"
9646                         "   %up_f16 = OpTypePointer Uniform %f16\n"
9647                         "   %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
9648                         "   %SSBO16 = OpTypeStruct %ra_f16\n"
9649                         "%up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
9650                         "%ssbo_src0 = OpVariable %up_SSBO16 Uniform\n"
9651                         "%ssbo_src1 = OpVariable %up_SSBO16 Uniform\n"
9652                         " %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
9653                 );
9654
9655                 const StringTemplate decoration
9656                 (
9657                         "OpDecorate %ra_f16 ArrayStride 2\n"
9658                         "OpMemberDecorate %SSBO16 0 Offset 0\n"
9659                         "OpDecorate %SSBO16 BufferBlock\n"
9660                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
9661                         "OpDecorate %ssbo_src0 Binding 0\n"
9662                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
9663                         "OpDecorate %ssbo_src1 Binding 1\n"
9664                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
9665                         "OpDecorate %ssbo_dst Binding 2\n"
9666                 );
9667
9668                 const StringTemplate testFun
9669                 (
9670                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9671                         "    %param = OpFunctionParameter %v4f32\n"
9672
9673                         "    %entry = OpLabel\n"
9674                         "        %i = OpVariable %fp_i32 Function\n"
9675                         "             OpStore %i %c_i32_0\n"
9676                         "             OpBranch %loop\n"
9677
9678                         "     %loop = OpLabel\n"
9679                         "    %i_cmp = OpLoad %i32 %i\n"
9680                         "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
9681                         "             OpLoopMerge %merge %next None\n"
9682                         "             OpBranchConditional %lt %write %merge\n"
9683
9684                         "    %write = OpLabel\n"
9685                         "      %ndx = OpLoad %i32 %i\n"
9686
9687                         "     %src0 = OpAccessChain %up_f16 %ssbo_src0 %c_i32_0 %ndx\n"
9688                         " %val_src0 = OpLoad %f16 %src0\n"
9689
9690                         "${op_arg1_calc}"
9691
9692                         " %val_bdst = ${op_code} %bool %val_src0 ${op_arg1}\n"
9693                         "  %val_dst = OpSelect %f16 %val_bdst %c_f16_1 %c_f16_0\n"
9694                         "      %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
9695                         "             OpStore %dst %val_dst\n"
9696                         "             OpBranch %next\n"
9697
9698                         "     %next = OpLabel\n"
9699                         "    %i_cur = OpLoad %i32 %i\n"
9700                         "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
9701                         "             OpStore %i %i_new\n"
9702                         "             OpBranch %loop\n"
9703
9704                         "    %merge = OpLabel\n"
9705                         "             OpReturnValue %param\n"
9706
9707                         "             OpFunctionEnd\n"
9708                 );
9709
9710                 const StringTemplate arg1Calc
9711                 (
9712                         "     %src1 = OpAccessChain %up_f16 %ssbo_src1 %c_i32_0 %ndx\n"
9713                         " %val_src1 = OpLoad %f16 %src1\n"
9714                 );
9715
9716                 for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
9717                 {
9718                         const size_t            iterations              = float16Data1.size();
9719                         const TestOp&           testOp                  = testOps[testOpsIdx];
9720                         const string            testName                = de::toLower(string(testOp.opCode)) + "_scalar";
9721                         SpecResource            specResource;
9722                         map<string, string>     specs;
9723                         VulkanFeatures          features;
9724                         map<string, string>     fragments;
9725                         vector<string>          extensions;
9726
9727                         specs["cap"]                            = "StorageUniformBufferBlock16";
9728                         specs["num_data_points"]        = de::toString(iterations);
9729                         specs["op_code"]                        = testOp.opCode;
9730                         specs["op_arg1"]                        = (testOp.argCount == 1) ? "" : "%val_src1";
9731                         specs["op_arg1_calc"]           = (testOp.argCount == 1) ? "" : arg1Calc.specialize(specs);
9732
9733                         fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
9734                         fragments["capability"]         = capabilities.specialize(specs);
9735                         fragments["decoration"]         = decoration.specialize(specs);
9736                         fragments["pre_main"]           = preMain.specialize(specs);
9737                         fragments["testfun"]            = testFun.specialize(specs);
9738
9739                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Data1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9740                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Data2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9741                         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9742                         specResource.verifyIO = nanSupported ? testOp.verifyFuncNan : testOp.verifyFuncNonNan;
9743
9744                         extensions.push_back("VK_KHR_16bit_storage");
9745                         extensions.push_back("VK_KHR_shader_float16_int8");
9746
9747                         if (nanSupported)
9748                         {
9749                                 extensions.push_back("VK_KHR_shader_float_controls");
9750
9751                                 features.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat16 = DE_TRUE;
9752                         }
9753
9754                         features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
9755                         features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
9756
9757                         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
9758                 }
9759         }
9760         { // vector cases
9761                 const StringTemplate preMain
9762                 (
9763                         "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
9764                         "     %v2bool = OpTypeVector %bool 2\n"
9765                         "        %f16 = OpTypeFloat 16\n"
9766                         "    %c_f16_0 = OpConstant %f16 0.0\n"
9767                         "    %c_f16_1 = OpConstant %f16 1.0\n"
9768                         "      %v2f16 = OpTypeVector %f16 2\n"
9769                         "%c_v2f16_0_0 = OpConstantComposite %v2f16 %c_f16_0 %c_f16_0\n"
9770                         "%c_v2f16_1_1 = OpConstantComposite %v2f16 %c_f16_1 %c_f16_1\n"
9771                         "   %up_v2f16 = OpTypePointer Uniform %v2f16\n"
9772                         "   %ra_v2f16 = OpTypeArray %v2f16 %c_i32_ndp\n"
9773                         "     %SSBO16 = OpTypeStruct %ra_v2f16\n"
9774                         "  %up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
9775                         "  %ssbo_src0 = OpVariable %up_SSBO16 Uniform\n"
9776                         "  %ssbo_src1 = OpVariable %up_SSBO16 Uniform\n"
9777                         "   %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
9778                 );
9779
9780                 const StringTemplate decoration
9781                 (
9782                         "OpDecorate %ra_v2f16 ArrayStride 4\n"
9783                         "OpMemberDecorate %SSBO16 0 Offset 0\n"
9784                         "OpDecorate %SSBO16 BufferBlock\n"
9785                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
9786                         "OpDecorate %ssbo_src0 Binding 0\n"
9787                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
9788                         "OpDecorate %ssbo_src1 Binding 1\n"
9789                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
9790                         "OpDecorate %ssbo_dst Binding 2\n"
9791                 );
9792
9793                 const StringTemplate testFun
9794                 (
9795                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9796                         "    %param = OpFunctionParameter %v4f32\n"
9797
9798                         "    %entry = OpLabel\n"
9799                         "        %i = OpVariable %fp_i32 Function\n"
9800                         "             OpStore %i %c_i32_0\n"
9801                         "             OpBranch %loop\n"
9802
9803                         "     %loop = OpLabel\n"
9804                         "    %i_cmp = OpLoad %i32 %i\n"
9805                         "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
9806                         "             OpLoopMerge %merge %next None\n"
9807                         "             OpBranchConditional %lt %write %merge\n"
9808
9809                         "    %write = OpLabel\n"
9810                         "      %ndx = OpLoad %i32 %i\n"
9811
9812                         "     %src0 = OpAccessChain %up_v2f16 %ssbo_src0 %c_i32_0 %ndx\n"
9813                         " %val_src0 = OpLoad %v2f16 %src0\n"
9814
9815                         "${op_arg1_calc}"
9816
9817                         " %val_bdst = ${op_code} %v2bool %val_src0 ${op_arg1}\n"
9818                         "  %val_dst = OpSelect %v2f16 %val_bdst %c_v2f16_1_1 %c_v2f16_0_0\n"
9819                         "      %dst = OpAccessChain %up_v2f16 %ssbo_dst %c_i32_0 %ndx\n"
9820                         "             OpStore %dst %val_dst\n"
9821                         "             OpBranch %next\n"
9822
9823                         "     %next = OpLabel\n"
9824                         "    %i_cur = OpLoad %i32 %i\n"
9825                         "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
9826                         "             OpStore %i %i_new\n"
9827                         "             OpBranch %loop\n"
9828
9829                         "    %merge = OpLabel\n"
9830                         "             OpReturnValue %param\n"
9831
9832                         "             OpFunctionEnd\n"
9833                 );
9834
9835                 const StringTemplate arg1Calc
9836                 (
9837                         "     %src1 = OpAccessChain %up_v2f16 %ssbo_src1 %c_i32_0 %ndx\n"
9838                         " %val_src1 = OpLoad %v2f16 %src1\n"
9839                 );
9840
9841                 for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
9842                 {
9843                         const deUint32          itemsPerVec     = 2;
9844                         const size_t            iterations      = float16DataVec1.size() / itemsPerVec;
9845                         const TestOp&           testOp          = testOps[testOpsIdx];
9846                         const string            testName        = de::toLower(string(testOp.opCode)) + "_vector";
9847                         SpecResource            specResource;
9848                         map<string, string>     specs;
9849                         vector<string>          extensions;
9850                         VulkanFeatures          features;
9851                         map<string, string>     fragments;
9852
9853                         specs["cap"]                            = "StorageUniformBufferBlock16";
9854                         specs["num_data_points"]        = de::toString(iterations);
9855                         specs["op_code"]                        = testOp.opCode;
9856                         specs["op_arg1"]                        = (testOp.argCount == 1) ? "" : "%val_src1";
9857                         specs["op_arg1_calc"]           = (testOp.argCount == 1) ? "" : arg1Calc.specialize(specs);
9858
9859                         fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
9860                         fragments["capability"]         = capabilities.specialize(specs);
9861                         fragments["decoration"]         = decoration.specialize(specs);
9862                         fragments["pre_main"]           = preMain.specialize(specs);
9863                         fragments["testfun"]            = testFun.specialize(specs);
9864
9865                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16DataVec1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9866                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16DataVec2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9867                         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutVecDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9868                         specResource.verifyIO = nanSupported ? testOp.verifyFuncNan : testOp.verifyFuncNonNan;
9869
9870                         extensions.push_back("VK_KHR_16bit_storage");
9871                         extensions.push_back("VK_KHR_shader_float16_int8");
9872
9873                         if (nanSupported)
9874                         {
9875                                 extensions.push_back("VK_KHR_shader_float_controls");
9876
9877                                 features.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat16 = DE_TRUE;
9878                         }
9879
9880                         features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
9881                         features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
9882
9883                         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
9884                 }
9885         }
9886
9887         return testGroup.release();
9888 }
9889
9890 bool compareFP16FunctionSetFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
9891 {
9892         if (inputs.size() != 1 || outputAllocs.size() != 1)
9893                 return false;
9894
9895         vector<deUint8> input1Bytes;
9896
9897         inputs[0].getBytes(input1Bytes);
9898
9899         const deUint16* const   input1AsFP16    = (const deUint16*)&input1Bytes[0];
9900         const deUint16* const   outputAsFP16    = (const deUint16*)outputAllocs[0]->getHostPtr();
9901         std::string                             error;
9902
9903         for (size_t idx = 0; idx < input1Bytes.size() / sizeof(deUint16); ++idx)
9904         {
9905                 if (!compare16BitFloat(input1AsFP16[idx], outputAsFP16[idx], error))
9906                 {
9907                         log << TestLog::Message << error << TestLog::EndMessage;
9908
9909                         return false;
9910                 }
9911         }
9912
9913         return true;
9914 }
9915
9916 template<class SpecResource>
9917 tcu::TestCaseGroup* createFloat16FuncSet (tcu::TestContext& testCtx)
9918 {
9919         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "function", "Float 16 function call related tests"));
9920
9921         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
9922         const StringTemplate                            capabilities            ("OpCapability ${cap}\n");
9923         const deUint32                                          numDataPoints           = 256;
9924         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
9925         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
9926         map<string, string>                                     fragments;
9927
9928         struct TestType
9929         {
9930                 const deUint32  typeComponents;
9931                 const char*             typeName;
9932                 const char*             typeDecls;
9933         };
9934
9935         const TestType  testTypes[]     =
9936         {
9937                 {
9938                         1,
9939                         "f16",
9940                         ""
9941                 },
9942                 {
9943                         2,
9944                         "v2f16",
9945                         "      %v2f16 = OpTypeVector %f16 2\n"
9946                         "  %c_v2f16_0 = OpConstantComposite %v2f16 %c_f16_0 %c_f16_0\n"
9947                 },
9948                 {
9949                         4,
9950                         "v4f16",
9951                         "      %v4f16 = OpTypeVector %f16 4\n"
9952                         "  %c_v4f16_0 = OpConstantComposite %v4f16 %c_f16_0 %c_f16_0 %c_f16_0 %c_f16_0\n"
9953                 },
9954         };
9955
9956         const StringTemplate preMain
9957         (
9958                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
9959                 "     %v2bool = OpTypeVector %bool 2\n"
9960                 "        %f16 = OpTypeFloat 16\n"
9961                 "    %c_f16_0 = OpConstant %f16 0.0\n"
9962
9963                 "${type_decls}"
9964
9965                 "  %${tt}_fun = OpTypeFunction %${tt} %${tt}\n"
9966                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
9967                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
9968                 "     %SSBO16 = OpTypeStruct %ra_${tt}\n"
9969                 "  %up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
9970                 "   %ssbo_src = OpVariable %up_SSBO16 Uniform\n"
9971                 "   %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
9972         );
9973
9974         const StringTemplate decoration
9975         (
9976                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
9977                 "OpMemberDecorate %SSBO16 0 Offset 0\n"
9978                 "OpDecorate %SSBO16 BufferBlock\n"
9979                 "OpDecorate %ssbo_src DescriptorSet 0\n"
9980                 "OpDecorate %ssbo_src Binding 0\n"
9981                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
9982                 "OpDecorate %ssbo_dst Binding 1\n"
9983         );
9984
9985         const StringTemplate testFun
9986         (
9987                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9988                 "    %param = OpFunctionParameter %v4f32\n"
9989                 "    %entry = OpLabel\n"
9990
9991                 "        %i = OpVariable %fp_i32 Function\n"
9992                 "             OpStore %i %c_i32_0\n"
9993                 "             OpBranch %loop\n"
9994
9995                 "     %loop = OpLabel\n"
9996                 "    %i_cmp = OpLoad %i32 %i\n"
9997                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
9998                 "             OpLoopMerge %merge %next None\n"
9999                 "             OpBranchConditional %lt %write %merge\n"
10000
10001                 "    %write = OpLabel\n"
10002                 "      %ndx = OpLoad %i32 %i\n"
10003
10004                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10005                 "  %val_src = OpLoad %${tt} %src\n"
10006
10007                 "  %val_dst = OpFunctionCall %${tt} %pass_fun %val_src\n"
10008                 "      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
10009                 "             OpStore %dst %val_dst\n"
10010                 "             OpBranch %next\n"
10011
10012                 "     %next = OpLabel\n"
10013                 "    %i_cur = OpLoad %i32 %i\n"
10014                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10015                 "             OpStore %i %i_new\n"
10016                 "             OpBranch %loop\n"
10017
10018                 "    %merge = OpLabel\n"
10019                 "             OpReturnValue %param\n"
10020
10021                 "             OpFunctionEnd\n"
10022
10023                 " %pass_fun = OpFunction %${tt} None %${tt}_fun\n"
10024                 "   %param0 = OpFunctionParameter %${tt}\n"
10025                 " %entry_pf = OpLabel\n"
10026                 "     %res0 = OpFAdd %${tt} %param0 %c_${tt}_0\n"
10027                 "             OpReturnValue %res0\n"
10028                 "             OpFunctionEnd\n"
10029         );
10030
10031         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
10032         {
10033                 const TestType&         testType                = testTypes[testTypeIdx];
10034                 const string            testName                = testType.typeName;
10035                 const deUint32          itemsPerType    = testType.typeComponents;
10036                 const size_t            iterations              = float16InputData.size() / itemsPerType;
10037                 const size_t            typeStride              = itemsPerType * sizeof(deFloat16);
10038                 SpecResource            specResource;
10039                 map<string, string>     specs;
10040                 VulkanFeatures          features;
10041                 vector<string>          extensions;
10042
10043                 specs["cap"]                            = "StorageUniformBufferBlock16";
10044                 specs["num_data_points"]        = de::toString(iterations);
10045                 specs["tt"]                                     = testType.typeName;
10046                 specs["tt_stride"]                      = de::toString(typeStride);
10047                 specs["type_decls"]                     = testType.typeDecls;
10048
10049                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
10050                 fragments["capability"]         = capabilities.specialize(specs);
10051                 fragments["decoration"]         = decoration.specialize(specs);
10052                 fragments["pre_main"]           = preMain.specialize(specs);
10053                 fragments["testfun"]            = testFun.specialize(specs);
10054
10055                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10056                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10057                 specResource.verifyIO = compareFP16FunctionSetFunc;
10058
10059                 extensions.push_back("VK_KHR_16bit_storage");
10060                 extensions.push_back("VK_KHR_shader_float16_int8");
10061
10062                 features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10063                 features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10064
10065                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10066         }
10067
10068         return testGroup.release();
10069 }
10070
10071 struct getV_    { deUint32 inline operator()(deUint32 v) const  { return v;        } getV_(){} };
10072 struct getV0    { deUint32 inline operator()(deUint32 v) const  { return v & (~1); } getV0(){} };
10073 struct getV1    { deUint32 inline operator()(deUint32 v) const  { return v | ( 1); } getV1(){} };
10074
10075 template<deUint32 R, deUint32 N>
10076 inline static deUint32 getOffset(deUint32 x, deUint32 y, deUint32 n)
10077 {
10078         return N * ((R * y) + x) + n;
10079 }
10080
10081 template<deUint32 R, deUint32 N, class X0, class X1, class Y0, class Y1>
10082 struct getFDelta
10083 {
10084         float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10085         {
10086                 DE_STATIC_ASSERT(R%2 == 0);
10087                 DE_ASSERT(flavor == 0);
10088                 DE_UNREF(flavor);
10089
10090                 const X0                        x0;
10091                 const X1                        x1;
10092                 const Y0                        y0;
10093                 const Y1                        y1;
10094                 const deFloat16         v0      = data[getOffset<R, N>(x0(x), y0(y), n)];
10095                 const deFloat16         v1      = data[getOffset<R, N>(x1(x), y1(y), n)];
10096                 const tcu::Float16      f0      = tcu::Float16(v0);
10097                 const tcu::Float16      f1      = tcu::Float16(v1);
10098                 const float                     d0      = f0.asFloat();
10099                 const float                     d1      = f1.asFloat();
10100                 const float                     d       = d1 - d0;
10101
10102                 return d;
10103         }
10104
10105         getFDelta(){}
10106 };
10107
10108 template<deUint32 F, class Class0, class Class1>
10109 struct getFOneOf
10110 {
10111         float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10112         {
10113                 DE_ASSERT(flavor < F);
10114
10115                 if (flavor == 0)
10116                 {
10117                         Class0 c;
10118
10119                         return c(data, x, y, n, flavor);
10120                 }
10121                 else
10122                 {
10123                         Class1 c;
10124
10125                         return c(data, x, y, n, flavor - 1);
10126                 }
10127         }
10128
10129         getFOneOf(){}
10130 };
10131
10132 template<class FineX0, class FineX1, class FineY0, class FineY1>
10133 struct calcWidthOf4
10134 {
10135         float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10136         {
10137                 DE_ASSERT(flavor < 4);
10138
10139                 const deUint32                                          flavorX = (flavor & 1) == 0 ? 0 : 1;
10140                 const deUint32                                          flavorY = (flavor & 2) == 0 ? 0 : 1;
10141                 const getFOneOf<2, FineX0, FineX1>      cx;
10142                 const getFOneOf<2, FineY0, FineY1>      cy;
10143                 float                                                           v               = 0;
10144
10145                 v += fabsf(cx(data, x, y, n, flavorX));
10146                 v += fabsf(cy(data, x, y, n, flavorY));
10147
10148                 return v;
10149         }
10150
10151         calcWidthOf4(){}
10152 };
10153
10154 template<deUint32 R, deUint32 N, class Derivative>
10155 bool compareDerivativeWithFlavor (const deFloat16* inputAsFP16, const deFloat16* outputAsFP16, deUint32 flavor, std::string& error)
10156 {
10157         const deUint32          numDataPointsByAxis     = R;
10158         const Derivative        derivativeFunc;
10159
10160         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10161         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10162         for (deUint32 n = 0; n < N; ++n)
10163         {
10164                 const float             expectedFloat   = derivativeFunc(inputAsFP16, x, y, n, flavor);
10165                 deFloat16               expected                = deFloat32To16Round(expectedFloat, DE_ROUNDINGMODE_TO_NEAREST_EVEN);
10166                 const deFloat16 output                  = outputAsFP16[getOffset<R, N>(x, y, n)];
10167
10168                 bool                    reportError             = !compare16BitFloat(expected, output, error);
10169
10170                 if (reportError)
10171                 {
10172                         expected        = deFloat32To16Round(expectedFloat, DE_ROUNDINGMODE_TO_ZERO);
10173                         reportError     = !compare16BitFloat(expected, output, error);
10174                 }
10175
10176                 if (reportError)
10177                 {
10178                         error = "subcase at " + de::toString(x) + "," + de::toString(y) + "," + de::toString(n) + ": " + error;
10179
10180                         return false;
10181                 }
10182         }
10183
10184         return true;
10185 }
10186
10187 template<deUint32 R, deUint32 N, deUint32 FLAVOUR_COUNT, class Derivative>
10188 bool compareDerivative (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10189 {
10190         if (inputs.size() != 1 || outputAllocs.size() != 1)
10191                 return false;
10192
10193         deUint32                        successfulRuns                  = FLAVOUR_COUNT;
10194         std::string                     results[FLAVOUR_COUNT];
10195         vector<deUint8>         inputBytes;
10196
10197         inputs[0].getBytes(inputBytes);
10198
10199         const deFloat16*        inputAsFP16             = reinterpret_cast<deFloat16* const>(&inputBytes.front());
10200         const deFloat16*        outputAsFP16    = static_cast<deFloat16*>(outputAllocs[0]->getHostPtr());
10201
10202         DE_ASSERT(inputBytes.size() ==  R * R * N * sizeof(deFloat16));
10203
10204         for (deUint32 flavor = 0; flavor < FLAVOUR_COUNT; ++flavor)
10205                 if (compareDerivativeWithFlavor<R, N, Derivative> (inputAsFP16, outputAsFP16, flavor, results[flavor]))
10206                 {
10207                         break;
10208                 }
10209                 else
10210                 {
10211                         successfulRuns--;
10212                 }
10213
10214         if (successfulRuns == 0)
10215                 for (deUint32 flavor = 0; flavor < FLAVOUR_COUNT; flavor++)
10216                         log << TestLog::Message << "At flavor #" << flavor << " " << results[flavor] << TestLog::EndMessage;
10217
10218         return successfulRuns > 0;
10219 }
10220
10221 template<deUint32 R, deUint32 N>
10222 tcu::TestCaseGroup* createDerivativeTests (tcu::TestContext& testCtx)
10223 {
10224         typedef getFDelta<R, N, getV0, getV1, getV_, getV_> getFDxFine;
10225         typedef getFDelta<R, N, getV_, getV_, getV0, getV1> getFDyFine;
10226
10227         typedef getFDelta<R, N, getV0, getV1, getV0, getV0> getFdxCoarse0;
10228         typedef getFDelta<R, N, getV0, getV1, getV1, getV1> getFdxCoarse1;
10229         typedef getFDelta<R, N, getV0, getV0, getV0, getV1> getFdyCoarse0;
10230         typedef getFDelta<R, N, getV1, getV1, getV0, getV1> getFdyCoarse1;
10231         typedef getFOneOf<2, getFdxCoarse0, getFdxCoarse1> getFDxCoarse;
10232         typedef getFOneOf<2, getFdyCoarse0, getFdyCoarse1> getFDyCoarse;
10233
10234         typedef calcWidthOf4<getFDxFine, getFDxFine, getFDyFine, getFDyFine> getFWidthFine;
10235         typedef calcWidthOf4<getFdxCoarse0, getFdxCoarse1, getFdyCoarse0, getFdyCoarse1> getFWidthCoarse;
10236
10237         typedef getFOneOf<3, getFDxFine, getFDxCoarse> getFDx;
10238         typedef getFOneOf<3, getFDyFine, getFDyCoarse> getFDy;
10239         typedef getFOneOf<5, getFWidthFine, getFWidthCoarse> getFWidth;
10240
10241         const std::string                                       testGroupName           (std::string("derivative_") + de::toString(N));
10242         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Derivative instruction tests"));
10243
10244         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10245         const deUint32                                          numDataPointsByAxis     = R;
10246         const deUint32                                          numDataPoints           = N * numDataPointsByAxis * numDataPointsByAxis;
10247         vector<deFloat16>                                       float16InputX;
10248         vector<deFloat16>                                       float16InputY;
10249         vector<deFloat16>                                       float16InputW;
10250         vector<deFloat16>                                       float16OutputDummy      (numDataPoints, 0);
10251         RGBA                                                            defaultColors[4];
10252
10253         getDefaultColors(defaultColors);
10254
10255         float16InputX.reserve(numDataPoints);
10256         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10257         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10258         for (deUint32 n = 0; n < N; ++n)
10259         {
10260                 const float arg = static_cast<float>(2 * DE_PI) * static_cast<float>(x * (n + 1)) / static_cast<float>(1 * numDataPointsByAxis);
10261
10262                 if (y%2 == 0)
10263                         float16InputX.push_back(tcu::Float16(sin(arg)).bits());
10264                 else
10265                         float16InputX.push_back(tcu::Float16(cos(arg)).bits());
10266         }
10267
10268         float16InputY.reserve(numDataPoints);
10269         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10270         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10271         for (deUint32 n = 0; n < N; ++n)
10272         {
10273                 const float arg = static_cast<float>(2 * DE_PI) * static_cast<float>(y * (n + 1)) / static_cast<float>(1 * numDataPointsByAxis);
10274
10275                 if (x%2 == 0)
10276                         float16InputY.push_back(tcu::Float16(sin(arg)).bits());
10277                 else
10278                         float16InputY.push_back(tcu::Float16(cos(arg)).bits());
10279         }
10280
10281         const deFloat16 testNumbers[]   =
10282         {
10283                 tcu::Float16( 2.0  ).bits(),
10284                 tcu::Float16( 4.0  ).bits(),
10285                 tcu::Float16( 8.0  ).bits(),
10286                 tcu::Float16( 16.0 ).bits(),
10287                 tcu::Float16( 32.0 ).bits(),
10288                 tcu::Float16( 64.0 ).bits(),
10289                 tcu::Float16( 128.0).bits(),
10290                 tcu::Float16( 256.0).bits(),
10291                 tcu::Float16( 512.0).bits(),
10292                 tcu::Float16(-2.0  ).bits(),
10293                 tcu::Float16(-4.0  ).bits(),
10294                 tcu::Float16(-8.0  ).bits(),
10295                 tcu::Float16(-16.0 ).bits(),
10296                 tcu::Float16(-32.0 ).bits(),
10297                 tcu::Float16(-64.0 ).bits(),
10298                 tcu::Float16(-128.0).bits(),
10299                 tcu::Float16(-256.0).bits(),
10300                 tcu::Float16(-512.0).bits(),
10301         };
10302
10303         float16InputW.reserve(numDataPoints);
10304         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10305         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10306         for (deUint32 n = 0; n < N; ++n)
10307                 float16InputW.push_back(testNumbers[rnd.getInt(0, DE_LENGTH_OF_ARRAY(testNumbers) - 1)]);
10308
10309         struct TestOp
10310         {
10311                 const char*                     opCode;
10312                 vector<deFloat16>&      inputData;
10313                 VerifyIOFunc            verifyFunc;
10314         };
10315
10316         const TestOp    testOps[]       =
10317         {
10318                 { "OpDPdxFine"          ,       float16InputX   ,       compareDerivative<R, N, 1, getFDxFine           >       },
10319                 { "OpDPdyFine"          ,       float16InputY   ,       compareDerivative<R, N, 1, getFDyFine           >       },
10320                 { "OpFwidthFine"        ,       float16InputW   ,       compareDerivative<R, N, 1, getFWidthFine        >       },
10321                 { "OpDPdxCoarse"        ,       float16InputX   ,       compareDerivative<R, N, 3, getFDx                       >       },
10322                 { "OpDPdyCoarse"        ,       float16InputY   ,       compareDerivative<R, N, 3, getFDy                       >       },
10323                 { "OpFwidthCoarse"      ,       float16InputW   ,       compareDerivative<R, N, 5, getFWidth            >       },
10324                 { "OpDPdx"                      ,       float16InputX   ,       compareDerivative<R, N, 3, getFDx                       >       },
10325                 { "OpDPdy"                      ,       float16InputY   ,       compareDerivative<R, N, 3, getFDy                       >       },
10326                 { "OpFwidth"            ,       float16InputW   ,       compareDerivative<R, N, 5, getFWidth            >       },
10327         };
10328
10329         struct TestType
10330         {
10331                 const deUint32  typeComponents;
10332                 const char*             typeName;
10333                 const char*             typeDecls;
10334         };
10335
10336         const TestType  testTypes[]     =
10337         {
10338                 {
10339                         1,
10340                         "f16",
10341                         ""
10342                 },
10343                 {
10344                         2,
10345                         "v2f16",
10346                         "      %v2f16 = OpTypeVector %f16 2\n"
10347                 },
10348                 {
10349                         4,
10350                         "v4f16",
10351                         "      %v4f16 = OpTypeVector %f16 4\n"
10352                 },
10353         };
10354
10355         const deUint32  testTypeNdx     = (N == 1) ? 0
10356                                                                 : (N == 2) ? 1
10357                                                                 : (N == 4) ? 2
10358                                                                 : DE_LENGTH_OF_ARRAY(testTypes);
10359         const TestType& testType        =       testTypes[testTypeNdx];
10360
10361         DE_ASSERT(testTypeNdx < DE_LENGTH_OF_ARRAY(testTypes));
10362         DE_ASSERT(testType.typeComponents == N);
10363
10364         const StringTemplate preMain
10365         (
10366                 "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10367                 " %c_u32_xw = OpConstant %u32 ${items_by_x}\n"
10368                 "      %f16 = OpTypeFloat 16\n"
10369                 "${type_decls}"
10370                 " %up_${tt} = OpTypePointer Uniform %${tt}\n"
10371                 " %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10372                 "   %SSBO16 = OpTypeStruct %ra_${tt}\n"
10373                 "%up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10374                 " %ssbo_src = OpVariable %up_SSBO16 Uniform\n"
10375                 " %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10376         );
10377
10378         const StringTemplate decoration
10379         (
10380                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10381                 "OpMemberDecorate %SSBO16 0 Offset 0\n"
10382                 "OpDecorate %SSBO16 BufferBlock\n"
10383                 "OpDecorate %ssbo_src DescriptorSet 0\n"
10384                 "OpDecorate %ssbo_src Binding 0\n"
10385                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
10386                 "OpDecorate %ssbo_dst Binding 1\n"
10387         );
10388
10389         const StringTemplate testFun
10390         (
10391                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10392                 "    %param = OpFunctionParameter %v4f32\n"
10393                 "    %entry = OpLabel\n"
10394
10395                 "  %loc_x_c = OpAccessChain %ip_f32 %BP_gl_FragCoord %c_i32_0\n"
10396                 "  %loc_y_c = OpAccessChain %ip_f32 %BP_gl_FragCoord %c_i32_1\n"
10397                 "      %x_c = OpLoad %f32 %loc_x_c\n"
10398                 "      %y_c = OpLoad %f32 %loc_y_c\n"
10399                 "    %x_idx = OpConvertFToU %u32 %x_c\n"
10400                 "    %y_idx = OpConvertFToU %u32 %y_c\n"
10401                 "    %ndx_y = OpIMul %u32 %y_idx %c_u32_xw\n"
10402                 "      %ndx = OpIAdd %u32 %ndx_y %x_idx\n"
10403
10404                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10405                 "  %val_src = OpLoad %${tt} %src\n"
10406                 "  %val_dst = ${op_code} %${tt} %val_src\n"
10407                 "      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
10408                 "             OpStore %dst %val_dst\n"
10409                 "             OpBranch %merge\n"
10410
10411                 "    %merge = OpLabel\n"
10412                 "             OpReturnValue %param\n"
10413
10414                 "             OpFunctionEnd\n"
10415         );
10416
10417         for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10418         {
10419                 const TestOp&           testOp                  = testOps[testOpsIdx];
10420                 const string            testName                = de::toLower(string(testOp.opCode));
10421                 const size_t            typeStride              = N * sizeof(deFloat16);
10422                 GraphicsResources       specResource;
10423                 map<string, string>     specs;
10424                 VulkanFeatures          features;
10425                 vector<string>          extensions;
10426                 map<string, string>     fragments;
10427                 SpecConstants           noSpecConstants;
10428                 PushConstants           noPushConstants;
10429                 GraphicsInterfaces      noInterfaces;
10430                 vector<string>          noFeatures;
10431
10432                 specs["op_code"]                        = testOp.opCode;
10433                 specs["num_data_points"]        = de::toString(testOp.inputData.size() / N);
10434                 specs["items_by_x"]                     = de::toString(numDataPointsByAxis);
10435                 specs["tt"]                                     = testType.typeName;
10436                 specs["tt_stride"]                      = de::toString(typeStride);
10437                 specs["type_decls"]                     = testType.typeDecls;
10438
10439                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
10440                 fragments["capability"]         = "OpCapability DerivativeControl\nOpCapability StorageUniformBufferBlock16\n";
10441                 fragments["decoration"]         = decoration.specialize(specs);
10442                 fragments["pre_main"]           = preMain.specialize(specs);
10443                 fragments["testfun"]            = testFun.specialize(specs);
10444
10445                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(testOp.inputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10446                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10447                 specResource.verifyIO = testOp.verifyFunc;
10448
10449                 extensions.push_back("VK_KHR_16bit_storage");
10450                 extensions.push_back("VK_KHR_shader_float16_int8");
10451
10452                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
10453                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10454
10455                 createTestForStage(VK_SHADER_STAGE_FRAGMENT_BIT, testName.c_str(), defaultColors, defaultColors, fragments, noSpecConstants,
10456                                                         noPushConstants, specResource, noInterfaces, extensions, noFeatures, features, testGroup.get(), QP_TEST_RESULT_FAIL, string(), true);
10457         }
10458
10459         return testGroup.release();
10460 }
10461
10462 bool compareFP16VectorExtractFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10463 {
10464         if (inputs.size() != 2 || outputAllocs.size() != 1)
10465                 return false;
10466
10467         vector<deUint8> input1Bytes;
10468         vector<deUint8> input2Bytes;
10469
10470         inputs[0].getBytes(input1Bytes);
10471         inputs[1].getBytes(input2Bytes);
10472
10473         DE_ASSERT(input1Bytes.size() > 0);
10474         DE_ASSERT(input2Bytes.size() > 0);
10475         DE_ASSERT(input2Bytes.size() % sizeof(deUint32) == 0);
10476
10477         const size_t                    iterations              = input2Bytes.size() / sizeof(deUint32);
10478         const size_t                    components              = input1Bytes.size() / (sizeof(deFloat16) * iterations);
10479         const deFloat16* const  input1AsFP16    = (const deFloat16*)&input1Bytes[0];
10480         const deUint32* const   inputIndices    = (const deUint32*)&input2Bytes[0];
10481         const deFloat16* const  outputAsFP16    = (const deFloat16*)outputAllocs[0]->getHostPtr();
10482         std::string                             error;
10483
10484         DE_ASSERT(components == 2 || components == 4);
10485         DE_ASSERT(input1Bytes.size() == iterations * components * sizeof(deFloat16));
10486
10487         for (size_t idx = 0; idx < iterations; ++idx)
10488         {
10489                 const deUint32  componentNdx    = inputIndices[idx];
10490
10491                 DE_ASSERT(componentNdx < components);
10492
10493                 const deFloat16 expected                = input1AsFP16[components * idx + componentNdx];
10494
10495                 if (!compare16BitFloat(expected, outputAsFP16[idx], error))
10496                 {
10497                         log << TestLog::Message << "At " << idx << error << TestLog::EndMessage;
10498
10499                         return false;
10500                 }
10501         }
10502
10503         return true;
10504 }
10505
10506 template<class SpecResource>
10507 tcu::TestCaseGroup* createFloat16VectorExtractSet (tcu::TestContext& testCtx)
10508 {
10509         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorextractdynamic", "OpVectorExtractDynamic tests"));
10510
10511         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10512         const deUint32                                          numDataPoints           = 256;
10513         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
10514         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
10515
10516         struct TestType
10517         {
10518                 const deUint32  typeComponents;
10519                 const size_t    typeStride;
10520                 const char*             typeName;
10521                 const char*             typeDecls;
10522         };
10523
10524         const TestType  testTypes[]     =
10525         {
10526                 {
10527                         2,
10528                         2 * sizeof(deFloat16),
10529                         "v2f16",
10530                         "      %v2f16 = OpTypeVector %f16 2\n"
10531                 },
10532                 {
10533                         3,
10534                         4 * sizeof(deFloat16),
10535                         "v3f16",
10536                         "      %v3f16 = OpTypeVector %f16 3\n"
10537                 },
10538                 {
10539                         4,
10540                         4 * sizeof(deFloat16),
10541                         "v4f16",
10542                         "      %v4f16 = OpTypeVector %f16 4\n"
10543                 },
10544         };
10545
10546         const StringTemplate preMain
10547         (
10548                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10549                 "        %f16 = OpTypeFloat 16\n"
10550
10551                 "${type_decl}"
10552
10553                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
10554                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10555                 "   %SSBO_SRC = OpTypeStruct %ra_${tt}\n"
10556                 "%up_SSBO_SRC = OpTypePointer Uniform %SSBO_SRC\n"
10557
10558                 "     %up_u32 = OpTypePointer Uniform %u32\n"
10559                 "     %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
10560                 "   %SSBO_IDX = OpTypeStruct %ra_u32\n"
10561                 "%up_SSBO_IDX = OpTypePointer Uniform %SSBO_IDX\n"
10562
10563                 "     %up_f16 = OpTypePointer Uniform %f16\n"
10564                 "     %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
10565                 "   %SSBO_DST = OpTypeStruct %ra_f16\n"
10566                 "%up_SSBO_DST = OpTypePointer Uniform %SSBO_DST\n"
10567
10568                 "   %ssbo_src = OpVariable %up_SSBO_SRC Uniform\n"
10569                 "   %ssbo_idx = OpVariable %up_SSBO_IDX Uniform\n"
10570                 "   %ssbo_dst = OpVariable %up_SSBO_DST Uniform\n"
10571         );
10572
10573         const StringTemplate decoration
10574         (
10575                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10576                 "OpMemberDecorate %SSBO_SRC 0 Offset 0\n"
10577                 "OpDecorate %SSBO_SRC BufferBlock\n"
10578                 "OpDecorate %ssbo_src DescriptorSet 0\n"
10579                 "OpDecorate %ssbo_src Binding 0\n"
10580
10581                 "OpDecorate %ra_u32 ArrayStride 4\n"
10582                 "OpMemberDecorate %SSBO_IDX 0 Offset 0\n"
10583                 "OpDecorate %SSBO_IDX BufferBlock\n"
10584                 "OpDecorate %ssbo_idx DescriptorSet 0\n"
10585                 "OpDecorate %ssbo_idx Binding 1\n"
10586
10587                 "OpDecorate %ra_f16 ArrayStride 2\n"
10588                 "OpMemberDecorate %SSBO_DST 0 Offset 0\n"
10589                 "OpDecorate %SSBO_DST BufferBlock\n"
10590                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
10591                 "OpDecorate %ssbo_dst Binding 2\n"
10592         );
10593
10594         const StringTemplate testFun
10595         (
10596                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10597                 "    %param = OpFunctionParameter %v4f32\n"
10598                 "    %entry = OpLabel\n"
10599
10600                 "        %i = OpVariable %fp_i32 Function\n"
10601                 "             OpStore %i %c_i32_0\n"
10602
10603                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
10604                 "             OpSelectionMerge %end_if None\n"
10605                 "             OpBranchConditional %will_run %run_test %end_if\n"
10606
10607                 " %run_test = OpLabel\n"
10608                 "             OpBranch %loop\n"
10609
10610                 "     %loop = OpLabel\n"
10611                 "    %i_cmp = OpLoad %i32 %i\n"
10612                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10613                 "             OpLoopMerge %merge %next None\n"
10614                 "             OpBranchConditional %lt %write %merge\n"
10615
10616                 "    %write = OpLabel\n"
10617                 "      %ndx = OpLoad %i32 %i\n"
10618
10619                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10620                 "  %val_src = OpLoad %${tt} %src\n"
10621
10622                 "  %src_idx = OpAccessChain %up_u32 %ssbo_idx %c_i32_0 %ndx\n"
10623                 "  %val_idx = OpLoad %u32 %src_idx\n"
10624
10625                 "  %val_dst = OpVectorExtractDynamic %f16 %val_src %val_idx\n"
10626                 "      %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
10627
10628                 "             OpStore %dst %val_dst\n"
10629                 "             OpBranch %next\n"
10630
10631                 "     %next = OpLabel\n"
10632                 "    %i_cur = OpLoad %i32 %i\n"
10633                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10634                 "             OpStore %i %i_new\n"
10635                 "             OpBranch %loop\n"
10636
10637                 "    %merge = OpLabel\n"
10638                 "             OpBranch %end_if\n"
10639                 "   %end_if = OpLabel\n"
10640                 "             OpReturnValue %param\n"
10641
10642                 "             OpFunctionEnd\n"
10643         );
10644
10645         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
10646         {
10647                 const TestType&         testType                = testTypes[testTypeIdx];
10648                 const string            testName                = testType.typeName;
10649                 const size_t            itemsPerType    = testType.typeStride / sizeof(deFloat16);
10650                 const size_t            iterations              = float16InputData.size() / itemsPerType;
10651                 SpecResource            specResource;
10652                 map<string, string>     specs;
10653                 VulkanFeatures          features;
10654                 vector<deUint32>        inputDataNdx;
10655                 map<string, string>     fragments;
10656                 vector<string>          extensions;
10657
10658                 for (deUint32 ndx = 0; ndx < iterations; ++ndx)
10659                         inputDataNdx.push_back(rnd.getUint32() % testType.typeComponents);
10660
10661                 specs["num_data_points"]        = de::toString(iterations);
10662                 specs["tt"]                                     = testType.typeName;
10663                 specs["tt_stride"]                      = de::toString(testType.typeStride);
10664                 specs["type_decl"]                      = testType.typeDecls;
10665
10666                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
10667                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
10668                 fragments["decoration"]         = decoration.specialize(specs);
10669                 fragments["pre_main"]           = preMain.specialize(specs);
10670                 fragments["testfun"]            = testFun.specialize(specs);
10671
10672                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10673                 specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inputDataNdx)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10674                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10675                 specResource.verifyIO = compareFP16VectorExtractFunc;
10676
10677                 extensions.push_back("VK_KHR_16bit_storage");
10678                 extensions.push_back("VK_KHR_shader_float16_int8");
10679
10680                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
10681                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10682
10683                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10684         }
10685
10686         return testGroup.release();
10687 }
10688
10689 template<deUint32 COMPONENTS_COUNT, deUint32 REPLACEMENT>
10690 bool compareFP16VectorInsertFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10691 {
10692         if (inputs.size() != 2 || outputAllocs.size() != 1)
10693                 return false;
10694
10695         vector<deUint8> input1Bytes;
10696         vector<deUint8> input2Bytes;
10697
10698         inputs[0].getBytes(input1Bytes);
10699         inputs[1].getBytes(input2Bytes);
10700
10701         DE_ASSERT(input1Bytes.size() > 0);
10702         DE_ASSERT(input2Bytes.size() > 0);
10703         DE_ASSERT(input2Bytes.size() % sizeof(deUint32) == 0);
10704
10705         const size_t                    iterations                      = input2Bytes.size() / sizeof(deUint32);
10706         const size_t                    componentsStride        = input1Bytes.size() / (sizeof(deFloat16) * iterations);
10707         const deFloat16* const  input1AsFP16            = (const deFloat16*)&input1Bytes[0];
10708         const deUint32* const   inputIndices            = (const deUint32*)&input2Bytes[0];
10709         const deFloat16* const  outputAsFP16            = (const deFloat16*)outputAllocs[0]->getHostPtr();
10710         const deFloat16                 magic                           = tcu::Float16(float(REPLACEMENT)).bits();
10711         std::string                             error;
10712
10713         DE_ASSERT(componentsStride == 2 || componentsStride == 4);
10714         DE_ASSERT(input1Bytes.size() == iterations * componentsStride * sizeof(deFloat16));
10715
10716         for (size_t idx = 0; idx < iterations; ++idx)
10717         {
10718                 const deFloat16*        inputVec                = &input1AsFP16[componentsStride * idx];
10719                 const deFloat16*        outputVec               = &outputAsFP16[componentsStride * idx];
10720                 const deUint32          replacedCompNdx = inputIndices[idx];
10721
10722                 DE_ASSERT(replacedCompNdx < COMPONENTS_COUNT);
10723
10724                 for (size_t compNdx = 0; compNdx < COMPONENTS_COUNT; ++compNdx)
10725                 {
10726                         const deFloat16 expected        = (compNdx == replacedCompNdx) ? magic : inputVec[compNdx];
10727
10728                         if (!compare16BitFloat(expected, outputVec[compNdx], error))
10729                         {
10730                                 log << TestLog::Message << "At " << idx << "[" << compNdx << "]: " << error << TestLog::EndMessage;
10731
10732                                 return false;
10733                         }
10734                 }
10735         }
10736
10737         return true;
10738 }
10739
10740 template<class SpecResource>
10741 tcu::TestCaseGroup* createFloat16VectorInsertSet (tcu::TestContext& testCtx)
10742 {
10743         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorinsertdynamic", "OpVectorInsertDynamic tests"));
10744
10745         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10746         const deUint32                                          replacement                     = 42;
10747         const deUint32                                          numDataPoints           = 256;
10748         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
10749         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
10750
10751         struct TestType
10752         {
10753                 const deUint32  typeComponents;
10754                 const size_t    typeStride;
10755                 const char*             typeName;
10756                 const char*             typeDecls;
10757                 VerifyIOFunc    verifyIOFunc;
10758         };
10759
10760         const TestType  testTypes[]     =
10761         {
10762                 {
10763                         2,
10764                         2 * sizeof(deFloat16),
10765                         "v2f16",
10766                         "      %v2f16 = OpTypeVector %f16 2\n",
10767                         compareFP16VectorInsertFunc<2, replacement>
10768                 },
10769                 {
10770                         3,
10771                         4 * sizeof(deFloat16),
10772                         "v3f16",
10773                         "      %v3f16 = OpTypeVector %f16 3\n",
10774                         compareFP16VectorInsertFunc<3, replacement>
10775                 },
10776                 {
10777                         4,
10778                         4 * sizeof(deFloat16),
10779                         "v4f16",
10780                         "      %v4f16 = OpTypeVector %f16 4\n",
10781                         compareFP16VectorInsertFunc<4, replacement>
10782                 },
10783         };
10784
10785         const StringTemplate preMain
10786         (
10787                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10788                 "        %f16 = OpTypeFloat 16\n"
10789                 "  %c_f16_ins = OpConstant %f16 ${replacement}\n"
10790
10791                 "${type_decl}"
10792
10793                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
10794                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10795                 "   %SSBO_SRC = OpTypeStruct %ra_${tt}\n"
10796                 "%up_SSBO_SRC = OpTypePointer Uniform %SSBO_SRC\n"
10797
10798                 "     %up_u32 = OpTypePointer Uniform %u32\n"
10799                 "     %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
10800                 "   %SSBO_IDX = OpTypeStruct %ra_u32\n"
10801                 "%up_SSBO_IDX = OpTypePointer Uniform %SSBO_IDX\n"
10802
10803                 "   %SSBO_DST = OpTypeStruct %ra_${tt}\n"
10804                 "%up_SSBO_DST = OpTypePointer Uniform %SSBO_DST\n"
10805
10806                 "   %ssbo_src = OpVariable %up_SSBO_SRC Uniform\n"
10807                 "   %ssbo_idx = OpVariable %up_SSBO_IDX Uniform\n"
10808                 "   %ssbo_dst = OpVariable %up_SSBO_DST Uniform\n"
10809         );
10810
10811         const StringTemplate decoration
10812         (
10813                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10814                 "OpMemberDecorate %SSBO_SRC 0 Offset 0\n"
10815                 "OpDecorate %SSBO_SRC BufferBlock\n"
10816                 "OpDecorate %ssbo_src DescriptorSet 0\n"
10817                 "OpDecorate %ssbo_src Binding 0\n"
10818
10819                 "OpDecorate %ra_u32 ArrayStride 4\n"
10820                 "OpMemberDecorate %SSBO_IDX 0 Offset 0\n"
10821                 "OpDecorate %SSBO_IDX BufferBlock\n"
10822                 "OpDecorate %ssbo_idx DescriptorSet 0\n"
10823                 "OpDecorate %ssbo_idx Binding 1\n"
10824
10825                 "OpMemberDecorate %SSBO_DST 0 Offset 0\n"
10826                 "OpDecorate %SSBO_DST BufferBlock\n"
10827                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
10828                 "OpDecorate %ssbo_dst Binding 2\n"
10829         );
10830
10831         const StringTemplate testFun
10832         (
10833                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10834                 "    %param = OpFunctionParameter %v4f32\n"
10835                 "    %entry = OpLabel\n"
10836
10837                 "        %i = OpVariable %fp_i32 Function\n"
10838                 "             OpStore %i %c_i32_0\n"
10839
10840                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
10841                 "             OpSelectionMerge %end_if None\n"
10842                 "             OpBranchConditional %will_run %run_test %end_if\n"
10843
10844                 " %run_test = OpLabel\n"
10845                 "             OpBranch %loop\n"
10846
10847                 "     %loop = OpLabel\n"
10848                 "    %i_cmp = OpLoad %i32 %i\n"
10849                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10850                 "             OpLoopMerge %merge %next None\n"
10851                 "             OpBranchConditional %lt %write %merge\n"
10852
10853                 "    %write = OpLabel\n"
10854                 "      %ndx = OpLoad %i32 %i\n"
10855
10856                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10857                 "  %val_src = OpLoad %${tt} %src\n"
10858
10859                 "  %src_idx = OpAccessChain %up_u32 %ssbo_idx %c_i32_0 %ndx\n"
10860                 "  %val_idx = OpLoad %u32 %src_idx\n"
10861
10862                 "  %val_dst = OpVectorInsertDynamic %${tt} %val_src %c_f16_ins %val_idx\n"
10863                 "      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
10864
10865                 "             OpStore %dst %val_dst\n"
10866                 "             OpBranch %next\n"
10867
10868                 "     %next = OpLabel\n"
10869                 "    %i_cur = OpLoad %i32 %i\n"
10870                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10871                 "             OpStore %i %i_new\n"
10872                 "             OpBranch %loop\n"
10873
10874                 "    %merge = OpLabel\n"
10875                 "             OpBranch %end_if\n"
10876                 "   %end_if = OpLabel\n"
10877                 "             OpReturnValue %param\n"
10878
10879                 "             OpFunctionEnd\n"
10880         );
10881
10882         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
10883         {
10884                 const TestType&         testType                = testTypes[testTypeIdx];
10885                 const string            testName                = testType.typeName;
10886                 const size_t            itemsPerType    = testType.typeStride / sizeof(deFloat16);
10887                 const size_t            iterations              = float16InputData.size() / itemsPerType;
10888                 SpecResource            specResource;
10889                 map<string, string>     specs;
10890                 VulkanFeatures          features;
10891                 vector<deUint32>        inputDataNdx;
10892                 map<string, string>     fragments;
10893                 vector<string>          extensions;
10894
10895                 for (deUint32 ndx = 0; ndx < iterations; ++ndx)
10896                         inputDataNdx.push_back(rnd.getUint32() % testType.typeComponents);
10897
10898                 specs["num_data_points"]        = de::toString(iterations);
10899                 specs["tt"]                                     = testType.typeName;
10900                 specs["tt_stride"]                      = de::toString(testType.typeStride);
10901                 specs["type_decl"]                      = testType.typeDecls;
10902                 specs["replacement"]            = de::toString(replacement);
10903
10904                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
10905                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
10906                 fragments["decoration"]         = decoration.specialize(specs);
10907                 fragments["pre_main"]           = preMain.specialize(specs);
10908                 fragments["testfun"]            = testFun.specialize(specs);
10909
10910                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10911                 specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inputDataNdx)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10912                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10913                 specResource.verifyIO = testType.verifyIOFunc;
10914
10915                 extensions.push_back("VK_KHR_16bit_storage");
10916                 extensions.push_back("VK_KHR_shader_float16_int8");
10917
10918                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
10919                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10920
10921                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10922         }
10923
10924         return testGroup.release();
10925 }
10926
10927 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)
10928 {
10929         const size_t    compNdxCount    = (vec1Len + vec2Len + 1);
10930         const size_t    compNdxLimited  = iteration % (compNdxCount * compNdxCount);
10931         size_t                  comp;
10932
10933         switch (componentNdx)
10934         {
10935                 case 0: comp = compNdxLimited / compNdxCount; break;
10936                 case 1: comp = compNdxLimited % compNdxCount; break;
10937                 case 2: comp = 0; break;
10938                 case 3: comp = 1; break;
10939                 default: TCU_THROW(InternalError, "Impossible");
10940         }
10941
10942         if (comp >= vec1Len + vec2Len)
10943         {
10944                 validate = false;
10945                 return 0;
10946         }
10947         else
10948         {
10949                 validate = true;
10950                 return (comp < vec1Len) ? input1Vec[comp] : input2Vec[comp - vec1Len];
10951         }
10952 }
10953
10954 template<deUint32 DST_COMPONENTS_COUNT, deUint32 SRC0_COMPONENTS_COUNT, deUint32 SRC1_COMPONENTS_COUNT>
10955 bool compareFP16VectorShuffleFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10956 {
10957         DE_STATIC_ASSERT(DST_COMPONENTS_COUNT == 2 || DST_COMPONENTS_COUNT == 3 || DST_COMPONENTS_COUNT == 4);
10958         DE_STATIC_ASSERT(SRC0_COMPONENTS_COUNT == 2 || SRC0_COMPONENTS_COUNT == 3 || SRC0_COMPONENTS_COUNT == 4);
10959         DE_STATIC_ASSERT(SRC1_COMPONENTS_COUNT == 2 || SRC1_COMPONENTS_COUNT == 3 || SRC1_COMPONENTS_COUNT == 4);
10960
10961         if (inputs.size() != 2 || outputAllocs.size() != 1)
10962                 return false;
10963
10964         vector<deUint8> input1Bytes;
10965         vector<deUint8> input2Bytes;
10966
10967         inputs[0].getBytes(input1Bytes);
10968         inputs[1].getBytes(input2Bytes);
10969
10970         DE_ASSERT(input1Bytes.size() > 0);
10971         DE_ASSERT(input2Bytes.size() > 0);
10972         DE_ASSERT(input2Bytes.size() % sizeof(deFloat16) == 0);
10973
10974         const size_t                    componentsStrideDst             = (DST_COMPONENTS_COUNT == 3) ? 4 : DST_COMPONENTS_COUNT;
10975         const size_t                    componentsStrideSrc0    = (SRC0_COMPONENTS_COUNT == 3) ? 4 : SRC0_COMPONENTS_COUNT;
10976         const size_t                    componentsStrideSrc1    = (SRC1_COMPONENTS_COUNT == 3) ? 4 : SRC1_COMPONENTS_COUNT;
10977         const size_t                    iterations                              = input1Bytes.size() / (componentsStrideSrc0 * sizeof(deFloat16));
10978         const deFloat16* const  input1AsFP16                    = (const deFloat16*)&input1Bytes[0];
10979         const deFloat16* const  input2AsFP16                    = (const deFloat16*)&input2Bytes[0];
10980         const deFloat16* const  outputAsFP16                    = (const deFloat16*)outputAllocs[0]->getHostPtr();
10981         std::string                             error;
10982
10983         DE_ASSERT(input1Bytes.size() == iterations * componentsStrideSrc0 * sizeof(deFloat16));
10984         DE_ASSERT(input2Bytes.size() == iterations * componentsStrideSrc1 * sizeof(deFloat16));
10985
10986         for (size_t idx = 0; idx < iterations; ++idx)
10987         {
10988                 const deFloat16*        input1Vec       = &input1AsFP16[componentsStrideSrc0 * idx];
10989                 const deFloat16*        input2Vec       = &input2AsFP16[componentsStrideSrc1 * idx];
10990                 const deFloat16*        outputVec       = &outputAsFP16[componentsStrideDst * idx];
10991
10992                 for (size_t compNdx = 0; compNdx < DST_COMPONENTS_COUNT; ++compNdx)
10993                 {
10994                         bool            validate        = true;
10995                         deFloat16       expected        = getShuffledComponent(idx, compNdx, input1Vec, input2Vec, SRC0_COMPONENTS_COUNT, SRC1_COMPONENTS_COUNT, validate);
10996
10997                         if (validate && !compare16BitFloat(expected, outputVec[compNdx], error))
10998                         {
10999                                 log << TestLog::Message << "At " << idx << "[" << compNdx << "]: " << error << TestLog::EndMessage;
11000
11001                                 return false;
11002                         }
11003                 }
11004         }
11005
11006         return true;
11007 }
11008
11009 VerifyIOFunc getFloat16VectorShuffleVerifyIOFunc (deUint32 dstComponentsCount, deUint32 src0ComponentsCount, deUint32 src1ComponentsCount)
11010 {
11011         DE_ASSERT(dstComponentsCount <= 4);
11012         DE_ASSERT(src0ComponentsCount <= 4);
11013         DE_ASSERT(src1ComponentsCount <= 4);
11014         deUint32 funcCode = 100 * dstComponentsCount + 10 * src0ComponentsCount + src1ComponentsCount;
11015
11016         switch (funcCode)
11017         {
11018                 case 222:return compareFP16VectorShuffleFunc<2, 2, 2>;
11019                 case 223:return compareFP16VectorShuffleFunc<2, 2, 3>;
11020                 case 224:return compareFP16VectorShuffleFunc<2, 2, 4>;
11021                 case 232:return compareFP16VectorShuffleFunc<2, 3, 2>;
11022                 case 233:return compareFP16VectorShuffleFunc<2, 3, 3>;
11023                 case 234:return compareFP16VectorShuffleFunc<2, 3, 4>;
11024                 case 242:return compareFP16VectorShuffleFunc<2, 4, 2>;
11025                 case 243:return compareFP16VectorShuffleFunc<2, 4, 3>;
11026                 case 244:return compareFP16VectorShuffleFunc<2, 4, 4>;
11027                 case 322:return compareFP16VectorShuffleFunc<3, 2, 2>;
11028                 case 323:return compareFP16VectorShuffleFunc<3, 2, 3>;
11029                 case 324:return compareFP16VectorShuffleFunc<3, 2, 4>;
11030                 case 332:return compareFP16VectorShuffleFunc<3, 3, 2>;
11031                 case 333:return compareFP16VectorShuffleFunc<3, 3, 3>;
11032                 case 334:return compareFP16VectorShuffleFunc<3, 3, 4>;
11033                 case 342:return compareFP16VectorShuffleFunc<3, 4, 2>;
11034                 case 343:return compareFP16VectorShuffleFunc<3, 4, 3>;
11035                 case 344:return compareFP16VectorShuffleFunc<3, 4, 4>;
11036                 case 422:return compareFP16VectorShuffleFunc<4, 2, 2>;
11037                 case 423:return compareFP16VectorShuffleFunc<4, 2, 3>;
11038                 case 424:return compareFP16VectorShuffleFunc<4, 2, 4>;
11039                 case 432:return compareFP16VectorShuffleFunc<4, 3, 2>;
11040                 case 433:return compareFP16VectorShuffleFunc<4, 3, 3>;
11041                 case 434:return compareFP16VectorShuffleFunc<4, 3, 4>;
11042                 case 442:return compareFP16VectorShuffleFunc<4, 4, 2>;
11043                 case 443:return compareFP16VectorShuffleFunc<4, 4, 3>;
11044                 case 444:return compareFP16VectorShuffleFunc<4, 4, 4>;
11045                 default: TCU_THROW(InternalError, "Invalid number of components specified.");
11046         }
11047 }
11048
11049 template<class SpecResource>
11050 tcu::TestCaseGroup* createFloat16VectorShuffleSet (tcu::TestContext& testCtx)
11051 {
11052         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorshuffle", "OpVectorShuffle tests"));
11053         const int                                                       testSpecificSeed        = deStringHash(testGroup->getName());
11054         const int                                                       seed                            = testCtx.getCommandLine().getBaseSeed() ^ testSpecificSeed;
11055         de::Random                                                      rnd                                     (seed);
11056         const deUint32                                          numDataPoints           = 128;
11057         map<string, string>                                     fragments;
11058
11059         struct TestType
11060         {
11061                 const deUint32  typeComponents;
11062                 const char*             typeName;
11063         };
11064
11065         const TestType  testTypes[]     =
11066         {
11067                 {
11068                         2,
11069                         "v2f16",
11070                 },
11071                 {
11072                         3,
11073                         "v3f16",
11074                 },
11075                 {
11076                         4,
11077                         "v4f16",
11078                 },
11079         };
11080
11081         const StringTemplate preMain
11082         (
11083                 "    %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
11084                 "     %c_i32_cc = OpConstant %i32 ${case_count}\n"
11085                 "          %f16 = OpTypeFloat 16\n"
11086                 "        %v2f16 = OpTypeVector %f16 2\n"
11087                 "        %v3f16 = OpTypeVector %f16 3\n"
11088                 "        %v4f16 = OpTypeVector %f16 4\n"
11089
11090                 "     %up_v2f16 = OpTypePointer Uniform %v2f16\n"
11091                 "     %ra_v2f16 = OpTypeArray %v2f16 %c_i32_ndp\n"
11092                 "   %SSBO_v2f16 = OpTypeStruct %ra_v2f16\n"
11093                 "%up_SSBO_v2f16 = OpTypePointer Uniform %SSBO_v2f16\n"
11094
11095                 "     %up_v3f16 = OpTypePointer Uniform %v3f16\n"
11096                 "     %ra_v3f16 = OpTypeArray %v3f16 %c_i32_ndp\n"
11097                 "   %SSBO_v3f16 = OpTypeStruct %ra_v3f16\n"
11098                 "%up_SSBO_v3f16 = OpTypePointer Uniform %SSBO_v3f16\n"
11099
11100                 "     %up_v4f16 = OpTypePointer Uniform %v4f16\n"
11101                 "     %ra_v4f16 = OpTypeArray %v4f16 %c_i32_ndp\n"
11102                 "   %SSBO_v4f16 = OpTypeStruct %ra_v4f16\n"
11103                 "%up_SSBO_v4f16 = OpTypePointer Uniform %SSBO_v4f16\n"
11104
11105                 "        %fun_t = OpTypeFunction %${tt_dst} %${tt_src0} %${tt_src1} %i32\n"
11106
11107                 "    %ssbo_src0 = OpVariable %up_SSBO_${tt_src0} Uniform\n"
11108                 "    %ssbo_src1 = OpVariable %up_SSBO_${tt_src1} Uniform\n"
11109                 "     %ssbo_dst = OpVariable %up_SSBO_${tt_dst} Uniform\n"
11110         );
11111
11112         const StringTemplate decoration
11113         (
11114                 "OpDecorate %ra_v2f16 ArrayStride 4\n"
11115                 "OpDecorate %ra_v3f16 ArrayStride 8\n"
11116                 "OpDecorate %ra_v4f16 ArrayStride 8\n"
11117
11118                 "OpMemberDecorate %SSBO_v2f16 0 Offset 0\n"
11119                 "OpDecorate %SSBO_v2f16 BufferBlock\n"
11120
11121                 "OpMemberDecorate %SSBO_v3f16 0 Offset 0\n"
11122                 "OpDecorate %SSBO_v3f16 BufferBlock\n"
11123
11124                 "OpMemberDecorate %SSBO_v4f16 0 Offset 0\n"
11125                 "OpDecorate %SSBO_v4f16 BufferBlock\n"
11126
11127                 "OpDecorate %ssbo_src0 DescriptorSet 0\n"
11128                 "OpDecorate %ssbo_src0 Binding 0\n"
11129                 "OpDecorate %ssbo_src1 DescriptorSet 0\n"
11130                 "OpDecorate %ssbo_src1 Binding 1\n"
11131                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11132                 "OpDecorate %ssbo_dst Binding 2\n"
11133         );
11134
11135         const StringTemplate testFun
11136         (
11137                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11138                 "    %param = OpFunctionParameter %v4f32\n"
11139                 "    %entry = OpLabel\n"
11140
11141                 "        %i = OpVariable %fp_i32 Function\n"
11142                 "             OpStore %i %c_i32_0\n"
11143
11144                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11145                 "             OpSelectionMerge %end_if None\n"
11146                 "             OpBranchConditional %will_run %run_test %end_if\n"
11147
11148                 " %run_test = OpLabel\n"
11149                 "             OpBranch %loop\n"
11150
11151                 "     %loop = OpLabel\n"
11152                 "    %i_cmp = OpLoad %i32 %i\n"
11153                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11154                 "             OpLoopMerge %merge %next None\n"
11155                 "             OpBranchConditional %lt %write %merge\n"
11156
11157                 "    %write = OpLabel\n"
11158                 "      %ndx = OpLoad %i32 %i\n"
11159                 "     %src0 = OpAccessChain %up_${tt_src0} %ssbo_src0 %c_i32_0 %ndx\n"
11160                 " %val_src0 = OpLoad %${tt_src0} %src0\n"
11161                 "     %src1 = OpAccessChain %up_${tt_src1} %ssbo_src1 %c_i32_0 %ndx\n"
11162                 " %val_src1 = OpLoad %${tt_src1} %src1\n"
11163                 "  %val_dst = OpFunctionCall %${tt_dst} %sw_fun %val_src0 %val_src1 %ndx\n"
11164                 "      %dst = OpAccessChain %up_${tt_dst} %ssbo_dst %c_i32_0 %ndx\n"
11165                 "             OpStore %dst %val_dst\n"
11166                 "             OpBranch %next\n"
11167
11168                 "     %next = OpLabel\n"
11169                 "    %i_cur = OpLoad %i32 %i\n"
11170                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11171                 "             OpStore %i %i_new\n"
11172                 "             OpBranch %loop\n"
11173
11174                 "    %merge = OpLabel\n"
11175                 "             OpBranch %end_if\n"
11176                 "   %end_if = OpLabel\n"
11177                 "             OpReturnValue %param\n"
11178                 "             OpFunctionEnd\n"
11179                 "\n"
11180
11181                 "   %sw_fun = OpFunction %${tt_dst} None %fun_t\n"
11182                 "%sw_param0 = OpFunctionParameter %${tt_src0}\n"
11183                 "%sw_param1 = OpFunctionParameter %${tt_src1}\n"
11184                 "%sw_paramn = OpFunctionParameter %i32\n"
11185                 " %sw_entry = OpLabel\n"
11186                 "   %modulo = OpSMod %i32 %sw_paramn %c_i32_cc\n"
11187                 "             OpSelectionMerge %switch_e None\n"
11188                 "             OpSwitch %modulo %default ${case_list}\n"
11189                 "${case_bodies}"
11190                 "%default   = OpLabel\n"
11191                 "             OpUnreachable\n" // Unreachable default case for switch statement
11192                 "%switch_e  = OpLabel\n"
11193                 "             OpUnreachable\n" // Unreachable merge block for switch statement
11194                 "             OpFunctionEnd\n"
11195         );
11196
11197         const StringTemplate testCaseBody
11198         (
11199                 "%case_${case_ndx}    = OpLabel\n"
11200                 "%val_dst_${case_ndx} = OpVectorShuffle %${tt_dst} %sw_param0 %sw_param1 ${shuffle}\n"
11201                 "             OpReturnValue %val_dst_${case_ndx}\n"
11202         );
11203
11204         for (deUint32 dstTypeIdx = 0; dstTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++dstTypeIdx)
11205         {
11206                 const TestType& dstType                 = testTypes[dstTypeIdx];
11207
11208                 for (deUint32 comp0Idx = 0; comp0Idx < DE_LENGTH_OF_ARRAY(testTypes); ++comp0Idx)
11209                 {
11210                         const TestType& src0Type        = testTypes[comp0Idx];
11211
11212                         for (deUint32 comp1Idx = 0; comp1Idx < DE_LENGTH_OF_ARRAY(testTypes); ++comp1Idx)
11213                         {
11214                                 const TestType&                 src1Type                        = testTypes[comp1Idx];
11215                                 const deUint32                  input0Stride            = (src0Type.typeComponents == 3) ? 4 : src0Type.typeComponents;
11216                                 const deUint32                  input1Stride            = (src1Type.typeComponents == 3) ? 4 : src1Type.typeComponents;
11217                                 const deUint32                  outputStride            = (dstType.typeComponents == 3) ? 4 : dstType.typeComponents;
11218                                 const vector<deFloat16> float16Input0Data       = getFloat16s(rnd, input0Stride * numDataPoints);
11219                                 const vector<deFloat16> float16Input1Data       = getFloat16s(rnd, input1Stride * numDataPoints);
11220                                 const vector<deFloat16> float16OutputDummy      (outputStride * numDataPoints, 0);
11221                                 const string                    testName                        = de::toString(dstType.typeComponents) + de::toString(src0Type.typeComponents) + de::toString(src1Type.typeComponents);
11222                                 deUint32                                caseCount                       = 0;
11223                                 SpecResource                    specResource;
11224                                 map<string, string>             specs;
11225                                 vector<string>                  extensions;
11226                                 VulkanFeatures                  features;
11227                                 string                                  caseBodies;
11228                                 string                                  caseList;
11229
11230                                 // Generate case
11231                                 {
11232                                         vector<string>  componentList;
11233
11234                                         // Generate component possible indices for OpVectorShuffle for components 0 and 1 in output vector
11235                                         {
11236                                                 deUint32                caseNo          = 0;
11237
11238                                                 for (deUint32 comp0IdxLocal = 0; comp0IdxLocal < src0Type.typeComponents; ++comp0IdxLocal)
11239                                                         componentList.push_back(de::toString(caseNo++));
11240                                                 for (deUint32 comp1IdxLocal = 0; comp1IdxLocal < src1Type.typeComponents; ++comp1IdxLocal)
11241                                                         componentList.push_back(de::toString(caseNo++));
11242                                                 componentList.push_back("0xFFFFFFFF");
11243                                         }
11244
11245                                         for (deUint32 comp0IdxLocal = 0; comp0IdxLocal < componentList.size(); ++comp0IdxLocal)
11246                                         {
11247                                                 for (deUint32 comp1IdxLocal = 0; comp1IdxLocal < componentList.size(); ++comp1IdxLocal)
11248                                                 {
11249                                                         map<string, string>     specCase;
11250                                                         string                          shuffle         = componentList[comp0IdxLocal] + " " + componentList[comp1IdxLocal];
11251
11252                                                         for (deUint32 compIdx = 2; compIdx < dstType.typeComponents; ++compIdx)
11253                                                                 shuffle += " " + de::toString(compIdx - 2);
11254
11255                                                         specCase["case_ndx"]    = de::toString(caseCount);
11256                                                         specCase["shuffle"]             = shuffle;
11257                                                         specCase["tt_dst"]              = dstType.typeName;
11258
11259                                                         caseBodies      += testCaseBody.specialize(specCase);
11260                                                         caseList        += de::toString(caseCount) + " %case_" + de::toString(caseCount) + " ";
11261
11262                                                         caseCount++;
11263                                                 }
11264                                         }
11265                                 }
11266
11267                                 specs["num_data_points"]        = de::toString(numDataPoints);
11268                                 specs["tt_dst"]                         = dstType.typeName;
11269                                 specs["tt_src0"]                        = src0Type.typeName;
11270                                 specs["tt_src1"]                        = src1Type.typeName;
11271                                 specs["case_bodies"]            = caseBodies;
11272                                 specs["case_list"]                      = caseList;
11273                                 specs["case_count"]                     = de::toString(caseCount);
11274
11275                                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11276                                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
11277                                 fragments["decoration"]         = decoration.specialize(specs);
11278                                 fragments["pre_main"]           = preMain.specialize(specs);
11279                                 fragments["testfun"]            = testFun.specialize(specs);
11280
11281                                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Input0Data)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11282                                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Input1Data)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11283                                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11284                                 specResource.verifyIO = getFloat16VectorShuffleVerifyIOFunc(dstType.typeComponents, src0Type.typeComponents, src1Type.typeComponents);
11285
11286                                 extensions.push_back("VK_KHR_16bit_storage");
11287                                 extensions.push_back("VK_KHR_shader_float16_int8");
11288
11289                                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11290                                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11291
11292                                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11293                         }
11294                 }
11295         }
11296
11297         return testGroup.release();
11298 }
11299
11300 bool compareFP16CompositeFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11301 {
11302         if (inputs.size() != 1 || outputAllocs.size() != 1)
11303                 return false;
11304
11305         vector<deUint8> input1Bytes;
11306
11307         inputs[0].getBytes(input1Bytes);
11308
11309         DE_ASSERT(input1Bytes.size() > 0);
11310         DE_ASSERT(input1Bytes.size() % sizeof(deFloat16) == 0);
11311
11312         const size_t                    iterations              = input1Bytes.size() / sizeof(deFloat16);
11313         const deFloat16* const  input1AsFP16    = (const deFloat16*)&input1Bytes[0];
11314         const deFloat16* const  outputAsFP16    = (const deFloat16*)outputAllocs[0]->getHostPtr();
11315         const deFloat16                 exceptionValue  = tcu::Float16(-1.0).bits();
11316         std::string                             error;
11317
11318         for (size_t idx = 0; idx < iterations; ++idx)
11319         {
11320                 if (input1AsFP16[idx] == exceptionValue)
11321                         continue;
11322
11323                 if (!compare16BitFloat(input1AsFP16[idx], outputAsFP16[idx], error))
11324                 {
11325                         log << TestLog::Message << "At " << idx << ":" << error << TestLog::EndMessage;
11326
11327                         return false;
11328                 }
11329         }
11330
11331         return true;
11332 }
11333
11334 template<class SpecResource>
11335 tcu::TestCaseGroup* createFloat16CompositeConstructSet (tcu::TestContext& testCtx)
11336 {
11337         de::MovePtr<tcu::TestCaseGroup>         testGroup                               (new tcu::TestCaseGroup(testCtx, "opcompositeconstruct", "OpCompositeConstruct tests"));
11338         const deUint32                                          numElements                             = 8;
11339         const string                                            testName                                = "struct";
11340         const deUint32                                          structItemsCount                = 88;
11341         const deUint32                                          exceptionIndices[]              = { 1, 7, 15, 17, 25, 33, 51, 55, 59, 63, 67, 71, 84, 85, 86, 87 };
11342         const deFloat16                                         exceptionValue                  = tcu::Float16(-1.0).bits();
11343         const deUint32                                          fieldModifier                   = 2;
11344         const deUint32                                          fieldModifiedMulIndex   = 60;
11345         const deUint32                                          fieldModifiedAddIndex   = 66;
11346
11347         const StringTemplate preMain
11348         (
11349                 "    %c_i32_ndp = OpConstant %i32 ${num_elements}\n"
11350                 "          %f16 = OpTypeFloat 16\n"
11351                 "        %v2f16 = OpTypeVector %f16 2\n"
11352                 "        %v3f16 = OpTypeVector %f16 3\n"
11353                 "        %v4f16 = OpTypeVector %f16 4\n"
11354                 "    %c_f16_mod = OpConstant %f16 ${field_modifier}\n"
11355
11356                 "${consts}"
11357
11358                 "      %c_u32_5 = OpConstant %u32 5\n"
11359
11360                 " %f16arr3      = OpTypeArray %f16 %c_u32_3\n"
11361                 " %v2f16arr3    = OpTypeArray %v2f16 %c_u32_3\n"
11362                 " %v2f16arr5    = OpTypeArray %v2f16 %c_u32_5\n"
11363                 " %v3f16arr5    = OpTypeArray %v3f16 %c_u32_5\n"
11364                 " %v4f16arr3    = OpTypeArray %v4f16 %c_u32_3\n"
11365                 " %struct16     = OpTypeStruct %f16 %v2f16arr3\n"
11366                 " %struct16arr3 = OpTypeArray %struct16 %c_u32_3\n"
11367                 " %st_test      = OpTypeStruct %f16 %v2f16 %v3f16 %v4f16 %f16arr3 %struct16arr3 %v2f16arr5 %f16 %v3f16arr5 %v4f16arr3\n"
11368
11369                 "        %up_st = OpTypePointer Uniform %st_test\n"
11370                 "        %ra_st = OpTypeArray %st_test %c_i32_ndp\n"
11371                 "      %SSBO_st = OpTypeStruct %ra_st\n"
11372                 "   %up_SSBO_st = OpTypePointer Uniform %SSBO_st\n"
11373
11374                 "     %ssbo_dst = OpVariable %up_SSBO_st Uniform\n"
11375         );
11376
11377         const StringTemplate decoration
11378         (
11379                 "OpDecorate %SSBO_st BufferBlock\n"
11380                 "OpDecorate %ra_st ArrayStride ${struct_item_size}\n"
11381                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11382                 "OpDecorate %ssbo_dst Binding 1\n"
11383
11384                 "OpMemberDecorate %SSBO_st 0 Offset 0\n"
11385
11386                 "OpDecorate %v2f16arr3 ArrayStride 4\n"
11387                 "OpMemberDecorate %struct16 0 Offset 0\n"
11388                 "OpMemberDecorate %struct16 1 Offset 4\n"
11389                 "OpDecorate %struct16arr3 ArrayStride 16\n"
11390                 "OpDecorate %f16arr3 ArrayStride 2\n"
11391                 "OpDecorate %v2f16arr5 ArrayStride 4\n"
11392                 "OpDecorate %v3f16arr5 ArrayStride 8\n"
11393                 "OpDecorate %v4f16arr3 ArrayStride 8\n"
11394
11395                 "OpMemberDecorate %st_test 0 Offset 0\n"
11396                 "OpMemberDecorate %st_test 1 Offset 4\n"
11397                 "OpMemberDecorate %st_test 2 Offset 8\n"
11398                 "OpMemberDecorate %st_test 3 Offset 16\n"
11399                 "OpMemberDecorate %st_test 4 Offset 24\n"
11400                 "OpMemberDecorate %st_test 5 Offset 32\n"
11401                 "OpMemberDecorate %st_test 6 Offset 80\n"
11402                 "OpMemberDecorate %st_test 7 Offset 100\n"
11403                 "OpMemberDecorate %st_test 8 Offset 104\n"
11404                 "OpMemberDecorate %st_test 9 Offset 144\n"
11405         );
11406
11407         const StringTemplate testFun
11408         (
11409                 " %test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11410                 "     %param = OpFunctionParameter %v4f32\n"
11411                 "     %entry = OpLabel\n"
11412
11413                 "         %i = OpVariable %fp_i32 Function\n"
11414                 "              OpStore %i %c_i32_0\n"
11415
11416                 "  %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11417                 "              OpSelectionMerge %end_if None\n"
11418                 "              OpBranchConditional %will_run %run_test %end_if\n"
11419
11420                 "  %run_test = OpLabel\n"
11421                 "              OpBranch %loop\n"
11422
11423                 "      %loop = OpLabel\n"
11424                 "     %i_cmp = OpLoad %i32 %i\n"
11425                 "        %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11426                 "              OpLoopMerge %merge %next None\n"
11427                 "              OpBranchConditional %lt %write %merge\n"
11428
11429                 "     %write = OpLabel\n"
11430                 "       %ndx = OpLoad %i32 %i\n"
11431
11432                 "      %fld1 = OpCompositeConstruct %v2f16 %c_f16_2 %c_f16_3\n"
11433                 "      %fld2 = OpCompositeConstruct %v3f16 %c_f16_4 %c_f16_5 %c_f16_6\n"
11434                 "      %fld3 = OpCompositeConstruct %v4f16 %c_f16_8 %c_f16_9 %c_f16_10 %c_f16_11\n"
11435
11436                 "      %fld4 = OpCompositeConstruct %f16arr3 %c_f16_12 %c_f16_13 %c_f16_14\n"
11437
11438                 "%fld5_0_1_0 = OpCompositeConstruct %v2f16 %c_f16_18 %c_f16_19\n"
11439                 "%fld5_0_1_1 = OpCompositeConstruct %v2f16 %c_f16_20 %c_f16_21\n"
11440                 "%fld5_0_1_2 = OpCompositeConstruct %v2f16 %c_f16_22 %c_f16_23\n"
11441                 "  %fld5_0_1 = OpCompositeConstruct %v2f16arr3 %fld5_0_1_0 %fld5_0_1_1 %fld5_0_1_2\n"
11442                 "    %fld5_0 = OpCompositeConstruct %struct16 %c_f16_16 %fld5_0_1\n"
11443
11444                 "%fld5_1_1_0 = OpCompositeConstruct %v2f16 %c_f16_26 %c_f16_27\n"
11445                 "%fld5_1_1_1 = OpCompositeConstruct %v2f16 %c_f16_28 %c_f16_29\n"
11446                 "%fld5_1_1_2 = OpCompositeConstruct %v2f16 %c_f16_30 %c_f16_31\n"
11447                 "  %fld5_1_1 = OpCompositeConstruct %v2f16arr3 %fld5_1_1_0 %fld5_1_1_1 %fld5_1_1_2\n"
11448                 "    %fld5_1 = OpCompositeConstruct %struct16 %c_f16_24 %fld5_1_1\n"
11449
11450                 "%fld5_2_1_0 = OpCompositeConstruct %v2f16 %c_f16_34 %c_f16_35\n"
11451                 "%fld5_2_1_1 = OpCompositeConstruct %v2f16 %c_f16_36 %c_f16_37\n"
11452                 "%fld5_2_1_2 = OpCompositeConstruct %v2f16 %c_f16_38 %c_f16_39\n"
11453                 "  %fld5_2_1 = OpCompositeConstruct %v2f16arr3 %fld5_2_1_0 %fld5_2_1_1 %fld5_2_1_2\n"
11454                 "    %fld5_2 = OpCompositeConstruct %struct16 %c_f16_32 %fld5_2_1\n"
11455
11456                 "      %fld5 = OpCompositeConstruct %struct16arr3 %fld5_0 %fld5_1 %fld5_2\n"
11457
11458                 "    %fld6_0 = OpCompositeConstruct %v2f16 %c_f16_40 %c_f16_41\n"
11459                 "    %fld6_1 = OpCompositeConstruct %v2f16 %c_f16_42 %c_f16_43\n"
11460                 "    %fld6_2 = OpCompositeConstruct %v2f16 %c_f16_44 %c_f16_45\n"
11461                 "    %fld6_3 = OpCompositeConstruct %v2f16 %c_f16_46 %c_f16_47\n"
11462                 "    %fld6_4 = OpCompositeConstruct %v2f16 %c_f16_48 %c_f16_49\n"
11463                 "      %fld6 = OpCompositeConstruct %v2f16arr5 %fld6_0 %fld6_1 %fld6_2 %fld6_3 %fld6_4\n"
11464
11465                 "      %fndx = OpConvertSToF %f16 %ndx\n"
11466                 "  %fld8_2a0 = OpFMul %f16 %fndx %c_f16_mod\n"
11467                 "  %fld8_3b1 = OpFAdd %f16 %fndx %c_f16_mod\n"
11468
11469                 "   %fld8_2a = OpCompositeConstruct %v2f16 %fld8_2a0 %c_f16_61\n"
11470                 "   %fld8_3b = OpCompositeConstruct %v2f16 %c_f16_65 %fld8_3b1\n"
11471                 "    %fld8_0 = OpCompositeConstruct %v3f16 %c_f16_52 %c_f16_53 %c_f16_54\n"
11472                 "    %fld8_1 = OpCompositeConstruct %v3f16 %c_f16_56 %c_f16_57 %c_f16_58\n"
11473                 "    %fld8_2 = OpCompositeConstruct %v3f16 %fld8_2a %c_f16_62\n"
11474                 "    %fld8_3 = OpCompositeConstruct %v3f16 %c_f16_64 %fld8_3b\n"
11475                 "    %fld8_4 = OpCompositeConstruct %v3f16 %c_f16_68 %c_f16_69 %c_f16_70\n"
11476                 "      %fld8 = OpCompositeConstruct %v3f16arr5 %fld8_0 %fld8_1 %fld8_2 %fld8_3 %fld8_4\n"
11477
11478                 "    %fld9_0 = OpCompositeConstruct %v4f16 %c_f16_72 %c_f16_73 %c_f16_74 %c_f16_75\n"
11479                 "    %fld9_1 = OpCompositeConstruct %v4f16 %c_f16_76 %c_f16_77 %c_f16_78 %c_f16_79\n"
11480                 "    %fld9_2 = OpCompositeConstruct %v4f16 %c_f16_80 %c_f16_81 %c_f16_82 %c_f16_83\n"
11481                 "      %fld9 = OpCompositeConstruct %v4f16arr3 %fld9_0 %fld9_1 %fld9_2\n"
11482
11483                 "    %st_val = OpCompositeConstruct %st_test %c_f16_0 %fld1 %fld2 %fld3 %fld4 %fld5 %fld6 %c_f16_50 %fld8 %fld9\n"
11484                 "       %dst = OpAccessChain %up_st %ssbo_dst %c_i32_0 %ndx\n"
11485                 "              OpStore %dst %st_val\n"
11486
11487                 "              OpBranch %next\n"
11488
11489                 "      %next = OpLabel\n"
11490                 "     %i_cur = OpLoad %i32 %i\n"
11491                 "     %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11492                 "              OpStore %i %i_new\n"
11493                 "              OpBranch %loop\n"
11494
11495                 "     %merge = OpLabel\n"
11496                 "              OpBranch %end_if\n"
11497                 "    %end_if = OpLabel\n"
11498                 "              OpReturnValue %param\n"
11499                 "              OpFunctionEnd\n"
11500         );
11501
11502         {
11503                 SpecResource            specResource;
11504                 map<string, string>     specs;
11505                 VulkanFeatures          features;
11506                 map<string, string>     fragments;
11507                 vector<string>          extensions;
11508                 vector<deFloat16>       expectedOutput;
11509                 string                          consts;
11510
11511                 for (deUint32 elementNdx = 0; elementNdx < numElements; ++elementNdx)
11512                 {
11513                         vector<deFloat16>       expectedIterationOutput;
11514
11515                         for (deUint32 structItemNdx = 0; structItemNdx < structItemsCount; ++structItemNdx)
11516                                 expectedIterationOutput.push_back(tcu::Float16(float(structItemNdx)).bits());
11517
11518                         for (deUint32 structItemNdx = 0; structItemNdx < DE_LENGTH_OF_ARRAY(exceptionIndices); ++structItemNdx)
11519                                 expectedIterationOutput[exceptionIndices[structItemNdx]] = exceptionValue;
11520
11521                         expectedIterationOutput[fieldModifiedMulIndex] = tcu::Float16(float(elementNdx * fieldModifier)).bits();
11522                         expectedIterationOutput[fieldModifiedAddIndex] = tcu::Float16(float(elementNdx + fieldModifier)).bits();
11523
11524                         expectedOutput.insert(expectedOutput.end(), expectedIterationOutput.begin(), expectedIterationOutput.end());
11525                 }
11526
11527                 for (deUint32 i = 0; i < structItemsCount; ++i)
11528                         consts += "     %c_f16_" + de::toString(i) + " = OpConstant %f16 "  + de::toString(i) + "\n";
11529
11530                 specs["num_elements"]           = de::toString(numElements);
11531                 specs["struct_item_size"]       = de::toString(structItemsCount * sizeof(deFloat16));
11532                 specs["field_modifier"]         = de::toString(fieldModifier);
11533                 specs["consts"]                         = consts;
11534
11535                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11536                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
11537                 fragments["decoration"]         = decoration.specialize(specs);
11538                 fragments["pre_main"]           = preMain.specialize(specs);
11539                 fragments["testfun"]            = testFun.specialize(specs);
11540
11541                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(expectedOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11542                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(expectedOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11543                 specResource.verifyIO = compareFP16CompositeFunc;
11544
11545                 extensions.push_back("VK_KHR_16bit_storage");
11546                 extensions.push_back("VK_KHR_shader_float16_int8");
11547
11548                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11549                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11550
11551                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11552         }
11553
11554         return testGroup.release();
11555 }
11556
11557 template<class SpecResource>
11558 tcu::TestCaseGroup* createFloat16CompositeInsertExtractSet (tcu::TestContext& testCtx, const char* op)
11559 {
11560         de::MovePtr<tcu::TestCaseGroup>         testGroup               (new tcu::TestCaseGroup(testCtx, de::toLower(op).c_str(), op));
11561         const deFloat16                                         exceptionValue  = tcu::Float16(-1.0).bits();
11562         const string                                            opName                  (op);
11563         const deUint32                                          opIndex                 = (opName == "OpCompositeInsert") ? 0
11564                                                                                                                 : (opName == "OpCompositeExtract") ? 1
11565                                                                                                                 : -1;
11566
11567         const StringTemplate preMain
11568         (
11569                 "   %c_i32_ndp = OpConstant %i32 ${num_elements}\n"
11570                 "         %f16 = OpTypeFloat 16\n"
11571                 "       %v2f16 = OpTypeVector %f16 2\n"
11572                 "       %v3f16 = OpTypeVector %f16 3\n"
11573                 "       %v4f16 = OpTypeVector %f16 4\n"
11574                 "    %c_f16_na = OpConstant %f16 -1.0\n"
11575                 "     %c_u32_5 = OpConstant %u32 5\n"
11576
11577                 "%f16arr3      = OpTypeArray %f16 %c_u32_3\n"
11578                 "%v2f16arr3    = OpTypeArray %v2f16 %c_u32_3\n"
11579                 "%v2f16arr5    = OpTypeArray %v2f16 %c_u32_5\n"
11580                 "%v3f16arr5    = OpTypeArray %v3f16 %c_u32_5\n"
11581                 "%v4f16arr3    = OpTypeArray %v4f16 %c_u32_3\n"
11582                 "%struct16     = OpTypeStruct %f16 %v2f16arr3\n"
11583                 "%struct16arr3 = OpTypeArray %struct16 %c_u32_3\n"
11584                 "%st_test      = OpTypeStruct %${field_type}\n"
11585
11586                 "      %up_f16 = OpTypePointer Uniform %f16\n"
11587                 "       %up_st = OpTypePointer Uniform %st_test\n"
11588                 "      %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
11589                 "       %ra_st = OpTypeArray %st_test %c_i32_1\n"
11590
11591                 "${op_premain_decls}"
11592
11593                 " %up_SSBO_src = OpTypePointer Uniform %SSBO_src\n"
11594                 " %up_SSBO_dst = OpTypePointer Uniform %SSBO_dst\n"
11595
11596                 "    %ssbo_src = OpVariable %up_SSBO_src Uniform\n"
11597                 "    %ssbo_dst = OpVariable %up_SSBO_dst Uniform\n"
11598         );
11599
11600         const StringTemplate decoration
11601         (
11602                 "OpDecorate %SSBO_src BufferBlock\n"
11603                 "OpDecorate %SSBO_dst BufferBlock\n"
11604                 "OpDecorate %ra_f16 ArrayStride 2\n"
11605                 "OpDecorate %ra_st ArrayStride ${struct_item_size}\n"
11606                 "OpDecorate %ssbo_src DescriptorSet 0\n"
11607                 "OpDecorate %ssbo_src Binding 0\n"
11608                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11609                 "OpDecorate %ssbo_dst Binding 1\n"
11610
11611                 "OpMemberDecorate %SSBO_src 0 Offset 0\n"
11612                 "OpMemberDecorate %SSBO_dst 0 Offset 0\n"
11613
11614                 "OpDecorate %v2f16arr3 ArrayStride 4\n"
11615                 "OpMemberDecorate %struct16 0 Offset 0\n"
11616                 "OpMemberDecorate %struct16 1 Offset 4\n"
11617                 "OpDecorate %struct16arr3 ArrayStride 16\n"
11618                 "OpDecorate %f16arr3 ArrayStride 2\n"
11619                 "OpDecorate %v2f16arr5 ArrayStride 4\n"
11620                 "OpDecorate %v3f16arr5 ArrayStride 8\n"
11621                 "OpDecorate %v4f16arr3 ArrayStride 8\n"
11622
11623                 "OpMemberDecorate %st_test 0 Offset 0\n"
11624         );
11625
11626         const StringTemplate testFun
11627         (
11628                 " %test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11629                 "     %param = OpFunctionParameter %v4f32\n"
11630                 "     %entry = OpLabel\n"
11631
11632                 "         %i = OpVariable %fp_i32 Function\n"
11633                 "              OpStore %i %c_i32_0\n"
11634
11635                 "  %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11636                 "              OpSelectionMerge %end_if None\n"
11637                 "              OpBranchConditional %will_run %run_test %end_if\n"
11638
11639                 "  %run_test = OpLabel\n"
11640                 "              OpBranch %loop\n"
11641
11642                 "      %loop = OpLabel\n"
11643                 "     %i_cmp = OpLoad %i32 %i\n"
11644                 "        %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11645                 "              OpLoopMerge %merge %next None\n"
11646                 "              OpBranchConditional %lt %write %merge\n"
11647
11648                 "     %write = OpLabel\n"
11649                 "       %ndx = OpLoad %i32 %i\n"
11650
11651                 "${op_sw_fun_call}"
11652
11653                 "              OpStore %dst %val_dst\n"
11654                 "              OpBranch %next\n"
11655
11656                 "      %next = OpLabel\n"
11657                 "     %i_cur = OpLoad %i32 %i\n"
11658                 "     %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11659                 "              OpStore %i %i_new\n"
11660                 "              OpBranch %loop\n"
11661
11662                 "     %merge = OpLabel\n"
11663                 "              OpBranch %end_if\n"
11664                 "    %end_if = OpLabel\n"
11665                 "              OpReturnValue %param\n"
11666                 "              OpFunctionEnd\n"
11667
11668                 "${op_sw_fun_header}"
11669                 " %sw_param = OpFunctionParameter %st_test\n"
11670                 "%sw_paramn = OpFunctionParameter %i32\n"
11671                 " %sw_entry = OpLabel\n"
11672                 "             OpSelectionMerge %switch_e None\n"
11673                 "             OpSwitch %sw_paramn %default ${case_list}\n"
11674
11675                 "${case_bodies}"
11676
11677                 "%default   = OpLabel\n"
11678                 "             OpReturnValue ${op_case_default_value}\n"
11679                 "%switch_e  = OpLabel\n"
11680                 "             OpUnreachable\n" // Unreachable merge block for switch statement
11681                 "             OpFunctionEnd\n"
11682         );
11683
11684         const StringTemplate testCaseBody
11685         (
11686                 "%case_${case_ndx}    = OpLabel\n"
11687                 "%val_ret_${case_ndx} = ${op_name} ${op_args_part} ${access_path}\n"
11688                 "             OpReturnValue %val_ret_${case_ndx}\n"
11689         );
11690
11691         struct OpParts
11692         {
11693                 const char*     premainDecls;
11694                 const char*     swFunCall;
11695                 const char*     swFunHeader;
11696                 const char*     caseDefaultValue;
11697                 const char*     argsPartial;
11698         };
11699
11700         OpParts                                                         opPartsArray[]                  =
11701         {
11702                 // OpCompositeInsert
11703                 {
11704                         "       %fun_t = OpTypeFunction %st_test %f16 %st_test %i32\n"
11705                         "    %SSBO_src = OpTypeStruct %ra_f16\n"
11706                         "    %SSBO_dst = OpTypeStruct %ra_st\n",
11707
11708                         "       %src = OpAccessChain %up_f16 %ssbo_src %c_i32_0 %ndx\n"
11709                         "       %dst = OpAccessChain %up_st %ssbo_dst %c_i32_0 %c_i32_0\n"
11710                         "   %val_new = OpLoad %f16 %src\n"
11711                         "   %val_old = OpLoad %st_test %dst\n"
11712                         "   %val_dst = OpFunctionCall %st_test %sw_fun %val_new %val_old %ndx\n",
11713
11714                         "   %sw_fun = OpFunction %st_test None %fun_t\n"
11715                         "%sw_paramv = OpFunctionParameter %f16\n",
11716
11717                         "%sw_param",
11718
11719                         "%st_test %sw_paramv %sw_param",
11720                 },
11721                 // OpCompositeExtract
11722                 {
11723                         "       %fun_t = OpTypeFunction %f16 %st_test %i32\n"
11724                         "    %SSBO_src = OpTypeStruct %ra_st\n"
11725                         "    %SSBO_dst = OpTypeStruct %ra_f16\n",
11726
11727                         "       %src = OpAccessChain %up_st %ssbo_src %c_i32_0 %c_i32_0\n"
11728                         "       %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
11729                         "   %val_src = OpLoad %st_test %src\n"
11730                         "   %val_dst = OpFunctionCall %f16 %sw_fun %val_src %ndx\n",
11731
11732                         "   %sw_fun = OpFunction %f16 None %fun_t\n",
11733
11734                         "%c_f16_na",
11735
11736                         "%f16 %sw_param",
11737                 },
11738         };
11739
11740         DE_ASSERT(opIndex >= 0 && opIndex < DE_LENGTH_OF_ARRAY(opPartsArray));
11741
11742         const char*     accessPathF16[] =
11743         {
11744                 "0",                    // %f16
11745                 DE_NULL,
11746         };
11747         const char*     accessPathV2F16[] =
11748         {
11749                 "0 0",                  // %v2f16
11750                 "0 1",
11751         };
11752         const char*     accessPathV3F16[] =
11753         {
11754                 "0 0",                  // %v3f16
11755                 "0 1",
11756                 "0 2",
11757                 DE_NULL,
11758         };
11759         const char*     accessPathV4F16[] =
11760         {
11761                 "0 0",                  // %v4f16"
11762                 "0 1",
11763                 "0 2",
11764                 "0 3",
11765         };
11766         const char*     accessPathF16Arr3[] =
11767         {
11768                 "0 0",                  // %f16arr3
11769                 "0 1",
11770                 "0 2",
11771                 DE_NULL,
11772         };
11773         const char*     accessPathStruct16Arr3[] =
11774         {
11775                 "0 0 0",                // %struct16arr3
11776                 DE_NULL,
11777                 "0 0 1 0 0",
11778                 "0 0 1 0 1",
11779                 "0 0 1 1 0",
11780                 "0 0 1 1 1",
11781                 "0 0 1 2 0",
11782                 "0 0 1 2 1",
11783                 "0 1 0",
11784                 DE_NULL,
11785                 "0 1 1 0 0",
11786                 "0 1 1 0 1",
11787                 "0 1 1 1 0",
11788                 "0 1 1 1 1",
11789                 "0 1 1 2 0",
11790                 "0 1 1 2 1",
11791                 "0 2 0",
11792                 DE_NULL,
11793                 "0 2 1 0 0",
11794                 "0 2 1 0 1",
11795                 "0 2 1 1 0",
11796                 "0 2 1 1 1",
11797                 "0 2 1 2 0",
11798                 "0 2 1 2 1",
11799         };
11800         const char*     accessPathV2F16Arr5[] =
11801         {
11802                 "0 0 0",                // %v2f16arr5
11803                 "0 0 1",
11804                 "0 1 0",
11805                 "0 1 1",
11806                 "0 2 0",
11807                 "0 2 1",
11808                 "0 3 0",
11809                 "0 3 1",
11810                 "0 4 0",
11811                 "0 4 1",
11812         };
11813         const char*     accessPathV3F16Arr5[] =
11814         {
11815                 "0 0 0",                // %v3f16arr5
11816                 "0 0 1",
11817                 "0 0 2",
11818                 DE_NULL,
11819                 "0 1 0",
11820                 "0 1 1",
11821                 "0 1 2",
11822                 DE_NULL,
11823                 "0 2 0",
11824                 "0 2 1",
11825                 "0 2 2",
11826                 DE_NULL,
11827                 "0 3 0",
11828                 "0 3 1",
11829                 "0 3 2",
11830                 DE_NULL,
11831                 "0 4 0",
11832                 "0 4 1",
11833                 "0 4 2",
11834                 DE_NULL,
11835         };
11836         const char*     accessPathV4F16Arr3[] =
11837         {
11838                 "0 0 0",                // %v4f16arr3
11839                 "0 0 1",
11840                 "0 0 2",
11841                 "0 0 3",
11842                 "0 1 0",
11843                 "0 1 1",
11844                 "0 1 2",
11845                 "0 1 3",
11846                 "0 2 0",
11847                 "0 2 1",
11848                 "0 2 2",
11849                 "0 2 3",
11850                 DE_NULL,
11851                 DE_NULL,
11852                 DE_NULL,
11853                 DE_NULL,
11854         };
11855
11856         struct TypeTestParameters
11857         {
11858                 const char*             name;
11859                 size_t                  accessPathLength;
11860                 const char**    accessPath;
11861         };
11862
11863         const TypeTestParameters typeTestParameters[] =
11864         {
11865                 {       "f16",                  DE_LENGTH_OF_ARRAY(accessPathF16),                      accessPathF16                   },
11866                 {       "v2f16",                DE_LENGTH_OF_ARRAY(accessPathV2F16),            accessPathV2F16                 },
11867                 {       "v3f16",                DE_LENGTH_OF_ARRAY(accessPathV3F16),            accessPathV3F16                 },
11868                 {       "v4f16",                DE_LENGTH_OF_ARRAY(accessPathV4F16),            accessPathV4F16                 },
11869                 {       "f16arr3",              DE_LENGTH_OF_ARRAY(accessPathF16Arr3),          accessPathF16Arr3               },
11870                 {       "v2f16arr5",    DE_LENGTH_OF_ARRAY(accessPathV2F16Arr5),        accessPathV2F16Arr5             },
11871                 {       "v3f16arr5",    DE_LENGTH_OF_ARRAY(accessPathV3F16Arr5),        accessPathV3F16Arr5             },
11872                 {       "v4f16arr3",    DE_LENGTH_OF_ARRAY(accessPathV4F16Arr3),        accessPathV4F16Arr3             },
11873                 {       "struct16arr3", DE_LENGTH_OF_ARRAY(accessPathStruct16Arr3),     accessPathStruct16Arr3  },
11874         };
11875
11876         for (size_t typeTestNdx = 0; typeTestNdx < DE_LENGTH_OF_ARRAY(typeTestParameters); ++typeTestNdx)
11877         {
11878                 const OpParts           opParts                         = opPartsArray[opIndex];
11879                 const string            testName                        = typeTestParameters[typeTestNdx].name;
11880                 const size_t            structItemsCount        = typeTestParameters[typeTestNdx].accessPathLength;
11881                 const char**            accessPath                      = typeTestParameters[typeTestNdx].accessPath;
11882                 SpecResource            specResource;
11883                 map<string, string>     specs;
11884                 VulkanFeatures          features;
11885                 map<string, string>     fragments;
11886                 vector<string>          extensions;
11887                 vector<deFloat16>       inputFP16;
11888                 vector<deFloat16>       dummyFP16Output;
11889
11890                 // Generate values for input
11891                 inputFP16.reserve(structItemsCount);
11892                 for (deUint32 structItemNdx = 0; structItemNdx < structItemsCount; ++structItemNdx)
11893                         inputFP16.push_back((accessPath[structItemNdx] == DE_NULL) ? exceptionValue : tcu::Float16(float(structItemNdx)).bits());
11894
11895                 dummyFP16Output.resize(structItemsCount);
11896
11897                 // Generate cases for OpSwitch
11898                 {
11899                         string  caseBodies;
11900                         string  caseList;
11901
11902                         for (deUint32 caseNdx = 0; caseNdx < structItemsCount; ++caseNdx)
11903                                 if (accessPath[caseNdx] != DE_NULL)
11904                                 {
11905                                         map<string, string>     specCase;
11906
11907                                         specCase["case_ndx"]            = de::toString(caseNdx);
11908                                         specCase["access_path"]         = accessPath[caseNdx];
11909                                         specCase["op_args_part"]        = opParts.argsPartial;
11910                                         specCase["op_name"]                     = opName;
11911
11912                                         caseBodies      += testCaseBody.specialize(specCase);
11913                                         caseList        += de::toString(caseNdx) + " %case_" + de::toString(caseNdx) + " ";
11914                                 }
11915
11916                         specs["case_bodies"]    = caseBodies;
11917                         specs["case_list"]              = caseList;
11918                 }
11919
11920                 specs["num_elements"]                   = de::toString(structItemsCount);
11921                 specs["field_type"]                             = typeTestParameters[typeTestNdx].name;
11922                 specs["struct_item_size"]               = de::toString(structItemsCount * sizeof(deFloat16));
11923                 specs["op_premain_decls"]               = opParts.premainDecls;
11924                 specs["op_sw_fun_call"]                 = opParts.swFunCall;
11925                 specs["op_sw_fun_header"]               = opParts.swFunHeader;
11926                 specs["op_case_default_value"]  = opParts.caseDefaultValue;
11927
11928                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11929                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
11930                 fragments["decoration"]         = decoration.specialize(specs);
11931                 fragments["pre_main"]           = preMain.specialize(specs);
11932                 fragments["testfun"]            = testFun.specialize(specs);
11933
11934                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(inputFP16)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11935                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(dummyFP16Output)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11936                 specResource.verifyIO = compareFP16CompositeFunc;
11937
11938                 extensions.push_back("VK_KHR_16bit_storage");
11939                 extensions.push_back("VK_KHR_shader_float16_int8");
11940
11941                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11942                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11943
11944                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11945         }
11946
11947         return testGroup.release();
11948 }
11949
11950 struct fp16PerComponent
11951 {
11952         fp16PerComponent()
11953                 : flavor(0)
11954                 , floatFormat16 (-14, 15, 10, true)
11955                 , outCompCount(0)
11956                 , argCompCount(3, 0)
11957         {
11958         }
11959
11960         bool                    callOncePerComponent    ()                                                                      { return true; }
11961         deUint32                getComponentValidity    ()                                                                      { return static_cast<deUint32>(-1); }
11962
11963         virtual double  getULPs                                 (vector<const deFloat16*>&)                     { return 1.0; }
11964         virtual double  getMin                                  (double value, double ulps)                     { return value - floatFormat16.ulp(deAbs(value), ulps); }
11965         virtual double  getMax                                  (double value, double ulps)                     { return value + floatFormat16.ulp(deAbs(value), ulps); }
11966
11967         virtual size_t  getFlavorCount                  ()                                                                      { return flavorNames.empty() ? 1 : flavorNames.size(); }
11968         virtual void    setFlavor                               (size_t flavorNo)                                       { DE_ASSERT(flavorNo < getFlavorCount()); flavor = flavorNo; }
11969         virtual size_t  getFlavor                               ()                                                                      { return flavor; }
11970         virtual string  getCurrentFlavorName    ()                                                                      { return flavorNames.empty() ? string("") : flavorNames[getFlavor()]; }
11971
11972         virtual void    setOutCompCount                 (size_t compCount)                                      { outCompCount = compCount; }
11973         virtual size_t  getOutCompCount                 ()                                                                      { return outCompCount; }
11974
11975         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)        { argCompCount[argNo] = compCount; }
11976         virtual size_t  getArgCompCount                 (size_t argNo)                                          { return argCompCount[argNo]; }
11977
11978 protected:
11979         size_t                          flavor;
11980         tcu::FloatFormat        floatFormat16;
11981         size_t                          outCompCount;
11982         vector<size_t>          argCompCount;
11983         vector<string>          flavorNames;
11984 };
11985
11986 struct fp16OpFNegate : public fp16PerComponent
11987 {
11988         template <class fp16type>
11989         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
11990         {
11991                 const fp16type  x               (*in[0]);
11992                 const double    d               (x.asDouble());
11993                 const double    result  (0.0 - d);
11994
11995                 out[0] = fp16type(result).bits();
11996                 min[0] = getMin(result, getULPs(in));
11997                 max[0] = getMax(result, getULPs(in));
11998
11999                 return true;
12000         }
12001 };
12002
12003 struct fp16Round : public fp16PerComponent
12004 {
12005         fp16Round() : fp16PerComponent()
12006         {
12007                 flavorNames.push_back("Floor(x+0.5)");
12008                 flavorNames.push_back("Floor(x-0.5)");
12009                 flavorNames.push_back("RoundEven");
12010         }
12011
12012         template<class fp16type>
12013         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12014         {
12015                 const fp16type  x               (*in[0]);
12016                 const double    d               (x.asDouble());
12017                 double                  result  (0.0);
12018
12019                 switch (flavor)
12020                 {
12021                         case 0:         result = deRound(d);            break;
12022                         case 1:         result = deFloor(d - 0.5);      break;
12023                         case 2:         result = deRoundEven(d);        break;
12024                         default:        TCU_THROW(InternalError, "Invalid flavor specified");
12025                 }
12026
12027                 out[0] = fp16type(result).bits();
12028                 min[0] = getMin(result, getULPs(in));
12029                 max[0] = getMax(result, getULPs(in));
12030
12031                 return true;
12032         }
12033 };
12034
12035 struct fp16RoundEven : public fp16PerComponent
12036 {
12037         template<class fp16type>
12038         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12039         {
12040                 const fp16type  x               (*in[0]);
12041                 const double    d               (x.asDouble());
12042                 const double    result  (deRoundEven(d));
12043
12044                 out[0] = fp16type(result).bits();
12045                 min[0] = getMin(result, getULPs(in));
12046                 max[0] = getMax(result, getULPs(in));
12047
12048                 return true;
12049         }
12050 };
12051
12052 struct fp16Trunc : public fp16PerComponent
12053 {
12054         template<class fp16type>
12055         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12056         {
12057                 const fp16type  x               (*in[0]);
12058                 const double    d               (x.asDouble());
12059                 const double    result  (deTrunc(d));
12060
12061                 out[0] = fp16type(result).bits();
12062                 min[0] = getMin(result, getULPs(in));
12063                 max[0] = getMax(result, getULPs(in));
12064
12065                 return true;
12066         }
12067 };
12068
12069 struct fp16FAbs : public fp16PerComponent
12070 {
12071         template<class fp16type>
12072         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12073         {
12074                 const fp16type  x               (*in[0]);
12075                 const double    d               (x.asDouble());
12076                 const double    result  (deAbs(d));
12077
12078                 out[0] = fp16type(result).bits();
12079                 min[0] = getMin(result, getULPs(in));
12080                 max[0] = getMax(result, getULPs(in));
12081
12082                 return true;
12083         }
12084 };
12085
12086 struct fp16FSign : public fp16PerComponent
12087 {
12088         template<class fp16type>
12089         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12090         {
12091                 const fp16type  x               (*in[0]);
12092                 const double    d               (x.asDouble());
12093                 const double    result  (deSign(d));
12094
12095                 if (x.isNaN())
12096                         return false;
12097
12098                 out[0] = fp16type(result).bits();
12099                 min[0] = getMin(result, getULPs(in));
12100                 max[0] = getMax(result, getULPs(in));
12101
12102                 return true;
12103         }
12104 };
12105
12106 struct fp16Floor : public fp16PerComponent
12107 {
12108         template<class fp16type>
12109         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12110         {
12111                 const fp16type  x               (*in[0]);
12112                 const double    d               (x.asDouble());
12113                 const double    result  (deFloor(d));
12114
12115                 out[0] = fp16type(result).bits();
12116                 min[0] = getMin(result, getULPs(in));
12117                 max[0] = getMax(result, getULPs(in));
12118
12119                 return true;
12120         }
12121 };
12122
12123 struct fp16Ceil : public fp16PerComponent
12124 {
12125         template<class fp16type>
12126         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12127         {
12128                 const fp16type  x               (*in[0]);
12129                 const double    d               (x.asDouble());
12130                 const double    result  (deCeil(d));
12131
12132                 out[0] = fp16type(result).bits();
12133                 min[0] = getMin(result, getULPs(in));
12134                 max[0] = getMax(result, getULPs(in));
12135
12136                 return true;
12137         }
12138 };
12139
12140 struct fp16Fract : public fp16PerComponent
12141 {
12142         template<class fp16type>
12143         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12144         {
12145                 const fp16type  x               (*in[0]);
12146                 const double    d               (x.asDouble());
12147                 const double    result  (deFrac(d));
12148
12149                 out[0] = fp16type(result).bits();
12150                 min[0] = getMin(result, getULPs(in));
12151                 max[0] = getMax(result, getULPs(in));
12152
12153                 return true;
12154         }
12155 };
12156
12157 struct fp16Radians : public fp16PerComponent
12158 {
12159         virtual double getULPs (vector<const deFloat16*>& in)
12160         {
12161                 DE_UNREF(in);
12162
12163                 return 2.5;
12164         }
12165
12166         template<class fp16type>
12167         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12168         {
12169                 const fp16type  x               (*in[0]);
12170                 const float             d               (x.asFloat());
12171                 const float             result  (deFloatRadians(d));
12172
12173                 out[0] = fp16type(result).bits();
12174                 min[0] = getMin(result, getULPs(in));
12175                 max[0] = getMax(result, getULPs(in));
12176
12177                 return true;
12178         }
12179 };
12180
12181 struct fp16Degrees : public fp16PerComponent
12182 {
12183         virtual double getULPs (vector<const deFloat16*>& in)
12184         {
12185                 DE_UNREF(in);
12186
12187                 return 2.5;
12188         }
12189
12190         template<class fp16type>
12191         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12192         {
12193                 const fp16type  x               (*in[0]);
12194                 const float             d               (x.asFloat());
12195                 const float             result  (deFloatDegrees(d));
12196
12197                 out[0] = fp16type(result).bits();
12198                 min[0] = getMin(result, getULPs(in));
12199                 max[0] = getMax(result, getULPs(in));
12200
12201                 return true;
12202         }
12203 };
12204
12205 struct fp16Sin : public fp16PerComponent
12206 {
12207         template<class fp16type>
12208         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12209         {
12210                 const fp16type  x                       (*in[0]);
12211                 const double    d                       (x.asDouble());
12212                 const double    result          (deSin(d));
12213                 const double    unspecUlp       (16.0);
12214                 const double    err                     (de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE) ? deLdExp(1.0, -7) : floatFormat16.ulp(deAbs(result), unspecUlp));
12215
12216                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12217                         return false;
12218
12219                 out[0] = fp16type(result).bits();
12220                 min[0] = result - err;
12221                 max[0] = result + err;
12222
12223                 return true;
12224         }
12225 };
12226
12227 struct fp16Cos : public fp16PerComponent
12228 {
12229         template<class fp16type>
12230         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12231         {
12232                 const fp16type  x                       (*in[0]);
12233                 const double    d                       (x.asDouble());
12234                 const double    result          (deCos(d));
12235                 const double    unspecUlp       (16.0);
12236                 const double    err                     (de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE) ? deLdExp(1.0, -7) : floatFormat16.ulp(deAbs(result), unspecUlp));
12237
12238                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12239                         return false;
12240
12241                 out[0] = fp16type(result).bits();
12242                 min[0] = result - err;
12243                 max[0] = result + err;
12244
12245                 return true;
12246         }
12247 };
12248
12249 struct fp16Tan : public fp16PerComponent
12250 {
12251         template<class fp16type>
12252         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12253         {
12254                 const fp16type  x               (*in[0]);
12255                 const double    d               (x.asDouble());
12256                 const double    result  (deTan(d));
12257
12258                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12259                         return false;
12260
12261                 out[0] = fp16type(result).bits();
12262                 {
12263                         const double    err                     = deLdExp(1.0, -7);
12264                         const double    s1                      = deSin(d) + err;
12265                         const double    s2                      = deSin(d) - err;
12266                         const double    c1                      = deCos(d) + err;
12267                         const double    c2                      = deCos(d) - err;
12268                         const double    edgeVals[]      = {s1/c1, s1/c2, s2/c1, s2/c2};
12269                         double                  edgeLeft        = out[0];
12270                         double                  edgeRight       = out[0];
12271
12272                         if (deSign(c1 * c2) < 0.0)
12273                         {
12274                                 edgeLeft        = -std::numeric_limits<double>::infinity();
12275                                 edgeRight       = +std::numeric_limits<double>::infinity();
12276                         }
12277                         else
12278                         {
12279                                 edgeLeft        = *std::min_element(&edgeVals[0], &edgeVals[DE_LENGTH_OF_ARRAY(edgeVals)]);
12280                                 edgeRight       = *std::max_element(&edgeVals[0], &edgeVals[DE_LENGTH_OF_ARRAY(edgeVals)]);
12281                         }
12282
12283                         min[0] = edgeLeft;
12284                         max[0] = edgeRight;
12285                 }
12286
12287                 return true;
12288         }
12289 };
12290
12291 struct fp16Asin : public fp16PerComponent
12292 {
12293         template<class fp16type>
12294         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12295         {
12296                 const fp16type  x               (*in[0]);
12297                 const double    d               (x.asDouble());
12298                 const double    result  (deAsin(d));
12299                 const double    error   (deAtan2(d, sqrt(1.0 - d * d)));
12300
12301                 if (!x.isNaN() && deAbs(d) > 1.0)
12302                         return false;
12303
12304                 out[0] = fp16type(result).bits();
12305                 min[0] = result - floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12306                 max[0] = result + floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12307
12308                 return true;
12309         }
12310 };
12311
12312 struct fp16Acos : public fp16PerComponent
12313 {
12314         template<class fp16type>
12315         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12316         {
12317                 const fp16type  x               (*in[0]);
12318                 const double    d               (x.asDouble());
12319                 const double    result  (deAcos(d));
12320                 const double    error   (deAtan2(sqrt(1.0 - d * d), d));
12321
12322                 if (!x.isNaN() && deAbs(d) > 1.0)
12323                         return false;
12324
12325                 out[0] = fp16type(result).bits();
12326                 min[0] = result - floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12327                 max[0] = result + floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12328
12329                 return true;
12330         }
12331 };
12332
12333 struct fp16Atan : public fp16PerComponent
12334 {
12335         virtual double getULPs(vector<const deFloat16*>& in)
12336         {
12337                 DE_UNREF(in);
12338
12339                 return 2 * 5.0; // This is not a precision test. Value is not from spec
12340         }
12341
12342         template<class fp16type>
12343         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12344         {
12345                 const fp16type  x               (*in[0]);
12346                 const double    d               (x.asDouble());
12347                 const double    result  (deAtanOver(d));
12348
12349                 out[0] = fp16type(result).bits();
12350                 min[0] = getMin(result, getULPs(in));
12351                 max[0] = getMax(result, getULPs(in));
12352
12353                 return true;
12354         }
12355 };
12356
12357 struct fp16Sinh : public fp16PerComponent
12358 {
12359         fp16Sinh() : fp16PerComponent()
12360         {
12361                 flavorNames.push_back("Double");
12362                 flavorNames.push_back("ExpFP16");
12363         }
12364
12365         template<class fp16type>
12366         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12367         {
12368                 const fp16type  x               (*in[0]);
12369                 const double    d               (x.asDouble());
12370                 const double    ulps    (64 * (1.0 + 2 * deAbs(d))); // This is not a precision test. Value is not from spec
12371                 double                  result  (0.0);
12372                 double                  error   (0.0);
12373
12374                 if (getFlavor() == 0)
12375                 {
12376                         result  = deSinh(d);
12377                         error   = floatFormat16.ulp(deAbs(result), ulps);
12378                 }
12379                 else if (getFlavor() == 1)
12380                 {
12381                         const fp16type  epx     (deExp(d));
12382                         const fp16type  enx     (deExp(-d));
12383                         const fp16type  esx     (epx.asDouble() - enx.asDouble());
12384                         const fp16type  sx2     (esx.asDouble() / 2.0);
12385
12386                         result  = sx2.asDouble();
12387                         error   = deAbs(floatFormat16.ulp(epx.asDouble(), ulps)) + deAbs(floatFormat16.ulp(enx.asDouble(), ulps));
12388                 }
12389                 else
12390                 {
12391                         TCU_THROW(InternalError, "Unknown flavor");
12392                 }
12393
12394                 out[0] = fp16type(result).bits();
12395                 min[0] = result - error;
12396                 max[0] = result + error;
12397
12398                 return true;
12399         }
12400 };
12401
12402 struct fp16Cosh : public fp16PerComponent
12403 {
12404         fp16Cosh() : fp16PerComponent()
12405         {
12406                 flavorNames.push_back("Double");
12407                 flavorNames.push_back("ExpFP16");
12408         }
12409
12410         template<class fp16type>
12411         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12412         {
12413                 const fp16type  x               (*in[0]);
12414                 const double    d               (x.asDouble());
12415                 const double    ulps    (64 * (1.0 + 2 * deAbs(d))); // This is not a precision test. Value is not from spec
12416                 double                  result  (0.0);
12417
12418                 if (getFlavor() == 0)
12419                 {
12420                         result = deCosh(d);
12421                 }
12422                 else if (getFlavor() == 1)
12423                 {
12424                         const fp16type  epx     (deExp(d));
12425                         const fp16type  enx     (deExp(-d));
12426                         const fp16type  esx     (epx.asDouble() + enx.asDouble());
12427                         const fp16type  sx2     (esx.asDouble() / 2.0);
12428
12429                         result = sx2.asDouble();
12430                 }
12431                 else
12432                 {
12433                         TCU_THROW(InternalError, "Unknown flavor");
12434                 }
12435
12436                 out[0] = fp16type(result).bits();
12437                 min[0] = result - floatFormat16.ulp(deAbs(result), ulps);
12438                 max[0] = result + floatFormat16.ulp(deAbs(result), ulps);
12439
12440                 return true;
12441         }
12442 };
12443
12444 struct fp16Tanh : public fp16PerComponent
12445 {
12446         fp16Tanh() : fp16PerComponent()
12447         {
12448                 flavorNames.push_back("Tanh");
12449                 flavorNames.push_back("SinhCosh");
12450                 flavorNames.push_back("SinhCoshFP16");
12451                 flavorNames.push_back("PolyFP16");
12452         }
12453
12454         virtual double getULPs (vector<const deFloat16*>& in)
12455         {
12456                 const tcu::Float16      x       (*in[0]);
12457                 const double            d       (x.asDouble());
12458
12459                 return 2 * (1.0 + 2 * deAbs(d)); // This is not a precision test. Value is not from spec
12460         }
12461
12462         template<class fp16type>
12463         inline double calcPoly (const fp16type& espx, const fp16type& esnx, const fp16type& ecpx, const fp16type& ecnx)
12464         {
12465                 const fp16type  esx     (espx.asDouble() - esnx.asDouble());
12466                 const fp16type  sx2     (esx.asDouble() / 2.0);
12467                 const fp16type  ecx     (ecpx.asDouble() + ecnx.asDouble());
12468                 const fp16type  cx2     (ecx.asDouble() / 2.0);
12469                 const fp16type  tg      (sx2.asDouble() / cx2.asDouble());
12470                 const double    rez     (tg.asDouble());
12471
12472                 return rez;
12473         }
12474
12475         template<class fp16type>
12476         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12477         {
12478                 const fp16type  x               (*in[0]);
12479                 const double    d               (x.asDouble());
12480                 double                  result  (0.0);
12481
12482                 if (getFlavor() == 0)
12483                 {
12484                         result  = deTanh(d);
12485                         min[0]  = getMin(result, getULPs(in));
12486                         max[0]  = getMax(result, getULPs(in));
12487                 }
12488                 else if (getFlavor() == 1)
12489                 {
12490                         result  = deSinh(d) / deCosh(d);
12491                         min[0]  = getMin(result, getULPs(in));
12492                         max[0]  = getMax(result, getULPs(in));
12493                 }
12494                 else if (getFlavor() == 2)
12495                 {
12496                         const fp16type  s       (deSinh(d));
12497                         const fp16type  c       (deCosh(d));
12498
12499                         result  = s.asDouble() / c.asDouble();
12500                         min[0]  = getMin(result, getULPs(in));
12501                         max[0]  = getMax(result, getULPs(in));
12502                 }
12503                 else if (getFlavor() == 3)
12504                 {
12505                         const double    ulps    (getULPs(in));
12506                         const double    epxm    (deExp( d));
12507                         const double    enxm    (deExp(-d));
12508                         const double    epxmerr = floatFormat16.ulp(epxm, ulps);
12509                         const double    enxmerr = floatFormat16.ulp(enxm, ulps);
12510                         const fp16type  epx[]   = { fp16type(epxm - epxmerr), fp16type(epxm + epxmerr) };
12511                         const fp16type  enx[]   = { fp16type(enxm - enxmerr), fp16type(enxm + enxmerr) };
12512                         const fp16type  epxm16  (epxm);
12513                         const fp16type  enxm16  (enxm);
12514                         vector<double>  tgs;
12515
12516                         for (size_t spNdx = 0; spNdx < DE_LENGTH_OF_ARRAY(epx); ++spNdx)
12517                         for (size_t snNdx = 0; snNdx < DE_LENGTH_OF_ARRAY(enx); ++snNdx)
12518                         for (size_t cpNdx = 0; cpNdx < DE_LENGTH_OF_ARRAY(epx); ++cpNdx)
12519                         for (size_t cnNdx = 0; cnNdx < DE_LENGTH_OF_ARRAY(enx); ++cnNdx)
12520                         {
12521                                 const double tgh = calcPoly(epx[spNdx], enx[snNdx], epx[cpNdx], enx[cnNdx]);
12522
12523                                 tgs.push_back(tgh);
12524                         }
12525
12526                         result = calcPoly(epxm16, enxm16, epxm16, enxm16);
12527                         min[0] = *std::min_element(tgs.begin(), tgs.end());
12528                         max[0] = *std::max_element(tgs.begin(), tgs.end());
12529                 }
12530                 else
12531                 {
12532                         TCU_THROW(InternalError, "Unknown flavor");
12533                 }
12534
12535                 out[0] = fp16type(result).bits();
12536
12537                 return true;
12538         }
12539 };
12540
12541 struct fp16Asinh : public fp16PerComponent
12542 {
12543         fp16Asinh() : fp16PerComponent()
12544         {
12545                 flavorNames.push_back("Double");
12546                 flavorNames.push_back("PolyFP16Wiki");
12547                 flavorNames.push_back("PolyFP16Abs");
12548         }
12549
12550         virtual double getULPs (vector<const deFloat16*>& in)
12551         {
12552                 DE_UNREF(in);
12553
12554                 return 256.0; // This is not a precision test. Value is not from spec
12555         }
12556
12557         template<class fp16type>
12558         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12559         {
12560                 const fp16type  x               (*in[0]);
12561                 const double    d               (x.asDouble());
12562                 double                  result  (0.0);
12563
12564                 if (getFlavor() == 0)
12565                 {
12566                         result = deAsinh(d);
12567                 }
12568                 else if (getFlavor() == 1)
12569                 {
12570                         const fp16type  x2              (d * d);
12571                         const fp16type  x2p1    (x2.asDouble() + 1.0);
12572                         const fp16type  sq              (deSqrt(x2p1.asDouble()));
12573                         const fp16type  sxsq    (d + sq.asDouble());
12574                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
12575
12576                         if (lsxsq.isInf())
12577                                 return false;
12578
12579                         result = lsxsq.asDouble();
12580                 }
12581                 else if (getFlavor() == 2)
12582                 {
12583                         const fp16type  x2              (d * d);
12584                         const fp16type  x2p1    (x2.asDouble() + 1.0);
12585                         const fp16type  sq              (deSqrt(x2p1.asDouble()));
12586                         const fp16type  sxsq    (deAbs(d) + sq.asDouble());
12587                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
12588
12589                         result = deSign(d) * lsxsq.asDouble();
12590                 }
12591                 else
12592                 {
12593                         TCU_THROW(InternalError, "Unknown flavor");
12594                 }
12595
12596                 out[0] = fp16type(result).bits();
12597                 min[0] = getMin(result, getULPs(in));
12598                 max[0] = getMax(result, getULPs(in));
12599
12600                 return true;
12601         }
12602 };
12603
12604 struct fp16Acosh : public fp16PerComponent
12605 {
12606         fp16Acosh() : fp16PerComponent()
12607         {
12608                 flavorNames.push_back("Double");
12609                 flavorNames.push_back("PolyFP16");
12610         }
12611
12612         virtual double getULPs (vector<const deFloat16*>& in)
12613         {
12614                 DE_UNREF(in);
12615
12616                 return 16.0; // This is not a precision test. Value is not from spec
12617         }
12618
12619         template<class fp16type>
12620         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12621         {
12622                 const fp16type  x               (*in[0]);
12623                 const double    d               (x.asDouble());
12624                 double                  result  (0.0);
12625
12626                 if (!x.isNaN() && d < 1.0)
12627                         return false;
12628
12629                 if (getFlavor() == 0)
12630                 {
12631                         result = deAcosh(d);
12632                 }
12633                 else if (getFlavor() == 1)
12634                 {
12635                         const fp16type  x2              (d * d);
12636                         const fp16type  x2m1    (x2.asDouble() - 1.0);
12637                         const fp16type  sq              (deSqrt(x2m1.asDouble()));
12638                         const fp16type  sxsq    (d + sq.asDouble());
12639                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
12640
12641                         result = lsxsq.asDouble();
12642                 }
12643                 else
12644                 {
12645                         TCU_THROW(InternalError, "Unknown flavor");
12646                 }
12647
12648                 out[0] = fp16type(result).bits();
12649                 min[0] = getMin(result, getULPs(in));
12650                 max[0] = getMax(result, getULPs(in));
12651
12652                 return true;
12653         }
12654 };
12655
12656 struct fp16Atanh : public fp16PerComponent
12657 {
12658         fp16Atanh() : fp16PerComponent()
12659         {
12660                 flavorNames.push_back("Double");
12661                 flavorNames.push_back("PolyFP16");
12662         }
12663
12664         template<class fp16type>
12665         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12666         {
12667                 const fp16type  x               (*in[0]);
12668                 const double    d               (x.asDouble());
12669                 double                  result  (0.0);
12670
12671                 if (deAbs(d) >= 1.0)
12672                         return false;
12673
12674                 if (getFlavor() == 0)
12675                 {
12676                         const double    ulps    (16.0); // This is not a precision test. Value is not from spec
12677
12678                         result = deAtanh(d);
12679                         min[0] = getMin(result, ulps);
12680                         max[0] = getMax(result, ulps);
12681                 }
12682                 else if (getFlavor() == 1)
12683                 {
12684                         const fp16type  x1a             (1.0 + d);
12685                         const fp16type  x1b             (1.0 - d);
12686                         const fp16type  x1d             (x1a.asDouble() / x1b.asDouble());
12687                         const fp16type  lx1d    (deLog(x1d.asDouble()));
12688                         const fp16type  lx1d2   (0.5 * lx1d.asDouble());
12689                         const double    error   (2 * (de::inRange(deAbs(x1d.asDouble()), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(x1d.asDouble()), 3.0)));
12690
12691                         result = lx1d2.asDouble();
12692                         min[0] = result - error;
12693                         max[0] = result + error;
12694                 }
12695                 else
12696                 {
12697                         TCU_THROW(InternalError, "Unknown flavor");
12698                 }
12699
12700                 out[0] = fp16type(result).bits();
12701
12702                 return true;
12703         }
12704 };
12705
12706 struct fp16Exp : public fp16PerComponent
12707 {
12708         template<class fp16type>
12709         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12710         {
12711                 const fp16type  x               (*in[0]);
12712                 const double    d               (x.asDouble());
12713                 const double    ulps    (10.0 * (1.0 + 2.0 * deAbs(d)));
12714                 const double    result  (deExp(d));
12715
12716                 out[0] = fp16type(result).bits();
12717                 min[0] = getMin(result, ulps);
12718                 max[0] = getMax(result, ulps);
12719
12720                 return true;
12721         }
12722 };
12723
12724 struct fp16Log : public fp16PerComponent
12725 {
12726         template<class fp16type>
12727         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12728         {
12729                 const fp16type  x               (*in[0]);
12730                 const double    d               (x.asDouble());
12731                 const double    result  (deLog(d));
12732                 const double    error   (de::inRange(deAbs(d), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(result), 3.0));
12733
12734                 if (d <= 0.0)
12735                         return false;
12736
12737                 out[0] = fp16type(result).bits();
12738                 min[0] = result - error;
12739                 max[0] = result + error;
12740
12741                 return true;
12742         }
12743 };
12744
12745 struct fp16Exp2 : public fp16PerComponent
12746 {
12747         template<class fp16type>
12748         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12749         {
12750                 const fp16type  x               (*in[0]);
12751                 const double    d               (x.asDouble());
12752                 const double    result  (deExp2(d));
12753                 const double    ulps    (1.0 + 2.0 * deAbs(fp16type(in[0][0]).asDouble()));
12754
12755                 out[0] = fp16type(result).bits();
12756                 min[0] = getMin(result, ulps);
12757                 max[0] = getMax(result, ulps);
12758
12759                 return true;
12760         }
12761 };
12762
12763 struct fp16Log2 : public fp16PerComponent
12764 {
12765         template<class fp16type>
12766         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12767         {
12768                 const fp16type  x               (*in[0]);
12769                 const double    d               (x.asDouble());
12770                 const double    result  (deLog2(d));
12771                 const double    error   (de::inRange(deAbs(d), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(result), 3.0));
12772
12773                 if (d <= 0.0)
12774                         return false;
12775
12776                 out[0] = fp16type(result).bits();
12777                 min[0] = result - error;
12778                 max[0] = result + error;
12779
12780                 return true;
12781         }
12782 };
12783
12784 struct fp16Sqrt : public fp16PerComponent
12785 {
12786         virtual double getULPs (vector<const deFloat16*>& in)
12787         {
12788                 DE_UNREF(in);
12789
12790                 return 6.0;
12791         }
12792
12793         template<class fp16type>
12794         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12795         {
12796                 const fp16type  x               (*in[0]);
12797                 const double    d               (x.asDouble());
12798                 const double    result  (deSqrt(d));
12799
12800                 if (!x.isNaN() && d < 0.0)
12801                         return false;
12802
12803                 out[0] = fp16type(result).bits();
12804                 min[0] = getMin(result, getULPs(in));
12805                 max[0] = getMax(result, getULPs(in));
12806
12807                 return true;
12808         }
12809 };
12810
12811 struct fp16InverseSqrt : public fp16PerComponent
12812 {
12813         virtual double getULPs (vector<const deFloat16*>& in)
12814         {
12815                 DE_UNREF(in);
12816
12817                 return 2.0;
12818         }
12819
12820         template<class fp16type>
12821         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12822         {
12823                 const fp16type  x               (*in[0]);
12824                 const double    d               (x.asDouble());
12825                 const double    result  (1.0/deSqrt(d));
12826
12827                 if (!x.isNaN() && d <= 0.0)
12828                         return false;
12829
12830                 out[0] = fp16type(result).bits();
12831                 min[0] = getMin(result, getULPs(in));
12832                 max[0] = getMax(result, getULPs(in));
12833
12834                 return true;
12835         }
12836 };
12837
12838 struct fp16ModfFrac : public fp16PerComponent
12839 {
12840         template<class fp16type>
12841         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12842         {
12843                 const fp16type  x               (*in[0]);
12844                 const double    d               (x.asDouble());
12845                 double                  i               (0.0);
12846                 const double    result  (deModf(d, &i));
12847
12848                 if (x.isInf() || x.isNaN())
12849                         return false;
12850
12851                 out[0] = fp16type(result).bits();
12852                 min[0] = getMin(result, getULPs(in));
12853                 max[0] = getMax(result, getULPs(in));
12854
12855                 return true;
12856         }
12857 };
12858
12859 struct fp16ModfInt : public fp16PerComponent
12860 {
12861         template<class fp16type>
12862         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12863         {
12864                 const fp16type  x               (*in[0]);
12865                 const double    d               (x.asDouble());
12866                 double                  i               (0.0);
12867                 const double    dummy   (deModf(d, &i));
12868                 const double    result  (i);
12869
12870                 DE_UNREF(dummy);
12871
12872                 if (x.isInf() || x.isNaN())
12873                         return false;
12874
12875                 out[0] = fp16type(result).bits();
12876                 min[0] = getMin(result, getULPs(in));
12877                 max[0] = getMax(result, getULPs(in));
12878
12879                 return true;
12880         }
12881 };
12882
12883 struct fp16FrexpS : public fp16PerComponent
12884 {
12885         template<class fp16type>
12886         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12887         {
12888                 const fp16type  x               (*in[0]);
12889                 const double    d               (x.asDouble());
12890                 int                             e               (0);
12891                 const double    result  (deFrExp(d, &e));
12892
12893                 if (x.isNaN() || x.isInf())
12894                         return false;
12895
12896                 out[0] = fp16type(result).bits();
12897                 min[0] = getMin(result, getULPs(in));
12898                 max[0] = getMax(result, getULPs(in));
12899
12900                 return true;
12901         }
12902 };
12903
12904 struct fp16FrexpE : public fp16PerComponent
12905 {
12906         template<class fp16type>
12907         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12908         {
12909                 const fp16type  x               (*in[0]);
12910                 const double    d               (x.asDouble());
12911                 int                             e               (0);
12912                 const double    dummy   (deFrExp(d, &e));
12913                 const double    result  (static_cast<double>(e));
12914
12915                 DE_UNREF(dummy);
12916
12917                 if (x.isNaN() || x.isInf())
12918                         return false;
12919
12920                 out[0] = fp16type(result).bits();
12921                 min[0] = getMin(result, getULPs(in));
12922                 max[0] = getMax(result, getULPs(in));
12923
12924                 return true;
12925         }
12926 };
12927
12928 struct fp16OpFAdd : public fp16PerComponent
12929 {
12930         template<class fp16type>
12931         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12932         {
12933                 const fp16type  x               (*in[0]);
12934                 const fp16type  y               (*in[1]);
12935                 const double    xd              (x.asDouble());
12936                 const double    yd              (y.asDouble());
12937                 const double    result  (xd + yd);
12938
12939                 out[0] = fp16type(result).bits();
12940                 min[0] = getMin(result, getULPs(in));
12941                 max[0] = getMax(result, getULPs(in));
12942
12943                 return true;
12944         }
12945 };
12946
12947 struct fp16OpFSub : public fp16PerComponent
12948 {
12949         template<class fp16type>
12950         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12951         {
12952                 const fp16type  x               (*in[0]);
12953                 const fp16type  y               (*in[1]);
12954                 const double    xd              (x.asDouble());
12955                 const double    yd              (y.asDouble());
12956                 const double    result  (xd - yd);
12957
12958                 out[0] = fp16type(result).bits();
12959                 min[0] = getMin(result, getULPs(in));
12960                 max[0] = getMax(result, getULPs(in));
12961
12962                 return true;
12963         }
12964 };
12965
12966 struct fp16OpFMul : public fp16PerComponent
12967 {
12968         template<class fp16type>
12969         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12970         {
12971                 const fp16type  x               (*in[0]);
12972                 const fp16type  y               (*in[1]);
12973                 const double    xd              (x.asDouble());
12974                 const double    yd              (y.asDouble());
12975                 const double    result  (xd * yd);
12976
12977                 out[0] = fp16type(result).bits();
12978                 min[0] = getMin(result, getULPs(in));
12979                 max[0] = getMax(result, getULPs(in));
12980
12981                 return true;
12982         }
12983 };
12984
12985 struct fp16OpFDiv : public fp16PerComponent
12986 {
12987         fp16OpFDiv() : fp16PerComponent()
12988         {
12989                 flavorNames.push_back("DirectDiv");
12990                 flavorNames.push_back("InverseDiv");
12991         }
12992
12993         template<class fp16type>
12994         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12995         {
12996                 const fp16type  x                       (*in[0]);
12997                 const fp16type  y                       (*in[1]);
12998                 const double    xd                      (x.asDouble());
12999                 const double    yd                      (y.asDouble());
13000                 const double    unspecUlp       (16.0);
13001                 const double    ulpCnt          (de::inRange(deAbs(yd), deLdExp(1, -14), deLdExp(1, 14)) ? 2.5 : unspecUlp);
13002                 double                  result          (0.0);
13003
13004                 if (y.isZero())
13005                         return false;
13006
13007                 if (getFlavor() == 0)
13008                 {
13009                         result = (xd / yd);
13010                 }
13011                 else if (getFlavor() == 1)
13012                 {
13013                         const double    invyd   (1.0 / yd);
13014                         const fp16type  invy    (invyd);
13015
13016                         result = (xd * invy.asDouble());
13017                 }
13018                 else
13019                 {
13020                         TCU_THROW(InternalError, "Unknown flavor");
13021                 }
13022
13023                 out[0] = fp16type(result).bits();
13024                 min[0] = getMin(result, ulpCnt);
13025                 max[0] = getMax(result, ulpCnt);
13026
13027                 return true;
13028         }
13029 };
13030
13031 struct fp16Atan2 : public fp16PerComponent
13032 {
13033         fp16Atan2() : fp16PerComponent()
13034         {
13035                 flavorNames.push_back("DoubleCalc");
13036                 flavorNames.push_back("DoubleCalc_PI");
13037         }
13038
13039         virtual double getULPs(vector<const deFloat16*>& in)
13040         {
13041                 DE_UNREF(in);
13042
13043                 return 2 * 5.0; // This is not a precision test. Value is not from spec
13044         }
13045
13046         template<class fp16type>
13047         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13048         {
13049                 const fp16type  x               (*in[0]);
13050                 const fp16type  y               (*in[1]);
13051                 const double    xd              (x.asDouble());
13052                 const double    yd              (y.asDouble());
13053                 double                  result  (0.0);
13054
13055                 if (x.isZero() && y.isZero())
13056                         return false;
13057
13058                 if (getFlavor() == 0)
13059                 {
13060                         result  = deAtan2(xd, yd);
13061                 }
13062                 else if (getFlavor() == 1)
13063                 {
13064                         const double    ulps    (2.0 * 5.0); // This is not a precision test. Value is not from spec
13065                         const double    eps             (floatFormat16.ulp(DE_PI_DOUBLE, ulps));
13066
13067                         result  = deAtan2(xd, yd);
13068
13069                         if (de::inRange(deAbs(result), DE_PI_DOUBLE - eps, DE_PI_DOUBLE + eps))
13070                                 result  = -result;
13071                 }
13072                 else
13073                 {
13074                         TCU_THROW(InternalError, "Unknown flavor");
13075                 }
13076
13077                 out[0] = fp16type(result).bits();
13078                 min[0] = getMin(result, getULPs(in));
13079                 max[0] = getMax(result, getULPs(in));
13080
13081                 return true;
13082         }
13083 };
13084
13085 struct fp16Pow : public fp16PerComponent
13086 {
13087         fp16Pow() : fp16PerComponent()
13088         {
13089                 flavorNames.push_back("Pow");
13090                 flavorNames.push_back("PowLog2");
13091                 flavorNames.push_back("PowLog2FP16");
13092         }
13093
13094         template<class fp16type>
13095         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13096         {
13097                 const fp16type  x               (*in[0]);
13098                 const fp16type  y               (*in[1]);
13099                 const double    xd              (x.asDouble());
13100                 const double    yd              (y.asDouble());
13101                 const double    logxeps (de::inRange(deAbs(xd), 0.5, 2.0) ? deLdExp(1.0, -7) : floatFormat16.ulp(deLog2(xd), 3.0));
13102                 const double    ulps1   (1.0 + 4.0 * deAbs(yd * (deLog2(xd) - logxeps)));
13103                 const double    ulps2   (1.0 + 4.0 * deAbs(yd * (deLog2(xd) + logxeps)));
13104                 const double    ulps    (deMax(deAbs(ulps1), deAbs(ulps2)));
13105                 double                  result  (0.0);
13106
13107                 if (xd < 0.0)
13108                         return false;
13109
13110                 if (x.isZero() && yd <= 0.0)
13111                         return false;
13112
13113                 if (getFlavor() == 0)
13114                 {
13115                         result = dePow(xd, yd);
13116                 }
13117                 else if (getFlavor() == 1)
13118                 {
13119                         const double    l2d     (deLog2(xd));
13120                         const double    e2d     (deExp2(yd * l2d));
13121
13122                         result = e2d;
13123                 }
13124                 else if (getFlavor() == 2)
13125                 {
13126                         const double    l2d     (deLog2(xd));
13127                         const fp16type  l2      (l2d);
13128                         const double    e2d     (deExp2(yd * l2.asDouble()));
13129                         const fp16type  e2      (e2d);
13130
13131                         result = e2.asDouble();
13132                 }
13133                 else
13134                 {
13135                         TCU_THROW(InternalError, "Unknown flavor");
13136                 }
13137
13138                 out[0] = fp16type(result).bits();
13139                 min[0] = getMin(result, ulps);
13140                 max[0] = getMax(result, ulps);
13141
13142                 return true;
13143         }
13144 };
13145
13146 struct fp16FMin : public fp16PerComponent
13147 {
13148         template<class fp16type>
13149         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13150         {
13151                 const fp16type  x               (*in[0]);
13152                 const fp16type  y               (*in[1]);
13153                 const double    xd              (x.asDouble());
13154                 const double    yd              (y.asDouble());
13155                 const double    result  (deMin(xd, yd));
13156
13157                 if (x.isNaN() || y.isNaN())
13158                         return false;
13159
13160                 out[0] = fp16type(result).bits();
13161                 min[0] = getMin(result, getULPs(in));
13162                 max[0] = getMax(result, getULPs(in));
13163
13164                 return true;
13165         }
13166 };
13167
13168 struct fp16FMax : public fp16PerComponent
13169 {
13170         template<class fp16type>
13171         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13172         {
13173                 const fp16type  x               (*in[0]);
13174                 const fp16type  y               (*in[1]);
13175                 const double    xd              (x.asDouble());
13176                 const double    yd              (y.asDouble());
13177                 const double    result  (deMax(xd, yd));
13178
13179                 if (x.isNaN() || y.isNaN())
13180                         return false;
13181
13182                 out[0] = fp16type(result).bits();
13183                 min[0] = getMin(result, getULPs(in));
13184                 max[0] = getMax(result, getULPs(in));
13185
13186                 return true;
13187         }
13188 };
13189
13190 struct fp16Step : public fp16PerComponent
13191 {
13192         template<class fp16type>
13193         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13194         {
13195                 const fp16type  edge    (*in[0]);
13196                 const fp16type  x               (*in[1]);
13197                 const double    edged   (edge.asDouble());
13198                 const double    xd              (x.asDouble());
13199                 const double    result  (deStep(edged, xd));
13200
13201                 out[0] = fp16type(result).bits();
13202                 min[0] = getMin(result, getULPs(in));
13203                 max[0] = getMax(result, getULPs(in));
13204
13205                 return true;
13206         }
13207 };
13208
13209 struct fp16Ldexp : public fp16PerComponent
13210 {
13211         template<class fp16type>
13212         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13213         {
13214                 const fp16type  x               (*in[0]);
13215                 const fp16type  y               (*in[1]);
13216                 const double    xd              (x.asDouble());
13217                 const int               yd              (static_cast<int>(deTrunc(y.asDouble())));
13218                 const double    result  (deLdExp(xd, yd));
13219
13220                 if (y.isNaN() || y.isInf() || y.isDenorm() || yd < -14 || yd > 15)
13221                         return false;
13222
13223                 // Spec: "If this product is too large to be represented in the floating-point type, the result is undefined."
13224                 if (fp16type(result).isInf())
13225                         return false;
13226
13227                 out[0] = fp16type(result).bits();
13228                 min[0] = getMin(result, getULPs(in));
13229                 max[0] = getMax(result, getULPs(in));
13230
13231                 return true;
13232         }
13233 };
13234
13235 struct fp16FClamp : public fp16PerComponent
13236 {
13237         template<class fp16type>
13238         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13239         {
13240                 const fp16type  x               (*in[0]);
13241                 const fp16type  minVal  (*in[1]);
13242                 const fp16type  maxVal  (*in[2]);
13243                 const double    xd              (x.asDouble());
13244                 const double    minVald (minVal.asDouble());
13245                 const double    maxVald (maxVal.asDouble());
13246                 const double    result  (deClamp(xd, minVald, maxVald));
13247
13248                 if (minVal.isNaN() || maxVal.isNaN() || minVald > maxVald)
13249                         return false;
13250
13251                 out[0] = fp16type(result).bits();
13252                 min[0] = getMin(result, getULPs(in));
13253                 max[0] = getMax(result, getULPs(in));
13254
13255                 return true;
13256         }
13257 };
13258
13259 struct fp16FMix : public fp16PerComponent
13260 {
13261         fp16FMix() : fp16PerComponent()
13262         {
13263                 flavorNames.push_back("DoubleCalc");
13264                 flavorNames.push_back("EmulatingFP16");
13265                 flavorNames.push_back("EmulatingFP16YminusX");
13266         }
13267
13268         template<class fp16type>
13269         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13270         {
13271                 const fp16type  x               (*in[0]);
13272                 const fp16type  y               (*in[1]);
13273                 const fp16type  a               (*in[2]);
13274                 const double    ulps    (8.0); // This is not a precision test. Value is not from spec
13275                 double                  result  (0.0);
13276
13277                 if (getFlavor() == 0)
13278                 {
13279                         const double    xd              (x.asDouble());
13280                         const double    yd              (y.asDouble());
13281                         const double    ad              (a.asDouble());
13282                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13283                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13284                         const double    eps             (xeps + yeps);
13285
13286                         result = deMix(xd, yd, ad);
13287                         min[0] = result - eps;
13288                         max[0] = result + eps;
13289                 }
13290                 else if (getFlavor() == 1)
13291                 {
13292                         const double    xd              (x.asDouble());
13293                         const double    yd              (y.asDouble());
13294                         const double    ad              (a.asDouble());
13295                         const fp16type  am              (1.0 - ad);
13296                         const double    amd             (am.asDouble());
13297                         const fp16type  xam             (xd * amd);
13298                         const double    xamd    (xam.asDouble());
13299                         const fp16type  ya              (yd * ad);
13300                         const double    yad             (ya.asDouble());
13301                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13302                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13303                         const double    eps             (xeps + yeps);
13304
13305                         result = xamd + yad;
13306                         min[0] = result - eps;
13307                         max[0] = result + eps;
13308                 }
13309                 else if (getFlavor() == 2)
13310                 {
13311                         const double    xd              (x.asDouble());
13312                         const double    yd              (y.asDouble());
13313                         const double    ad              (a.asDouble());
13314                         const fp16type  ymx             (yd - xd);
13315                         const double    ymxd    (ymx.asDouble());
13316                         const fp16type  ymxa    (ymxd * ad);
13317                         const double    ymxad   (ymxa.asDouble());
13318                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13319                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13320                         const double    eps             (xeps + yeps);
13321
13322                         result = xd + ymxad;
13323                         min[0] = result - eps;
13324                         max[0] = result + eps;
13325                 }
13326                 else
13327                 {
13328                         TCU_THROW(InternalError, "Unknown flavor");
13329                 }
13330
13331                 out[0] = fp16type(result).bits();
13332
13333                 return true;
13334         }
13335 };
13336
13337 struct fp16SmoothStep : public fp16PerComponent
13338 {
13339         fp16SmoothStep() : fp16PerComponent()
13340         {
13341                 flavorNames.push_back("FloatCalc");
13342                 flavorNames.push_back("EmulatingFP16");
13343                 flavorNames.push_back("EmulatingFP16WClamp");
13344         }
13345
13346         virtual double getULPs(vector<const deFloat16*>& in)
13347         {
13348                 DE_UNREF(in);
13349
13350                 return 4.0; // This is not a precision test. Value is not from spec
13351         }
13352
13353         template<class fp16type>
13354         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13355         {
13356                 const fp16type  edge0   (*in[0]);
13357                 const fp16type  edge1   (*in[1]);
13358                 const fp16type  x               (*in[2]);
13359                 double                  result  (0.0);
13360
13361                 if (edge0.isNaN() || edge1.isNaN() || x.isNaN() || edge0.asDouble() >= edge1.asDouble())
13362                         return false;
13363
13364                 if (edge0.isInf() || edge1.isInf() || x.isInf())
13365                         return false;
13366
13367                 if (getFlavor() == 0)
13368                 {
13369                         const float     edge0d  (edge0.asFloat());
13370                         const float     edge1d  (edge1.asFloat());
13371                         const float     xd              (x.asFloat());
13372                         const float     sstep   (deFloatSmoothStep(edge0d, edge1d, xd));
13373
13374                         result = sstep;
13375                 }
13376                 else if (getFlavor() == 1)
13377                 {
13378                         const double    edge0d  (edge0.asDouble());
13379                         const double    edge1d  (edge1.asDouble());
13380                         const double    xd              (x.asDouble());
13381
13382                         if (xd <= edge0d)
13383                                 result = 0.0;
13384                         else if (xd >= edge1d)
13385                                 result = 1.0;
13386                         else
13387                         {
13388                                 const fp16type  a       (xd - edge0d);
13389                                 const fp16type  b       (edge1d - edge0d);
13390                                 const fp16type  t       (a.asDouble() / b.asDouble());
13391                                 const fp16type  t2      (2.0 * t.asDouble());
13392                                 const fp16type  t3      (3.0 - t2.asDouble());
13393                                 const fp16type  t4      (t.asDouble() * t3.asDouble());
13394                                 const fp16type  t5      (t.asDouble() * t4.asDouble());
13395
13396                                 result = t5.asDouble();
13397                         }
13398                 }
13399                 else if (getFlavor() == 2)
13400                 {
13401                         const double    edge0d  (edge0.asDouble());
13402                         const double    edge1d  (edge1.asDouble());
13403                         const double    xd              (x.asDouble());
13404                         const fp16type  a       (xd - edge0d);
13405                         const fp16type  b       (edge1d - edge0d);
13406                         const fp16type  bi      (1.0 / b.asDouble());
13407                         const fp16type  t0      (a.asDouble() * bi.asDouble());
13408                         const double    tc      (deClamp(t0.asDouble(), 0.0, 1.0));
13409                         const fp16type  t       (tc);
13410                         const fp16type  t2      (2.0 * t.asDouble());
13411                         const fp16type  t3      (3.0 - t2.asDouble());
13412                         const fp16type  t4      (t.asDouble() * t3.asDouble());
13413                         const fp16type  t5      (t.asDouble() * t4.asDouble());
13414
13415                         result = t5.asDouble();
13416                 }
13417                 else
13418                 {
13419                         TCU_THROW(InternalError, "Unknown flavor");
13420                 }
13421
13422                 out[0] = fp16type(result).bits();
13423                 min[0] = getMin(result, getULPs(in));
13424                 max[0] = getMax(result, getULPs(in));
13425
13426                 return true;
13427         }
13428 };
13429
13430 struct fp16Fma : public fp16PerComponent
13431 {
13432         virtual double getULPs(vector<const deFloat16*>& in)
13433         {
13434                 DE_UNREF(in);
13435
13436                 return 16.0;
13437         }
13438
13439         template<class fp16type>
13440         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13441         {
13442                 DE_ASSERT(in.size() == 3);
13443                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
13444                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
13445                 DE_ASSERT(getArgCompCount(2) == getOutCompCount());
13446                 DE_ASSERT(getOutCompCount() > 0);
13447
13448                 const fp16type  a               (*in[0]);
13449                 const fp16type  b               (*in[1]);
13450                 const fp16type  c               (*in[2]);
13451                 const double    ad              (a.asDouble());
13452                 const double    bd              (b.asDouble());
13453                 const double    cd              (c.asDouble());
13454                 const double    result  (deMadd(ad, bd, cd));
13455
13456                 out[0] = fp16type(result).bits();
13457                 min[0] = getMin(result, getULPs(in));
13458                 max[0] = getMax(result, getULPs(in));
13459
13460                 return true;
13461         }
13462 };
13463
13464
13465 struct fp16AllComponents : public fp16PerComponent
13466 {
13467         bool            callOncePerComponent    ()      { return false; }
13468 };
13469
13470 struct fp16Length : public fp16AllComponents
13471 {
13472         fp16Length() : fp16AllComponents()
13473         {
13474                 flavorNames.push_back("EmulatingFP16");
13475                 flavorNames.push_back("DoubleCalc");
13476         }
13477
13478         virtual double getULPs(vector<const deFloat16*>& in)
13479         {
13480                 DE_UNREF(in);
13481
13482                 return 4.0;
13483         }
13484
13485         template<class fp16type>
13486         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13487         {
13488                 DE_ASSERT(getOutCompCount() == 1);
13489                 DE_ASSERT(in.size() == 1);
13490
13491                 double  result  (0.0);
13492
13493                 if (getFlavor() == 0)
13494                 {
13495                         fp16type        r       (0.0);
13496
13497                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13498                         {
13499                                 const fp16type  x       (in[0][componentNdx]);
13500                                 const fp16type  q       (x.asDouble() * x.asDouble());
13501
13502                                 r = fp16type(r.asDouble() + q.asDouble());
13503                         }
13504
13505                         result = deSqrt(r.asDouble());
13506
13507                         out[0] = fp16type(result).bits();
13508                 }
13509                 else if (getFlavor() == 1)
13510                 {
13511                         double  r       (0.0);
13512
13513                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13514                         {
13515                                 const fp16type  x       (in[0][componentNdx]);
13516                                 const double    q       (x.asDouble() * x.asDouble());
13517
13518                                 r += q;
13519                         }
13520
13521                         result = deSqrt(r);
13522
13523                         out[0] = fp16type(result).bits();
13524                 }
13525                 else
13526                 {
13527                         TCU_THROW(InternalError, "Unknown flavor");
13528                 }
13529
13530                 min[0] = getMin(result, getULPs(in));
13531                 max[0] = getMax(result, getULPs(in));
13532
13533                 return true;
13534         }
13535 };
13536
13537 struct fp16Distance : public fp16AllComponents
13538 {
13539         fp16Distance() : fp16AllComponents()
13540         {
13541                 flavorNames.push_back("EmulatingFP16");
13542                 flavorNames.push_back("DoubleCalc");
13543         }
13544
13545         virtual double getULPs(vector<const deFloat16*>& in)
13546         {
13547                 DE_UNREF(in);
13548
13549                 return 4.0;
13550         }
13551
13552         template<class fp16type>
13553         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13554         {
13555                 DE_ASSERT(getOutCompCount() == 1);
13556                 DE_ASSERT(in.size() == 2);
13557                 DE_ASSERT(getArgCompCount(0) == getArgCompCount(1));
13558
13559                 double  result  (0.0);
13560
13561                 if (getFlavor() == 0)
13562                 {
13563                         fp16type        r       (0.0);
13564
13565                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13566                         {
13567                                 const fp16type  x       (in[0][componentNdx]);
13568                                 const fp16type  y       (in[1][componentNdx]);
13569                                 const fp16type  d       (x.asDouble() - y.asDouble());
13570                                 const fp16type  q       (d.asDouble() * d.asDouble());
13571
13572                                 r = fp16type(r.asDouble() + q.asDouble());
13573                         }
13574
13575                         result = deSqrt(r.asDouble());
13576                 }
13577                 else if (getFlavor() == 1)
13578                 {
13579                         double  r       (0.0);
13580
13581                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13582                         {
13583                                 const fp16type  x       (in[0][componentNdx]);
13584                                 const fp16type  y       (in[1][componentNdx]);
13585                                 const double    d       (x.asDouble() - y.asDouble());
13586                                 const double    q       (d * d);
13587
13588                                 r += q;
13589                         }
13590
13591                         result = deSqrt(r);
13592                 }
13593                 else
13594                 {
13595                         TCU_THROW(InternalError, "Unknown flavor");
13596                 }
13597
13598                 out[0] = fp16type(result).bits();
13599                 min[0] = getMin(result, getULPs(in));
13600                 max[0] = getMax(result, getULPs(in));
13601
13602                 return true;
13603         }
13604 };
13605
13606 struct fp16Cross : public fp16AllComponents
13607 {
13608         fp16Cross() : fp16AllComponents()
13609         {
13610                 flavorNames.push_back("EmulatingFP16");
13611                 flavorNames.push_back("DoubleCalc");
13612         }
13613
13614         virtual double getULPs(vector<const deFloat16*>& in)
13615         {
13616                 DE_UNREF(in);
13617
13618                 return 4.0;
13619         }
13620
13621         template<class fp16type>
13622         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13623         {
13624                 DE_ASSERT(getOutCompCount() == 3);
13625                 DE_ASSERT(in.size() == 2);
13626                 DE_ASSERT(getArgCompCount(0) == 3);
13627                 DE_ASSERT(getArgCompCount(1) == 3);
13628
13629                 if (getFlavor() == 0)
13630                 {
13631                         const fp16type  x0              (in[0][0]);
13632                         const fp16type  x1              (in[0][1]);
13633                         const fp16type  x2              (in[0][2]);
13634                         const fp16type  y0              (in[1][0]);
13635                         const fp16type  y1              (in[1][1]);
13636                         const fp16type  y2              (in[1][2]);
13637                         const fp16type  x1y2    (x1.asDouble() * y2.asDouble());
13638                         const fp16type  y1x2    (y1.asDouble() * x2.asDouble());
13639                         const fp16type  x2y0    (x2.asDouble() * y0.asDouble());
13640                         const fp16type  y2x0    (y2.asDouble() * x0.asDouble());
13641                         const fp16type  x0y1    (x0.asDouble() * y1.asDouble());
13642                         const fp16type  y0x1    (y0.asDouble() * x1.asDouble());
13643
13644                         out[0] = fp16type(x1y2.asDouble() - y1x2.asDouble()).bits();
13645                         out[1] = fp16type(x2y0.asDouble() - y2x0.asDouble()).bits();
13646                         out[2] = fp16type(x0y1.asDouble() - y0x1.asDouble()).bits();
13647                 }
13648                 else if (getFlavor() == 1)
13649                 {
13650                         const fp16type  x0              (in[0][0]);
13651                         const fp16type  x1              (in[0][1]);
13652                         const fp16type  x2              (in[0][2]);
13653                         const fp16type  y0              (in[1][0]);
13654                         const fp16type  y1              (in[1][1]);
13655                         const fp16type  y2              (in[1][2]);
13656                         const double    x1y2    (x1.asDouble() * y2.asDouble());
13657                         const double    y1x2    (y1.asDouble() * x2.asDouble());
13658                         const double    x2y0    (x2.asDouble() * y0.asDouble());
13659                         const double    y2x0    (y2.asDouble() * x0.asDouble());
13660                         const double    x0y1    (x0.asDouble() * y1.asDouble());
13661                         const double    y0x1    (y0.asDouble() * x1.asDouble());
13662
13663                         out[0] = fp16type(x1y2 - y1x2).bits();
13664                         out[1] = fp16type(x2y0 - y2x0).bits();
13665                         out[2] = fp16type(x0y1 - y0x1).bits();
13666                 }
13667                 else
13668                 {
13669                         TCU_THROW(InternalError, "Unknown flavor");
13670                 }
13671
13672                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
13673                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
13674                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
13675                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
13676
13677                 return true;
13678         }
13679 };
13680
13681 struct fp16Normalize : public fp16AllComponents
13682 {
13683         fp16Normalize() : fp16AllComponents()
13684         {
13685                 flavorNames.push_back("EmulatingFP16");
13686                 flavorNames.push_back("DoubleCalc");
13687
13688                 // flavorNames will be extended later
13689         }
13690
13691         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)
13692         {
13693                 DE_ASSERT(argCompCount[argNo] == 0); // Once only
13694
13695                 if (argNo == 0 && argCompCount[argNo] == 0)
13696                 {
13697                         const size_t            maxPermutationsCount    = 24u; // Equal to 4!
13698                         std::vector<int>        indices;
13699
13700                         for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
13701                                 indices.push_back(static_cast<int>(componentNdx));
13702
13703                         m_permutations.reserve(maxPermutationsCount);
13704
13705                         permutationsFlavorStart = flavorNames.size();
13706
13707                         do
13708                         {
13709                                 tcu::UVec4      permutation;
13710                                 std::string     name            = "Permutted_";
13711
13712                                 for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
13713                                 {
13714                                         permutation[static_cast<int>(componentNdx)] = indices[componentNdx];
13715                                         name += de::toString(indices[componentNdx]);
13716                                 }
13717
13718                                 m_permutations.push_back(permutation);
13719                                 flavorNames.push_back(name);
13720
13721                         } while(std::next_permutation(indices.begin(), indices.end()));
13722
13723                         permutationsFlavorEnd = flavorNames.size();
13724                 }
13725
13726                 fp16AllComponents::setArgCompCount(argNo, compCount);
13727         }
13728         virtual double getULPs(vector<const deFloat16*>& in)
13729         {
13730                 DE_UNREF(in);
13731
13732                 return 8.0;
13733         }
13734
13735         template<class fp16type>
13736         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13737         {
13738                 DE_ASSERT(in.size() == 1);
13739                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
13740
13741                 if (getFlavor() == 0)
13742                 {
13743                         fp16type        r(0.0);
13744
13745                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13746                         {
13747                                 const fp16type  x       (in[0][componentNdx]);
13748                                 const fp16type  q       (x.asDouble() * x.asDouble());
13749
13750                                 r = fp16type(r.asDouble() + q.asDouble());
13751                         }
13752
13753                         r = fp16type(deSqrt(r.asDouble()));
13754
13755                         if (r.isZero())
13756                                 return false;
13757
13758                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13759                         {
13760                                 const fp16type  x       (in[0][componentNdx]);
13761
13762                                 out[componentNdx] = fp16type(x.asDouble() / r.asDouble()).bits();
13763                         }
13764                 }
13765                 else if (getFlavor() == 1)
13766                 {
13767                         double  r(0.0);
13768
13769                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13770                         {
13771                                 const fp16type  x       (in[0][componentNdx]);
13772                                 const double    q       (x.asDouble() * x.asDouble());
13773
13774                                 r += q;
13775                         }
13776
13777                         r = deSqrt(r);
13778
13779                         if (r == 0)
13780                                 return false;
13781
13782                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13783                         {
13784                                 const fp16type  x       (in[0][componentNdx]);
13785
13786                                 out[componentNdx] = fp16type(x.asDouble() / r).bits();
13787                         }
13788                 }
13789                 else if (de::inBounds<size_t>(getFlavor(), permutationsFlavorStart, permutationsFlavorEnd))
13790                 {
13791                         const int                       compCount               (static_cast<int>(getArgCompCount(0)));
13792                         const size_t            permutationNdx  (getFlavor() - permutationsFlavorStart);
13793                         const tcu::UVec4&       permutation             (m_permutations[permutationNdx]);
13794                         fp16type                        r                               (0.0);
13795
13796                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
13797                         {
13798                                 const size_t    componentNdx    (permutation[permComponentNdx]);
13799                                 const fp16type  x                               (in[0][componentNdx]);
13800                                 const fp16type  q                               (x.asDouble() * x.asDouble());
13801
13802                                 r = fp16type(r.asDouble() + q.asDouble());
13803                         }
13804
13805                         r = fp16type(deSqrt(r.asDouble()));
13806
13807                         if (r.isZero())
13808                                 return false;
13809
13810                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
13811                         {
13812                                 const size_t    componentNdx    (permutation[permComponentNdx]);
13813                                 const fp16type  x                               (in[0][componentNdx]);
13814
13815                                 out[componentNdx] = fp16type(x.asDouble() / r.asDouble()).bits();
13816                         }
13817                 }
13818                 else
13819                 {
13820                         TCU_THROW(InternalError, "Unknown flavor");
13821                 }
13822
13823                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
13824                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
13825                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
13826                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
13827
13828                 return true;
13829         }
13830
13831 private:
13832         std::vector<tcu::UVec4> m_permutations;
13833         size_t                                  permutationsFlavorStart;
13834         size_t                                  permutationsFlavorEnd;
13835 };
13836
13837 struct fp16FaceForward : public fp16AllComponents
13838 {
13839         virtual double getULPs(vector<const deFloat16*>& in)
13840         {
13841                 DE_UNREF(in);
13842
13843                 return 4.0;
13844         }
13845
13846         template<class fp16type>
13847         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13848         {
13849                 DE_ASSERT(in.size() == 3);
13850                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
13851                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
13852                 DE_ASSERT(getArgCompCount(2) == getOutCompCount());
13853
13854                 fp16type        dp(0.0);
13855
13856                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
13857                 {
13858                         const fp16type  x       (in[1][componentNdx]);
13859                         const fp16type  y       (in[2][componentNdx]);
13860                         const double    xd      (x.asDouble());
13861                         const double    yd      (y.asDouble());
13862                         const fp16type  q       (xd * yd);
13863
13864                         dp = fp16type(dp.asDouble() + q.asDouble());
13865                 }
13866
13867                 if (dp.isNaN() || dp.isZero())
13868                         return false;
13869
13870                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
13871                 {
13872                         const fp16type  n       (in[0][componentNdx]);
13873
13874                         out[componentNdx] = (dp.signBit() == 1) ? n.bits() : fp16type(-n.asDouble()).bits();
13875                 }
13876
13877                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
13878                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
13879                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
13880                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
13881
13882                 return true;
13883         }
13884 };
13885
13886 struct fp16Reflect : public fp16AllComponents
13887 {
13888         fp16Reflect() : fp16AllComponents()
13889         {
13890                 flavorNames.push_back("EmulatingFP16");
13891                 flavorNames.push_back("EmulatingFP16+KeepZeroSign");
13892                 flavorNames.push_back("FloatCalc");
13893                 flavorNames.push_back("FloatCalc+KeepZeroSign");
13894                 flavorNames.push_back("EmulatingFP16+2Nfirst");
13895                 flavorNames.push_back("EmulatingFP16+2Ifirst");
13896         }
13897
13898         virtual double getULPs(vector<const deFloat16*>& in)
13899         {
13900                 DE_UNREF(in);
13901
13902                 return 256.0; // This is not a precision test. Value is not from spec
13903         }
13904
13905         template<class fp16type>
13906         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13907         {
13908                 DE_ASSERT(in.size() == 2);
13909                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
13910                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
13911
13912                 if (getFlavor() < 4)
13913                 {
13914                         const bool      keepZeroSign    ((flavor & 1) != 0 ? true : false);
13915                         const bool      floatCalc               ((flavor & 2) != 0 ? true : false);
13916
13917                         if (floatCalc)
13918                         {
13919                                 float   dp(0.0f);
13920
13921                                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
13922                                 {
13923                                         const fp16type  i       (in[0][componentNdx]);
13924                                         const fp16type  n       (in[1][componentNdx]);
13925                                         const float             id      (i.asFloat());
13926                                         const float             nd      (n.asFloat());
13927                                         const float             qd      (id * nd);
13928
13929                                         if (keepZeroSign)
13930                                                 dp = (componentNdx == 0) ? qd : dp + qd;
13931                                         else
13932                                                 dp = dp + qd;
13933                                 }
13934
13935                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
13936                                 {
13937                                         const fp16type  i               (in[0][componentNdx]);
13938                                         const fp16type  n               (in[1][componentNdx]);
13939                                         const float             dpnd    (dp * n.asFloat());
13940                                         const float             dpn2d   (2.0f * dpnd);
13941                                         const float             idpn2d  (i.asFloat() - dpn2d);
13942                                         const fp16type  result  (idpn2d);
13943
13944                                         out[componentNdx] = result.bits();
13945                                 }
13946                         }
13947                         else
13948                         {
13949                                 fp16type        dp(0.0);
13950
13951                                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
13952                                 {
13953                                         const fp16type  i       (in[0][componentNdx]);
13954                                         const fp16type  n       (in[1][componentNdx]);
13955                                         const double    id      (i.asDouble());
13956                                         const double    nd      (n.asDouble());
13957                                         const fp16type  q       (id * nd);
13958
13959                                         if (keepZeroSign)
13960                                                 dp = (componentNdx == 0) ? q : fp16type(dp.asDouble() + q.asDouble());
13961                                         else
13962                                                 dp = fp16type(dp.asDouble() + q.asDouble());
13963                                 }
13964
13965                                 if (dp.isNaN())
13966                                         return false;
13967
13968                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
13969                                 {
13970                                         const fp16type  i               (in[0][componentNdx]);
13971                                         const fp16type  n               (in[1][componentNdx]);
13972                                         const fp16type  dpn             (dp.asDouble() * n.asDouble());
13973                                         const fp16type  dpn2    (2 * dpn.asDouble());
13974                                         const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
13975
13976                                         out[componentNdx] = idpn2.bits();
13977                                 }
13978                         }
13979                 }
13980                 else if (getFlavor() == 4)
13981                 {
13982                         fp16type        dp(0.0);
13983
13984                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
13985                         {
13986                                 const fp16type  i       (in[0][componentNdx]);
13987                                 const fp16type  n       (in[1][componentNdx]);
13988                                 const double    id      (i.asDouble());
13989                                 const double    nd      (n.asDouble());
13990                                 const fp16type  q       (id * nd);
13991
13992                                 dp = fp16type(dp.asDouble() + q.asDouble());
13993                         }
13994
13995                         if (dp.isNaN())
13996                                 return false;
13997
13998                         for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
13999                         {
14000                                 const fp16type  i               (in[0][componentNdx]);
14001                                 const fp16type  n               (in[1][componentNdx]);
14002                                 const fp16type  n2              (2 * n.asDouble());
14003                                 const fp16type  dpn2    (dp.asDouble() * n2.asDouble());
14004                                 const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
14005
14006                                 out[componentNdx] = idpn2.bits();
14007                         }
14008                 }
14009                 else if (getFlavor() == 5)
14010                 {
14011                         fp16type        dp2(0.0);
14012
14013                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14014                         {
14015                                 const fp16type  i       (in[0][componentNdx]);
14016                                 const fp16type  n       (in[1][componentNdx]);
14017                                 const fp16type  i2      (2.0 * i.asDouble());
14018                                 const double    i2d     (i2.asDouble());
14019                                 const double    nd      (n.asDouble());
14020                                 const fp16type  q       (i2d * nd);
14021
14022                                 dp2 = fp16type(dp2.asDouble() + q.asDouble());
14023                         }
14024
14025                         if (dp2.isNaN())
14026                                 return false;
14027
14028                         for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14029                         {
14030                                 const fp16type  i               (in[0][componentNdx]);
14031                                 const fp16type  n               (in[1][componentNdx]);
14032                                 const fp16type  dpn2    (dp2.asDouble() * n.asDouble());
14033                                 const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
14034
14035                                 out[componentNdx] = idpn2.bits();
14036                         }
14037                 }
14038                 else
14039                 {
14040                         TCU_THROW(InternalError, "Unknown flavor");
14041                 }
14042
14043                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14044                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14045                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14046                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14047
14048                 return true;
14049         }
14050 };
14051
14052 struct fp16Refract : public fp16AllComponents
14053 {
14054         fp16Refract() : fp16AllComponents()
14055         {
14056                 flavorNames.push_back("EmulatingFP16");
14057                 flavorNames.push_back("EmulatingFP16+KeepZeroSign");
14058                 flavorNames.push_back("FloatCalc");
14059                 flavorNames.push_back("FloatCalc+KeepZeroSign");
14060         }
14061
14062         virtual double getULPs(vector<const deFloat16*>& in)
14063         {
14064                 DE_UNREF(in);
14065
14066                 return 8192.0; // This is not a precision test. Value is not from spec
14067         }
14068
14069         template<class fp16type>
14070         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14071         {
14072                 DE_ASSERT(in.size() == 3);
14073                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14074                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14075                 DE_ASSERT(getArgCompCount(2) == 1);
14076
14077                 const bool              keepZeroSign    ((flavor & 1) != 0 ? true : false);
14078                 const bool              doubleCalc              ((flavor & 2) != 0 ? true : false);
14079                 const fp16type  eta                             (*in[2]);
14080
14081                 if (doubleCalc)
14082                 {
14083                         double  dp      (0.0);
14084
14085                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14086                         {
14087                                 const fp16type  i       (in[0][componentNdx]);
14088                                 const fp16type  n       (in[1][componentNdx]);
14089                                 const double    id      (i.asDouble());
14090                                 const double    nd      (n.asDouble());
14091                                 const double    qd      (id * nd);
14092
14093                                 if (keepZeroSign)
14094                                         dp = (componentNdx == 0) ? qd : dp + qd;
14095                                 else
14096                                         dp = dp + qd;
14097                         }
14098
14099                         const double    eta2    (eta.asDouble() * eta.asDouble());
14100                         const double    dp2             (dp * dp);
14101                         const double    dp1             (1.0 - dp2);
14102                         const double    dpe             (eta2 * dp1);
14103                         const double    k               (1.0 - dpe);
14104
14105                         if (k < 0.0)
14106                         {
14107                                 const fp16type  zero    (0.0);
14108
14109                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14110                                         out[componentNdx] = zero.bits();
14111                         }
14112                         else
14113                         {
14114                                 const double    sk      (deSqrt(k));
14115
14116                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14117                                 {
14118                                         const fp16type  i               (in[0][componentNdx]);
14119                                         const fp16type  n               (in[1][componentNdx]);
14120                                         const double    etai    (i.asDouble() * eta.asDouble());
14121                                         const double    etadp   (eta.asDouble() * dp);
14122                                         const double    etadpk  (etadp + sk);
14123                                         const double    etadpkn (etadpk * n.asDouble());
14124                                         const double    full    (etai - etadpkn);
14125                                         const fp16type  result  (full);
14126
14127                                         if (result.isInf())
14128                                                 return false;
14129
14130                                         out[componentNdx] = result.bits();
14131                                 }
14132                         }
14133                 }
14134                 else
14135                 {
14136                         fp16type        dp      (0.0);
14137
14138                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14139                         {
14140                                 const fp16type  i       (in[0][componentNdx]);
14141                                 const fp16type  n       (in[1][componentNdx]);
14142                                 const double    id      (i.asDouble());
14143                                 const double    nd      (n.asDouble());
14144                                 const fp16type  q       (id * nd);
14145
14146                                 if (keepZeroSign)
14147                                         dp = (componentNdx == 0) ? q : fp16type(dp.asDouble() + q.asDouble());
14148                                 else
14149                                         dp = fp16type(dp.asDouble() + q.asDouble());
14150                         }
14151
14152                         if (dp.isNaN())
14153                                 return false;
14154
14155                         const fp16type  eta2(eta.asDouble() * eta.asDouble());
14156                         const fp16type  dp2     (dp.asDouble() * dp.asDouble());
14157                         const fp16type  dp1     (1.0 - dp2.asDouble());
14158                         const fp16type  dpe     (eta2.asDouble() * dp1.asDouble());
14159                         const fp16type  k       (1.0 - dpe.asDouble());
14160
14161                         if (k.asDouble() < 0.0)
14162                         {
14163                                 const fp16type  zero    (0.0);
14164
14165                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14166                                         out[componentNdx] = zero.bits();
14167                         }
14168                         else
14169                         {
14170                                 const fp16type  sk      (deSqrt(k.asDouble()));
14171
14172                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14173                                 {
14174                                         const fp16type  i               (in[0][componentNdx]);
14175                                         const fp16type  n               (in[1][componentNdx]);
14176                                         const fp16type  etai    (i.asDouble() * eta.asDouble());
14177                                         const fp16type  etadp   (eta.asDouble() * dp.asDouble());
14178                                         const fp16type  etadpk  (etadp.asDouble() + sk.asDouble());
14179                                         const fp16type  etadpkn (etadpk.asDouble() * n.asDouble());
14180                                         const fp16type  full    (etai.asDouble() - etadpkn.asDouble());
14181
14182                                         if (full.isNaN() || full.isInf())
14183                                                 return false;
14184
14185                                         out[componentNdx] = full.bits();
14186                                 }
14187                         }
14188                 }
14189
14190                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14191                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14192                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14193                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14194
14195                 return true;
14196         }
14197 };
14198
14199 struct fp16Dot : public fp16AllComponents
14200 {
14201         fp16Dot() : fp16AllComponents()
14202         {
14203                 flavorNames.push_back("EmulatingFP16");
14204                 flavorNames.push_back("FloatCalc");
14205                 flavorNames.push_back("DoubleCalc");
14206
14207                 // flavorNames will be extended later
14208         }
14209
14210         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)
14211         {
14212                 DE_ASSERT(argCompCount[argNo] == 0); // Once only
14213
14214                 if (argNo == 0 && argCompCount[argNo] == 0)
14215                 {
14216                         const size_t            maxPermutationsCount    = 24u; // Equal to 4!
14217                         std::vector<int>        indices;
14218
14219                         for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14220                                 indices.push_back(static_cast<int>(componentNdx));
14221
14222                         m_permutations.reserve(maxPermutationsCount);
14223
14224                         permutationsFlavorStart = flavorNames.size();
14225
14226                         do
14227                         {
14228                                 tcu::UVec4      permutation;
14229                                 std::string     name            = "Permutted_";
14230
14231                                 for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14232                                 {
14233                                         permutation[static_cast<int>(componentNdx)] = indices[componentNdx];
14234                                         name += de::toString(indices[componentNdx]);
14235                                 }
14236
14237                                 m_permutations.push_back(permutation);
14238                                 flavorNames.push_back(name);
14239
14240                         } while(std::next_permutation(indices.begin(), indices.end()));
14241
14242                         permutationsFlavorEnd = flavorNames.size();
14243                 }
14244
14245                 fp16AllComponents::setArgCompCount(argNo, compCount);
14246         }
14247
14248         virtual double  getULPs(vector<const deFloat16*>& in)
14249         {
14250                 DE_UNREF(in);
14251
14252                 return 16.0; // This is not a precision test. Value is not from spec
14253         }
14254
14255         template<class fp16type>
14256         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14257         {
14258                 DE_ASSERT(in.size() == 2);
14259                 DE_ASSERT(getArgCompCount(0) == getArgCompCount(1));
14260                 DE_ASSERT(getOutCompCount() == 1);
14261
14262                 double  result  (0.0);
14263                 double  eps             (0.0);
14264
14265                 if (getFlavor() == 0)
14266                 {
14267                         fp16type        dp      (0.0);
14268
14269                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14270                         {
14271                                 const fp16type  x       (in[0][componentNdx]);
14272                                 const fp16type  y       (in[1][componentNdx]);
14273                                 const fp16type  q       (x.asDouble() * y.asDouble());
14274
14275                                 dp = fp16type(dp.asDouble() + q.asDouble());
14276                                 eps += floatFormat16.ulp(q.asDouble(), 2.0);
14277                         }
14278
14279                         result = dp.asDouble();
14280                 }
14281                 else if (getFlavor() == 1)
14282                 {
14283                         float   dp      (0.0);
14284
14285                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14286                         {
14287                                 const fp16type  x       (in[0][componentNdx]);
14288                                 const fp16type  y       (in[1][componentNdx]);
14289                                 const float             q       (x.asFloat() * y.asFloat());
14290
14291                                 dp += q;
14292                                 eps += floatFormat16.ulp(static_cast<double>(q), 2.0);
14293                         }
14294
14295                         result = dp;
14296                 }
14297                 else if (getFlavor() == 2)
14298                 {
14299                         double  dp      (0.0);
14300
14301                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14302                         {
14303                                 const fp16type  x       (in[0][componentNdx]);
14304                                 const fp16type  y       (in[1][componentNdx]);
14305                                 const double    q       (x.asDouble() * y.asDouble());
14306
14307                                 dp += q;
14308                                 eps += floatFormat16.ulp(q, 2.0);
14309                         }
14310
14311                         result = dp;
14312                 }
14313                 else if (de::inBounds<size_t>(getFlavor(), permutationsFlavorStart, permutationsFlavorEnd))
14314                 {
14315                         const int                       compCount               (static_cast<int>(getArgCompCount(1)));
14316                         const size_t            permutationNdx  (getFlavor() - permutationsFlavorStart);
14317                         const tcu::UVec4&       permutation             (m_permutations[permutationNdx]);
14318                         fp16type                        dp                              (0.0);
14319
14320                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14321                         {
14322                                 const size_t            componentNdx    (permutation[permComponentNdx]);
14323                                 const fp16type          x                               (in[0][componentNdx]);
14324                                 const fp16type          y                               (in[1][componentNdx]);
14325                                 const fp16type          q                               (x.asDouble() * y.asDouble());
14326
14327                                 dp = fp16type(dp.asDouble() + q.asDouble());
14328                                 eps += floatFormat16.ulp(q.asDouble(), 2.0);
14329                         }
14330
14331                         result = dp.asDouble();
14332                 }
14333                 else
14334                 {
14335                         TCU_THROW(InternalError, "Unknown flavor");
14336                 }
14337
14338                 out[0] = fp16type(result).bits();
14339                 min[0] = result - eps;
14340                 max[0] = result + eps;
14341
14342                 return true;
14343         }
14344
14345 private:
14346         std::vector<tcu::UVec4> m_permutations;
14347         size_t                                  permutationsFlavorStart;
14348         size_t                                  permutationsFlavorEnd;
14349 };
14350
14351 struct fp16VectorTimesScalar : public fp16AllComponents
14352 {
14353         virtual double getULPs(vector<const deFloat16*>& in)
14354         {
14355                 DE_UNREF(in);
14356
14357                 return 2.0;
14358         }
14359
14360         template<class fp16type>
14361         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14362         {
14363                 DE_ASSERT(in.size() == 2);
14364                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14365                 DE_ASSERT(getArgCompCount(1) == 1);
14366
14367                 fp16type        s       (*in[1]);
14368
14369                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14370                 {
14371                         const fp16type  x          (in[0][componentNdx]);
14372                         const double    result (s.asDouble() * x.asDouble());
14373                         const fp16type  m          (result);
14374
14375                         out[componentNdx] = m.bits();
14376                         min[componentNdx] = getMin(result, getULPs(in));
14377                         max[componentNdx] = getMax(result, getULPs(in));
14378                 }
14379
14380                 return true;
14381         }
14382 };
14383
14384 struct fp16MatrixBase : public fp16AllComponents
14385 {
14386         deUint32                getComponentValidity                    ()
14387         {
14388                 return static_cast<deUint32>(-1);
14389         }
14390
14391         inline size_t   getNdx                                                  (const size_t rowCount, const size_t col, const size_t row)
14392         {
14393                 const size_t minComponentCount  = 0;
14394                 const size_t maxComponentCount  = 3;
14395                 const size_t alignedRowsCount   = (rowCount == 3) ? 4 : rowCount;
14396
14397                 DE_ASSERT(de::inRange(rowCount, minComponentCount + 1, maxComponentCount + 1));
14398                 DE_ASSERT(de::inRange(col, minComponentCount, maxComponentCount));
14399                 DE_ASSERT(de::inBounds(row, minComponentCount, rowCount));
14400                 DE_UNREF(minComponentCount);
14401                 DE_UNREF(maxComponentCount);
14402
14403                 return col * alignedRowsCount + row;
14404         }
14405
14406         deUint32                getComponentMatrixValidityMask  (size_t cols, size_t rows)
14407         {
14408                 deUint32        result  = 0u;
14409
14410                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14411                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14412                         {
14413                                 const size_t bitNdx = getNdx(rows, colNdx, rowNdx);
14414
14415                                 DE_ASSERT(bitNdx < sizeof(result) * 8);
14416
14417                                 result |= (1<<bitNdx);
14418                         }
14419
14420                 return result;
14421         }
14422 };
14423
14424 template<size_t cols, size_t rows>
14425 struct fp16Transpose : public fp16MatrixBase
14426 {
14427         virtual double getULPs(vector<const deFloat16*>& in)
14428         {
14429                 DE_UNREF(in);
14430
14431                 return 1.0;
14432         }
14433
14434         deUint32        getComponentValidity    ()
14435         {
14436                 return getComponentMatrixValidityMask(rows, cols);
14437         }
14438
14439         template<class fp16type>
14440         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14441         {
14442                 DE_ASSERT(in.size() == 1);
14443
14444                 const size_t            alignedCols     = (cols == 3) ? 4 : cols;
14445                 const size_t            alignedRows     = (rows == 3) ? 4 : rows;
14446                 vector<deFloat16>       output          (alignedCols * alignedRows, 0);
14447
14448                 DE_ASSERT(output.size() == alignedCols * alignedRows);
14449
14450                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14451                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14452                                 output[rowNdx * alignedCols + colNdx] = in[0][colNdx * alignedRows + rowNdx];
14453
14454                 deMemcpy(out, &output[0], sizeof(deFloat16) * output.size());
14455                 deMemcpy(min, &output[0], sizeof(deFloat16) * output.size());
14456                 deMemcpy(max, &output[0], sizeof(deFloat16) * output.size());
14457
14458                 return true;
14459         }
14460 };
14461
14462 template<size_t cols, size_t rows>
14463 struct fp16MatrixTimesScalar : public fp16MatrixBase
14464 {
14465         virtual double getULPs(vector<const deFloat16*>& in)
14466         {
14467                 DE_UNREF(in);
14468
14469                 return 4.0;
14470         }
14471
14472         deUint32        getComponentValidity    ()
14473         {
14474                 return getComponentMatrixValidityMask(cols, rows);
14475         }
14476
14477         template<class fp16type>
14478         bool calc(vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14479         {
14480                 DE_ASSERT(in.size() == 2);
14481                 DE_ASSERT(getArgCompCount(1) == 1);
14482
14483                 const fp16type  y                       (in[1][0]);
14484                 const float             scalar          (y.asFloat());
14485                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
14486                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
14487
14488                 DE_ASSERT(getArgCompCount(0) == alignedCols * alignedRows);
14489                 DE_ASSERT(getOutCompCount() == alignedCols * alignedRows);
14490                 DE_UNREF(alignedCols);
14491
14492                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14493                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14494                         {
14495                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
14496                                 const fp16type  x       (in[0][ndx]);
14497                                 const double    result  (scalar * x.asFloat());
14498
14499                                 out[ndx] = fp16type(result).bits();
14500                                 min[ndx] = getMin(result, getULPs(in));
14501                                 max[ndx] = getMax(result, getULPs(in));
14502                         }
14503
14504                 return true;
14505         }
14506 };
14507
14508 template<size_t cols, size_t rows>
14509 struct fp16VectorTimesMatrix : public fp16MatrixBase
14510 {
14511         fp16VectorTimesMatrix() : fp16MatrixBase()
14512         {
14513                 flavorNames.push_back("EmulatingFP16");
14514                 flavorNames.push_back("FloatCalc");
14515         }
14516
14517         virtual double getULPs (vector<const deFloat16*>& in)
14518         {
14519                 DE_UNREF(in);
14520
14521                 return (8.0 * cols);
14522         }
14523
14524         deUint32 getComponentValidity ()
14525         {
14526                 return getComponentMatrixValidityMask(cols, 1);
14527         }
14528
14529         template<class fp16type>
14530         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14531         {
14532                 DE_ASSERT(in.size() == 2);
14533
14534                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
14535                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
14536
14537                 DE_ASSERT(getOutCompCount() == cols);
14538                 DE_ASSERT(getArgCompCount(0) == rows);
14539                 DE_ASSERT(getArgCompCount(1) == alignedCols * alignedRows);
14540                 DE_UNREF(alignedCols);
14541
14542                 if (getFlavor() == 0)
14543                 {
14544                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14545                         {
14546                                 fp16type        s       (fp16type::zero(1));
14547
14548                                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14549                                 {
14550                                         const fp16type  v       (in[0][rowNdx]);
14551                                         const float             vf      (v.asFloat());
14552                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
14553                                         const fp16type  x       (in[1][ndx]);
14554                                         const float             xf      (x.asFloat());
14555                                         const fp16type  m       (vf * xf);
14556
14557                                         s = fp16type(s.asFloat() + m.asFloat());
14558                                 }
14559
14560                                 out[colNdx] = s.bits();
14561                                 min[colNdx] = getMin(s.asDouble(), getULPs(in));
14562                                 max[colNdx] = getMax(s.asDouble(), getULPs(in));
14563                         }
14564                 }
14565                 else if (getFlavor() == 1)
14566                 {
14567                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14568                         {
14569                                 float   s       (0.0f);
14570
14571                                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14572                                 {
14573                                         const fp16type  v       (in[0][rowNdx]);
14574                                         const float             vf      (v.asFloat());
14575                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
14576                                         const fp16type  x       (in[1][ndx]);
14577                                         const float             xf      (x.asFloat());
14578                                         const float             m       (vf * xf);
14579
14580                                         s += m;
14581                                 }
14582
14583                                 out[colNdx] = fp16type(s).bits();
14584                                 min[colNdx] = getMin(static_cast<double>(s), getULPs(in));
14585                                 max[colNdx] = getMax(static_cast<double>(s), getULPs(in));
14586                         }
14587                 }
14588                 else
14589                 {
14590                         TCU_THROW(InternalError, "Unknown flavor");
14591                 }
14592
14593                 return true;
14594         }
14595 };
14596
14597 template<size_t cols, size_t rows>
14598 struct fp16MatrixTimesVector : public fp16MatrixBase
14599 {
14600         fp16MatrixTimesVector() : fp16MatrixBase()
14601         {
14602                 flavorNames.push_back("EmulatingFP16");
14603                 flavorNames.push_back("FloatCalc");
14604         }
14605
14606         virtual double getULPs (vector<const deFloat16*>& in)
14607         {
14608                 DE_UNREF(in);
14609
14610                 return (8.0 * rows);
14611         }
14612
14613         deUint32 getComponentValidity ()
14614         {
14615                 return getComponentMatrixValidityMask(rows, 1);
14616         }
14617
14618         template<class fp16type>
14619         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14620         {
14621                 DE_ASSERT(in.size() == 2);
14622
14623                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
14624                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
14625
14626                 DE_ASSERT(getOutCompCount() == rows);
14627                 DE_ASSERT(getArgCompCount(0) == alignedCols * alignedRows);
14628                 DE_ASSERT(getArgCompCount(1) == cols);
14629                 DE_UNREF(alignedCols);
14630
14631                 if (getFlavor() == 0)
14632                 {
14633                         for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14634                         {
14635                                 fp16type        s       (fp16type::zero(1));
14636
14637                                 for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14638                                 {
14639                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
14640                                         const fp16type  x       (in[0][ndx]);
14641                                         const float             xf      (x.asFloat());
14642                                         const fp16type  v       (in[1][colNdx]);
14643                                         const float             vf      (v.asFloat());
14644                                         const fp16type  m       (vf * xf);
14645
14646                                         s = fp16type(s.asFloat() + m.asFloat());
14647                                 }
14648
14649                                 out[rowNdx] = s.bits();
14650                                 min[rowNdx] = getMin(s.asDouble(), getULPs(in));
14651                                 max[rowNdx] = getMax(s.asDouble(), getULPs(in));
14652                         }
14653                 }
14654                 else if (getFlavor() == 1)
14655                 {
14656                         for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14657                         {
14658                                 float   s       (0.0f);
14659
14660                                 for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14661                                 {
14662                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
14663                                         const fp16type  x       (in[0][ndx]);
14664                                         const float             xf      (x.asFloat());
14665                                         const fp16type  v       (in[1][colNdx]);
14666                                         const float             vf      (v.asFloat());
14667                                         const float             m       (vf * xf);
14668
14669                                         s += m;
14670                                 }
14671
14672                                 out[rowNdx] = fp16type(s).bits();
14673                                 min[rowNdx] = getMin(static_cast<double>(s), getULPs(in));
14674                                 max[rowNdx] = getMax(static_cast<double>(s), getULPs(in));
14675                         }
14676                 }
14677                 else
14678                 {
14679                         TCU_THROW(InternalError, "Unknown flavor");
14680                 }
14681
14682                 return true;
14683         }
14684 };
14685
14686 template<size_t colsL, size_t rowsL, size_t colsR, size_t rowsR>
14687 struct fp16MatrixTimesMatrix : public fp16MatrixBase
14688 {
14689         fp16MatrixTimesMatrix() : fp16MatrixBase()
14690         {
14691                 flavorNames.push_back("EmulatingFP16");
14692                 flavorNames.push_back("FloatCalc");
14693         }
14694
14695         virtual double getULPs (vector<const deFloat16*>& in)
14696         {
14697                 DE_UNREF(in);
14698
14699                 return 32.0;
14700         }
14701
14702         deUint32 getComponentValidity ()
14703         {
14704                 return getComponentMatrixValidityMask(colsR, rowsL);
14705         }
14706
14707         template<class fp16type>
14708         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14709         {
14710                 DE_STATIC_ASSERT(colsL == rowsR);
14711
14712                 DE_ASSERT(in.size() == 2);
14713
14714                 const size_t    alignedColsL    = (colsL == 3) ? 4 : colsL;
14715                 const size_t    alignedRowsL    = (rowsL == 3) ? 4 : rowsL;
14716                 const size_t    alignedColsR    = (colsR == 3) ? 4 : colsR;
14717                 const size_t    alignedRowsR    = (rowsR == 3) ? 4 : rowsR;
14718
14719                 DE_ASSERT(getOutCompCount() == alignedColsR * alignedRowsL);
14720                 DE_ASSERT(getArgCompCount(0) == alignedColsL * alignedRowsL);
14721                 DE_ASSERT(getArgCompCount(1) == alignedColsR * alignedRowsR);
14722                 DE_UNREF(alignedColsL);
14723                 DE_UNREF(alignedColsR);
14724
14725                 if (getFlavor() == 0)
14726                 {
14727                         for (size_t rowNdx = 0; rowNdx < rowsL; ++rowNdx)
14728                         {
14729                                 for (size_t colNdx = 0; colNdx < colsR; ++colNdx)
14730                                 {
14731                                         const size_t    ndx     (colNdx * alignedRowsL + rowNdx);
14732                                         fp16type                s       (fp16type::zero(1));
14733
14734                                         for (size_t commonNdx = 0; commonNdx < colsL; ++commonNdx)
14735                                         {
14736                                                 const size_t    ndxl    (commonNdx * alignedRowsL + rowNdx);
14737                                                 const fp16type  l               (in[0][ndxl]);
14738                                                 const float             lf              (l.asFloat());
14739                                                 const size_t    ndxr    (colNdx * alignedRowsR + commonNdx);
14740                                                 const fp16type  r               (in[1][ndxr]);
14741                                                 const float             rf              (r.asFloat());
14742                                                 const fp16type  m               (lf * rf);
14743
14744                                                 s = fp16type(s.asFloat() + m.asFloat());
14745                                         }
14746
14747                                         out[ndx] = s.bits();
14748                                         min[ndx] = getMin(s.asDouble(), getULPs(in));
14749                                         max[ndx] = getMax(s.asDouble(), getULPs(in));
14750                                 }
14751                         }
14752                 }
14753                 else if (getFlavor() == 1)
14754                 {
14755                         for (size_t rowNdx = 0; rowNdx < rowsL; ++rowNdx)
14756                         {
14757                                 for (size_t colNdx = 0; colNdx < colsR; ++colNdx)
14758                                 {
14759                                         const size_t    ndx     (colNdx * alignedRowsL + rowNdx);
14760                                         float                   s       (0.0f);
14761
14762                                         for (size_t commonNdx = 0; commonNdx < colsL; ++commonNdx)
14763                                         {
14764                                                 const size_t    ndxl    (commonNdx * alignedRowsL + rowNdx);
14765                                                 const fp16type  l               (in[0][ndxl]);
14766                                                 const float             lf              (l.asFloat());
14767                                                 const size_t    ndxr    (colNdx * alignedRowsR + commonNdx);
14768                                                 const fp16type  r               (in[1][ndxr]);
14769                                                 const float             rf              (r.asFloat());
14770                                                 const float             m               (lf * rf);
14771
14772                                                 s += m;
14773                                         }
14774
14775                                         out[ndx] = fp16type(s).bits();
14776                                         min[ndx] = getMin(static_cast<double>(s), getULPs(in));
14777                                         max[ndx] = getMax(static_cast<double>(s), getULPs(in));
14778                                 }
14779                         }
14780                 }
14781                 else
14782                 {
14783                         TCU_THROW(InternalError, "Unknown flavor");
14784                 }
14785
14786                 return true;
14787         }
14788 };
14789
14790 template<size_t cols, size_t rows>
14791 struct fp16OuterProduct : public fp16MatrixBase
14792 {
14793         virtual double getULPs (vector<const deFloat16*>& in)
14794         {
14795                 DE_UNREF(in);
14796
14797                 return 2.0;
14798         }
14799
14800         deUint32 getComponentValidity ()
14801         {
14802                 return getComponentMatrixValidityMask(cols, rows);
14803         }
14804
14805         template<class fp16type>
14806         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14807         {
14808                 DE_ASSERT(in.size() == 2);
14809
14810                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
14811                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
14812
14813                 DE_ASSERT(getArgCompCount(0) == rows);
14814                 DE_ASSERT(getArgCompCount(1) == cols);
14815                 DE_ASSERT(getOutCompCount() == alignedCols * alignedRows);
14816                 DE_UNREF(alignedCols);
14817
14818                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14819                 {
14820                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14821                         {
14822                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
14823                                 const fp16type  x       (in[0][rowNdx]);
14824                                 const float             xf      (x.asFloat());
14825                                 const fp16type  y       (in[1][colNdx]);
14826                                 const float             yf      (y.asFloat());
14827                                 const fp16type  m       (xf * yf);
14828
14829                                 out[ndx] = m.bits();
14830                                 min[ndx] = getMin(m.asDouble(), getULPs(in));
14831                                 max[ndx] = getMax(m.asDouble(), getULPs(in));
14832                         }
14833                 }
14834
14835                 return true;
14836         }
14837 };
14838
14839 template<size_t size>
14840 struct fp16Determinant;
14841
14842 template<>
14843 struct fp16Determinant<2> : public fp16MatrixBase
14844 {
14845         virtual double getULPs (vector<const deFloat16*>& in)
14846         {
14847                 DE_UNREF(in);
14848
14849                 return 128.0; // This is not a precision test. Value is not from spec
14850         }
14851
14852         deUint32 getComponentValidity ()
14853         {
14854                 return 1;
14855         }
14856
14857         template<class fp16type>
14858         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14859         {
14860                 const size_t    cols            = 2;
14861                 const size_t    rows            = 2;
14862                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
14863                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
14864
14865                 DE_ASSERT(in.size() == 1);
14866                 DE_ASSERT(getOutCompCount() == 1);
14867                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
14868                 DE_UNREF(alignedCols);
14869                 DE_UNREF(alignedRows);
14870
14871                 // [ a b ]
14872                 // [ c d ]
14873                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
14874                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
14875                 const float             c               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
14876                 const float             d               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
14877                 const float             ad              (a * d);
14878                 const fp16type  adf16   (ad);
14879                 const float             bc              (b * c);
14880                 const fp16type  bcf16   (bc);
14881                 const float             r               (adf16.asFloat() - bcf16.asFloat());
14882                 const fp16type  rf16    (r);
14883
14884                 out[0] = rf16.bits();
14885                 min[0] = getMin(r, getULPs(in));
14886                 max[0] = getMax(r, getULPs(in));
14887
14888                 return true;
14889         }
14890 };
14891
14892 template<>
14893 struct fp16Determinant<3> : public fp16MatrixBase
14894 {
14895         virtual double getULPs (vector<const deFloat16*>& in)
14896         {
14897                 DE_UNREF(in);
14898
14899                 return 128.0; // This is not a precision test. Value is not from spec
14900         }
14901
14902         deUint32 getComponentValidity ()
14903         {
14904                 return 1;
14905         }
14906
14907         template<class fp16type>
14908         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14909         {
14910                 const size_t    cols            = 3;
14911                 const size_t    rows            = 3;
14912                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
14913                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
14914
14915                 DE_ASSERT(in.size() == 1);
14916                 DE_ASSERT(getOutCompCount() == 1);
14917                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
14918                 DE_UNREF(alignedCols);
14919                 DE_UNREF(alignedRows);
14920
14921                 // [ a b c ]
14922                 // [ d e f ]
14923                 // [ g h i ]
14924                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
14925                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
14926                 const float             c               (fp16type(in[0][getNdx(rows, 2, 0)]).asFloat());
14927                 const float             d               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
14928                 const float             e               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
14929                 const float             f               (fp16type(in[0][getNdx(rows, 2, 1)]).asFloat());
14930                 const float             g               (fp16type(in[0][getNdx(rows, 0, 2)]).asFloat());
14931                 const float             h               (fp16type(in[0][getNdx(rows, 1, 2)]).asFloat());
14932                 const float             i               (fp16type(in[0][getNdx(rows, 2, 2)]).asFloat());
14933                 const fp16type  aei             (a * e * i);
14934                 const fp16type  bfg             (b * f * g);
14935                 const fp16type  cdh             (c * d * h);
14936                 const fp16type  ceg             (c * e * g);
14937                 const fp16type  bdi             (b * d * i);
14938                 const fp16type  afh             (a * f * h);
14939                 const float             r               (aei.asFloat() + bfg.asFloat() + cdh.asFloat() - ceg.asFloat() - bdi.asFloat() - afh.asFloat());
14940                 const fp16type  rf16    (r);
14941
14942                 out[0] = rf16.bits();
14943                 min[0] = getMin(r, getULPs(in));
14944                 max[0] = getMax(r, getULPs(in));
14945
14946                 return true;
14947         }
14948 };
14949
14950 template<>
14951 struct fp16Determinant<4> : public fp16MatrixBase
14952 {
14953         virtual double getULPs (vector<const deFloat16*>& in)
14954         {
14955                 DE_UNREF(in);
14956
14957                 return 128.0; // This is not a precision test. Value is not from spec
14958         }
14959
14960         deUint32 getComponentValidity ()
14961         {
14962                 return 1;
14963         }
14964
14965         template<class fp16type>
14966         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14967         {
14968                 const size_t    rows            = 4;
14969                 const size_t    cols            = 4;
14970                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
14971                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
14972
14973                 DE_ASSERT(in.size() == 1);
14974                 DE_ASSERT(getOutCompCount() == 1);
14975                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
14976                 DE_UNREF(alignedCols);
14977                 DE_UNREF(alignedRows);
14978
14979                 // [ a b c d ]
14980                 // [ e f g h ]
14981                 // [ i j k l ]
14982                 // [ m n o p ]
14983                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
14984                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
14985                 const float             c               (fp16type(in[0][getNdx(rows, 2, 0)]).asFloat());
14986                 const float             d               (fp16type(in[0][getNdx(rows, 3, 0)]).asFloat());
14987                 const float             e               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
14988                 const float             f               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
14989                 const float             g               (fp16type(in[0][getNdx(rows, 2, 1)]).asFloat());
14990                 const float             h               (fp16type(in[0][getNdx(rows, 3, 1)]).asFloat());
14991                 const float             i               (fp16type(in[0][getNdx(rows, 0, 2)]).asFloat());
14992                 const float             j               (fp16type(in[0][getNdx(rows, 1, 2)]).asFloat());
14993                 const float             k               (fp16type(in[0][getNdx(rows, 2, 2)]).asFloat());
14994                 const float             l               (fp16type(in[0][getNdx(rows, 3, 2)]).asFloat());
14995                 const float             m               (fp16type(in[0][getNdx(rows, 0, 3)]).asFloat());
14996                 const float             n               (fp16type(in[0][getNdx(rows, 1, 3)]).asFloat());
14997                 const float             o               (fp16type(in[0][getNdx(rows, 2, 3)]).asFloat());
14998                 const float             p               (fp16type(in[0][getNdx(rows, 3, 3)]).asFloat());
14999
15000                 // [ f g h ]
15001                 // [ j k l ]
15002                 // [ n o p ]
15003                 const fp16type  fkp             (f * k * p);
15004                 const fp16type  gln             (g * l * n);
15005                 const fp16type  hjo             (h * j * o);
15006                 const fp16type  hkn             (h * k * n);
15007                 const fp16type  gjp             (g * j * p);
15008                 const fp16type  flo             (f * l * o);
15009                 const fp16type  detA    (a * (fkp.asFloat() + gln.asFloat() + hjo.asFloat() - hkn.asFloat() - gjp.asFloat() - flo.asFloat()));
15010
15011                 // [ e g h ]
15012                 // [ i k l ]
15013                 // [ m o p ]
15014                 const fp16type  ekp             (e * k * p);
15015                 const fp16type  glm             (g * l * m);
15016                 const fp16type  hio             (h * i * o);
15017                 const fp16type  hkm             (h * k * m);
15018                 const fp16type  gip             (g * i * p);
15019                 const fp16type  elo             (e * l * o);
15020                 const fp16type  detB    (b * (ekp.asFloat() + glm.asFloat() + hio.asFloat() - hkm.asFloat() - gip.asFloat() - elo.asFloat()));
15021
15022                 // [ e f h ]
15023                 // [ i j l ]
15024                 // [ m n p ]
15025                 const fp16type  ejp             (e * j * p);
15026                 const fp16type  flm             (f * l * m);
15027                 const fp16type  hin             (h * i * n);
15028                 const fp16type  hjm             (h * j * m);
15029                 const fp16type  fip             (f * i * p);
15030                 const fp16type  eln             (e * l * n);
15031                 const fp16type  detC    (c * (ejp.asFloat() + flm.asFloat() + hin.asFloat() - hjm.asFloat() - fip.asFloat() - eln.asFloat()));
15032
15033                 // [ e f g ]
15034                 // [ i j k ]
15035                 // [ m n o ]
15036                 const fp16type  ejo             (e * j * o);
15037                 const fp16type  fkm             (f * k * m);
15038                 const fp16type  gin             (g * i * n);
15039                 const fp16type  gjm             (g * j * m);
15040                 const fp16type  fio             (f * i * o);
15041                 const fp16type  ekn             (e * k * n);
15042                 const fp16type  detD    (d * (ejo.asFloat() + fkm.asFloat() + gin.asFloat() - gjm.asFloat() - fio.asFloat() - ekn.asFloat()));
15043
15044                 const float             r               (detA.asFloat() - detB.asFloat() + detC.asFloat() - detD.asFloat());
15045                 const fp16type  rf16    (r);
15046
15047                 out[0] = rf16.bits();
15048                 min[0] = getMin(r, getULPs(in));
15049                 max[0] = getMax(r, getULPs(in));
15050
15051                 return true;
15052         }
15053 };
15054
15055 template<size_t size>
15056 struct fp16Inverse;
15057
15058 template<>
15059 struct fp16Inverse<2> : public fp16MatrixBase
15060 {
15061         virtual double getULPs (vector<const deFloat16*>& in)
15062         {
15063                 DE_UNREF(in);
15064
15065                 return 128.0; // This is not a precision test. Value is not from spec
15066         }
15067
15068         deUint32 getComponentValidity ()
15069         {
15070                 return getComponentMatrixValidityMask(2, 2);
15071         }
15072
15073         template<class fp16type>
15074         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15075         {
15076                 const size_t    cols            = 2;
15077                 const size_t    rows            = 2;
15078                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15079                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15080
15081                 DE_ASSERT(in.size() == 1);
15082                 DE_ASSERT(getOutCompCount() == alignedRows * alignedCols);
15083                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15084                 DE_UNREF(alignedCols);
15085
15086                 // [ a b ]
15087                 // [ c d ]
15088                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15089                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15090                 const float             c               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15091                 const float             d               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15092                 const float             ad              (a * d);
15093                 const fp16type  adf16   (ad);
15094                 const float             bc              (b * c);
15095                 const fp16type  bcf16   (bc);
15096                 const float             det             (adf16.asFloat() - bcf16.asFloat());
15097                 const fp16type  det16   (det);
15098
15099                 out[0] = fp16type( d / det16.asFloat()).bits();
15100                 out[1] = fp16type(-c / det16.asFloat()).bits();
15101                 out[2] = fp16type(-b / det16.asFloat()).bits();
15102                 out[3] = fp16type( a / det16.asFloat()).bits();
15103
15104                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15105                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15106                         {
15107                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
15108                                 const fp16type  s       (out[ndx]);
15109
15110                                 min[ndx] = getMin(s.asDouble(), getULPs(in));
15111                                 max[ndx] = getMax(s.asDouble(), getULPs(in));
15112                         }
15113
15114                 return true;
15115         }
15116 };
15117
15118 inline std::string fp16ToString(deFloat16 val)
15119 {
15120         return tcu::toHex<4>(val).toString() + " (" + de::floatToString(tcu::Float16(val).asFloat(), 10) + ")";
15121 }
15122
15123 template <size_t RES_COMPONENTS, size_t ARG0_COMPONENTS, size_t ARG1_COMPONENTS, size_t ARG2_COMPONENTS, class TestedArithmeticFunction>
15124 bool compareFP16ArithmeticFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
15125 {
15126         if (inputs.size() < 1 || inputs.size() > 3 || outputAllocs.size() != 1 || expectedOutputs.size() != 1)
15127                 return false;
15128
15129         const size_t    resultStep                      = (RES_COMPONENTS == 3) ? 4 : RES_COMPONENTS;
15130         const size_t    iterationsCount         = expectedOutputs[0].getByteSize() / (sizeof(deFloat16) * resultStep);
15131         const size_t    inputsSteps[3]          =
15132         {
15133                 (ARG0_COMPONENTS == 3) ? 4 : ARG0_COMPONENTS,
15134                 (ARG1_COMPONENTS == 3) ? 4 : ARG1_COMPONENTS,
15135                 (ARG2_COMPONENTS == 3) ? 4 : ARG2_COMPONENTS,
15136         };
15137
15138         DE_ASSERT(expectedOutputs[0].getByteSize() > 0);
15139         DE_ASSERT(expectedOutputs[0].getByteSize() == sizeof(deFloat16) * iterationsCount * resultStep);
15140
15141         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15142         {
15143                 DE_ASSERT(inputs[inputNdx].getByteSize() > 0);
15144                 DE_ASSERT(inputs[inputNdx].getByteSize() == sizeof(deFloat16) * iterationsCount * inputsSteps[inputNdx]);
15145         }
15146
15147         const deFloat16* const          outputAsFP16                                    = (const deFloat16*)outputAllocs[0]->getHostPtr();
15148         TestedArithmeticFunction        func;
15149
15150         func.setOutCompCount(RES_COMPONENTS);
15151         func.setArgCompCount(0, ARG0_COMPONENTS);
15152         func.setArgCompCount(1, ARG1_COMPONENTS);
15153         func.setArgCompCount(2, ARG2_COMPONENTS);
15154
15155         const bool                                      callOncePerComponent                    = func.callOncePerComponent();
15156         const deUint32                          componentValidityMask                   = func.getComponentValidity();
15157         const size_t                            denormModesCount                                = 2;
15158         const char*                                     denormModes[denormModesCount]   = { "keep denormal numbers", "flush to zero" };
15159         const size_t                            successfulRunsPerComponent              = denormModesCount * func.getFlavorCount();
15160         bool                                            success                                                 = true;
15161         size_t                                          validatedCount                                  = 0;
15162
15163         vector<deUint8> inputBytes[3];
15164
15165         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15166                 inputs[inputNdx].getBytes(inputBytes[inputNdx]);
15167
15168         const deFloat16* const                  inputsAsFP16[3]                 =
15169         {
15170                 inputs.size() >= 1 ? (const deFloat16*)&inputBytes[0][0] : DE_NULL,
15171                 inputs.size() >= 2 ? (const deFloat16*)&inputBytes[1][0] : DE_NULL,
15172                 inputs.size() >= 3 ? (const deFloat16*)&inputBytes[2][0] : DE_NULL,
15173         };
15174
15175         for (size_t idx = 0; idx < iterationsCount; ++idx)
15176         {
15177                 std::vector<size_t>                     successfulRuns          (RES_COMPONENTS, successfulRunsPerComponent);
15178                 std::vector<std::string>        errors                          (RES_COMPONENTS);
15179                 bool                                            iterationValidated      (true);
15180
15181                 for (size_t denormNdx = 0; denormNdx < 2; ++denormNdx)
15182                 {
15183                         for (size_t flavorNdx = 0; flavorNdx < func.getFlavorCount(); ++flavorNdx)
15184                         {
15185                                 func.setFlavor(flavorNdx);
15186
15187                                 const deFloat16*                        iterationOutputFP16             = &outputAsFP16[idx * resultStep];
15188                                 vector<deFloat16>                       iterationCalculatedFP16 (resultStep, 0);
15189                                 vector<double>                          iterationEdgeMin                (resultStep, 0.0);
15190                                 vector<double>                          iterationEdgeMax                (resultStep, 0.0);
15191                                 vector<const deFloat16*>        arguments;
15192
15193                                 for (size_t componentNdx = 0; componentNdx < RES_COMPONENTS; ++componentNdx)
15194                                 {
15195                                         std::string     error;
15196                                         bool            reportError = false;
15197
15198                                         if (callOncePerComponent || componentNdx == 0)
15199                                         {
15200                                                 bool funcCallResult;
15201
15202                                                 arguments.clear();
15203
15204                                                 for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15205                                                         arguments.push_back(&inputsAsFP16[inputNdx][idx * inputsSteps[inputNdx] + componentNdx]);
15206
15207                                                 if (denormNdx == 0)
15208                                                         funcCallResult = func.template calc<tcu::Float16>(arguments, &iterationCalculatedFP16[componentNdx], &iterationEdgeMin[componentNdx], &iterationEdgeMax[componentNdx]);
15209                                                 else
15210                                                         funcCallResult = func.template calc<tcu::Float16Denormless>(arguments, &iterationCalculatedFP16[componentNdx], &iterationEdgeMin[componentNdx], &iterationEdgeMax[componentNdx]);
15211
15212                                                 if (!funcCallResult)
15213                                                 {
15214                                                         iterationValidated = false;
15215
15216                                                         if (callOncePerComponent)
15217                                                                 continue;
15218                                                         else
15219                                                                 break;
15220                                                 }
15221                                         }
15222
15223                                         if ((componentValidityMask != 0) && (componentValidityMask & (1<<componentNdx)) == 0)
15224                                                 continue;
15225
15226                                         reportError = !compare16BitFloat(iterationCalculatedFP16[componentNdx], iterationOutputFP16[componentNdx], error);
15227
15228                                         if (reportError)
15229                                         {
15230                                                 tcu::Float16 expected   (iterationCalculatedFP16[componentNdx]);
15231                                                 tcu::Float16 outputted  (iterationOutputFP16[componentNdx]);
15232
15233                                                 if (reportError && expected.isNaN())
15234                                                         reportError = false;
15235
15236                                                 if (reportError && !expected.isNaN() && !outputted.isNaN())
15237                                                 {
15238                                                         if (reportError && !expected.isInf() && !outputted.isInf())
15239                                                         {
15240                                                                 // Ignore rounding
15241                                                                 if (expected.bits() == outputted.bits() + 1 || expected.bits() + 1 == outputted.bits())
15242                                                                         reportError = false;
15243                                                         }
15244
15245                                                         if (reportError && expected.isInf())
15246                                                         {
15247                                                                 // RTZ rounding mode returns +/-65504 instead of Inf on overflow
15248                                                                 if (expected.sign() == 1 && outputted.bits() == 0x7bff && iterationEdgeMin[componentNdx] <= std::numeric_limits<double>::max())
15249                                                                         reportError = false;
15250                                                                 else if (expected.sign() == -1 && outputted.bits() == 0xfbff && iterationEdgeMax[componentNdx] >= -std::numeric_limits<double>::max())
15251                                                                         reportError = false;
15252                                                         }
15253
15254                                                         if (reportError)
15255                                                         {
15256                                                                 const double    outputtedDouble = outputted.asDouble();
15257
15258                                                                 DE_ASSERT(iterationEdgeMin[componentNdx] <= iterationEdgeMax[componentNdx]);
15259
15260                                                                 if (de::inRange(outputtedDouble, iterationEdgeMin[componentNdx], iterationEdgeMax[componentNdx]))
15261                                                                         reportError = false;
15262                                                         }
15263                                                 }
15264
15265                                                 if (reportError)
15266                                                 {
15267                                                         const size_t            inputsComps[3]  =
15268                                                         {
15269                                                                 ARG0_COMPONENTS,
15270                                                                 ARG1_COMPONENTS,
15271                                                                 ARG2_COMPONENTS,
15272                                                         };
15273                                                         string                          inputsValues    ("Inputs:");
15274                                                         string                          flavorName              (func.getFlavorCount() == 1 ? "" : string(" flavor ") + de::toString(flavorNdx) + " (" + func.getCurrentFlavorName() + ")");
15275                                                         std::stringstream       errStream;
15276
15277                                                         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15278                                                         {
15279                                                                 const size_t    inputCompsCount = inputsComps[inputNdx];
15280
15281                                                                 inputsValues += " [" + de::toString(inputNdx) + "]=(";
15282
15283                                                                 for (size_t compNdx = 0; compNdx < inputCompsCount; ++compNdx)
15284                                                                 {
15285                                                                         const deFloat16 inputComponentValue = inputsAsFP16[inputNdx][idx * inputsSteps[inputNdx] + compNdx];
15286
15287                                                                         inputsValues += fp16ToString(inputComponentValue) + ((compNdx + 1 == inputCompsCount) ? ")": ", ");
15288                                                                 }
15289                                                         }
15290
15291                                                         errStream       << "At"
15292                                                                                 << " iteration " << de::toString(idx)
15293                                                                                 << " component " << de::toString(componentNdx)
15294                                                                                 << " denormMode " << de::toString(denormNdx)
15295                                                                                 << " (" << denormModes[denormNdx] << ")"
15296                                                                                 << " " << flavorName
15297                                                                                 << " " << inputsValues
15298                                                                                 << " outputted:" + fp16ToString(iterationOutputFP16[componentNdx])
15299                                                                                 << " expected:" + fp16ToString(iterationCalculatedFP16[componentNdx])
15300                                                                                 << " or in range: [" << iterationEdgeMin[componentNdx] << ", " << iterationEdgeMax[componentNdx] << "]."
15301                                                                                 << " " << error << "."
15302                                                                                 << std::endl;
15303
15304                                                         errors[componentNdx] += errStream.str();
15305
15306                                                         successfulRuns[componentNdx]--;
15307                                                 }
15308                                         }
15309                                 }
15310                         }
15311                 }
15312
15313                 for (size_t componentNdx = 0; componentNdx < RES_COMPONENTS; ++componentNdx)
15314                 {
15315                         // Check if any component has total failure
15316                         if (successfulRuns[componentNdx] == 0)
15317                         {
15318                                 // Test failed in all denorm modes and all flavors for certain component: dump errors
15319                                 log << TestLog::Message << errors[componentNdx] << TestLog::EndMessage;
15320
15321                                 success = false;
15322                         }
15323                 }
15324
15325                 if (iterationValidated)
15326                         validatedCount++;
15327         }
15328
15329         if (validatedCount < 16)
15330                 TCU_THROW(InternalError, "Too few samples has been validated.");
15331
15332         return success;
15333 }
15334
15335 // IEEE-754 floating point numbers:
15336 // +--------+------+----------+-------------+
15337 // | binary | sign | exponent | significand |
15338 // +--------+------+----------+-------------+
15339 // | 16-bit |  1   |    5     |     10      |
15340 // +--------+------+----------+-------------+
15341 // | 32-bit |  1   |    8     |     23      |
15342 // +--------+------+----------+-------------+
15343 //
15344 // 16-bit floats:
15345 //
15346 // 0   000 00   00 0000 0001 (0x0001: 2e-24:         minimum positive denormalized)
15347 // 0   000 00   11 1111 1111 (0x03ff: 2e-14 - 2e-24: maximum positive denormalized)
15348 // 0   000 01   00 0000 0000 (0x0400: 2e-14:         minimum positive normalized)
15349 // 0   111 10   11 1111 1111 (0x7bff: 65504:         maximum positive normalized)
15350 //
15351 // 0   000 00   00 0000 0000 (0x0000: +0)
15352 // 0   111 11   00 0000 0000 (0x7c00: +Inf)
15353 // 0   000 00   11 1111 0000 (0x03f0: +Denorm)
15354 // 0   000 01   00 0000 0001 (0x0401: +Norm)
15355 // 0   111 11   00 0000 1111 (0x7c0f: +SNaN)
15356 // 0   111 11   11 1111 0000 (0x7ff0: +QNaN)
15357 // Generate and return 16-bit floats and their corresponding 32-bit values.
15358 //
15359 // The first 14 number pairs are manually picked, while the rest are randomly generated.
15360 // Expected count to be at least 14 (numPicks).
15361 vector<deFloat16> getFloat16a (de::Random& rnd, deUint32 count)
15362 {
15363         vector<deFloat16>       float16;
15364
15365         float16.reserve(count);
15366
15367         // Zero
15368         float16.push_back(deUint16(0x0000));
15369         float16.push_back(deUint16(0x8000));
15370         // Infinity
15371         float16.push_back(deUint16(0x7c00));
15372         float16.push_back(deUint16(0xfc00));
15373         // Normalized
15374         float16.push_back(deUint16(0x0401));
15375         float16.push_back(deUint16(0x8401));
15376         // Some normal number
15377         float16.push_back(deUint16(0x14cb));
15378         float16.push_back(deUint16(0x94cb));
15379         // Min/max positive normal
15380         float16.push_back(deUint16(0x0400));
15381         float16.push_back(deUint16(0x7bff));
15382         // Min/max negative normal
15383         float16.push_back(deUint16(0x8400));
15384         float16.push_back(deUint16(0xfbff));
15385         // PI
15386         float16.push_back(deUint16(0x4248)); // 3.140625
15387         float16.push_back(deUint16(0xb248)); // -3.140625
15388         // PI/2
15389         float16.push_back(deUint16(0x3e48)); // 1.5703125
15390         float16.push_back(deUint16(0xbe48)); // -1.5703125
15391         float16.push_back(deUint16(0x3c00)); // 1.0
15392         float16.push_back(deUint16(0x3800)); // 0.5
15393         // Some useful constants
15394         float16.push_back(tcu::Float16(-2.5f).bits());
15395         float16.push_back(tcu::Float16(-1.0f).bits());
15396         float16.push_back(tcu::Float16( 0.4f).bits());
15397         float16.push_back(tcu::Float16( 2.5f).bits());
15398
15399         const deUint32          numPicks        = static_cast<deUint32>(float16.size());
15400
15401         DE_ASSERT(count >= numPicks);
15402         count -= numPicks;
15403
15404         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
15405         {
15406                 int                     sign            = (rnd.getUint16() % 2 == 0) ? +1 : -1;
15407                 int                     exponent        = (rnd.getUint16() % 29) - 14 + 1;
15408                 deUint16        mantissa        = static_cast<deUint16>(2 * (rnd.getUint16() % 512));
15409
15410                 // Exclude power of -14 to avoid denorms
15411                 DE_ASSERT(de::inRange(exponent, -13, 15));
15412
15413                 float16.push_back(tcu::Float16::constructBits(sign, exponent, mantissa).bits());
15414         }
15415
15416         return float16;
15417 }
15418
15419 static inline vector<deFloat16> getInputData1 (deUint32 seed, size_t count, size_t argNo)
15420 {
15421         DE_UNREF(argNo);
15422
15423         de::Random      rnd(seed);
15424
15425         return getFloat16a(rnd, static_cast<deUint32>(count));
15426 }
15427
15428 static inline vector<deFloat16> getInputData2 (deUint32 seed, size_t count, size_t argNo)
15429 {
15430         de::Random      rnd             (seed);
15431         size_t          newCount = static_cast<size_t>(deSqrt(double(count)));
15432
15433         DE_ASSERT(newCount * newCount == count);
15434
15435         vector<deFloat16>       float16 = getFloat16a(rnd, static_cast<deUint32>(newCount));
15436
15437         return squarize(float16, static_cast<deUint32>(argNo));
15438 }
15439
15440 static inline vector<deFloat16> getInputData3 (deUint32 seed, size_t count, size_t argNo)
15441 {
15442         if (argNo == 0 || argNo == 1)
15443                 return getInputData2(seed, count, argNo);
15444         else
15445                 return getInputData1(seed<<argNo, count, argNo);
15446 }
15447
15448 vector<deFloat16> getInputData (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15449 {
15450         DE_UNREF(stride);
15451
15452         vector<deFloat16>       result;
15453
15454         switch (argCount)
15455         {
15456                 case 1:result = getInputData1(seed, count, argNo); break;
15457                 case 2:result = getInputData2(seed, count, argNo); break;
15458                 case 3:result = getInputData3(seed, count, argNo); break;
15459                 default: TCU_THROW(InternalError, "Invalid argument count specified");
15460         }
15461
15462         if (compCount == 3)
15463         {
15464                 const size_t            newCount = (3 * count) / 4;
15465                 vector<deFloat16>       newResult;
15466
15467                 newResult.reserve(result.size());
15468
15469                 for (size_t ndx = 0; ndx < newCount; ++ndx)
15470                 {
15471                         newResult.push_back(result[ndx]);
15472
15473                         if (ndx % 3 == 2)
15474                                 newResult.push_back(0);
15475                 }
15476
15477                 result = newResult;
15478         }
15479
15480         DE_ASSERT(result.size() == count);
15481
15482         return result;
15483 }
15484
15485 // Generator for functions requiring data in range [1, inf]
15486 vector<deFloat16> getInputDataAC (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15487 {
15488         vector<deFloat16>       result;
15489
15490         result = getInputData(seed, count, compCount, stride, argCount, argNo);
15491
15492         // Filter out values below 1.0 from upper half of numbers
15493         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15494         {
15495                 const float f = tcu::Float16(result[idx]).asFloat();
15496
15497                 if (f < 1.0f)
15498                         result[idx] = tcu::Float16(1.0f - f).bits();
15499         }
15500
15501         return result;
15502 }
15503
15504 // Generator for functions requiring data in range [-1, 1]
15505 vector<deFloat16> getInputDataA (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15506 {
15507         vector<deFloat16>       result;
15508
15509         result = getInputData(seed, count, compCount, stride, argCount, argNo);
15510
15511         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15512         {
15513                 const float f = tcu::Float16(result[idx]).asFloat();
15514
15515                 if (!de::inRange(f, -1.0f, 1.0f))
15516                         result[idx] = tcu::Float16(deFloatFrac(f)).bits();
15517         }
15518
15519         return result;
15520 }
15521
15522 // Generator for functions requiring data in range [-pi, pi]
15523 vector<deFloat16> getInputDataPI (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15524 {
15525         vector<deFloat16>       result;
15526
15527         result = getInputData(seed, count, compCount, stride, argCount, argNo);
15528
15529         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15530         {
15531                 const float f = tcu::Float16(result[idx]).asFloat();
15532
15533                 if (!de::inRange(f, -DE_PI, DE_PI))
15534                         result[idx] = tcu::Float16(fmodf(f, DE_PI)).bits();
15535         }
15536
15537         return result;
15538 }
15539
15540 // Generator for functions requiring data in range [0, inf]
15541 vector<deFloat16> getInputDataP (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15542 {
15543         vector<deFloat16>       result;
15544
15545         result = getInputData(seed, count, compCount, stride, argCount, argNo);
15546
15547         if (argNo == 0)
15548         {
15549                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15550                         result[idx] &= static_cast<deFloat16>(~0x8000);
15551         }
15552
15553         return result;
15554 }
15555
15556 vector<deFloat16> getInputDataV (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15557 {
15558         DE_UNREF(stride);
15559         DE_UNREF(argCount);
15560
15561         vector<deFloat16>       result;
15562
15563         if (argNo == 0)
15564                 result = getInputData2(seed, count, argNo);
15565         else
15566         {
15567                 const size_t            alignedCount    = (compCount == 3) ? 4 : compCount;
15568                 const size_t            newCountX               = static_cast<size_t>(deSqrt(double(count * alignedCount)));
15569                 const size_t            newCountY               = count / newCountX;
15570                 de::Random                      rnd                             (seed);
15571                 vector<deFloat16>       float16                 = getFloat16a(rnd, static_cast<deUint32>(newCountX));
15572
15573                 DE_ASSERT(newCountX * newCountX == alignedCount * count);
15574
15575                 for (size_t numIdx = 0; numIdx < newCountX; ++numIdx)
15576                 {
15577                         const vector<deFloat16> tmp(newCountY, float16[numIdx]);
15578
15579                         result.insert(result.end(), tmp.begin(), tmp.end());
15580                 }
15581         }
15582
15583         DE_ASSERT(result.size() == count);
15584
15585         return result;
15586 }
15587
15588 vector<deFloat16> getInputDataM (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15589 {
15590         DE_UNREF(compCount);
15591         DE_UNREF(stride);
15592         DE_UNREF(argCount);
15593
15594         de::Random                      rnd             (seed << argNo);
15595         vector<deFloat16>       result;
15596
15597         result = getFloat16a(rnd, static_cast<deUint32>(count));
15598
15599         DE_ASSERT(result.size() == count);
15600
15601         return result;
15602 }
15603
15604 vector<deFloat16> getInputDataD (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15605 {
15606         DE_UNREF(compCount);
15607         DE_UNREF(argCount);
15608
15609         de::Random                      rnd             (seed << argNo);
15610         vector<deFloat16>       result;
15611
15612         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
15613         {
15614                 int num = (rnd.getUint16() % 16) - 8;
15615
15616                 result.push_back(tcu::Float16(float(num)).bits());
15617         }
15618
15619         result[0 * stride] = deUint16(0x7c00); // +Inf
15620         result[1 * stride] = deUint16(0xfc00); // -Inf
15621
15622         DE_ASSERT(result.size() == count);
15623
15624         return result;
15625 }
15626
15627 // Generator for smoothstep function
15628 vector<deFloat16> getInputDataSS (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15629 {
15630         vector<deFloat16>       result;
15631
15632         result = getInputDataD(seed, count, compCount, stride, argCount, argNo);
15633
15634         if (argNo == 0)
15635         {
15636                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15637                 {
15638                         const float f = tcu::Float16(result[idx]).asFloat();
15639
15640                         if (f > 4.0f)
15641                                 result[idx] = tcu::Float16(-f).bits();
15642                 }
15643         }
15644
15645         if (argNo == 1)
15646         {
15647                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15648                 {
15649                         const float f = tcu::Float16(result[idx]).asFloat();
15650
15651                         if (f < 4.0f)
15652                                 result[idx] = tcu::Float16(-f).bits();
15653                 }
15654         }
15655
15656         return result;
15657 }
15658
15659 // Generates normalized vectors for arguments 0 and 1
15660 vector<deFloat16> getInputDataN (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15661 {
15662         DE_UNREF(compCount);
15663         DE_UNREF(argCount);
15664
15665         de::Random                      rnd             (seed << argNo);
15666         vector<deFloat16>       result;
15667
15668         if (argNo == 0 || argNo == 1)
15669         {
15670                 // The input parameters for the incident vector I and the surface normal N must already be normalized
15671                 for (size_t numIdx = 0; numIdx < count; numIdx += stride)
15672                 {
15673                         vector <float>  unnormolized;
15674                         float                   sum                             = 0;
15675
15676                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
15677                                 unnormolized.push_back(float((rnd.getUint16() % 16) - 8));
15678
15679                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
15680                                 sum += unnormolized[compIdx] * unnormolized[compIdx];
15681
15682                         sum = deFloatSqrt(sum);
15683                         if (sum == 0.0f)
15684                                 unnormolized[0] = sum = 1.0f;
15685
15686                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
15687                                 result.push_back(tcu::Float16(unnormolized[compIdx] / sum).bits());
15688
15689                         for (size_t compIdx = compCount; compIdx < stride; ++compIdx)
15690                                 result.push_back(0);
15691                 }
15692         }
15693         else
15694         {
15695                 // Input parameter eta
15696                 for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
15697                 {
15698                         int num = (rnd.getUint16() % 16) - 8;
15699
15700                         result.push_back(tcu::Float16(float(num)).bits());
15701                 }
15702         }
15703
15704         DE_ASSERT(result.size() == count);
15705
15706         return result;
15707 }
15708
15709 // Data generator for complex matrix functions like determinant and inverse
15710 vector<deFloat16> getInputDataC (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15711 {
15712         DE_UNREF(compCount);
15713         DE_UNREF(stride);
15714         DE_UNREF(argCount);
15715
15716         de::Random                      rnd             (seed << argNo);
15717         vector<deFloat16>       result;
15718
15719         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
15720         {
15721                 int num = (rnd.getUint16() % 16) - 8;
15722
15723                 result.push_back(tcu::Float16(float(num)).bits());
15724         }
15725
15726         DE_ASSERT(result.size() == count);
15727
15728         return result;
15729 }
15730
15731 struct Math16TestType
15732 {
15733         const char*             typePrefix;
15734         const size_t    typeComponents;
15735         const size_t    typeArrayStride;
15736         const size_t    typeStructStride;
15737 };
15738
15739 enum Math16DataTypes
15740 {
15741         NONE    = 0,
15742         SCALAR  = 1,
15743         VEC2    = 2,
15744         VEC3    = 3,
15745         VEC4    = 4,
15746         MAT2X2,
15747         MAT2X3,
15748         MAT2X4,
15749         MAT3X2,
15750         MAT3X3,
15751         MAT3X4,
15752         MAT4X2,
15753         MAT4X3,
15754         MAT4X4,
15755         MATH16_TYPE_LAST
15756 };
15757
15758 struct Math16ArgFragments
15759 {
15760         const char*     bodies;
15761         const char*     variables;
15762         const char*     decorations;
15763         const char*     funcVariables;
15764 };
15765
15766 typedef vector<deFloat16> Math16GetInputData (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo);
15767
15768 struct Math16TestFunc
15769 {
15770         const char*                                     funcName;
15771         const char*                                     funcSuffix;
15772         size_t                                          funcArgsCount;
15773         size_t                                          typeResult;
15774         size_t                                          typeArg0;
15775         size_t                                          typeArg1;
15776         size_t                                          typeArg2;
15777         Math16GetInputData*                     getInputDataFunc;
15778         VerifyIOFunc                            verifyFunc;
15779 };
15780
15781 template<class SpecResource>
15782 void createFloat16ArithmeticFuncTest (tcu::TestContext& testCtx, tcu::TestCaseGroup& testGroup, const size_t testTypeIdx, const Math16TestFunc& testFunc)
15783 {
15784         const int                                       testSpecificSeed                        = deStringHash(testGroup.getName());
15785         const int                                       seed                                            = testCtx.getCommandLine().getBaseSeed() ^ testSpecificSeed;
15786         const size_t                            numDataPointsByAxis                     = 32;
15787         const size_t                            numDataPoints                           = numDataPointsByAxis * numDataPointsByAxis;
15788         const char*                                     componentType                           = "f16";
15789         const Math16TestType            testTypes[MATH16_TYPE_LAST]     =
15790         {
15791                 { "",           0,       0,                                              0,                                             },
15792                 { "",           1,       1 * sizeof(deFloat16),  2 * sizeof(deFloat16)  },
15793                 { "v2",         2,       2 * sizeof(deFloat16),  2 * sizeof(deFloat16)  },
15794                 { "v3",         3,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
15795                 { "v4",         4,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
15796                 { "m2x2",       0,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
15797                 { "m2x3",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
15798                 { "m2x4",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
15799                 { "m3x2",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
15800                 { "m3x3",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
15801                 { "m3x4",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
15802                 { "m4x2",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
15803                 { "m4x3",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
15804                 { "m4x4",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
15805         };
15806
15807         DE_ASSERT(testTypeIdx == testTypes[testTypeIdx].typeComponents);
15808
15809
15810         const StringTemplate preMain
15811         (
15812                 "     %c_i32_ndp  = OpConstant %i32 ${num_data_points}\n"
15813
15814                 "        %f16     = OpTypeFloat 16\n"
15815                 "        %v2f16   = OpTypeVector %f16 2\n"
15816                 "        %v3f16   = OpTypeVector %f16 3\n"
15817                 "        %v4f16   = OpTypeVector %f16 4\n"
15818                 "        %m2x2f16 = OpTypeMatrix %v2f16 2\n"
15819                 "        %m2x3f16 = OpTypeMatrix %v3f16 2\n"
15820                 "        %m2x4f16 = OpTypeMatrix %v4f16 2\n"
15821                 "        %m3x2f16 = OpTypeMatrix %v2f16 3\n"
15822                 "        %m3x3f16 = OpTypeMatrix %v3f16 3\n"
15823                 "        %m3x4f16 = OpTypeMatrix %v4f16 3\n"
15824                 "        %m4x2f16 = OpTypeMatrix %v2f16 4\n"
15825                 "        %m4x3f16 = OpTypeMatrix %v3f16 4\n"
15826                 "        %m4x4f16 = OpTypeMatrix %v4f16 4\n"
15827
15828                 "     %up_f16     = OpTypePointer Uniform %f16    \n"
15829                 "     %up_v2f16   = OpTypePointer Uniform %v2f16  \n"
15830                 "     %up_v3f16   = OpTypePointer Uniform %v3f16  \n"
15831                 "     %up_v4f16   = OpTypePointer Uniform %v4f16  \n"
15832                 "     %up_m2x2f16 = OpTypePointer Uniform %m2x2f16\n"
15833                 "     %up_m2x3f16 = OpTypePointer Uniform %m2x3f16\n"
15834                 "     %up_m2x4f16 = OpTypePointer Uniform %m2x4f16\n"
15835                 "     %up_m3x2f16 = OpTypePointer Uniform %m3x2f16\n"
15836                 "     %up_m3x3f16 = OpTypePointer Uniform %m3x3f16\n"
15837                 "     %up_m3x4f16 = OpTypePointer Uniform %m3x4f16\n"
15838                 "     %up_m4x2f16 = OpTypePointer Uniform %m4x2f16\n"
15839                 "     %up_m4x3f16 = OpTypePointer Uniform %m4x3f16\n"
15840                 "     %up_m4x4f16 = OpTypePointer Uniform %m4x4f16\n"
15841
15842                 "     %ra_f16     = OpTypeArray %f16     %c_i32_ndp\n"
15843                 "     %ra_v2f16   = OpTypeArray %v2f16   %c_i32_ndp\n"
15844                 "     %ra_v3f16   = OpTypeArray %v3f16   %c_i32_ndp\n"
15845                 "     %ra_v4f16   = OpTypeArray %v4f16   %c_i32_ndp\n"
15846                 "     %ra_m2x2f16 = OpTypeArray %m2x2f16 %c_i32_ndp\n"
15847                 "     %ra_m2x3f16 = OpTypeArray %m2x3f16 %c_i32_ndp\n"
15848                 "     %ra_m2x4f16 = OpTypeArray %m2x4f16 %c_i32_ndp\n"
15849                 "     %ra_m3x2f16 = OpTypeArray %m3x2f16 %c_i32_ndp\n"
15850                 "     %ra_m3x3f16 = OpTypeArray %m3x3f16 %c_i32_ndp\n"
15851                 "     %ra_m3x4f16 = OpTypeArray %m3x4f16 %c_i32_ndp\n"
15852                 "     %ra_m4x2f16 = OpTypeArray %m4x2f16 %c_i32_ndp\n"
15853                 "     %ra_m4x3f16 = OpTypeArray %m4x3f16 %c_i32_ndp\n"
15854                 "     %ra_m4x4f16 = OpTypeArray %m4x4f16 %c_i32_ndp\n"
15855
15856                 "   %SSBO_f16     = OpTypeStruct %ra_f16    \n"
15857                 "   %SSBO_v2f16   = OpTypeStruct %ra_v2f16  \n"
15858                 "   %SSBO_v3f16   = OpTypeStruct %ra_v3f16  \n"
15859                 "   %SSBO_v4f16   = OpTypeStruct %ra_v4f16  \n"
15860                 "   %SSBO_m2x2f16 = OpTypeStruct %ra_m2x2f16\n"
15861                 "   %SSBO_m2x3f16 = OpTypeStruct %ra_m2x3f16\n"
15862                 "   %SSBO_m2x4f16 = OpTypeStruct %ra_m2x4f16\n"
15863                 "   %SSBO_m3x2f16 = OpTypeStruct %ra_m3x2f16\n"
15864                 "   %SSBO_m3x3f16 = OpTypeStruct %ra_m3x3f16\n"
15865                 "   %SSBO_m3x4f16 = OpTypeStruct %ra_m3x4f16\n"
15866                 "   %SSBO_m4x2f16 = OpTypeStruct %ra_m4x2f16\n"
15867                 "   %SSBO_m4x3f16 = OpTypeStruct %ra_m4x3f16\n"
15868                 "   %SSBO_m4x4f16 = OpTypeStruct %ra_m4x4f16\n"
15869
15870                 "%up_SSBO_f16     = OpTypePointer Uniform %SSBO_f16    \n"
15871                 "%up_SSBO_v2f16   = OpTypePointer Uniform %SSBO_v2f16  \n"
15872                 "%up_SSBO_v3f16   = OpTypePointer Uniform %SSBO_v3f16  \n"
15873                 "%up_SSBO_v4f16   = OpTypePointer Uniform %SSBO_v4f16  \n"
15874                 "%up_SSBO_m2x2f16 = OpTypePointer Uniform %SSBO_m2x2f16\n"
15875                 "%up_SSBO_m2x3f16 = OpTypePointer Uniform %SSBO_m2x3f16\n"
15876                 "%up_SSBO_m2x4f16 = OpTypePointer Uniform %SSBO_m2x4f16\n"
15877                 "%up_SSBO_m3x2f16 = OpTypePointer Uniform %SSBO_m3x2f16\n"
15878                 "%up_SSBO_m3x3f16 = OpTypePointer Uniform %SSBO_m3x3f16\n"
15879                 "%up_SSBO_m3x4f16 = OpTypePointer Uniform %SSBO_m3x4f16\n"
15880                 "%up_SSBO_m4x2f16 = OpTypePointer Uniform %SSBO_m4x2f16\n"
15881                 "%up_SSBO_m4x3f16 = OpTypePointer Uniform %SSBO_m4x3f16\n"
15882                 "%up_SSBO_m4x4f16 = OpTypePointer Uniform %SSBO_m4x4f16\n"
15883
15884                 "       %fp_v2i32 = OpTypePointer Function %v2i32\n"
15885                 "       %fp_v3i32 = OpTypePointer Function %v3i32\n"
15886                 "       %fp_v4i32 = OpTypePointer Function %v4i32\n"
15887                 "${arg_vars}"
15888         );
15889
15890         const StringTemplate decoration
15891         (
15892                 "OpDecorate %ra_f16     ArrayStride 2 \n"
15893                 "OpDecorate %ra_v2f16   ArrayStride 4 \n"
15894                 "OpDecorate %ra_v3f16   ArrayStride 8 \n"
15895                 "OpDecorate %ra_v4f16   ArrayStride 8 \n"
15896                 "OpDecorate %ra_m2x2f16 ArrayStride 8 \n"
15897                 "OpDecorate %ra_m2x3f16 ArrayStride 16\n"
15898                 "OpDecorate %ra_m2x4f16 ArrayStride 16\n"
15899                 "OpDecorate %ra_m3x2f16 ArrayStride 16\n"
15900                 "OpDecorate %ra_m3x3f16 ArrayStride 32\n"
15901                 "OpDecorate %ra_m3x4f16 ArrayStride 32\n"
15902                 "OpDecorate %ra_m4x2f16 ArrayStride 16\n"
15903                 "OpDecorate %ra_m4x3f16 ArrayStride 32\n"
15904                 "OpDecorate %ra_m4x4f16 ArrayStride 32\n"
15905
15906                 "OpMemberDecorate %SSBO_f16     0 Offset 0\n"
15907                 "OpMemberDecorate %SSBO_v2f16   0 Offset 0\n"
15908                 "OpMemberDecorate %SSBO_v3f16   0 Offset 0\n"
15909                 "OpMemberDecorate %SSBO_v4f16   0 Offset 0\n"
15910                 "OpMemberDecorate %SSBO_m2x2f16 0 Offset 0\n"
15911                 "OpMemberDecorate %SSBO_m2x3f16 0 Offset 0\n"
15912                 "OpMemberDecorate %SSBO_m2x4f16 0 Offset 0\n"
15913                 "OpMemberDecorate %SSBO_m3x2f16 0 Offset 0\n"
15914                 "OpMemberDecorate %SSBO_m3x3f16 0 Offset 0\n"
15915                 "OpMemberDecorate %SSBO_m3x4f16 0 Offset 0\n"
15916                 "OpMemberDecorate %SSBO_m4x2f16 0 Offset 0\n"
15917                 "OpMemberDecorate %SSBO_m4x3f16 0 Offset 0\n"
15918                 "OpMemberDecorate %SSBO_m4x4f16 0 Offset 0\n"
15919
15920                 "OpDecorate %SSBO_f16     BufferBlock\n"
15921                 "OpDecorate %SSBO_v2f16   BufferBlock\n"
15922                 "OpDecorate %SSBO_v3f16   BufferBlock\n"
15923                 "OpDecorate %SSBO_v4f16   BufferBlock\n"
15924                 "OpDecorate %SSBO_m2x2f16 BufferBlock\n"
15925                 "OpDecorate %SSBO_m2x3f16 BufferBlock\n"
15926                 "OpDecorate %SSBO_m2x4f16 BufferBlock\n"
15927                 "OpDecorate %SSBO_m3x2f16 BufferBlock\n"
15928                 "OpDecorate %SSBO_m3x3f16 BufferBlock\n"
15929                 "OpDecorate %SSBO_m3x4f16 BufferBlock\n"
15930                 "OpDecorate %SSBO_m4x2f16 BufferBlock\n"
15931                 "OpDecorate %SSBO_m4x3f16 BufferBlock\n"
15932                 "OpDecorate %SSBO_m4x4f16 BufferBlock\n"
15933
15934                 "OpMemberDecorate %SSBO_m2x2f16 0 ColMajor\n"
15935                 "OpMemberDecorate %SSBO_m2x3f16 0 ColMajor\n"
15936                 "OpMemberDecorate %SSBO_m2x4f16 0 ColMajor\n"
15937                 "OpMemberDecorate %SSBO_m3x2f16 0 ColMajor\n"
15938                 "OpMemberDecorate %SSBO_m3x3f16 0 ColMajor\n"
15939                 "OpMemberDecorate %SSBO_m3x4f16 0 ColMajor\n"
15940                 "OpMemberDecorate %SSBO_m4x2f16 0 ColMajor\n"
15941                 "OpMemberDecorate %SSBO_m4x3f16 0 ColMajor\n"
15942                 "OpMemberDecorate %SSBO_m4x4f16 0 ColMajor\n"
15943
15944                 "OpMemberDecorate %SSBO_m2x2f16 0 MatrixStride 4\n"
15945                 "OpMemberDecorate %SSBO_m2x3f16 0 MatrixStride 8\n"
15946                 "OpMemberDecorate %SSBO_m2x4f16 0 MatrixStride 8\n"
15947                 "OpMemberDecorate %SSBO_m3x2f16 0 MatrixStride 4\n"
15948                 "OpMemberDecorate %SSBO_m3x3f16 0 MatrixStride 8\n"
15949                 "OpMemberDecorate %SSBO_m3x4f16 0 MatrixStride 8\n"
15950                 "OpMemberDecorate %SSBO_m4x2f16 0 MatrixStride 4\n"
15951                 "OpMemberDecorate %SSBO_m4x3f16 0 MatrixStride 8\n"
15952                 "OpMemberDecorate %SSBO_m4x4f16 0 MatrixStride 8\n"
15953
15954                 "${arg_decorations}"
15955         );
15956
15957         const StringTemplate testFun
15958         (
15959                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
15960                 "    %param = OpFunctionParameter %v4f32\n"
15961                 "    %entry = OpLabel\n"
15962
15963                 "        %i = OpVariable %fp_i32 Function\n"
15964                 "${arg_infunc_vars}"
15965                 "             OpStore %i %c_i32_0\n"
15966                 "             OpBranch %loop\n"
15967
15968                 "     %loop = OpLabel\n"
15969                 "    %i_cmp = OpLoad %i32 %i\n"
15970                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
15971                 "             OpLoopMerge %merge %next None\n"
15972                 "             OpBranchConditional %lt %write %merge\n"
15973
15974                 "    %write = OpLabel\n"
15975                 "      %ndx = OpLoad %i32 %i\n"
15976
15977                 "${arg_func_call}"
15978
15979                 "             OpBranch %next\n"
15980
15981                 "     %next = OpLabel\n"
15982                 "    %i_cur = OpLoad %i32 %i\n"
15983                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
15984                 "             OpStore %i %i_new\n"
15985                 "             OpBranch %loop\n"
15986
15987                 "    %merge = OpLabel\n"
15988                 "             OpReturnValue %param\n"
15989                 "             OpFunctionEnd\n"
15990         );
15991
15992         const Math16ArgFragments        argFragment1    =
15993         {
15994                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
15995                 " %val_src0 = OpLoad %${t0} %src0\n"
15996                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0\n"
15997                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
15998                 "             OpStore %dst %val_dst\n",
15999                 "",
16000                 "",
16001                 "",
16002         };
16003
16004         const Math16ArgFragments        argFragment2    =
16005         {
16006                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16007                 " %val_src0 = OpLoad %${t0} %src0\n"
16008                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16009                 " %val_src1 = OpLoad %${t1} %src1\n"
16010                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1\n"
16011                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16012                 "             OpStore %dst %val_dst\n",
16013                 "",
16014                 "",
16015                 "",
16016         };
16017
16018         const Math16ArgFragments        argFragment3    =
16019         {
16020                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16021                 " %val_src0 = OpLoad %${t0} %src0\n"
16022                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16023                 " %val_src1 = OpLoad %${t1} %src1\n"
16024                 "     %src2 = OpAccessChain %up_${t2} %ssbo_src2 %c_i32_0 %ndx\n"
16025                 " %val_src2 = OpLoad %${t2} %src2\n"
16026                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1 %val_src2\n"
16027                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16028                 "             OpStore %dst %val_dst\n",
16029                 "",
16030                 "",
16031                 "",
16032         };
16033
16034         const Math16ArgFragments        argFragmentLdExp        =
16035         {
16036                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16037                 " %val_src0 = OpLoad %${t0} %src0\n"
16038                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16039                 " %val_src1 = OpLoad %${t1} %src1\n"
16040                 "%val_src1i = OpConvertFToS %${dr}i32 %val_src1\n"
16041                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1i\n"
16042                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16043                 "             OpStore %dst %val_dst\n",
16044
16045                 "",
16046
16047                 "",
16048
16049                 "",
16050         };
16051
16052         const Math16ArgFragments        argFragmentModfFrac     =
16053         {
16054                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16055                 " %val_src0 = OpLoad %${t0} %src0\n"
16056                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %tmp\n"
16057                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16058                 "             OpStore %dst %val_dst\n",
16059
16060                 "   %fp_tmp = OpTypePointer Function %${tr}\n",
16061
16062                 "",
16063
16064                 "      %tmp = OpVariable %fp_tmp Function\n",
16065         };
16066
16067         const Math16ArgFragments        argFragmentModfInt      =
16068         {
16069                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16070                 " %val_src0 = OpLoad %${t0} %src0\n"
16071                 "%val_dummy = ${op} %${tr} ${ext_inst} %val_src0 %tmp\n"
16072                 "     %tmp0 = OpAccessChain %fp_tmp %tmp\n"
16073                 "  %val_dst = OpLoad %${tr} %tmp0\n"
16074                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16075                 "             OpStore %dst %val_dst\n",
16076
16077                 "   %fp_tmp = OpTypePointer Function %${tr}\n",
16078
16079                 "",
16080
16081                 "      %tmp = OpVariable %fp_tmp Function\n",
16082         };
16083
16084         const Math16ArgFragments        argFragmentModfStruct   =
16085         {
16086                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16087                 " %val_src0 = OpLoad %${t0} %src0\n"
16088                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16089                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16090                 "             OpStore %tmp_ptr_s %val_tmp\n"
16091                 "%tmp_ptr_l = OpAccessChain %fp_${tr} %tmp %c_${struct_member}\n"
16092                 "  %val_dst = OpLoad %${tr} %tmp_ptr_l\n"
16093                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16094                 "             OpStore %dst %val_dst\n",
16095
16096                 "  %fp_${tr} = OpTypePointer Function %${tr}\n"
16097                 "   %st_tmp = OpTypeStruct %${tr} %${tr}\n"
16098                 "   %fp_tmp = OpTypePointer Function %st_tmp\n"
16099                 "   %c_frac = OpConstant %i32 0\n"
16100                 "    %c_int = OpConstant %i32 1\n",
16101
16102                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16103                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16104
16105                 "      %tmp = OpVariable %fp_tmp Function\n",
16106         };
16107
16108         const Math16ArgFragments        argFragmentFrexpStructS =
16109         {
16110                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16111                 " %val_src0 = OpLoad %${t0} %src0\n"
16112                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16113                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16114                 "             OpStore %tmp_ptr_s %val_tmp\n"
16115                 "%tmp_ptr_l = OpAccessChain %fp_${tr} %tmp %c_i32_0\n"
16116                 "  %val_dst = OpLoad %${tr} %tmp_ptr_l\n"
16117                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16118                 "             OpStore %dst %val_dst\n",
16119
16120                 "  %fp_${tr} = OpTypePointer Function %${tr}\n"
16121                 "   %st_tmp = OpTypeStruct %${tr} %${dr}i32\n"
16122                 "   %fp_tmp = OpTypePointer Function %st_tmp\n",
16123
16124                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16125                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16126
16127                 "      %tmp = OpVariable %fp_tmp Function\n",
16128         };
16129
16130         const Math16ArgFragments        argFragmentFrexpStructE =
16131         {
16132                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16133                 " %val_src0 = OpLoad %${t0} %src0\n"
16134                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16135                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16136                 "             OpStore %tmp_ptr_s %val_tmp\n"
16137                 "%tmp_ptr_l = OpAccessChain %fp_${dr}i32 %tmp %c_i32_1\n"
16138                 "%val_dst_i = OpLoad %${dr}i32 %tmp_ptr_l\n"
16139                 "  %val_dst = OpConvertSToF %${tr} %val_dst_i\n"
16140                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16141                 "             OpStore %dst %val_dst\n",
16142
16143                 "   %st_tmp = OpTypeStruct %${tr} %${dr}i32\n"
16144                 "   %fp_tmp = OpTypePointer Function %st_tmp\n",
16145
16146                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16147                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16148
16149                 "      %tmp = OpVariable %fp_tmp Function\n",
16150         };
16151
16152         const Math16ArgFragments        argFragmentFrexpS               =
16153         {
16154                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16155                 " %val_src0 = OpLoad %${t0} %src0\n"
16156                 "  %out_exp = OpAccessChain %fp_${dr}i32 %tmp\n"
16157                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %out_exp\n"
16158                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16159                 "             OpStore %dst %val_dst\n",
16160
16161                 "",
16162
16163                 "",
16164
16165                 "      %tmp = OpVariable %fp_${dr}i32 Function\n",
16166         };
16167
16168         const Math16ArgFragments        argFragmentFrexpE               =
16169         {
16170                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16171                 " %val_src0 = OpLoad %${t0} %src0\n"
16172                 "  %out_exp = OpAccessChain %fp_${dr}i32 %tmp\n"
16173                 "%val_dummy = ${op} %${tr} ${ext_inst} %val_src0 %out_exp\n"
16174                 "%val_dst_i = OpLoad %${dr}i32 %out_exp\n"
16175                 "  %val_dst = OpConvertSToF %${tr} %val_dst_i\n"
16176                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16177                 "             OpStore %dst %val_dst\n",
16178
16179                 "",
16180
16181                 "",
16182
16183                 "      %tmp = OpVariable %fp_${dr}i32 Function\n",
16184         };
16185
16186         const Math16TestType&           testType                                = testTypes[testTypeIdx];
16187         const string                            funcNameString                  = string(testFunc.funcName) + string(testFunc.funcSuffix);
16188         const string                            testName                                = de::toLower(funcNameString);
16189         const Math16ArgFragments*       argFragments                    = DE_NULL;
16190         const size_t                            typeStructStride                = testType.typeStructStride;
16191         const bool                                      extInst                                 = !(testFunc.funcName[0] == 'O' && testFunc.funcName[1] == 'p');
16192         const size_t                            numFloatsPerArg0Type    = testTypes[testFunc.typeArg0].typeArrayStride / sizeof(deFloat16);
16193         const size_t                            iterations                              = numDataPoints / numFloatsPerArg0Type;
16194         const size_t                            numFloatsPerResultType  = testTypes[testFunc.typeResult].typeArrayStride / sizeof(deFloat16);
16195         const vector<deFloat16>         float16DummyOutput              (iterations * numFloatsPerResultType, 0);
16196         VulkanFeatures                          features;
16197         SpecResource                            specResource;
16198         map<string, string>                     specs;
16199         map<string, string>                     fragments;
16200         vector<string>                          extensions;
16201         string                                          funcCall;
16202         string                                          funcVariables;
16203         string                                          variables;
16204         string                                          declarations;
16205         string                                          decorations;
16206
16207         switch (testFunc.funcArgsCount)
16208         {
16209                 case 1:
16210                 {
16211                         argFragments = &argFragment1;
16212
16213                         if (funcNameString == "ModfFrac")               argFragments = &argFragmentModfFrac;
16214                         if (funcNameString == "ModfInt")                argFragments = &argFragmentModfInt;
16215                         if (funcNameString == "ModfStructFrac") argFragments = &argFragmentModfStruct;
16216                         if (funcNameString == "ModfStructInt")  argFragments = &argFragmentModfStruct;
16217                         if (funcNameString == "FrexpS")                 argFragments = &argFragmentFrexpS;
16218                         if (funcNameString == "FrexpE")                 argFragments = &argFragmentFrexpE;
16219                         if (funcNameString == "FrexpStructS")   argFragments = &argFragmentFrexpStructS;
16220                         if (funcNameString == "FrexpStructE")   argFragments = &argFragmentFrexpStructE;
16221
16222                         break;
16223                 }
16224                 case 2:
16225                 {
16226                         argFragments = &argFragment2;
16227
16228                         if (funcNameString == "Ldexp")                  argFragments = &argFragmentLdExp;
16229
16230                         break;
16231                 }
16232                 case 3:
16233                 {
16234                         argFragments = &argFragment3;
16235
16236                         break;
16237                 }
16238                 default:
16239                 {
16240                         TCU_THROW(InternalError, "Invalid number of arguments");
16241                 }
16242         }
16243
16244         if (testFunc.funcArgsCount == 1)
16245         {
16246                 variables +=
16247                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16248                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16249
16250                 decorations +=
16251                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16252                         "OpDecorate %ssbo_src0 Binding 0\n"
16253                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16254                         "OpDecorate %ssbo_dst Binding 1\n";
16255         }
16256         else if (testFunc.funcArgsCount == 2)
16257         {
16258                 variables +=
16259                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16260                         " %ssbo_src1 = OpVariable %up_SSBO_${t1} Uniform\n"
16261                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16262
16263                 decorations +=
16264                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16265                         "OpDecorate %ssbo_src0 Binding 0\n"
16266                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
16267                         "OpDecorate %ssbo_src1 Binding 1\n"
16268                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16269                         "OpDecorate %ssbo_dst Binding 2\n";
16270         }
16271         else if (testFunc.funcArgsCount == 3)
16272         {
16273                 variables +=
16274                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16275                         " %ssbo_src1 = OpVariable %up_SSBO_${t1} Uniform\n"
16276                         " %ssbo_src2 = OpVariable %up_SSBO_${t2} Uniform\n"
16277                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16278
16279                 decorations +=
16280                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16281                         "OpDecorate %ssbo_src0 Binding 0\n"
16282                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
16283                         "OpDecorate %ssbo_src1 Binding 1\n"
16284                         "OpDecorate %ssbo_src2 DescriptorSet 0\n"
16285                         "OpDecorate %ssbo_src2 Binding 2\n"
16286                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16287                         "OpDecorate %ssbo_dst Binding 3\n";
16288         }
16289         else
16290         {
16291                 TCU_THROW(InternalError, "Invalid number of function arguments");
16292         }
16293
16294         variables       += argFragments->variables;
16295         decorations     += argFragments->decorations;
16296
16297         specs["dr"]                                     = testTypes[testFunc.typeResult].typePrefix;
16298         specs["d0"]                                     = testTypes[testFunc.typeArg0].typePrefix;
16299         specs["d1"]                                     = testTypes[testFunc.typeArg1].typePrefix;
16300         specs["d2"]                                     = testTypes[testFunc.typeArg2].typePrefix;
16301         specs["tr"]                                     = string(testTypes[testFunc.typeResult].typePrefix) + componentType;
16302         specs["t0"]                                     = string(testTypes[testFunc.typeArg0].typePrefix) + componentType;
16303         specs["t1"]                                     = string(testTypes[testFunc.typeArg1].typePrefix) + componentType;
16304         specs["t2"]                                     = string(testTypes[testFunc.typeArg2].typePrefix) + componentType;
16305         specs["struct_stride"]          = de::toString(typeStructStride);
16306         specs["op"]                                     = extInst ? "OpExtInst" : testFunc.funcName;
16307         specs["ext_inst"]                       = extInst ? string("%ext_import ") + testFunc.funcName : "";
16308         specs["struct_member"]          = de::toLower(testFunc.funcSuffix);
16309
16310         variables                                       = StringTemplate(variables).specialize(specs);
16311         decorations                                     = StringTemplate(decorations).specialize(specs);
16312         funcVariables                           = StringTemplate(argFragments->funcVariables).specialize(specs);
16313         funcCall                                        = StringTemplate(argFragments->bodies).specialize(specs);
16314
16315         specs["num_data_points"]        = de::toString(iterations);
16316         specs["arg_vars"]                       = variables;
16317         specs["arg_decorations"]        = decorations;
16318         specs["arg_infunc_vars"]        = funcVariables;
16319         specs["arg_func_call"]          = funcCall;
16320
16321         fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"\n%ext_import = OpExtInstImport \"GLSL.std.450\"";
16322         fragments["capability"]         = "OpCapability Matrix\nOpCapability StorageUniformBufferBlock16";
16323         fragments["decoration"]         = decoration.specialize(specs);
16324         fragments["pre_main"]           = preMain.specialize(specs);
16325         fragments["testfun"]            = testFun.specialize(specs);
16326
16327         for (size_t inputArgNdx = 0; inputArgNdx < testFunc.funcArgsCount; ++inputArgNdx)
16328         {
16329                 const size_t                    numFloatsPerItem        = (inputArgNdx == 0) ? testTypes[testFunc.typeArg0].typeArrayStride / sizeof(deFloat16)
16330                                                                                                         : (inputArgNdx == 1) ? testTypes[testFunc.typeArg1].typeArrayStride / sizeof(deFloat16)
16331                                                                                                         : (inputArgNdx == 2) ? testTypes[testFunc.typeArg2].typeArrayStride / sizeof(deFloat16)
16332                                                                                                         : -1;
16333                 const vector<deFloat16> inputData                       = testFunc.getInputDataFunc(seed, numFloatsPerItem * iterations, testTypeIdx, numFloatsPerItem, testFunc.funcArgsCount, inputArgNdx);
16334
16335                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(inputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
16336         }
16337
16338         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16DummyOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
16339         specResource.verifyIO = testFunc.verifyFunc;
16340
16341         extensions.push_back("VK_KHR_16bit_storage");
16342         extensions.push_back("VK_KHR_shader_float16_int8");
16343
16344         features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
16345         features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
16346
16347         finalizeTestsCreation(specResource, fragments, testCtx, testGroup, testName, features, extensions, IVec3(1, 1, 1));
16348 }
16349
16350 template<size_t C, class SpecResource>
16351 tcu::TestCaseGroup* createFloat16ArithmeticSet (tcu::TestContext& testCtx)
16352 {
16353         DE_STATIC_ASSERT(C >= 1 && C <= 4);
16354
16355         const std::string                               testGroupName   (string("arithmetic_") + de::toString(C));
16356         de::MovePtr<tcu::TestCaseGroup> testGroup               (new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Float 16 arithmetic and related tests"));
16357         const Math16TestFunc                    testFuncs[]             =
16358         {
16359                 {       "OpFNegate",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16OpFNegate>                                       },
16360                 {       "Round",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Round>                                           },
16361                 {       "RoundEven",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16RoundEven>                                       },
16362                 {       "Trunc",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Trunc>                                           },
16363                 {       "FAbs",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FAbs>                                            },
16364                 {       "FSign",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FSign>                                           },
16365                 {       "Floor",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Floor>                                           },
16366                 {       "Ceil",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Ceil>                                            },
16367                 {       "Fract",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Fract>                                           },
16368                 {       "Radians",                              "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Radians>                                         },
16369                 {       "Degrees",                              "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Degrees>                                         },
16370                 {       "Sin",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sin>                                                     },
16371                 {       "Cos",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Cos>                                                     },
16372                 {       "Tan",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Tan>                                                     },
16373                 {       "Asin",                                 "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Asin>                                            },
16374                 {       "Acos",                                 "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Acos>                                            },
16375                 {       "Atan",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Atan>                                            },
16376                 {       "Sinh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sinh>                                            },
16377                 {       "Cosh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Cosh>                                            },
16378                 {       "Tanh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Tanh>                                            },
16379                 {       "Asinh",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Asinh>                                           },
16380                 {       "Acosh",                                "",                     1,      C,              C,              0,              0, &getInputDataAC,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Acosh>                                           },
16381                 {       "Atanh",                                "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Atanh>                                           },
16382                 {       "Exp",                                  "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Exp>                                                     },
16383                 {       "Log",                                  "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Log>                                                     },
16384                 {       "Exp2",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Exp2>                                            },
16385                 {       "Log2",                                 "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Log2>                                            },
16386                 {       "Sqrt",                                 "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sqrt>                                            },
16387                 {       "InverseSqrt",                  "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16InverseSqrt>                                     },
16388                 {       "Modf",                                 "Frac",         1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfFrac>                                        },
16389                 {       "Modf",                                 "Int",          1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfInt>                                         },
16390                 {       "ModfStruct",                   "Frac",         1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfFrac>                                        },
16391                 {       "ModfStruct",                   "Int",          1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfInt>                                         },
16392                 {       "Frexp",                                "S",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpS>                                          },
16393                 {       "Frexp",                                "E",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpE>                                          },
16394                 {       "FrexpStruct",                  "S",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpS>                                          },
16395                 {       "FrexpStruct",                  "E",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpE>                                          },
16396                 {       "OpFAdd",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFAdd>                                          },
16397                 {       "OpFSub",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFSub>                                          },
16398                 {       "OpFMul",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFMul>                                          },
16399                 {       "OpFDiv",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFDiv>                                          },
16400                 {       "Atan2",                                "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Atan2>                                           },
16401                 {       "Pow",                                  "",                     2,      C,              C,              C,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Pow>                                                     },
16402                 {       "FMin",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16FMin>                                            },
16403                 {       "FMax",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16FMax>                                            },
16404                 {       "Step",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Step>                                            },
16405                 {       "Ldexp",                                "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Ldexp>                                           },
16406                 {       "FClamp",                               "",                     3,      C,              C,              C,              C, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FClamp>                                          },
16407                 {       "FMix",                                 "",                     3,      C,              C,              C,              C, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FMix>                                            },
16408                 {       "SmoothStep",                   "",                     3,      C,              C,              C,              C, &getInputDataSS,     compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16SmoothStep>                                      },
16409                 {       "Fma",                                  "",                     3,      C,              C,              C,              C, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16Fma>                                                     },
16410                 {       "Length",                               "",                     1,      1,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  1,  C,  0,  0, fp16Length>                                          },
16411                 {       "Distance",                             "",                     2,      1,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  1,  C,  C,  0, fp16Distance>                                        },
16412                 {       "Cross",                                "",                     2,      C,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Cross>                                           },
16413                 {       "Normalize",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Normalize>                                       },
16414                 {       "FaceForward",                  "",                     3,      C,              C,              C,              C, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FaceForward>                                     },
16415                 {       "Reflect",                              "",                     2,      C,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Reflect>                                         },
16416                 {       "Refract",                              "",                     3,      C,              C,              C,              1, &getInputDataN,      compareFP16ArithmeticFunc<  C,  C,  C,  1, fp16Refract>                                         },
16417                 {       "OpDot",                                "",                     2,      1,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  1,  C,  C,  0, fp16Dot>                                                     },
16418                 {       "OpVectorTimesScalar",  "",                     2,      C,              C,              1,              0, &getInputDataV,      compareFP16ArithmeticFunc<  C,  C,  1,  0, fp16VectorTimesScalar>                       },
16419         };
16420
16421         for (deUint32 testFuncIdx = 0; testFuncIdx < DE_LENGTH_OF_ARRAY(testFuncs); ++testFuncIdx)
16422         {
16423                 const Math16TestFunc&   testFunc                = testFuncs[testFuncIdx];
16424                 const string                    funcNameString  = testFunc.funcName;
16425
16426                 if ((C != 3) && funcNameString == "Cross")
16427                         continue;
16428
16429                 if ((C < 2) && funcNameString == "OpDot")
16430                         continue;
16431
16432                 if ((C < 2) && funcNameString == "OpVectorTimesScalar")
16433                         continue;
16434
16435                 createFloat16ArithmeticFuncTest<SpecResource>(testCtx, *testGroup.get(), C, testFunc);
16436         }
16437
16438         return testGroup.release();
16439 }
16440
16441 template<class SpecResource>
16442 tcu::TestCaseGroup* createFloat16ArithmeticSet (tcu::TestContext& testCtx)
16443 {
16444         const std::string                               testGroupName   ("arithmetic");
16445         de::MovePtr<tcu::TestCaseGroup> testGroup               (new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Float 16 arithmetic and related tests"));
16446         const Math16TestFunc                    testFuncs[]             =
16447         {
16448                 {       "OpTranspose",                  "2x2",          1,      MAT2X2, MAT2X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  4,  4,  0,  0, fp16Transpose<2,2> >                         },
16449                 {       "OpTranspose",                  "3x2",          1,      MAT2X3, MAT3X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<3,2> >                         },
16450                 {       "OpTranspose",                  "4x2",          1,      MAT2X4, MAT4X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<4,2> >                         },
16451                 {       "OpTranspose",                  "2x3",          1,      MAT3X2, MAT2X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<2,3> >                         },
16452                 {       "OpTranspose",                  "3x3",          1,      MAT3X3, MAT3X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<3,3> >                         },
16453                 {       "OpTranspose",                  "4x3",          1,      MAT3X4, MAT4X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<4,3> >                         },
16454                 {       "OpTranspose",                  "2x4",          1,      MAT4X2, MAT2X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<2,4> >                         },
16455                 {       "OpTranspose",                  "3x4",          1,      MAT4X3, MAT3X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<3,4> >                         },
16456                 {       "OpTranspose",                  "4x4",          1,      MAT4X4, MAT4X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<4,4> >                         },
16457                 {       "OpMatrixTimesScalar",  "2x2",          2,      MAT2X2, MAT2X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4,  1,  0, fp16MatrixTimesScalar<2,2> >         },
16458                 {       "OpMatrixTimesScalar",  "2x3",          2,      MAT2X3, MAT2X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<2,3> >         },
16459                 {       "OpMatrixTimesScalar",  "2x4",          2,      MAT2X4, MAT2X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<2,4> >         },
16460                 {       "OpMatrixTimesScalar",  "3x2",          2,      MAT3X2, MAT3X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<3,2> >         },
16461                 {       "OpMatrixTimesScalar",  "3x3",          2,      MAT3X3, MAT3X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<3,3> >         },
16462                 {       "OpMatrixTimesScalar",  "3x4",          2,      MAT3X4, MAT3X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<3,4> >         },
16463                 {       "OpMatrixTimesScalar",  "4x2",          2,      MAT4X2, MAT4X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<4,2> >         },
16464                 {       "OpMatrixTimesScalar",  "4x3",          2,      MAT4X3, MAT4X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<4,3> >         },
16465                 {       "OpMatrixTimesScalar",  "4x4",          2,      MAT4X4, MAT4X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<4,4> >         },
16466                 {       "OpVectorTimesMatrix",  "2x2",          2,      VEC2,   VEC2,   MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  2,  4,  0, fp16VectorTimesMatrix<2,2> >         },
16467                 {       "OpVectorTimesMatrix",  "2x3",          2,      VEC2,   VEC3,   MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  3,  8,  0, fp16VectorTimesMatrix<2,3> >         },
16468                 {       "OpVectorTimesMatrix",  "2x4",          2,      VEC2,   VEC4,   MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  4,  8,  0, fp16VectorTimesMatrix<2,4> >         },
16469                 {       "OpVectorTimesMatrix",  "3x2",          2,      VEC3,   VEC2,   MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  2,  8,  0, fp16VectorTimesMatrix<3,2> >         },
16470                 {       "OpVectorTimesMatrix",  "3x3",          2,      VEC3,   VEC3,   MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  3, 16,  0, fp16VectorTimesMatrix<3,3> >         },
16471                 {       "OpVectorTimesMatrix",  "3x4",          2,      VEC3,   VEC4,   MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  4, 16,  0, fp16VectorTimesMatrix<3,4> >         },
16472                 {       "OpVectorTimesMatrix",  "4x2",          2,      VEC4,   VEC2,   MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  2,  8,  0, fp16VectorTimesMatrix<4,2> >         },
16473                 {       "OpVectorTimesMatrix",  "4x3",          2,      VEC4,   VEC3,   MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  3, 16,  0, fp16VectorTimesMatrix<4,3> >         },
16474                 {       "OpVectorTimesMatrix",  "4x4",          2,      VEC4,   VEC4,   MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4, 16,  0, fp16VectorTimesMatrix<4,4> >         },
16475                 {       "OpMatrixTimesVector",  "2x2",          2,      VEC2,   MAT2X2, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  4,  2,  0, fp16MatrixTimesVector<2,2> >         },
16476                 {       "OpMatrixTimesVector",  "2x3",          2,      VEC3,   MAT2X3, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  8,  2,  0, fp16MatrixTimesVector<2,3> >         },
16477                 {       "OpMatrixTimesVector",  "2x4",          2,      VEC4,   MAT2X4, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  2,  0, fp16MatrixTimesVector<2,4> >         },
16478                 {       "OpMatrixTimesVector",  "3x2",          2,      VEC2,   MAT3X2, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  8,  3,  0, fp16MatrixTimesVector<3,2> >         },
16479                 {       "OpMatrixTimesVector",  "3x3",          2,      VEC3,   MAT3X3, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3, 16,  3,  0, fp16MatrixTimesVector<3,3> >         },
16480                 {       "OpMatrixTimesVector",  "3x4",          2,      VEC4,   MAT3X4, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4, 16,  3,  0, fp16MatrixTimesVector<3,4> >         },
16481                 {       "OpMatrixTimesVector",  "4x2",          2,      VEC2,   MAT4X2, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  8,  4,  0, fp16MatrixTimesVector<4,2> >         },
16482                 {       "OpMatrixTimesVector",  "4x3",          2,      VEC3,   MAT4X3, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3, 16,  4,  0, fp16MatrixTimesVector<4,3> >         },
16483                 {       "OpMatrixTimesVector",  "4x4",          2,      VEC4,   MAT4X4, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4, 16,  4,  0, fp16MatrixTimesVector<4,4> >         },
16484                 {       "OpMatrixTimesMatrix",  "2x2_2x2",      2,      MAT2X2, MAT2X2, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4,  4,  0, fp16MatrixTimesMatrix<2,2,2,2> >     },
16485                 {       "OpMatrixTimesMatrix",  "2x2_3x2",      2,      MAT3X2, MAT2X2, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  8,  0, fp16MatrixTimesMatrix<2,2,3,2> >     },
16486                 {       "OpMatrixTimesMatrix",  "2x2_4x2",      2,      MAT4X2, MAT2X2, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  8,  0, fp16MatrixTimesMatrix<2,2,4,2> >     },
16487                 {       "OpMatrixTimesMatrix",  "2x3_2x2",      2,      MAT2X3, MAT2X3, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  4,  0, fp16MatrixTimesMatrix<2,3,2,2> >     },
16488                 {       "OpMatrixTimesMatrix",  "2x3_3x2",      2,      MAT3X3, MAT2X3, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,3,3,2> >     },
16489                 {       "OpMatrixTimesMatrix",  "2x3_4x2",      2,      MAT4X3, MAT2X3, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,3,4,2> >     },
16490                 {       "OpMatrixTimesMatrix",  "2x4_2x2",      2,      MAT2X4, MAT2X4, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  4,  0, fp16MatrixTimesMatrix<2,4,2,2> >     },
16491                 {       "OpMatrixTimesMatrix",  "2x4_3x2",      2,      MAT3X4, MAT2X4, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,4,3,2> >     },
16492                 {       "OpMatrixTimesMatrix",  "2x4_4x2",      2,      MAT4X4, MAT2X4, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,4,4,2> >     },
16493                 {       "OpMatrixTimesMatrix",  "3x2_2x3",      2,      MAT2X2, MAT3X2, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  8,  0, fp16MatrixTimesMatrix<3,2,2,3> >     },
16494                 {       "OpMatrixTimesMatrix",  "3x2_3x3",      2,      MAT3X2, MAT3X2, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<3,2,3,3> >     },
16495                 {       "OpMatrixTimesMatrix",  "3x2_4x3",      2,      MAT4X2, MAT3X2, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<3,2,4,3> >     },
16496                 {       "OpMatrixTimesMatrix",  "3x3_2x3",      2,      MAT2X3, MAT3X3, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<3,3,2,3> >     },
16497                 {       "OpMatrixTimesMatrix",  "3x3_3x3",      2,      MAT3X3, MAT3X3, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,3,3,3> >     },
16498                 {       "OpMatrixTimesMatrix",  "3x3_4x3",      2,      MAT4X3, MAT3X3, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,3,4,3> >     },
16499                 {       "OpMatrixTimesMatrix",  "3x4_2x3",      2,      MAT2X4, MAT3X4, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<3,4,2,3> >     },
16500                 {       "OpMatrixTimesMatrix",  "3x4_3x3",      2,      MAT3X4, MAT3X4, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,4,3,3> >     },
16501                 {       "OpMatrixTimesMatrix",  "3x4_4x3",      2,      MAT4X4, MAT3X4, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,4,4,3> >     },
16502                 {       "OpMatrixTimesMatrix",  "4x2_2x4",      2,      MAT2X2, MAT4X2, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  8,  0, fp16MatrixTimesMatrix<4,2,2,4> >     },
16503                 {       "OpMatrixTimesMatrix",  "4x2_3x4",      2,      MAT3X2, MAT4X2, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<4,2,3,4> >     },
16504                 {       "OpMatrixTimesMatrix",  "4x2_4x4",      2,      MAT4X2, MAT4X2, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<4,2,4,4> >     },
16505                 {       "OpMatrixTimesMatrix",  "4x3_2x4",      2,      MAT2X3, MAT4X3, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<4,3,2,4> >     },
16506                 {       "OpMatrixTimesMatrix",  "4x3_3x4",      2,      MAT3X3, MAT4X3, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,3,3,4> >     },
16507                 {       "OpMatrixTimesMatrix",  "4x3_4x4",      2,      MAT4X3, MAT4X3, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,3,4,4> >     },
16508                 {       "OpMatrixTimesMatrix",  "4x4_2x4",      2,      MAT2X4, MAT4X4, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<4,4,2,4> >     },
16509                 {       "OpMatrixTimesMatrix",  "4x4_3x4",      2,      MAT3X4, MAT4X4, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,4,3,4> >     },
16510                 {       "OpMatrixTimesMatrix",  "4x4_4x4",      2,      MAT4X4, MAT4X4, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,4,4,4> >     },
16511                 {       "OpOuterProduct",               "2x2",          2,      MAT2X2, VEC2,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  2,  2,  0, fp16OuterProduct<2,2> >                      },
16512                 {       "OpOuterProduct",               "2x3",          2,      MAT2X3, VEC3,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  3,  2,  0, fp16OuterProduct<2,3> >                      },
16513                 {       "OpOuterProduct",               "2x4",          2,      MAT2X4, VEC4,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  2,  0, fp16OuterProduct<2,4> >                      },
16514                 {       "OpOuterProduct",               "3x2",          2,      MAT3X2, VEC2,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  2,  3,  0, fp16OuterProduct<3,2> >                      },
16515                 {       "OpOuterProduct",               "3x3",          2,      MAT3X3, VEC3,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  3,  3,  0, fp16OuterProduct<3,3> >                      },
16516                 {       "OpOuterProduct",               "3x4",          2,      MAT3X4, VEC4,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  4,  3,  0, fp16OuterProduct<3,4> >                      },
16517                 {       "OpOuterProduct",               "4x2",          2,      MAT4X2, VEC2,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  2,  4,  0, fp16OuterProduct<4,2> >                      },
16518                 {       "OpOuterProduct",               "4x3",          2,      MAT4X3, VEC3,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  3,  4,  0, fp16OuterProduct<4,3> >                      },
16519                 {       "OpOuterProduct",               "4x4",          2,      MAT4X4, VEC4,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  4,  4,  0, fp16OuterProduct<4,4> >                      },
16520                 {       "Determinant",                  "2x2",          1,      SCALAR, MAT2X2, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1,  4,  0,  0, fp16Determinant<2> >                         },
16521                 {       "Determinant",                  "3x3",          1,      SCALAR, MAT3X3, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1, 16,  0,  0, fp16Determinant<3> >                         },
16522                 {       "Determinant",                  "4x4",          1,      SCALAR, MAT4X4, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1, 16,  0,  0, fp16Determinant<4> >                         },
16523                 {       "MatrixInverse",                "2x2",          1,      MAT2X2, MAT2X2, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  4,  4,  0,  0, fp16Inverse<2> >                                     },
16524         };
16525
16526         for (deUint32 testFuncIdx = 0; testFuncIdx < DE_LENGTH_OF_ARRAY(testFuncs); ++testFuncIdx)
16527         {
16528                 const Math16TestFunc&   testFunc        = testFuncs[testFuncIdx];
16529
16530                 createFloat16ArithmeticFuncTest<SpecResource>(testCtx, *testGroup.get(), 0, testFunc);
16531         }
16532
16533         return testGroup.release();
16534 }
16535
16536 const string getNumberTypeName (const NumberType type)
16537 {
16538         if (type == NUMBERTYPE_INT32)
16539         {
16540                 return "int";
16541         }
16542         else if (type == NUMBERTYPE_UINT32)
16543         {
16544                 return "uint";
16545         }
16546         else if (type == NUMBERTYPE_FLOAT32)
16547         {
16548                 return "float";
16549         }
16550         else
16551         {
16552                 DE_ASSERT(false);
16553                 return "";
16554         }
16555 }
16556
16557 deInt32 getInt(de::Random& rnd)
16558 {
16559         return rnd.getInt(std::numeric_limits<int>::min(), std::numeric_limits<int>::max());
16560 }
16561
16562 const string repeatString (const string& str, int times)
16563 {
16564         string filler;
16565         for (int i = 0; i < times; ++i)
16566         {
16567                 filler += str;
16568         }
16569         return filler;
16570 }
16571
16572 const string getRandomConstantString (const NumberType type, de::Random& rnd)
16573 {
16574         if (type == NUMBERTYPE_INT32)
16575         {
16576                 return numberToString<deInt32>(getInt(rnd));
16577         }
16578         else if (type == NUMBERTYPE_UINT32)
16579         {
16580                 return numberToString<deUint32>(rnd.getUint32());
16581         }
16582         else if (type == NUMBERTYPE_FLOAT32)
16583         {
16584                 return numberToString<float>(rnd.getFloat());
16585         }
16586         else
16587         {
16588                 DE_ASSERT(false);
16589                 return "";
16590         }
16591 }
16592
16593 void createVectorCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16594 {
16595         map<string, string> params;
16596
16597         // Vec2 to Vec4
16598         for (int width = 2; width <= 4; ++width)
16599         {
16600                 const string randomConst = numberToString(getInt(rnd));
16601                 const string widthStr = numberToString(width);
16602                 const string composite_type = "${customType}vec" + widthStr;
16603                 const int index = rnd.getInt(0, width-1);
16604
16605                 params["type"]                  = "vec";
16606                 params["name"]                  = params["type"] + "_" + widthStr;
16607                 params["compositeDecl"]         = composite_type + " = OpTypeVector ${customType} " + widthStr +"\n";
16608                 params["compositeType"]         = composite_type;
16609                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
16610                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct " + composite_type + repeatString(" %filler", width) + "\n";
16611                 params["indexes"]               = numberToString(index);
16612                 testCases.push_back(params);
16613         }
16614 }
16615
16616 void createArrayCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16617 {
16618         const int limit = 10;
16619         map<string, string> params;
16620
16621         for (int width = 2; width <= limit; ++width)
16622         {
16623                 string randomConst = numberToString(getInt(rnd));
16624                 string widthStr = numberToString(width);
16625                 int index = rnd.getInt(0, width-1);
16626
16627                 params["type"]                  = "array";
16628                 params["name"]                  = params["type"] + "_" + widthStr;
16629                 params["compositeDecl"]         = string("%arraywidth = OpConstant %u32 " + widthStr + "\n")
16630                                                                                         +        "%composite = OpTypeArray ${customType} %arraywidth\n";
16631                 params["compositeType"]         = "%composite";
16632                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
16633                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
16634                 params["indexes"]               = numberToString(index);
16635                 testCases.push_back(params);
16636         }
16637 }
16638
16639 void createStructCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16640 {
16641         const int limit = 10;
16642         map<string, string> params;
16643
16644         for (int width = 2; width <= limit; ++width)
16645         {
16646                 string randomConst = numberToString(getInt(rnd));
16647                 int index = rnd.getInt(0, width-1);
16648
16649                 params["type"]                  = "struct";
16650                 params["name"]                  = params["type"] + "_" + numberToString(width);
16651                 params["compositeDecl"]         = "%composite = OpTypeStruct" + repeatString(" ${customType}", width) + "\n";
16652                 params["compositeType"]         = "%composite";
16653                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
16654                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
16655                 params["indexes"]               = numberToString(index);
16656                 testCases.push_back(params);
16657         }
16658 }
16659
16660 void createMatrixCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16661 {
16662         map<string, string> params;
16663
16664         // Vec2 to Vec4
16665         for (int width = 2; width <= 4; ++width)
16666         {
16667                 string widthStr = numberToString(width);
16668
16669                 for (int column = 2 ; column <= 4; ++column)
16670                 {
16671                         int index_0 = rnd.getInt(0, column-1);
16672                         int index_1 = rnd.getInt(0, width-1);
16673                         string columnStr = numberToString(column);
16674
16675                         params["type"]          = "matrix";
16676                         params["name"]          = params["type"] + "_" + widthStr + "x" + columnStr;
16677                         params["compositeDecl"] = string("%vectype   = OpTypeVector ${customType} " + widthStr + "\n")
16678                                                                                                 +        "%composite = OpTypeMatrix %vectype " + columnStr + "\n";
16679                         params["compositeType"] = "%composite";
16680
16681                         params["filler"]        = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n"
16682                                                                                                 +        "%fillerVec = OpConstantComposite %vectype" + repeatString(" %filler", width) + "\n";
16683
16684                         params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %fillerVec", column) + "\n";
16685                         params["indexes"]       = numberToString(index_0) + " " + numberToString(index_1);
16686                         testCases.push_back(params);
16687                 }
16688         }
16689 }
16690
16691 void createCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16692 {
16693         createVectorCompositeCases(testCases, rnd, type);
16694         createArrayCompositeCases(testCases, rnd, type);
16695         createStructCompositeCases(testCases, rnd, type);
16696         // Matrix only supports float types
16697         if (type == NUMBERTYPE_FLOAT32)
16698         {
16699                 createMatrixCompositeCases(testCases, rnd, type);
16700         }
16701 }
16702
16703 const string getAssemblyTypeDeclaration (const NumberType type)
16704 {
16705         switch (type)
16706         {
16707                 case NUMBERTYPE_INT32:          return "OpTypeInt 32 1";
16708                 case NUMBERTYPE_UINT32:         return "OpTypeInt 32 0";
16709                 case NUMBERTYPE_FLOAT32:        return "OpTypeFloat 32";
16710                 default:                        DE_ASSERT(false); return "";
16711         }
16712 }
16713
16714 const string getAssemblyTypeName (const NumberType type)
16715 {
16716         switch (type)
16717         {
16718                 case NUMBERTYPE_INT32:          return "%i32";
16719                 case NUMBERTYPE_UINT32:         return "%u32";
16720                 case NUMBERTYPE_FLOAT32:        return "%f32";
16721                 default:                        DE_ASSERT(false); return "";
16722         }
16723 }
16724
16725 const string specializeCompositeInsertShaderTemplate (const NumberType type, const map<string, string>& params)
16726 {
16727         map<string, string>     parameters(params);
16728
16729         const string customType = getAssemblyTypeName(type);
16730         map<string, string> substCustomType;
16731         substCustomType["customType"] = customType;
16732         parameters["compositeDecl"] = StringTemplate(parameters.at("compositeDecl")).specialize(substCustomType);
16733         parameters["compositeType"] = StringTemplate(parameters.at("compositeType")).specialize(substCustomType);
16734         parameters["compositeConstruct"] = StringTemplate(parameters.at("compositeConstruct")).specialize(substCustomType);
16735         parameters["filler"] = StringTemplate(parameters.at("filler")).specialize(substCustomType);
16736         parameters["customType"] = customType;
16737         parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
16738
16739         if (parameters.at("compositeType") != "%u32vec3")
16740         {
16741                 parameters["u32vec3Decl"] = "%u32vec3   = OpTypeVector %u32 3\n";
16742         }
16743
16744         return StringTemplate(
16745                 "OpCapability Shader\n"
16746                 "OpCapability Matrix\n"
16747                 "OpMemoryModel Logical GLSL450\n"
16748                 "OpEntryPoint GLCompute %main \"main\" %id\n"
16749                 "OpExecutionMode %main LocalSize 1 1 1\n"
16750
16751                 "OpSource GLSL 430\n"
16752                 "OpName %main           \"main\"\n"
16753                 "OpName %id             \"gl_GlobalInvocationID\"\n"
16754
16755                 // Decorators
16756                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
16757                 "OpDecorate %buf BufferBlock\n"
16758                 "OpDecorate %indata DescriptorSet 0\n"
16759                 "OpDecorate %indata Binding 0\n"
16760                 "OpDecorate %outdata DescriptorSet 0\n"
16761                 "OpDecorate %outdata Binding 1\n"
16762                 "OpDecorate %customarr ArrayStride 4\n"
16763                 "${compositeDecorator}"
16764                 "OpMemberDecorate %buf 0 Offset 0\n"
16765
16766                 // General types
16767                 "%void      = OpTypeVoid\n"
16768                 "%voidf     = OpTypeFunction %void\n"
16769                 "%u32       = OpTypeInt 32 0\n"
16770                 "%i32       = OpTypeInt 32 1\n"
16771                 "%f32       = OpTypeFloat 32\n"
16772
16773                 // Composite declaration
16774                 "${compositeDecl}"
16775
16776                 // Constants
16777                 "${filler}"
16778
16779                 "${u32vec3Decl:opt}"
16780                 "%uvec3ptr  = OpTypePointer Input %u32vec3\n"
16781
16782                 // Inherited from custom
16783                 "%customptr = OpTypePointer Uniform ${customType}\n"
16784                 "%customarr = OpTypeRuntimeArray ${customType}\n"
16785                 "%buf       = OpTypeStruct %customarr\n"
16786                 "%bufptr    = OpTypePointer Uniform %buf\n"
16787
16788                 "%indata    = OpVariable %bufptr Uniform\n"
16789                 "%outdata   = OpVariable %bufptr Uniform\n"
16790
16791                 "%id        = OpVariable %uvec3ptr Input\n"
16792                 "%zero      = OpConstant %i32 0\n"
16793
16794                 "%main      = OpFunction %void None %voidf\n"
16795                 "%label     = OpLabel\n"
16796                 "%idval     = OpLoad %u32vec3 %id\n"
16797                 "%x         = OpCompositeExtract %u32 %idval 0\n"
16798
16799                 "%inloc     = OpAccessChain %customptr %indata %zero %x\n"
16800                 "%outloc    = OpAccessChain %customptr %outdata %zero %x\n"
16801                 // Read the input value
16802                 "%inval     = OpLoad ${customType} %inloc\n"
16803                 // Create the composite and fill it
16804                 "${compositeConstruct}"
16805                 // Insert the input value to a place
16806                 "%instance2 = OpCompositeInsert ${compositeType} %inval %instance ${indexes}\n"
16807                 // Read back the value from the position
16808                 "%out_val   = OpCompositeExtract ${customType} %instance2 ${indexes}\n"
16809                 // Store it in the output position
16810                 "             OpStore %outloc %out_val\n"
16811                 "             OpReturn\n"
16812                 "             OpFunctionEnd\n"
16813         ).specialize(parameters);
16814 }
16815
16816 template<typename T>
16817 BufferSp createCompositeBuffer(T number)
16818 {
16819         return BufferSp(new Buffer<T>(vector<T>(1, number)));
16820 }
16821
16822 tcu::TestCaseGroup* createOpCompositeInsertGroup (tcu::TestContext& testCtx)
16823 {
16824         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "opcompositeinsert", "Test the OpCompositeInsert instruction"));
16825         de::Random                                              rnd             (deStringHash(group->getName()));
16826
16827         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
16828         {
16829                 NumberType                                              numberType              = NumberType(type);
16830                 const string                                    typeName                = getNumberTypeName(numberType);
16831                 const string                                    description             = "Test the OpCompositeInsert instruction with " + typeName + "s";
16832                 de::MovePtr<tcu::TestCaseGroup> subGroup                (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
16833                 vector<map<string, string> >    testCases;
16834
16835                 createCompositeCases(testCases, rnd, numberType);
16836
16837                 for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
16838                 {
16839                         ComputeShaderSpec       spec;
16840
16841                         spec.assembly = specializeCompositeInsertShaderTemplate(numberType, *test);
16842
16843                         switch (numberType)
16844                         {
16845                                 case NUMBERTYPE_INT32:
16846                                 {
16847                                         deInt32 number = getInt(rnd);
16848                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
16849                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
16850                                         break;
16851                                 }
16852                                 case NUMBERTYPE_UINT32:
16853                                 {
16854                                         deUint32 number = rnd.getUint32();
16855                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
16856                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
16857                                         break;
16858                                 }
16859                                 case NUMBERTYPE_FLOAT32:
16860                                 {
16861                                         float number = rnd.getFloat();
16862                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
16863                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
16864                                         break;
16865                                 }
16866                                 default:
16867                                         DE_ASSERT(false);
16868                         }
16869
16870                         spec.numWorkGroups = IVec3(1, 1, 1);
16871                         subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpCompositeInsert test", spec));
16872                 }
16873                 group->addChild(subGroup.release());
16874         }
16875         return group.release();
16876 }
16877
16878 struct AssemblyStructInfo
16879 {
16880         AssemblyStructInfo (const deUint32 comp, const deUint32 idx)
16881         : components    (comp)
16882         , index                 (idx)
16883         {}
16884
16885         deUint32 components;
16886         deUint32 index;
16887 };
16888
16889 const string specializeInBoundsShaderTemplate (const NumberType type, const AssemblyStructInfo& structInfo, const map<string, string>& params)
16890 {
16891         // Create the full index string
16892         string                          fullIndex       = numberToString(structInfo.index) + " " + params.at("indexes");
16893         // Convert it to list of indexes
16894         vector<string>          indexes         = de::splitString(fullIndex, ' ');
16895
16896         map<string, string>     parameters      (params);
16897         parameters["structType"]        = repeatString(" ${compositeType}", structInfo.components);
16898         parameters["structConstruct"]   = repeatString(" %instance", structInfo.components);
16899         parameters["insertIndexes"]     = fullIndex;
16900
16901         // In matrix cases the last two index is the CompositeExtract indexes
16902         const deUint32 extractIndexes = (parameters["type"] == "matrix") ? 2 : 1;
16903
16904         // Construct the extractIndex
16905         for (vector<string>::const_iterator index = indexes.end() - extractIndexes; index != indexes.end(); ++index)
16906         {
16907                 parameters["extractIndexes"] += " " + *index;
16908         }
16909
16910         // Remove the last 1 or 2 element depends on matrix case or not
16911         indexes.erase(indexes.end() - extractIndexes, indexes.end());
16912
16913         deUint32 id = 0;
16914         // Generate AccessChain index expressions (except for the last one, because we use ptr to the composite)
16915         for (vector<string>::const_iterator index = indexes.begin(); index != indexes.end(); ++index)
16916         {
16917                 string indexId = "%index_" + numberToString(id++);
16918                 parameters["accessChainConstDeclaration"] += indexId + "   = OpConstant %u32 " + *index + "\n";
16919                 parameters["accessChainIndexes"] += " " + indexId;
16920         }
16921
16922         parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
16923
16924         const string customType = getAssemblyTypeName(type);
16925         map<string, string> substCustomType;
16926         substCustomType["customType"] = customType;
16927         parameters["compositeDecl"] = StringTemplate(parameters.at("compositeDecl")).specialize(substCustomType);
16928         parameters["compositeType"] = StringTemplate(parameters.at("compositeType")).specialize(substCustomType);
16929         parameters["compositeConstruct"] = StringTemplate(parameters.at("compositeConstruct")).specialize(substCustomType);
16930         parameters["filler"] = StringTemplate(parameters.at("filler")).specialize(substCustomType);
16931         parameters["customType"] = customType;
16932
16933         const string compositeType = parameters.at("compositeType");
16934         map<string, string> substCompositeType;
16935         substCompositeType["compositeType"] = compositeType;
16936         parameters["structType"] = StringTemplate(parameters.at("structType")).specialize(substCompositeType);
16937         if (compositeType != "%u32vec3")
16938         {
16939                 parameters["u32vec3Decl"] = "%u32vec3   = OpTypeVector %u32 3\n";
16940         }
16941
16942         return StringTemplate(
16943                 "OpCapability Shader\n"
16944                 "OpCapability Matrix\n"
16945                 "OpMemoryModel Logical GLSL450\n"
16946                 "OpEntryPoint GLCompute %main \"main\" %id\n"
16947                 "OpExecutionMode %main LocalSize 1 1 1\n"
16948
16949                 "OpSource GLSL 430\n"
16950                 "OpName %main           \"main\"\n"
16951                 "OpName %id             \"gl_GlobalInvocationID\"\n"
16952                 // Decorators
16953                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
16954                 "OpDecorate %buf BufferBlock\n"
16955                 "OpDecorate %indata DescriptorSet 0\n"
16956                 "OpDecorate %indata Binding 0\n"
16957                 "OpDecorate %outdata DescriptorSet 0\n"
16958                 "OpDecorate %outdata Binding 1\n"
16959                 "OpDecorate %customarr ArrayStride 4\n"
16960                 "${compositeDecorator}"
16961                 "OpMemberDecorate %buf 0 Offset 0\n"
16962                 // General types
16963                 "%void      = OpTypeVoid\n"
16964                 "%voidf     = OpTypeFunction %void\n"
16965                 "%i32       = OpTypeInt 32 1\n"
16966                 "%u32       = OpTypeInt 32 0\n"
16967                 "%f32       = OpTypeFloat 32\n"
16968                 // Custom types
16969                 "${compositeDecl}"
16970                 // %u32vec3 if not already declared in ${compositeDecl}
16971                 "${u32vec3Decl:opt}"
16972                 "%uvec3ptr  = OpTypePointer Input %u32vec3\n"
16973                 // Inherited from composite
16974                 "%composite_p = OpTypePointer Function ${compositeType}\n"
16975                 "%struct_t  = OpTypeStruct${structType}\n"
16976                 "%struct_p  = OpTypePointer Function %struct_t\n"
16977                 // Constants
16978                 "${filler}"
16979                 "${accessChainConstDeclaration}"
16980                 // Inherited from custom
16981                 "%customptr = OpTypePointer Uniform ${customType}\n"
16982                 "%customarr = OpTypeRuntimeArray ${customType}\n"
16983                 "%buf       = OpTypeStruct %customarr\n"
16984                 "%bufptr    = OpTypePointer Uniform %buf\n"
16985                 "%indata    = OpVariable %bufptr Uniform\n"
16986                 "%outdata   = OpVariable %bufptr Uniform\n"
16987
16988                 "%id        = OpVariable %uvec3ptr Input\n"
16989                 "%zero      = OpConstant %u32 0\n"
16990                 "%main      = OpFunction %void None %voidf\n"
16991                 "%label     = OpLabel\n"
16992                 "%struct_v  = OpVariable %struct_p Function\n"
16993                 "%idval     = OpLoad %u32vec3 %id\n"
16994                 "%x         = OpCompositeExtract %u32 %idval 0\n"
16995                 // Create the input/output type
16996                 "%inloc     = OpInBoundsAccessChain %customptr %indata %zero %x\n"
16997                 "%outloc    = OpInBoundsAccessChain %customptr %outdata %zero %x\n"
16998                 // Read the input value
16999                 "%inval     = OpLoad ${customType} %inloc\n"
17000                 // Create the composite and fill it
17001                 "${compositeConstruct}"
17002                 // Create the struct and fill it with the composite
17003                 "%struct    = OpCompositeConstruct %struct_t${structConstruct}\n"
17004                 // Insert the value
17005                 "%comp_obj  = OpCompositeInsert %struct_t %inval %struct ${insertIndexes}\n"
17006                 // Store the object
17007                 "             OpStore %struct_v %comp_obj\n"
17008                 // Get deepest possible composite pointer
17009                 "%inner_ptr = OpInBoundsAccessChain %composite_p %struct_v${accessChainIndexes}\n"
17010                 "%read_obj  = OpLoad ${compositeType} %inner_ptr\n"
17011                 // Read back the stored value
17012                 "%read_val  = OpCompositeExtract ${customType} %read_obj${extractIndexes}\n"
17013                 "             OpStore %outloc %read_val\n"
17014                 "             OpReturn\n"
17015                 "             OpFunctionEnd\n"
17016         ).specialize(parameters);
17017 }
17018
17019 tcu::TestCaseGroup* createOpInBoundsAccessChainGroup (tcu::TestContext& testCtx)
17020 {
17021         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opinboundsaccesschain", "Test the OpInBoundsAccessChain instruction"));
17022         de::Random                                              rnd                             (deStringHash(group->getName()));
17023
17024         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17025         {
17026                 NumberType                                              numberType      = NumberType(type);
17027                 const string                                    typeName        = getNumberTypeName(numberType);
17028                 const string                                    description     = "Test the OpInBoundsAccessChain instruction with " + typeName + "s";
17029                 de::MovePtr<tcu::TestCaseGroup> subGroup        (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17030
17031                 vector<map<string, string> >    testCases;
17032                 createCompositeCases(testCases, rnd, numberType);
17033
17034                 for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
17035                 {
17036                         ComputeShaderSpec       spec;
17037
17038                         // Number of components inside of a struct
17039                         deUint32 structComponents = rnd.getInt(2, 8);
17040                         // Component index value
17041                         deUint32 structIndex = rnd.getInt(0, structComponents - 1);
17042                         AssemblyStructInfo structInfo(structComponents, structIndex);
17043
17044                         spec.assembly = specializeInBoundsShaderTemplate(numberType, structInfo, *test);
17045
17046                         switch (numberType)
17047                         {
17048                                 case NUMBERTYPE_INT32:
17049                                 {
17050                                         deInt32 number = getInt(rnd);
17051                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17052                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17053                                         break;
17054                                 }
17055                                 case NUMBERTYPE_UINT32:
17056                                 {
17057                                         deUint32 number = rnd.getUint32();
17058                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17059                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17060                                         break;
17061                                 }
17062                                 case NUMBERTYPE_FLOAT32:
17063                                 {
17064                                         float number = rnd.getFloat();
17065                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
17066                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
17067                                         break;
17068                                 }
17069                                 default:
17070                                         DE_ASSERT(false);
17071                         }
17072                         spec.numWorkGroups = IVec3(1, 1, 1);
17073                         subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpInBoundsAccessChain test", spec));
17074                 }
17075                 group->addChild(subGroup.release());
17076         }
17077         return group.release();
17078 }
17079
17080 // If the params missing, uninitialized case
17081 const string specializeDefaultOutputShaderTemplate (const NumberType type, const map<string, string>& params = map<string, string>())
17082 {
17083         map<string, string> parameters(params);
17084
17085         parameters["customType"]        = getAssemblyTypeName(type);
17086
17087         // Declare the const value, and use it in the initializer
17088         if (params.find("constValue") != params.end())
17089         {
17090                 parameters["variableInitializer"]       = " %const";
17091         }
17092         // Uninitialized case
17093         else
17094         {
17095                 parameters["commentDecl"]       = ";";
17096         }
17097
17098         return StringTemplate(
17099                 "OpCapability Shader\n"
17100                 "OpMemoryModel Logical GLSL450\n"
17101                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17102                 "OpExecutionMode %main LocalSize 1 1 1\n"
17103                 "OpSource GLSL 430\n"
17104                 "OpName %main           \"main\"\n"
17105                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17106                 // Decorators
17107                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17108                 "OpDecorate %indata DescriptorSet 0\n"
17109                 "OpDecorate %indata Binding 0\n"
17110                 "OpDecorate %outdata DescriptorSet 0\n"
17111                 "OpDecorate %outdata Binding 1\n"
17112                 "OpDecorate %in_arr ArrayStride 4\n"
17113                 "OpDecorate %in_buf BufferBlock\n"
17114                 "OpMemberDecorate %in_buf 0 Offset 0\n"
17115                 // Base types
17116                 "%void       = OpTypeVoid\n"
17117                 "%voidf      = OpTypeFunction %void\n"
17118                 "%u32        = OpTypeInt 32 0\n"
17119                 "%i32        = OpTypeInt 32 1\n"
17120                 "%f32        = OpTypeFloat 32\n"
17121                 "%uvec3      = OpTypeVector %u32 3\n"
17122                 "%uvec3ptr   = OpTypePointer Input %uvec3\n"
17123                 "${commentDecl:opt}%const      = OpConstant ${customType} ${constValue:opt}\n"
17124                 // Derived types
17125                 "%in_ptr     = OpTypePointer Uniform ${customType}\n"
17126                 "%in_arr     = OpTypeRuntimeArray ${customType}\n"
17127                 "%in_buf     = OpTypeStruct %in_arr\n"
17128                 "%in_bufptr  = OpTypePointer Uniform %in_buf\n"
17129                 "%indata     = OpVariable %in_bufptr Uniform\n"
17130                 "%outdata    = OpVariable %in_bufptr Uniform\n"
17131                 "%id         = OpVariable %uvec3ptr Input\n"
17132                 "%var_ptr    = OpTypePointer Function ${customType}\n"
17133                 // Constants
17134                 "%zero       = OpConstant %i32 0\n"
17135                 // Main function
17136                 "%main       = OpFunction %void None %voidf\n"
17137                 "%label      = OpLabel\n"
17138                 "%out_var    = OpVariable %var_ptr Function${variableInitializer:opt}\n"
17139                 "%idval      = OpLoad %uvec3 %id\n"
17140                 "%x          = OpCompositeExtract %u32 %idval 0\n"
17141                 "%inloc      = OpAccessChain %in_ptr %indata %zero %x\n"
17142                 "%outloc     = OpAccessChain %in_ptr %outdata %zero %x\n"
17143
17144                 "%outval     = OpLoad ${customType} %out_var\n"
17145                 "              OpStore %outloc %outval\n"
17146                 "              OpReturn\n"
17147                 "              OpFunctionEnd\n"
17148         ).specialize(parameters);
17149 }
17150
17151 bool compareFloats (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
17152 {
17153         DE_ASSERT(outputAllocs.size() != 0);
17154         DE_ASSERT(outputAllocs.size() == expectedOutputs.size());
17155
17156         // Use custom epsilon because of the float->string conversion
17157         const float     epsilon = 0.00001f;
17158
17159         for (size_t outputNdx = 0; outputNdx < outputAllocs.size(); ++outputNdx)
17160         {
17161                 vector<deUint8> expectedBytes;
17162                 float                   expected;
17163                 float                   actual;
17164
17165                 expectedOutputs[outputNdx].getBytes(expectedBytes);
17166                 memcpy(&expected, &expectedBytes.front(), expectedBytes.size());
17167                 memcpy(&actual, outputAllocs[outputNdx]->getHostPtr(), expectedBytes.size());
17168
17169                 // Test with epsilon
17170                 if (fabs(expected - actual) > epsilon)
17171                 {
17172                         log << TestLog::Message << "Error: The actual and expected values not matching."
17173                                 << " Expected: " << expected << " Actual: " << actual << " Epsilon: " << epsilon << TestLog::EndMessage;
17174                         return false;
17175                 }
17176         }
17177         return true;
17178 }
17179
17180 // Checks if the driver crash with uninitialized cases
17181 bool passthruVerify (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
17182 {
17183         DE_ASSERT(outputAllocs.size() != 0);
17184         DE_ASSERT(outputAllocs.size() == expectedOutputs.size());
17185
17186         // Copy and discard the result.
17187         for (size_t outputNdx = 0; outputNdx < outputAllocs.size(); ++outputNdx)
17188         {
17189                 vector<deUint8> expectedBytes;
17190                 expectedOutputs[outputNdx].getBytes(expectedBytes);
17191
17192                 const size_t    width                   = expectedBytes.size();
17193                 vector<char>    data                    (width);
17194
17195                 memcpy(&data[0], outputAllocs[outputNdx]->getHostPtr(), width);
17196         }
17197         return true;
17198 }
17199
17200 tcu::TestCaseGroup* createShaderDefaultOutputGroup (tcu::TestContext& testCtx)
17201 {
17202         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "shader_default_output", "Test shader default output."));
17203         de::Random                                              rnd             (deStringHash(group->getName()));
17204
17205         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17206         {
17207                 NumberType                                              numberType      = NumberType(type);
17208                 const string                                    typeName        = getNumberTypeName(numberType);
17209                 const string                                    description     = "Test the OpVariable initializer with " + typeName + ".";
17210                 de::MovePtr<tcu::TestCaseGroup> subGroup        (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17211
17212                 // 2 similar subcases (initialized and uninitialized)
17213                 for (int subCase = 0; subCase < 2; ++subCase)
17214                 {
17215                         ComputeShaderSpec spec;
17216                         spec.numWorkGroups = IVec3(1, 1, 1);
17217
17218                         map<string, string>                             params;
17219
17220                         switch (numberType)
17221                         {
17222                                 case NUMBERTYPE_INT32:
17223                                 {
17224                                         deInt32 number = getInt(rnd);
17225                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17226                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17227                                         params["constValue"] = numberToString(number);
17228                                         break;
17229                                 }
17230                                 case NUMBERTYPE_UINT32:
17231                                 {
17232                                         deUint32 number = rnd.getUint32();
17233                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17234                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17235                                         params["constValue"] = numberToString(number);
17236                                         break;
17237                                 }
17238                                 case NUMBERTYPE_FLOAT32:
17239                                 {
17240                                         float number = rnd.getFloat();
17241                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
17242                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
17243                                         spec.verifyIO = &compareFloats;
17244                                         params["constValue"] = numberToString(number);
17245                                         break;
17246                                 }
17247                                 default:
17248                                         DE_ASSERT(false);
17249                         }
17250
17251                         // Initialized subcase
17252                         if (!subCase)
17253                         {
17254                                 spec.assembly = specializeDefaultOutputShaderTemplate(numberType, params);
17255                                 subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "initialized", "OpVariable initializer tests.", spec));
17256                         }
17257                         // Uninitialized subcase
17258                         else
17259                         {
17260                                 spec.assembly = specializeDefaultOutputShaderTemplate(numberType);
17261                                 spec.verifyIO = &passthruVerify;
17262                                 subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "uninitialized", "OpVariable initializer tests.", spec));
17263                         }
17264                 }
17265                 group->addChild(subGroup.release());
17266         }
17267         return group.release();
17268 }
17269
17270 tcu::TestCaseGroup* createOpNopTests (tcu::TestContext& testCtx)
17271 {
17272         de::MovePtr<tcu::TestCaseGroup> testGroup (new tcu::TestCaseGroup(testCtx, "opnop", "Test OpNop"));
17273         RGBA                                                    defaultColors[4];
17274         map<string, string>                             opNopFragments;
17275
17276         getDefaultColors(defaultColors);
17277
17278         opNopFragments["testfun"]               =
17279                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17280                 "%param1 = OpFunctionParameter %v4f32\n"
17281                 "%label_testfun = OpLabel\n"
17282                 "OpNop\n"
17283                 "OpNop\n"
17284                 "OpNop\n"
17285                 "OpNop\n"
17286                 "OpNop\n"
17287                 "OpNop\n"
17288                 "OpNop\n"
17289                 "OpNop\n"
17290                 "%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17291                 "%b = OpFAdd %f32 %a %a\n"
17292                 "OpNop\n"
17293                 "%c = OpFSub %f32 %b %a\n"
17294                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
17295                 "OpNop\n"
17296                 "OpNop\n"
17297                 "OpReturnValue %ret\n"
17298                 "OpFunctionEnd\n";
17299
17300         createTestsForAllStages("opnop", defaultColors, defaultColors, opNopFragments, testGroup.get());
17301
17302         return testGroup.release();
17303 }
17304
17305 tcu::TestCaseGroup* createOpNameTests (tcu::TestContext& testCtx)
17306 {
17307         de::MovePtr<tcu::TestCaseGroup> testGroup (new tcu::TestCaseGroup(testCtx, "opname","Test OpName"));
17308         RGBA                                                    defaultColors[4];
17309         map<string, string>                             opNameFragments;
17310
17311         getDefaultColors(defaultColors);
17312
17313         opNameFragments["debug"]                =
17314                 "OpName %BP_main \"not_main\"";
17315
17316         opNameFragments["testfun"]              =
17317                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17318                 "%param1 = OpFunctionParameter %v4f32\n"
17319                 "%label_func = OpLabel\n"
17320                 "%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17321                 "%b = OpFAdd %f32 %a %a\n"
17322                 "%c = OpFSub %f32 %b %a\n"
17323                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
17324                 "OpReturnValue %ret\n"
17325                 "OpFunctionEnd\n";
17326
17327         createTestsForAllStages("opname", defaultColors, defaultColors, opNameFragments, testGroup.get());
17328
17329         return testGroup.release();
17330 }
17331
17332 tcu::TestCaseGroup* createFloat16Tests (tcu::TestContext& testCtx)
17333 {
17334         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "float16", "Float 16 tests"));
17335
17336         testGroup->addChild(createOpConstantFloat16Tests(testCtx));
17337         testGroup->addChild(createFloat16LogicalSet<GraphicsResources>(testCtx, TEST_WITHOUT_NAN));
17338         testGroup->addChild(createFloat16FuncSet<GraphicsResources>(testCtx));
17339         testGroup->addChild(createDerivativeTests<256, 1>(testCtx));
17340         testGroup->addChild(createDerivativeTests<256, 2>(testCtx));
17341         testGroup->addChild(createDerivativeTests<256, 4>(testCtx));
17342         testGroup->addChild(createFloat16VectorExtractSet<GraphicsResources>(testCtx));
17343         testGroup->addChild(createFloat16VectorInsertSet<GraphicsResources>(testCtx));
17344         testGroup->addChild(createFloat16VectorShuffleSet<GraphicsResources>(testCtx));
17345         testGroup->addChild(createFloat16CompositeConstructSet<GraphicsResources>(testCtx));
17346         testGroup->addChild(createFloat16CompositeInsertExtractSet<GraphicsResources>(testCtx, "OpCompositeExtract"));
17347         testGroup->addChild(createFloat16CompositeInsertExtractSet<GraphicsResources>(testCtx, "OpCompositeInsert"));
17348         testGroup->addChild(createFloat16ArithmeticSet<GraphicsResources>(testCtx));
17349         testGroup->addChild(createFloat16ArithmeticSet<1, GraphicsResources>(testCtx));
17350         testGroup->addChild(createFloat16ArithmeticSet<2, GraphicsResources>(testCtx));
17351         testGroup->addChild(createFloat16ArithmeticSet<3, GraphicsResources>(testCtx));
17352         testGroup->addChild(createFloat16ArithmeticSet<4, GraphicsResources>(testCtx));
17353
17354         return testGroup.release();
17355 }
17356
17357 tcu::TestCaseGroup* createFloat16Group (tcu::TestContext& testCtx)
17358 {
17359         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "float16", "Float 16 tests"));
17360
17361         testGroup->addChild(createFloat16OpConstantCompositeGroup(testCtx));
17362         testGroup->addChild(createFloat16LogicalSet<ComputeShaderSpec>(testCtx, TEST_WITHOUT_NAN));
17363         testGroup->addChild(createFloat16FuncSet<ComputeShaderSpec>(testCtx));
17364         testGroup->addChild(createFloat16VectorExtractSet<ComputeShaderSpec>(testCtx));
17365         testGroup->addChild(createFloat16VectorInsertSet<ComputeShaderSpec>(testCtx));
17366         testGroup->addChild(createFloat16VectorShuffleSet<ComputeShaderSpec>(testCtx));
17367         testGroup->addChild(createFloat16CompositeConstructSet<ComputeShaderSpec>(testCtx));
17368         testGroup->addChild(createFloat16CompositeInsertExtractSet<ComputeShaderSpec>(testCtx, "OpCompositeExtract"));
17369         testGroup->addChild(createFloat16CompositeInsertExtractSet<ComputeShaderSpec>(testCtx, "OpCompositeInsert"));
17370         testGroup->addChild(createFloat16ArithmeticSet<ComputeShaderSpec>(testCtx));
17371         testGroup->addChild(createFloat16ArithmeticSet<1, ComputeShaderSpec>(testCtx));
17372         testGroup->addChild(createFloat16ArithmeticSet<2, ComputeShaderSpec>(testCtx));
17373         testGroup->addChild(createFloat16ArithmeticSet<3, ComputeShaderSpec>(testCtx));
17374         testGroup->addChild(createFloat16ArithmeticSet<4, ComputeShaderSpec>(testCtx));
17375
17376         return testGroup.release();
17377 }
17378
17379 tcu::TestCaseGroup* createInstructionTests (tcu::TestContext& testCtx)
17380 {
17381         const bool testComputePipeline = true;
17382
17383         de::MovePtr<tcu::TestCaseGroup> instructionTests        (new tcu::TestCaseGroup(testCtx, "instruction", "Instructions with special opcodes/operands"));
17384         de::MovePtr<tcu::TestCaseGroup> computeTests            (new tcu::TestCaseGroup(testCtx, "compute", "Compute Instructions with special opcodes/operands"));
17385         de::MovePtr<tcu::TestCaseGroup> graphicsTests           (new tcu::TestCaseGroup(testCtx, "graphics", "Graphics Instructions with special opcodes/operands"));
17386
17387         computeTests->addChild(createSpivVersionCheckTests(testCtx, testComputePipeline));
17388         computeTests->addChild(createLocalSizeGroup(testCtx));
17389         computeTests->addChild(createOpNopGroup(testCtx));
17390         computeTests->addChild(createOpFUnordGroup(testCtx));
17391         computeTests->addChild(createOpAtomicGroup(testCtx, false));
17392         computeTests->addChild(createOpAtomicGroup(testCtx, true));                                     // Using new StorageBuffer decoration
17393         computeTests->addChild(createOpAtomicGroup(testCtx, false, 1024, true));        // Return value validation
17394         computeTests->addChild(createOpLineGroup(testCtx));
17395         computeTests->addChild(createOpModuleProcessedGroup(testCtx));
17396         computeTests->addChild(createOpNoLineGroup(testCtx));
17397         computeTests->addChild(createOpConstantNullGroup(testCtx));
17398         computeTests->addChild(createOpConstantCompositeGroup(testCtx));
17399         computeTests->addChild(createOpConstantUsageGroup(testCtx));
17400         computeTests->addChild(createSpecConstantGroup(testCtx));
17401         computeTests->addChild(createOpSourceGroup(testCtx));
17402         computeTests->addChild(createOpSourceExtensionGroup(testCtx));
17403         computeTests->addChild(createDecorationGroupGroup(testCtx));
17404         computeTests->addChild(createOpPhiGroup(testCtx));
17405         computeTests->addChild(createLoopControlGroup(testCtx));
17406         computeTests->addChild(createFunctionControlGroup(testCtx));
17407         computeTests->addChild(createSelectionControlGroup(testCtx));
17408         computeTests->addChild(createBlockOrderGroup(testCtx));
17409         computeTests->addChild(createMultipleShaderGroup(testCtx));
17410         computeTests->addChild(createMemoryAccessGroup(testCtx));
17411         computeTests->addChild(createOpCopyMemoryGroup(testCtx));
17412         computeTests->addChild(createOpCopyObjectGroup(testCtx));
17413         computeTests->addChild(createNoContractionGroup(testCtx));
17414         computeTests->addChild(createOpUndefGroup(testCtx));
17415         computeTests->addChild(createOpUnreachableGroup(testCtx));
17416         computeTests->addChild(createOpQuantizeToF16Group(testCtx));
17417         computeTests->addChild(createOpFRemGroup(testCtx));
17418         computeTests->addChild(createOpSRemComputeGroup(testCtx, QP_TEST_RESULT_PASS));
17419         computeTests->addChild(createOpSRemComputeGroup64(testCtx, QP_TEST_RESULT_PASS));
17420         computeTests->addChild(createOpSModComputeGroup(testCtx, QP_TEST_RESULT_PASS));
17421         computeTests->addChild(createOpSModComputeGroup64(testCtx, QP_TEST_RESULT_PASS));
17422         computeTests->addChild(createConvertComputeTests(testCtx, "OpSConvert", "sconvert"));
17423         computeTests->addChild(createConvertComputeTests(testCtx, "OpUConvert", "uconvert"));
17424         computeTests->addChild(createConvertComputeTests(testCtx, "OpFConvert", "fconvert"));
17425         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertSToF", "convertstof"));
17426         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertFToS", "convertftos"));
17427         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertUToF", "convertutof"));
17428         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertFToU", "convertftou"));
17429         computeTests->addChild(createOpCompositeInsertGroup(testCtx));
17430         computeTests->addChild(createOpInBoundsAccessChainGroup(testCtx));
17431         computeTests->addChild(createShaderDefaultOutputGroup(testCtx));
17432         computeTests->addChild(createOpNMinGroup(testCtx));
17433         computeTests->addChild(createOpNMaxGroup(testCtx));
17434         computeTests->addChild(createOpNClampGroup(testCtx));
17435         {
17436                 de::MovePtr<tcu::TestCaseGroup> computeAndroidTests     (new tcu::TestCaseGroup(testCtx, "android", "Android CTS Tests"));
17437
17438                 computeAndroidTests->addChild(createOpSRemComputeGroup(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
17439                 computeAndroidTests->addChild(createOpSModComputeGroup(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
17440
17441                 computeTests->addChild(computeAndroidTests.release());
17442         }
17443
17444         computeTests->addChild(create8BitStorageComputeGroup(testCtx));
17445         computeTests->addChild(create16BitStorageComputeGroup(testCtx));
17446         computeTests->addChild(createFloatControlsComputeGroup(testCtx));
17447         computeTests->addChild(createUboMatrixPaddingComputeGroup(testCtx));
17448         computeTests->addChild(createVariableInitComputeGroup(testCtx));
17449         computeTests->addChild(createConditionalBranchComputeGroup(testCtx));
17450         computeTests->addChild(createIndexingComputeGroup(testCtx));
17451         computeTests->addChild(createVariablePointersComputeGroup(testCtx));
17452         computeTests->addChild(createImageSamplerComputeGroup(testCtx));
17453         computeTests->addChild(createOpNameGroup(testCtx));
17454         computeTests->addChild(createPointerParameterComputeGroup(testCtx));
17455         computeTests->addChild(createFloat16Group(testCtx));
17456
17457         graphicsTests->addChild(createCrossStageInterfaceTests(testCtx));
17458         graphicsTests->addChild(createSpivVersionCheckTests(testCtx, !testComputePipeline));
17459         graphicsTests->addChild(createOpNopTests(testCtx));
17460         graphicsTests->addChild(createOpSourceTests(testCtx));
17461         graphicsTests->addChild(createOpSourceContinuedTests(testCtx));
17462         graphicsTests->addChild(createOpModuleProcessedTests(testCtx));
17463         graphicsTests->addChild(createOpLineTests(testCtx));
17464         graphicsTests->addChild(createOpNoLineTests(testCtx));
17465         graphicsTests->addChild(createOpConstantNullTests(testCtx));
17466         graphicsTests->addChild(createOpConstantCompositeTests(testCtx));
17467         graphicsTests->addChild(createMemoryAccessTests(testCtx));
17468         graphicsTests->addChild(createOpUndefTests(testCtx));
17469         graphicsTests->addChild(createSelectionBlockOrderTests(testCtx));
17470         graphicsTests->addChild(createModuleTests(testCtx));
17471         graphicsTests->addChild(createSwitchBlockOrderTests(testCtx));
17472         graphicsTests->addChild(createOpPhiTests(testCtx));
17473         graphicsTests->addChild(createNoContractionTests(testCtx));
17474         graphicsTests->addChild(createOpQuantizeTests(testCtx));
17475         graphicsTests->addChild(createLoopTests(testCtx));
17476         graphicsTests->addChild(createSpecConstantTests(testCtx));
17477         graphicsTests->addChild(createSpecConstantOpQuantizeToF16Group(testCtx));
17478         graphicsTests->addChild(createBarrierTests(testCtx));
17479         graphicsTests->addChild(createDecorationGroupTests(testCtx));
17480         graphicsTests->addChild(createFRemTests(testCtx));
17481         graphicsTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
17482         graphicsTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
17483
17484         {
17485                 de::MovePtr<tcu::TestCaseGroup> graphicsAndroidTests    (new tcu::TestCaseGroup(testCtx, "android", "Android CTS Tests"));
17486
17487                 graphicsAndroidTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
17488                 graphicsAndroidTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
17489
17490                 graphicsTests->addChild(graphicsAndroidTests.release());
17491         }
17492         graphicsTests->addChild(createOpNameTests(testCtx));
17493
17494         graphicsTests->addChild(create8BitStorageGraphicsGroup(testCtx));
17495         graphicsTests->addChild(create16BitStorageGraphicsGroup(testCtx));
17496         graphicsTests->addChild(createFloatControlsGraphicsGroup(testCtx));
17497         graphicsTests->addChild(createUboMatrixPaddingGraphicsGroup(testCtx));
17498         graphicsTests->addChild(createVariableInitGraphicsGroup(testCtx));
17499         graphicsTests->addChild(createConditionalBranchGraphicsGroup(testCtx));
17500         graphicsTests->addChild(createIndexingGraphicsGroup(testCtx));
17501         graphicsTests->addChild(createVariablePointersGraphicsGroup(testCtx));
17502         graphicsTests->addChild(createImageSamplerGraphicsGroup(testCtx));
17503         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpSConvert", "sconvert"));
17504         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpUConvert", "uconvert"));
17505         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpFConvert", "fconvert"));
17506         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertSToF", "convertstof"));
17507         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertFToS", "convertftos"));
17508         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertUToF", "convertutof"));
17509         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertFToU", "convertftou"));
17510         graphicsTests->addChild(createPointerParameterGraphicsGroup(testCtx));
17511
17512         graphicsTests->addChild(createFloat16Tests(testCtx));
17513
17514         instructionTests->addChild(computeTests.release());
17515         instructionTests->addChild(graphicsTests.release());
17516
17517         return instructionTests.release();
17518 }
17519
17520 } // SpirVAssembly
17521 } // vkt