Merge remote-tracking branch 'khronos/master' into deqp-dev
[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 "tcuRGBA.hpp"
31 #include "tcuStringTemplate.hpp"
32 #include "tcuTestLog.hpp"
33 #include "tcuVectorUtil.hpp"
34 #include "tcuInterval.hpp"
35
36 #include "vkDefs.hpp"
37 #include "vkDeviceUtil.hpp"
38 #include "vkMemUtil.hpp"
39 #include "vkPlatform.hpp"
40 #include "vkPrograms.hpp"
41 #include "vkQueryUtil.hpp"
42 #include "vkRef.hpp"
43 #include "vkRefUtil.hpp"
44 #include "vkStrUtil.hpp"
45 #include "vkTypeUtil.hpp"
46
47 #include "deStringUtil.hpp"
48 #include "deUniquePtr.hpp"
49 #include "deMath.h"
50 #include "tcuStringTemplate.hpp"
51
52 #include "vktSpvAsmCrossStageInterfaceTests.hpp"
53 #include "vktSpvAsm8bitStorageTests.hpp"
54 #include "vktSpvAsm16bitStorageTests.hpp"
55 #include "vktSpvAsmUboMatrixPaddingTests.hpp"
56 #include "vktSpvAsmConditionalBranchTests.hpp"
57 #include "vktSpvAsmIndexingTests.hpp"
58 #include "vktSpvAsmImageSamplerTests.hpp"
59 #include "vktSpvAsmComputeShaderCase.hpp"
60 #include "vktSpvAsmComputeShaderTestUtil.hpp"
61 #include "vktSpvAsmGraphicsShaderTestUtil.hpp"
62 #include "vktSpvAsmVariablePointersTests.hpp"
63 #include "vktSpvAsmVariableInitTests.hpp"
64 #include "vktSpvAsmPointerParameterTests.hpp"
65 #include "vktSpvAsmSpirvVersionTests.hpp"
66 #include "vktTestCaseUtil.hpp"
67 #include "vktSpvAsmLoopDepLenTests.hpp"
68 #include "vktSpvAsmLoopDepInfTests.hpp"
69
70 #include <cmath>
71 #include <limits>
72 #include <map>
73 #include <string>
74 #include <sstream>
75 #include <utility>
76 #include <stack>
77
78 namespace vkt
79 {
80 namespace SpirVAssembly
81 {
82
83 namespace
84 {
85
86 using namespace vk;
87 using std::map;
88 using std::string;
89 using std::vector;
90 using tcu::IVec3;
91 using tcu::IVec4;
92 using tcu::RGBA;
93 using tcu::TestLog;
94 using tcu::TestStatus;
95 using tcu::Vec4;
96 using de::UniquePtr;
97 using tcu::StringTemplate;
98 using tcu::Vec4;
99
100 template<typename T>
101 static void fillRandomScalars (de::Random& rnd, T minValue, T maxValue, void* dst, int numValues, int offset = 0)
102 {
103         T* const typedPtr = (T*)dst;
104         for (int ndx = 0; ndx < numValues; ndx++)
105                 typedPtr[offset + ndx] = randomScalar<T>(rnd, minValue, maxValue);
106 }
107
108 // Filter is a function that returns true if a value should pass, false otherwise.
109 template<typename T, typename FilterT>
110 static void fillRandomScalars (de::Random& rnd, T minValue, T maxValue, void* dst, int numValues, FilterT filter, int offset = 0)
111 {
112         T* const typedPtr = (T*)dst;
113         T value;
114         for (int ndx = 0; ndx < numValues; ndx++)
115         {
116                 do
117                         value = randomScalar<T>(rnd, minValue, maxValue);
118                 while (!filter(value));
119
120                 typedPtr[offset + ndx] = value;
121         }
122 }
123
124 // Gets a 64-bit integer with a more logarithmic distribution
125 deInt64 randomInt64LogDistributed (de::Random& rnd)
126 {
127         deInt64 val = rnd.getUint64();
128         val &= (1ull << rnd.getInt(1, 63)) - 1;
129         if (rnd.getBool())
130                 val = -val;
131         return val;
132 }
133
134 static void fillRandomInt64sLogDistributed (de::Random& rnd, vector<deInt64>& dst, int numValues)
135 {
136         for (int ndx = 0; ndx < numValues; ndx++)
137                 dst[ndx] = randomInt64LogDistributed(rnd);
138 }
139
140 template<typename FilterT>
141 static void fillRandomInt64sLogDistributed (de::Random& rnd, vector<deInt64>& dst, int numValues, FilterT filter)
142 {
143         for (int ndx = 0; ndx < numValues; ndx++)
144         {
145                 deInt64 value;
146                 do {
147                         value = randomInt64LogDistributed(rnd);
148                 } while (!filter(value));
149                 dst[ndx] = value;
150         }
151 }
152
153 inline bool filterNonNegative (const deInt64 value)
154 {
155         return value >= 0;
156 }
157
158 inline bool filterPositive (const deInt64 value)
159 {
160         return value > 0;
161 }
162
163 inline bool filterNotZero (const deInt64 value)
164 {
165         return value != 0;
166 }
167
168 static void floorAll (vector<float>& values)
169 {
170         for (size_t i = 0; i < values.size(); i++)
171                 values[i] = deFloatFloor(values[i]);
172 }
173
174 static void floorAll (vector<Vec4>& values)
175 {
176         for (size_t i = 0; i < values.size(); i++)
177                 values[i] = floor(values[i]);
178 }
179
180 struct CaseParameter
181 {
182         const char*             name;
183         string                  param;
184
185         CaseParameter   (const char* case_, const string& param_) : name(case_), param(param_) {}
186 };
187
188 // Assembly code used for testing LocalSize, OpNop, OpConstant{Null|Composite}, Op[No]Line, OpSource[Continued], OpSourceExtension, OpUndef is based on GLSL source code:
189 //
190 // #version 430
191 //
192 // layout(std140, set = 0, binding = 0) readonly buffer Input {
193 //   float elements[];
194 // } input_data;
195 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
196 //   float elements[];
197 // } output_data;
198 //
199 // layout (local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
200 //
201 // void main() {
202 //   uint x = gl_GlobalInvocationID.x;
203 //   output_data.elements[x] = -input_data.elements[x];
204 // }
205
206 static string getAsmForLocalSizeTest(bool useLiteralLocalSize, bool useSpecConstantWorkgroupSize, IVec3 workGroupSize, deUint32 ndx)
207 {
208         std::ostringstream out;
209         out << getComputeAsmShaderPreambleWithoutLocalSize();
210
211         if (useLiteralLocalSize)
212         {
213                 out << "OpExecutionMode %main LocalSize "
214                         << workGroupSize.x() << " " << workGroupSize.y() << " " << workGroupSize.z() << "\n";
215         }
216
217         out << "OpSource GLSL 430\n"
218                 "OpName %main           \"main\"\n"
219                 "OpName %id             \"gl_GlobalInvocationID\"\n"
220                 "OpDecorate %id BuiltIn GlobalInvocationId\n";
221
222         if (useSpecConstantWorkgroupSize)
223         {
224                 out << "OpDecorate %spec_0 SpecId 100\n"
225                         << "OpDecorate %spec_1 SpecId 101\n"
226                         << "OpDecorate %spec_2 SpecId 102\n"
227                         << "OpDecorate %gl_WorkGroupSize BuiltIn WorkgroupSize\n";
228         }
229
230         out << getComputeAsmInputOutputBufferTraits()
231                 << getComputeAsmCommonTypes()
232                 << getComputeAsmInputOutputBuffer()
233                 << "%id        = OpVariable %uvec3ptr Input\n"
234                 << "%zero      = OpConstant %i32 0 \n";
235
236         if (useSpecConstantWorkgroupSize)
237         {
238                 out     << "%spec_0   = OpSpecConstant %u32 "<< workGroupSize.x() << "\n"
239                         << "%spec_1   = OpSpecConstant %u32 "<< workGroupSize.y() << "\n"
240                         << "%spec_2   = OpSpecConstant %u32 "<< workGroupSize.z() << "\n"
241                         << "%gl_WorkGroupSize = OpSpecConstantComposite %uvec3 %spec_0 %spec_1 %spec_2\n";
242         }
243
244         out << "%main      = OpFunction %void None %voidf\n"
245                 << "%label     = OpLabel\n"
246                 << "%idval     = OpLoad %uvec3 %id\n"
247                 << "%ndx         = OpCompositeExtract %u32 %idval " << ndx << "\n"
248
249                         "%inloc     = OpAccessChain %f32ptr %indata %zero %ndx\n"
250                         "%inval     = OpLoad %f32 %inloc\n"
251                         "%neg       = OpFNegate %f32 %inval\n"
252                         "%outloc    = OpAccessChain %f32ptr %outdata %zero %ndx\n"
253                         "             OpStore %outloc %neg\n"
254                         "             OpReturn\n"
255                         "             OpFunctionEnd\n";
256         return out.str();
257 }
258
259 tcu::TestCaseGroup* createLocalSizeGroup (tcu::TestContext& testCtx)
260 {
261         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "localsize", ""));
262         ComputeShaderSpec                               spec;
263         de::Random                                              rnd                             (deStringHash(group->getName()));
264         const deUint32                                  numElements             = 64u;
265         vector<float>                                   positiveFloats  (numElements, 0);
266         vector<float>                                   negativeFloats  (numElements, 0);
267
268         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
269
270         for (size_t ndx = 0; ndx < numElements; ++ndx)
271                 negativeFloats[ndx] = -positiveFloats[ndx];
272
273         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
274         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
275
276         spec.numWorkGroups = IVec3(numElements, 1, 1);
277
278         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, 1, 1), 0u);
279         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize", "", spec));
280
281         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, 1, 1), 0u);
282         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize", "", spec));
283
284         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, 1, 1), 0u);
285         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize", "", spec));
286
287         spec.numWorkGroups = IVec3(1, 1, 1);
288
289         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(numElements, 1, 1), 0u);
290         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_x", "", spec));
291
292         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(numElements, 1, 1), 0u);
293         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_x", "", spec));
294
295         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(numElements, 1, 1), 0u);
296         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_x", "", spec));
297
298         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, numElements, 1), 1u);
299         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_y", "", spec));
300
301         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, numElements, 1), 1u);
302         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_y", "", spec));
303
304         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, numElements, 1), 1u);
305         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_y", "", spec));
306
307         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, 1, numElements), 2u);
308         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_z", "", spec));
309
310         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, 1, numElements), 2u);
311         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_z", "", spec));
312
313         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, 1, numElements), 2u);
314         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_z", "", spec));
315
316         return group.release();
317 }
318
319 tcu::TestCaseGroup* createOpNopGroup (tcu::TestContext& testCtx)
320 {
321         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnop", "Test the OpNop instruction"));
322         ComputeShaderSpec                               spec;
323         de::Random                                              rnd                             (deStringHash(group->getName()));
324         const int                                               numElements             = 100;
325         vector<float>                                   positiveFloats  (numElements, 0);
326         vector<float>                                   negativeFloats  (numElements, 0);
327
328         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
329
330         for (size_t ndx = 0; ndx < numElements; ++ndx)
331                 negativeFloats[ndx] = -positiveFloats[ndx];
332
333         spec.assembly =
334                 string(getComputeAsmShaderPreamble()) +
335
336                 "OpSource GLSL 430\n"
337                 "OpName %main           \"main\"\n"
338                 "OpName %id             \"gl_GlobalInvocationID\"\n"
339
340                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
341
342                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes())
343
344                 + string(getComputeAsmInputOutputBuffer()) +
345
346                 "%id        = OpVariable %uvec3ptr Input\n"
347                 "%zero      = OpConstant %i32 0\n"
348
349                 "%main      = OpFunction %void None %voidf\n"
350                 "%label     = OpLabel\n"
351                 "%idval     = OpLoad %uvec3 %id\n"
352                 "%x         = OpCompositeExtract %u32 %idval 0\n"
353
354                 "             OpNop\n" // Inside a function body
355
356                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
357                 "%inval     = OpLoad %f32 %inloc\n"
358                 "%neg       = OpFNegate %f32 %inval\n"
359                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
360                 "             OpStore %outloc %neg\n"
361                 "             OpReturn\n"
362                 "             OpFunctionEnd\n";
363         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
364         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
365         spec.numWorkGroups = IVec3(numElements, 1, 1);
366
367         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpNop appearing at different places", spec));
368
369         return group.release();
370 }
371
372 bool compareFUnord (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
373 {
374         if (outputAllocs.size() != 1)
375                 return false;
376
377         vector<deUint8> input1Bytes;
378         vector<deUint8> input2Bytes;
379         vector<deUint8> expectedBytes;
380
381         inputs[0].getBytes(input1Bytes);
382         inputs[1].getBytes(input2Bytes);
383         expectedOutputs[0].getBytes(expectedBytes);
384
385         const deInt32* const    expectedOutputAsInt             = reinterpret_cast<const deInt32*>(&expectedBytes.front());
386         const deInt32* const    outputAsInt                             = static_cast<const deInt32*>(outputAllocs[0]->getHostPtr());
387         const float* const              input1AsFloat                   = reinterpret_cast<const float*>(&input1Bytes.front());
388         const float* const              input2AsFloat                   = reinterpret_cast<const float*>(&input2Bytes.front());
389         bool returnValue                                                                = true;
390
391         for (size_t idx = 0; idx < expectedBytes.size() / sizeof(deInt32); ++idx)
392         {
393                 if (outputAsInt[idx] != expectedOutputAsInt[idx])
394                 {
395                         log << TestLog::Message << "ERROR: Sub-case failed. inputs: " << input1AsFloat[idx] << "," << input2AsFloat[idx] << " output: " << outputAsInt[idx]<< " expected output: " << expectedOutputAsInt[idx] << TestLog::EndMessage;
396                         returnValue = false;
397                 }
398         }
399         return returnValue;
400 }
401
402 typedef VkBool32 (*compareFuncType) (float, float);
403
404 struct OpFUnordCase
405 {
406         const char*             name;
407         const char*             opCode;
408         compareFuncType compareFunc;
409
410                                         OpFUnordCase                    (const char* _name, const char* _opCode, compareFuncType _compareFunc)
411                                                 : name                          (_name)
412                                                 , opCode                        (_opCode)
413                                                 , compareFunc           (_compareFunc) {}
414 };
415
416 #define ADD_OPFUNORD_CASE(NAME, OPCODE, OPERATOR) \
417 do { \
418         struct compare_##NAME { static VkBool32 compare(float x, float y) { return (x OPERATOR y) ? VK_TRUE : VK_FALSE; } }; \
419         cases.push_back(OpFUnordCase(#NAME, OPCODE, compare_##NAME::compare)); \
420 } while (deGetFalse())
421
422 tcu::TestCaseGroup* createOpFUnordGroup (tcu::TestContext& testCtx)
423 {
424         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opfunord", "Test the OpFUnord* opcodes"));
425         de::Random                                              rnd                             (deStringHash(group->getName()));
426         const int                                               numElements             = 100;
427         vector<OpFUnordCase>                    cases;
428
429         const StringTemplate                    shaderTemplate  (
430
431                 string(getComputeAsmShaderPreamble()) +
432
433                 "OpSource GLSL 430\n"
434                 "OpName %main           \"main\"\n"
435                 "OpName %id             \"gl_GlobalInvocationID\"\n"
436
437                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
438
439                 "OpDecorate %buf BufferBlock\n"
440                 "OpDecorate %buf2 BufferBlock\n"
441                 "OpDecorate %indata1 DescriptorSet 0\n"
442                 "OpDecorate %indata1 Binding 0\n"
443                 "OpDecorate %indata2 DescriptorSet 0\n"
444                 "OpDecorate %indata2 Binding 1\n"
445                 "OpDecorate %outdata DescriptorSet 0\n"
446                 "OpDecorate %outdata Binding 2\n"
447                 "OpDecorate %f32arr ArrayStride 4\n"
448                 "OpDecorate %i32arr ArrayStride 4\n"
449                 "OpMemberDecorate %buf 0 Offset 0\n"
450                 "OpMemberDecorate %buf2 0 Offset 0\n"
451
452                 + string(getComputeAsmCommonTypes()) +
453
454                 "%buf        = OpTypeStruct %f32arr\n"
455                 "%bufptr     = OpTypePointer Uniform %buf\n"
456                 "%indata1    = OpVariable %bufptr Uniform\n"
457                 "%indata2    = OpVariable %bufptr Uniform\n"
458
459                 "%buf2       = OpTypeStruct %i32arr\n"
460                 "%buf2ptr    = OpTypePointer Uniform %buf2\n"
461                 "%outdata    = OpVariable %buf2ptr Uniform\n"
462
463                 "%id        = OpVariable %uvec3ptr Input\n"
464                 "%zero      = OpConstant %i32 0\n"
465                 "%consti1   = OpConstant %i32 1\n"
466                 "%constf1   = OpConstant %f32 1.0\n"
467
468                 "%main      = OpFunction %void None %voidf\n"
469                 "%label     = OpLabel\n"
470                 "%idval     = OpLoad %uvec3 %id\n"
471                 "%x         = OpCompositeExtract %u32 %idval 0\n"
472
473                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
474                 "%inval1    = OpLoad %f32 %inloc1\n"
475                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
476                 "%inval2    = OpLoad %f32 %inloc2\n"
477                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
478
479                 "%result    = ${OPCODE} %bool %inval1 %inval2\n"
480                 "%int_res   = OpSelect %i32 %result %consti1 %zero\n"
481                 "             OpStore %outloc %int_res\n"
482
483                 "             OpReturn\n"
484                 "             OpFunctionEnd\n");
485
486         ADD_OPFUNORD_CASE(equal, "OpFUnordEqual", ==);
487         ADD_OPFUNORD_CASE(less, "OpFUnordLessThan", <);
488         ADD_OPFUNORD_CASE(lessequal, "OpFUnordLessThanEqual", <=);
489         ADD_OPFUNORD_CASE(greater, "OpFUnordGreaterThan", >);
490         ADD_OPFUNORD_CASE(greaterequal, "OpFUnordGreaterThanEqual", >=);
491         ADD_OPFUNORD_CASE(notequal, "OpFUnordNotEqual", !=);
492
493         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
494         {
495                 map<string, string>                     specializations;
496                 ComputeShaderSpec                       spec;
497                 const float                                     NaN                             = std::numeric_limits<float>::quiet_NaN();
498                 vector<float>                           inputFloats1    (numElements, 0);
499                 vector<float>                           inputFloats2    (numElements, 0);
500                 vector<deInt32>                         expectedInts    (numElements, 0);
501
502                 specializations["OPCODE"]       = cases[caseNdx].opCode;
503                 spec.assembly                           = shaderTemplate.specialize(specializations);
504
505                 fillRandomScalars(rnd, 1.f, 100.f, &inputFloats1[0], numElements);
506                 for (size_t ndx = 0; ndx < numElements; ++ndx)
507                 {
508                         switch (ndx % 6)
509                         {
510                                 case 0:         inputFloats2[ndx] = inputFloats1[ndx] + 1.0f; break;
511                                 case 1:         inputFloats2[ndx] = inputFloats1[ndx] - 1.0f; break;
512                                 case 2:         inputFloats2[ndx] = inputFloats1[ndx]; break;
513                                 case 3:         inputFloats2[ndx] = NaN; break;
514                                 case 4:         inputFloats2[ndx] = inputFloats1[ndx];  inputFloats1[ndx] = NaN; break;
515                                 case 5:         inputFloats2[ndx] = NaN;                                inputFloats1[ndx] = NaN; break;
516                         }
517                         expectedInts[ndx] = tcu::Float32(inputFloats1[ndx]).isNaN() || tcu::Float32(inputFloats2[ndx]).isNaN() || cases[caseNdx].compareFunc(inputFloats1[ndx], inputFloats2[ndx]);
518                 }
519
520                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
521                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
522                 spec.outputs.push_back(BufferSp(new Int32Buffer(expectedInts)));
523                 spec.numWorkGroups = IVec3(numElements, 1, 1);
524                 spec.verifyIO = &compareFUnord;
525                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
526         }
527
528         return group.release();
529 }
530
531 struct OpAtomicCase
532 {
533         const char*             name;
534         const char*             assembly;
535         const char*             retValAssembly;
536         OpAtomicType    opAtomic;
537         deInt32                 numOutputElements;
538
539                                         OpAtomicCase(const char* _name, const char* _assembly, const char* _retValAssembly, OpAtomicType _opAtomic, deInt32 _numOutputElements)
540                                                 : name                          (_name)
541                                                 , assembly                      (_assembly)
542                                                 , retValAssembly        (_retValAssembly)
543                                                 , opAtomic                      (_opAtomic)
544                                                 , numOutputElements     (_numOutputElements) {}
545 };
546
547 tcu::TestCaseGroup* createOpAtomicGroup (tcu::TestContext& testCtx, bool useStorageBuffer, int numElements = 65535, bool verifyReturnValues = false)
548 {
549         std::string                                             groupName                       ("opatomic");
550         if (useStorageBuffer)
551                 groupName += "_storage_buffer";
552         if (verifyReturnValues)
553                 groupName += "_return_values";
554         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Test the OpAtomic* opcodes"));
555         vector<OpAtomicCase>                    cases;
556
557         const StringTemplate                    shaderTemplate  (
558
559                 string("OpCapability Shader\n") +
560                 (useStorageBuffer ? "OpExtension \"SPV_KHR_storage_buffer_storage_class\"\n" : "") +
561                 "OpMemoryModel Logical GLSL450\n"
562                 "OpEntryPoint GLCompute %main \"main\" %id\n"
563                 "OpExecutionMode %main LocalSize 1 1 1\n" +
564
565                 "OpSource GLSL 430\n"
566                 "OpName %main           \"main\"\n"
567                 "OpName %id             \"gl_GlobalInvocationID\"\n"
568
569                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
570
571                 "OpDecorate %buf ${BLOCK_DECORATION}\n"
572                 "OpDecorate %indata DescriptorSet 0\n"
573                 "OpDecorate %indata Binding 0\n"
574                 "OpDecorate %i32arr ArrayStride 4\n"
575                 "OpMemberDecorate %buf 0 Offset 0\n"
576
577                 "OpDecorate %sumbuf ${BLOCK_DECORATION}\n"
578                 "OpDecorate %sum DescriptorSet 0\n"
579                 "OpDecorate %sum Binding 1\n"
580                 "OpMemberDecorate %sumbuf 0 Coherent\n"
581                 "OpMemberDecorate %sumbuf 0 Offset 0\n"
582
583                 "${RETVAL_BUF_DECORATE}"
584
585                 + getComputeAsmCommonTypes("${BLOCK_POINTER_TYPE}") +
586
587                 "%buf       = OpTypeStruct %i32arr\n"
588                 "%bufptr    = OpTypePointer ${BLOCK_POINTER_TYPE} %buf\n"
589                 "%indata    = OpVariable %bufptr ${BLOCK_POINTER_TYPE}\n"
590
591                 "%sumbuf    = OpTypeStruct %i32arr\n"
592                 "%sumbufptr = OpTypePointer ${BLOCK_POINTER_TYPE} %sumbuf\n"
593                 "%sum       = OpVariable %sumbufptr ${BLOCK_POINTER_TYPE}\n"
594
595                 "${RETVAL_BUF_DECL}"
596
597                 "%id        = OpVariable %uvec3ptr Input\n"
598                 "%minusone  = OpConstant %i32 -1\n"
599                 "%zero      = OpConstant %i32 0\n"
600                 "%one       = OpConstant %u32 1\n"
601                 "%two       = OpConstant %i32 2\n"
602
603                 "%main      = OpFunction %void None %voidf\n"
604                 "%label     = OpLabel\n"
605                 "%idval     = OpLoad %uvec3 %id\n"
606                 "%x         = OpCompositeExtract %u32 %idval 0\n"
607
608                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
609                 "%inval     = OpLoad %i32 %inloc\n"
610
611                 "%outloc    = OpAccessChain %i32ptr %sum %zero ${INDEX}\n"
612                 "${INSTRUCTION}"
613                 "${RETVAL_ASSEMBLY}"
614
615                 "             OpReturn\n"
616                 "             OpFunctionEnd\n");
617
618         #define ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, NUM_OUTPUT_ELEMENTS) \
619         do { \
620                 DE_ASSERT((NUM_OUTPUT_ELEMENTS) == 1 || (NUM_OUTPUT_ELEMENTS) == numElements); \
621                 cases.push_back(OpAtomicCase(#NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, NUM_OUTPUT_ELEMENTS)); \
622         } while (deGetFalse())
623         #define ADD_OPATOMIC_CASE_1(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, 1)
624         #define ADD_OPATOMIC_CASE_N(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, numElements)
625
626         ADD_OPATOMIC_CASE_1(iadd,       "%retv      = OpAtomicIAdd %i32 %outloc %one %zero %inval\n",
627                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IADD );
628         ADD_OPATOMIC_CASE_1(isub,       "%retv      = OpAtomicISub %i32 %outloc %one %zero %inval\n",
629                                                                 "             OpStore %retloc %retv\n", OPATOMIC_ISUB );
630         ADD_OPATOMIC_CASE_1(iinc,       "%retv      = OpAtomicIIncrement %i32 %outloc %one %zero\n",
631                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IINC );
632         ADD_OPATOMIC_CASE_1(idec,       "%retv      = OpAtomicIDecrement %i32 %outloc %one %zero\n",
633                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IDEC );
634         if (!verifyReturnValues)
635         {
636                 ADD_OPATOMIC_CASE_N(load,       "%inval2    = OpAtomicLoad %i32 %inloc %one %zero\n"
637                                                                         "             OpStore %outloc %inval2\n", "", OPATOMIC_LOAD );
638                 ADD_OPATOMIC_CASE_N(store,      "             OpAtomicStore %outloc %one %zero %inval\n", "", OPATOMIC_STORE );
639         }
640
641         ADD_OPATOMIC_CASE_N(compex, "%even      = OpSMod %i32 %inval %two\n"
642                                                                 "             OpStore %outloc %even\n"
643                                                                 "%retv      = OpAtomicCompareExchange %i32 %outloc %one %zero %zero %minusone %zero\n",
644                                                                 "                         OpStore %retloc %retv\n", OPATOMIC_COMPEX );
645
646
647         #undef ADD_OPATOMIC_CASE
648         #undef ADD_OPATOMIC_CASE_1
649         #undef ADD_OPATOMIC_CASE_N
650
651         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
652         {
653                 map<string, string>                     specializations;
654                 ComputeShaderSpec                       spec;
655                 vector<deInt32>                         inputInts               (numElements, 0);
656                 vector<deInt32>                         expected                (cases[caseNdx].numOutputElements, -1);
657
658                 specializations["INDEX"]                                = (cases[caseNdx].numOutputElements == 1) ? "%zero" : "%x";
659                 specializations["INSTRUCTION"]                  = cases[caseNdx].assembly;
660                 specializations["BLOCK_DECORATION"]             = useStorageBuffer ? "Block" : "BufferBlock";
661                 specializations["BLOCK_POINTER_TYPE"]   = useStorageBuffer ? "StorageBuffer" : "Uniform";
662
663                 if (verifyReturnValues)
664                 {
665                         const StringTemplate blockDecoration    (
666                                 "\n"
667                                 "OpDecorate %retbuf ${BLOCK_DECORATION}\n"
668                                 "OpDecorate %ret DescriptorSet 0\n"
669                                 "OpDecorate %ret Binding 2\n"
670                                 "OpMemberDecorate %retbuf 0 Offset 0\n\n");
671
672                         const StringTemplate blockDeclaration   (
673                                 "\n"
674                                 "%retbuf    = OpTypeStruct %i32arr\n"
675                                 "%retbufptr = OpTypePointer ${BLOCK_POINTER_TYPE} %retbuf\n"
676                                 "%ret       = OpVariable %retbufptr ${BLOCK_POINTER_TYPE}\n\n");
677
678                         specializations["RETVAL_ASSEMBLY"] =
679                                 "%retloc    = OpAccessChain %i32ptr %ret %zero %x\n"
680                                 + std::string(cases[caseNdx].retValAssembly);
681
682                         specializations["RETVAL_BUF_DECORATE"]  = blockDecoration.specialize(specializations);
683                         specializations["RETVAL_BUF_DECL"]              = blockDeclaration.specialize(specializations);
684                 }
685                 else
686                 {
687                         specializations["RETVAL_ASSEMBLY"]              = "";
688                         specializations["RETVAL_BUF_DECORATE"]  = "";
689                         specializations["RETVAL_BUF_DECL"]              = "";
690                 }
691
692                 spec.assembly                                                   = shaderTemplate.specialize(specializations);
693
694                 if (useStorageBuffer)
695                         spec.extensions.push_back("VK_KHR_storage_buffer_storage_class");
696
697                 spec.inputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_INPUT)));
698                 spec.outputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_EXPECTED)));
699                 if (verifyReturnValues)
700                         spec.outputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_ATOMIC_RET)));
701                 spec.numWorkGroups = IVec3(numElements, 1, 1);
702
703                 if (verifyReturnValues)
704                 {
705                         switch (cases[caseNdx].opAtomic)
706                         {
707                                 case OPATOMIC_IADD:
708                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IADD>;
709                                         break;
710                                 case OPATOMIC_ISUB:
711                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_ISUB>;
712                                         break;
713                                 case OPATOMIC_IINC:
714                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IINC>;
715                                         break;
716                                 case OPATOMIC_IDEC:
717                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IDEC>;
718                                         break;
719                                 case OPATOMIC_COMPEX:
720                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_COMPEX>;
721                                         break;
722                                 default:
723                                         DE_FATAL("Unsupported OpAtomic type for return value verification");
724                         }
725                 }
726                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
727         }
728
729         return group.release();
730 }
731
732 tcu::TestCaseGroup* createOpLineGroup (tcu::TestContext& testCtx)
733 {
734         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opline", "Test the OpLine instruction"));
735         ComputeShaderSpec                               spec;
736         de::Random                                              rnd                             (deStringHash(group->getName()));
737         const int                                               numElements             = 100;
738         vector<float>                                   positiveFloats  (numElements, 0);
739         vector<float>                                   negativeFloats  (numElements, 0);
740
741         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
742
743         for (size_t ndx = 0; ndx < numElements; ++ndx)
744                 negativeFloats[ndx] = -positiveFloats[ndx];
745
746         spec.assembly =
747                 string(getComputeAsmShaderPreamble()) +
748
749                 "%fname1 = OpString \"negateInputs.comp\"\n"
750                 "%fname2 = OpString \"negateInputs\"\n"
751
752                 "OpSource GLSL 430\n"
753                 "OpName %main           \"main\"\n"
754                 "OpName %id             \"gl_GlobalInvocationID\"\n"
755
756                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
757
758                 + string(getComputeAsmInputOutputBufferTraits()) +
759
760                 "OpLine %fname1 0 0\n" // At the earliest possible position
761
762                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
763
764                 "OpLine %fname1 0 1\n" // Multiple OpLines in sequence
765                 "OpLine %fname2 1 0\n" // Different filenames
766                 "OpLine %fname1 1000 100000\n"
767
768                 "%id        = OpVariable %uvec3ptr Input\n"
769                 "%zero      = OpConstant %i32 0\n"
770
771                 "OpLine %fname1 1 1\n" // Before a function
772
773                 "%main      = OpFunction %void None %voidf\n"
774                 "%label     = OpLabel\n"
775
776                 "OpLine %fname1 1 1\n" // In a function
777
778                 "%idval     = OpLoad %uvec3 %id\n"
779                 "%x         = OpCompositeExtract %u32 %idval 0\n"
780                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
781                 "%inval     = OpLoad %f32 %inloc\n"
782                 "%neg       = OpFNegate %f32 %inval\n"
783                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
784                 "             OpStore %outloc %neg\n"
785                 "             OpReturn\n"
786                 "             OpFunctionEnd\n";
787         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
788         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
789         spec.numWorkGroups = IVec3(numElements, 1, 1);
790
791         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpLine appearing at different places", spec));
792
793         return group.release();
794 }
795
796 bool veryfiBinaryShader (const ProgramBinary& binary)
797 {
798         const size_t    paternCount                     = 3u;
799         bool paternsCheck[paternCount]          =
800         {
801                 false, false, false
802         };
803         const string patersns[paternCount]      =
804         {
805                 "VULKAN CTS",
806                 "Negative values",
807                 "Date: 2017/09/21"
808         };
809         size_t                  paternNdx               = 0u;
810
811         for (size_t ndx = 0u; ndx < binary.getSize(); ++ndx)
812         {
813                 if (false == paternsCheck[paternNdx] &&
814                         patersns[paternNdx][0] == static_cast<char>(binary.getBinary()[ndx]) &&
815                         deMemoryEqual((const char*)&binary.getBinary()[ndx], &patersns[paternNdx][0], patersns[paternNdx].length()))
816                 {
817                         paternsCheck[paternNdx]= true;
818                         paternNdx++;
819                         if (paternNdx == paternCount)
820                                 break;
821                 }
822         }
823
824         for (size_t ndx = 0u; ndx < paternCount; ++ndx)
825         {
826                 if (!paternsCheck[ndx])
827                         return false;
828         }
829
830         return true;
831 }
832
833 tcu::TestCaseGroup* createOpModuleProcessedGroup (tcu::TestContext& testCtx)
834 {
835         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opmoduleprocessed", "Test the OpModuleProcessed instruction"));
836         ComputeShaderSpec                               spec;
837         de::Random                                              rnd                             (deStringHash(group->getName()));
838         const int                                               numElements             = 10;
839         vector<float>                                   positiveFloats  (numElements, 0);
840         vector<float>                                   negativeFloats  (numElements, 0);
841
842         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
843
844         for (size_t ndx = 0; ndx < numElements; ++ndx)
845                 negativeFloats[ndx] = -positiveFloats[ndx];
846
847         spec.assembly =
848                 string(getComputeAsmShaderPreamble()) +
849                 "%fname = OpString \"negateInputs.comp\"\n"
850
851                 "OpSource GLSL 430\n"
852                 "OpName %main           \"main\"\n"
853                 "OpName %id             \"gl_GlobalInvocationID\"\n"
854                 "OpModuleProcessed \"VULKAN CTS\"\n"                                    //OpModuleProcessed;
855                 "OpModuleProcessed \"Negative values\"\n"
856                 "OpModuleProcessed \"Date: 2017/09/21\"\n"
857                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
858
859                 + string(getComputeAsmInputOutputBufferTraits())
860
861                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
862
863                 "OpLine %fname 0 1\n"
864
865                 "OpLine %fname 1000 1\n"
866
867                 "%id        = OpVariable %uvec3ptr Input\n"
868                 "%zero      = OpConstant %i32 0\n"
869                 "%main      = OpFunction %void None %voidf\n"
870
871                 "%label     = OpLabel\n"
872                 "%idval     = OpLoad %uvec3 %id\n"
873                 "%x         = OpCompositeExtract %u32 %idval 0\n"
874
875                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
876                 "%inval     = OpLoad %f32 %inloc\n"
877                 "%neg       = OpFNegate %f32 %inval\n"
878                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
879                 "             OpStore %outloc %neg\n"
880                 "             OpReturn\n"
881                 "             OpFunctionEnd\n";
882         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
883         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
884         spec.numWorkGroups = IVec3(numElements, 1, 1);
885         spec.verifyBinary = veryfiBinaryShader;
886         spec.spirvVersion = SPIRV_VERSION_1_3;
887
888         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpModuleProcessed Tests", spec));
889
890         return group.release();
891 }
892
893 tcu::TestCaseGroup* createOpNoLineGroup (tcu::TestContext& testCtx)
894 {
895         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnoline", "Test the OpNoLine instruction"));
896         ComputeShaderSpec                               spec;
897         de::Random                                              rnd                             (deStringHash(group->getName()));
898         const int                                               numElements             = 100;
899         vector<float>                                   positiveFloats  (numElements, 0);
900         vector<float>                                   negativeFloats  (numElements, 0);
901
902         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
903
904         for (size_t ndx = 0; ndx < numElements; ++ndx)
905                 negativeFloats[ndx] = -positiveFloats[ndx];
906
907         spec.assembly =
908                 string(getComputeAsmShaderPreamble()) +
909
910                 "%fname = OpString \"negateInputs.comp\"\n"
911
912                 "OpSource GLSL 430\n"
913                 "OpName %main           \"main\"\n"
914                 "OpName %id             \"gl_GlobalInvocationID\"\n"
915
916                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
917
918                 + string(getComputeAsmInputOutputBufferTraits()) +
919
920                 "OpNoLine\n" // At the earliest possible position, without preceding OpLine
921
922                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
923
924                 "OpLine %fname 0 1\n"
925                 "OpNoLine\n" // Immediately following a preceding OpLine
926
927                 "OpLine %fname 1000 1\n"
928
929                 "%id        = OpVariable %uvec3ptr Input\n"
930                 "%zero      = OpConstant %i32 0\n"
931
932                 "OpNoLine\n" // Contents after the previous OpLine
933
934                 "%main      = OpFunction %void None %voidf\n"
935                 "%label     = OpLabel\n"
936                 "%idval     = OpLoad %uvec3 %id\n"
937                 "%x         = OpCompositeExtract %u32 %idval 0\n"
938
939                 "OpNoLine\n" // Multiple OpNoLine
940                 "OpNoLine\n"
941                 "OpNoLine\n"
942
943                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
944                 "%inval     = OpLoad %f32 %inloc\n"
945                 "%neg       = OpFNegate %f32 %inval\n"
946                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
947                 "             OpStore %outloc %neg\n"
948                 "             OpReturn\n"
949                 "             OpFunctionEnd\n";
950         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
951         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
952         spec.numWorkGroups = IVec3(numElements, 1, 1);
953
954         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpNoLine appearing at different places", spec));
955
956         return group.release();
957 }
958
959 // Compare instruction for the contraction compute case.
960 // Returns true if the output is what is expected from the test case.
961 bool compareNoContractCase(const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
962 {
963         if (outputAllocs.size() != 1)
964                 return false;
965
966         // Only size is needed because we are not comparing the exact values.
967         size_t byteSize = expectedOutputs[0].getByteSize();
968
969         const float*    outputAsFloat   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
970
971         for(size_t i = 0; i < byteSize / sizeof(float); ++i) {
972                 if (outputAsFloat[i] != 0.f &&
973                         outputAsFloat[i] != -ldexp(1, -24)) {
974                         return false;
975                 }
976         }
977
978         return true;
979 }
980
981 tcu::TestCaseGroup* createNoContractionGroup (tcu::TestContext& testCtx)
982 {
983         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
984         vector<CaseParameter>                   cases;
985         const int                                               numElements             = 100;
986         vector<float>                                   inputFloats1    (numElements, 0);
987         vector<float>                                   inputFloats2    (numElements, 0);
988         vector<float>                                   outputFloats    (numElements, 0);
989         const StringTemplate                    shaderTemplate  (
990                 string(getComputeAsmShaderPreamble()) +
991
992                 "OpName %main           \"main\"\n"
993                 "OpName %id             \"gl_GlobalInvocationID\"\n"
994
995                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
996
997                 "${DECORATION}\n"
998
999                 "OpDecorate %buf BufferBlock\n"
1000                 "OpDecorate %indata1 DescriptorSet 0\n"
1001                 "OpDecorate %indata1 Binding 0\n"
1002                 "OpDecorate %indata2 DescriptorSet 0\n"
1003                 "OpDecorate %indata2 Binding 1\n"
1004                 "OpDecorate %outdata DescriptorSet 0\n"
1005                 "OpDecorate %outdata Binding 2\n"
1006                 "OpDecorate %f32arr ArrayStride 4\n"
1007                 "OpMemberDecorate %buf 0 Offset 0\n"
1008
1009                 + string(getComputeAsmCommonTypes()) +
1010
1011                 "%buf        = OpTypeStruct %f32arr\n"
1012                 "%bufptr     = OpTypePointer Uniform %buf\n"
1013                 "%indata1    = OpVariable %bufptr Uniform\n"
1014                 "%indata2    = OpVariable %bufptr Uniform\n"
1015                 "%outdata    = OpVariable %bufptr Uniform\n"
1016
1017                 "%id         = OpVariable %uvec3ptr Input\n"
1018                 "%zero       = OpConstant %i32 0\n"
1019                 "%c_f_m1     = OpConstant %f32 -1.\n"
1020
1021                 "%main       = OpFunction %void None %voidf\n"
1022                 "%label      = OpLabel\n"
1023                 "%idval      = OpLoad %uvec3 %id\n"
1024                 "%x          = OpCompositeExtract %u32 %idval 0\n"
1025                 "%inloc1     = OpAccessChain %f32ptr %indata1 %zero %x\n"
1026                 "%inval1     = OpLoad %f32 %inloc1\n"
1027                 "%inloc2     = OpAccessChain %f32ptr %indata2 %zero %x\n"
1028                 "%inval2     = OpLoad %f32 %inloc2\n"
1029                 "%mul        = OpFMul %f32 %inval1 %inval2\n"
1030                 "%add        = OpFAdd %f32 %mul %c_f_m1\n"
1031                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
1032                 "              OpStore %outloc %add\n"
1033                 "              OpReturn\n"
1034                 "              OpFunctionEnd\n");
1035
1036         cases.push_back(CaseParameter("multiplication", "OpDecorate %mul NoContraction"));
1037         cases.push_back(CaseParameter("addition",               "OpDecorate %add NoContraction"));
1038         cases.push_back(CaseParameter("both",                   "OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"));
1039
1040         for (size_t ndx = 0; ndx < numElements; ++ndx)
1041         {
1042                 inputFloats1[ndx]       = 1.f + std::ldexp(1.f, -23); // 1 + 2^-23.
1043                 inputFloats2[ndx]       = 1.f - std::ldexp(1.f, -23); // 1 - 2^-23.
1044                 // Result for (1 + 2^-23) * (1 - 2^-23) - 1. With NoContraction, the multiplication will be
1045                 // conducted separately and the result is rounded to 1, or 0x1.fffffcp-1
1046                 // So the final result will be 0.f or 0x1p-24.
1047                 // If the operation is combined into a precise fused multiply-add, then the result would be
1048                 // 2^-46 (0xa8800000).
1049                 outputFloats[ndx]       = 0.f;
1050         }
1051
1052         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
1053         {
1054                 map<string, string>             specializations;
1055                 ComputeShaderSpec               spec;
1056
1057                 specializations["DECORATION"] = cases[caseNdx].param;
1058                 spec.assembly = shaderTemplate.specialize(specializations);
1059                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1060                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1061                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1062                 spec.numWorkGroups = IVec3(numElements, 1, 1);
1063                 // Check against the two possible answers based on rounding mode.
1064                 spec.verifyIO = &compareNoContractCase;
1065
1066                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
1067         }
1068         return group.release();
1069 }
1070
1071 bool compareFRem(const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1072 {
1073         if (outputAllocs.size() != 1)
1074                 return false;
1075
1076         vector<deUint8> expectedBytes;
1077         expectedOutputs[0].getBytes(expectedBytes);
1078
1079         const float*    expectedOutputAsFloat   = reinterpret_cast<const float*>(&expectedBytes.front());
1080         const float*    outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1081
1082         for (size_t idx = 0; idx < expectedBytes.size() / sizeof(float); ++idx)
1083         {
1084                 const float f0 = expectedOutputAsFloat[idx];
1085                 const float f1 = outputAsFloat[idx];
1086                 // \todo relative error needs to be fairly high because FRem may be implemented as
1087                 // (roughly) frac(a/b)*b, so LSB errors can be magnified. But this should be fine for now.
1088                 if (deFloatAbs((f1 - f0) / f0) > 0.02)
1089                         return false;
1090         }
1091
1092         return true;
1093 }
1094
1095 tcu::TestCaseGroup* createOpFRemGroup (tcu::TestContext& testCtx)
1096 {
1097         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opfrem", "Test the OpFRem instruction"));
1098         ComputeShaderSpec                               spec;
1099         de::Random                                              rnd                             (deStringHash(group->getName()));
1100         const int                                               numElements             = 200;
1101         vector<float>                                   inputFloats1    (numElements, 0);
1102         vector<float>                                   inputFloats2    (numElements, 0);
1103         vector<float>                                   outputFloats    (numElements, 0);
1104
1105         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1106         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats2[0], numElements);
1107
1108         for (size_t ndx = 0; ndx < numElements; ++ndx)
1109         {
1110                 // Guard against divisors near zero.
1111                 if (std::fabs(inputFloats2[ndx]) < 1e-3)
1112                         inputFloats2[ndx] = 8.f;
1113
1114                 // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1115                 outputFloats[ndx] = std::fmod(inputFloats1[ndx], inputFloats2[ndx]);
1116         }
1117
1118         spec.assembly =
1119                 string(getComputeAsmShaderPreamble()) +
1120
1121                 "OpName %main           \"main\"\n"
1122                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1123
1124                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1125
1126                 "OpDecorate %buf BufferBlock\n"
1127                 "OpDecorate %indata1 DescriptorSet 0\n"
1128                 "OpDecorate %indata1 Binding 0\n"
1129                 "OpDecorate %indata2 DescriptorSet 0\n"
1130                 "OpDecorate %indata2 Binding 1\n"
1131                 "OpDecorate %outdata DescriptorSet 0\n"
1132                 "OpDecorate %outdata Binding 2\n"
1133                 "OpDecorate %f32arr ArrayStride 4\n"
1134                 "OpMemberDecorate %buf 0 Offset 0\n"
1135
1136                 + string(getComputeAsmCommonTypes()) +
1137
1138                 "%buf        = OpTypeStruct %f32arr\n"
1139                 "%bufptr     = OpTypePointer Uniform %buf\n"
1140                 "%indata1    = OpVariable %bufptr Uniform\n"
1141                 "%indata2    = OpVariable %bufptr Uniform\n"
1142                 "%outdata    = OpVariable %bufptr Uniform\n"
1143
1144                 "%id        = OpVariable %uvec3ptr Input\n"
1145                 "%zero      = OpConstant %i32 0\n"
1146
1147                 "%main      = OpFunction %void None %voidf\n"
1148                 "%label     = OpLabel\n"
1149                 "%idval     = OpLoad %uvec3 %id\n"
1150                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1151                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1152                 "%inval1    = OpLoad %f32 %inloc1\n"
1153                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1154                 "%inval2    = OpLoad %f32 %inloc2\n"
1155                 "%rem       = OpFRem %f32 %inval1 %inval2\n"
1156                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1157                 "             OpStore %outloc %rem\n"
1158                 "             OpReturn\n"
1159                 "             OpFunctionEnd\n";
1160
1161         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1162         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1163         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1164         spec.numWorkGroups = IVec3(numElements, 1, 1);
1165         spec.verifyIO = &compareFRem;
1166
1167         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1168
1169         return group.release();
1170 }
1171
1172 bool compareNMin (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1173 {
1174         if (outputAllocs.size() != 1)
1175                 return false;
1176
1177         const BufferSp&                 expectedOutput                  (expectedOutputs[0].getBuffer());
1178         std::vector<deUint8>    data;
1179         expectedOutput->getBytes(data);
1180
1181         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1182         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1183
1184         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float); ++idx)
1185         {
1186                 const float f0 = expectedOutputAsFloat[idx];
1187                 const float f1 = outputAsFloat[idx];
1188
1189                 // For NMin, we accept NaN as output if both inputs were NaN.
1190                 // Otherwise the NaN is the wrong choise, as on architectures that
1191                 // do not handle NaN, those are huge values.
1192                 if (!(tcu::Float32(f1).isNaN() && tcu::Float32(f0).isNaN()) && deFloatAbs(f1 - f0) > 0.00001f)
1193                         return false;
1194         }
1195
1196         return true;
1197 }
1198
1199 tcu::TestCaseGroup* createOpNMinGroup (tcu::TestContext& testCtx)
1200 {
1201         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnmin", "Test the OpNMin instruction"));
1202         ComputeShaderSpec                               spec;
1203         de::Random                                              rnd                             (deStringHash(group->getName()));
1204         const int                                               numElements             = 200;
1205         vector<float>                                   inputFloats1    (numElements, 0);
1206         vector<float>                                   inputFloats2    (numElements, 0);
1207         vector<float>                                   outputFloats    (numElements, 0);
1208
1209         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1210         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1211
1212         // Make the first case a full-NAN case.
1213         inputFloats1[0] = TCU_NAN;
1214         inputFloats2[0] = TCU_NAN;
1215
1216         for (size_t ndx = 0; ndx < numElements; ++ndx)
1217         {
1218                 // By default, pick the smallest
1219                 outputFloats[ndx] = std::min(inputFloats1[ndx], inputFloats2[ndx]);
1220
1221                 // Make half of the cases NaN cases
1222                 if ((ndx & 1) == 0)
1223                 {
1224                         // Alternate between the NaN operand
1225                         if ((ndx & 2) == 0)
1226                         {
1227                                 outputFloats[ndx] = inputFloats2[ndx];
1228                                 inputFloats1[ndx] = TCU_NAN;
1229                         }
1230                         else
1231                         {
1232                                 outputFloats[ndx] = inputFloats1[ndx];
1233                                 inputFloats2[ndx] = TCU_NAN;
1234                         }
1235                 }
1236         }
1237
1238         spec.assembly =
1239                 "OpCapability Shader\n"
1240                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1241                 "OpMemoryModel Logical GLSL450\n"
1242                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1243                 "OpExecutionMode %main LocalSize 1 1 1\n"
1244
1245                 "OpName %main           \"main\"\n"
1246                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1247
1248                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1249
1250                 "OpDecorate %buf BufferBlock\n"
1251                 "OpDecorate %indata1 DescriptorSet 0\n"
1252                 "OpDecorate %indata1 Binding 0\n"
1253                 "OpDecorate %indata2 DescriptorSet 0\n"
1254                 "OpDecorate %indata2 Binding 1\n"
1255                 "OpDecorate %outdata DescriptorSet 0\n"
1256                 "OpDecorate %outdata Binding 2\n"
1257                 "OpDecorate %f32arr ArrayStride 4\n"
1258                 "OpMemberDecorate %buf 0 Offset 0\n"
1259
1260                 + string(getComputeAsmCommonTypes()) +
1261
1262                 "%buf        = OpTypeStruct %f32arr\n"
1263                 "%bufptr     = OpTypePointer Uniform %buf\n"
1264                 "%indata1    = OpVariable %bufptr Uniform\n"
1265                 "%indata2    = OpVariable %bufptr Uniform\n"
1266                 "%outdata    = OpVariable %bufptr Uniform\n"
1267
1268                 "%id        = OpVariable %uvec3ptr Input\n"
1269                 "%zero      = OpConstant %i32 0\n"
1270
1271                 "%main      = OpFunction %void None %voidf\n"
1272                 "%label     = OpLabel\n"
1273                 "%idval     = OpLoad %uvec3 %id\n"
1274                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1275                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1276                 "%inval1    = OpLoad %f32 %inloc1\n"
1277                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1278                 "%inval2    = OpLoad %f32 %inloc2\n"
1279                 "%rem       = OpExtInst %f32 %std450 NMin %inval1 %inval2\n"
1280                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1281                 "             OpStore %outloc %rem\n"
1282                 "             OpReturn\n"
1283                 "             OpFunctionEnd\n";
1284
1285         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1286         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1287         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1288         spec.numWorkGroups = IVec3(numElements, 1, 1);
1289         spec.verifyIO = &compareNMin;
1290
1291         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1292
1293         return group.release();
1294 }
1295
1296 bool compareNMax (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1297 {
1298         if (outputAllocs.size() != 1)
1299                 return false;
1300
1301         const BufferSp&                 expectedOutput                  = expectedOutputs[0].getBuffer();
1302         std::vector<deUint8>    data;
1303         expectedOutput->getBytes(data);
1304
1305         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1306         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1307
1308         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float); ++idx)
1309         {
1310                 const float f0 = expectedOutputAsFloat[idx];
1311                 const float f1 = outputAsFloat[idx];
1312
1313                 // For NMax, NaN is considered acceptable result, since in
1314                 // architectures that do not handle NaNs, those are huge values.
1315                 if (!tcu::Float32(f1).isNaN() && deFloatAbs(f1 - f0) > 0.00001f)
1316                         return false;
1317         }
1318
1319         return true;
1320 }
1321
1322 tcu::TestCaseGroup* createOpNMaxGroup (tcu::TestContext& testCtx)
1323 {
1324         de::MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "opnmax", "Test the OpNMax instruction"));
1325         ComputeShaderSpec                               spec;
1326         de::Random                                              rnd                             (deStringHash(group->getName()));
1327         const int                                               numElements             = 200;
1328         vector<float>                                   inputFloats1    (numElements, 0);
1329         vector<float>                                   inputFloats2    (numElements, 0);
1330         vector<float>                                   outputFloats    (numElements, 0);
1331
1332         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1333         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1334
1335         // Make the first case a full-NAN case.
1336         inputFloats1[0] = TCU_NAN;
1337         inputFloats2[0] = TCU_NAN;
1338
1339         for (size_t ndx = 0; ndx < numElements; ++ndx)
1340         {
1341                 // By default, pick the biggest
1342                 outputFloats[ndx] = std::max(inputFloats1[ndx], inputFloats2[ndx]);
1343
1344                 // Make half of the cases NaN cases
1345                 if ((ndx & 1) == 0)
1346                 {
1347                         // Alternate between the NaN operand
1348                         if ((ndx & 2) == 0)
1349                         {
1350                                 outputFloats[ndx] = inputFloats2[ndx];
1351                                 inputFloats1[ndx] = TCU_NAN;
1352                         }
1353                         else
1354                         {
1355                                 outputFloats[ndx] = inputFloats1[ndx];
1356                                 inputFloats2[ndx] = TCU_NAN;
1357                         }
1358                 }
1359         }
1360
1361         spec.assembly =
1362                 "OpCapability Shader\n"
1363                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1364                 "OpMemoryModel Logical GLSL450\n"
1365                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1366                 "OpExecutionMode %main LocalSize 1 1 1\n"
1367
1368                 "OpName %main           \"main\"\n"
1369                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1370
1371                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1372
1373                 "OpDecorate %buf BufferBlock\n"
1374                 "OpDecorate %indata1 DescriptorSet 0\n"
1375                 "OpDecorate %indata1 Binding 0\n"
1376                 "OpDecorate %indata2 DescriptorSet 0\n"
1377                 "OpDecorate %indata2 Binding 1\n"
1378                 "OpDecorate %outdata DescriptorSet 0\n"
1379                 "OpDecorate %outdata Binding 2\n"
1380                 "OpDecorate %f32arr ArrayStride 4\n"
1381                 "OpMemberDecorate %buf 0 Offset 0\n"
1382
1383                 + string(getComputeAsmCommonTypes()) +
1384
1385                 "%buf        = OpTypeStruct %f32arr\n"
1386                 "%bufptr     = OpTypePointer Uniform %buf\n"
1387                 "%indata1    = OpVariable %bufptr Uniform\n"
1388                 "%indata2    = OpVariable %bufptr Uniform\n"
1389                 "%outdata    = OpVariable %bufptr Uniform\n"
1390
1391                 "%id        = OpVariable %uvec3ptr Input\n"
1392                 "%zero      = OpConstant %i32 0\n"
1393
1394                 "%main      = OpFunction %void None %voidf\n"
1395                 "%label     = OpLabel\n"
1396                 "%idval     = OpLoad %uvec3 %id\n"
1397                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1398                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1399                 "%inval1    = OpLoad %f32 %inloc1\n"
1400                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1401                 "%inval2    = OpLoad %f32 %inloc2\n"
1402                 "%rem       = OpExtInst %f32 %std450 NMax %inval1 %inval2\n"
1403                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1404                 "             OpStore %outloc %rem\n"
1405                 "             OpReturn\n"
1406                 "             OpFunctionEnd\n";
1407
1408         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1409         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1410         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1411         spec.numWorkGroups = IVec3(numElements, 1, 1);
1412         spec.verifyIO = &compareNMax;
1413
1414         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1415
1416         return group.release();
1417 }
1418
1419 bool compareNClamp (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1420 {
1421         if (outputAllocs.size() != 1)
1422                 return false;
1423
1424         const BufferSp&                 expectedOutput                  = expectedOutputs[0].getBuffer();
1425         std::vector<deUint8>    data;
1426         expectedOutput->getBytes(data);
1427
1428         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1429         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1430
1431         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float) / 2; ++idx)
1432         {
1433                 const float e0 = expectedOutputAsFloat[idx * 2];
1434                 const float e1 = expectedOutputAsFloat[idx * 2 + 1];
1435                 const float res = outputAsFloat[idx];
1436
1437                 // For NClamp, we have two possible outcomes based on
1438                 // whether NaNs are handled or not.
1439                 // If either min or max value is NaN, the result is undefined,
1440                 // so this test doesn't stress those. If the clamped value is
1441                 // NaN, and NaNs are handled, the result is min; if NaNs are not
1442                 // handled, they are big values that result in max.
1443                 // If all three parameters are NaN, the result should be NaN.
1444                 if (!((tcu::Float32(e0).isNaN() && tcu::Float32(res).isNaN()) ||
1445                          (deFloatAbs(e0 - res) < 0.00001f) ||
1446                          (deFloatAbs(e1 - res) < 0.00001f)))
1447                         return false;
1448         }
1449
1450         return true;
1451 }
1452
1453 tcu::TestCaseGroup* createOpNClampGroup (tcu::TestContext& testCtx)
1454 {
1455         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnclamp", "Test the OpNClamp instruction"));
1456         ComputeShaderSpec                               spec;
1457         de::Random                                              rnd                             (deStringHash(group->getName()));
1458         const int                                               numElements             = 200;
1459         vector<float>                                   inputFloats1    (numElements, 0);
1460         vector<float>                                   inputFloats2    (numElements, 0);
1461         vector<float>                                   inputFloats3    (numElements, 0);
1462         vector<float>                                   outputFloats    (numElements * 2, 0);
1463
1464         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1465         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1466         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats3[0], numElements);
1467
1468         for (size_t ndx = 0; ndx < numElements; ++ndx)
1469         {
1470                 // Results are only defined if max value is bigger than min value.
1471                 if (inputFloats2[ndx] > inputFloats3[ndx])
1472                 {
1473                         float t = inputFloats2[ndx];
1474                         inputFloats2[ndx] = inputFloats3[ndx];
1475                         inputFloats3[ndx] = t;
1476                 }
1477
1478                 // By default, do the clamp, setting both possible answers
1479                 float defaultRes = std::min(std::max(inputFloats1[ndx], inputFloats2[ndx]), inputFloats3[ndx]);
1480
1481                 float maxResA = std::max(inputFloats1[ndx], inputFloats2[ndx]);
1482                 float maxResB = maxResA;
1483
1484                 // Alternate between the NaN cases
1485                 if (ndx & 1)
1486                 {
1487                         inputFloats1[ndx] = TCU_NAN;
1488                         // If NaN is handled, the result should be same as the clamp minimum.
1489                         // If NaN is not handled, the result should clamp to the clamp maximum.
1490                         maxResA = inputFloats2[ndx];
1491                         maxResB = inputFloats3[ndx];
1492                 }
1493                 else
1494                 {
1495                         // Not a NaN case - only one legal result.
1496                         maxResA = defaultRes;
1497                         maxResB = defaultRes;
1498                 }
1499
1500                 outputFloats[ndx * 2] = maxResA;
1501                 outputFloats[ndx * 2 + 1] = maxResB;
1502         }
1503
1504         // Make the first case a full-NAN case.
1505         inputFloats1[0] = TCU_NAN;
1506         inputFloats2[0] = TCU_NAN;
1507         inputFloats3[0] = TCU_NAN;
1508         outputFloats[0] = TCU_NAN;
1509         outputFloats[1] = TCU_NAN;
1510
1511         spec.assembly =
1512                 "OpCapability Shader\n"
1513                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1514                 "OpMemoryModel Logical GLSL450\n"
1515                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1516                 "OpExecutionMode %main LocalSize 1 1 1\n"
1517
1518                 "OpName %main           \"main\"\n"
1519                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1520
1521                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1522
1523                 "OpDecorate %buf BufferBlock\n"
1524                 "OpDecorate %indata1 DescriptorSet 0\n"
1525                 "OpDecorate %indata1 Binding 0\n"
1526                 "OpDecorate %indata2 DescriptorSet 0\n"
1527                 "OpDecorate %indata2 Binding 1\n"
1528                 "OpDecorate %indata3 DescriptorSet 0\n"
1529                 "OpDecorate %indata3 Binding 2\n"
1530                 "OpDecorate %outdata DescriptorSet 0\n"
1531                 "OpDecorate %outdata Binding 3\n"
1532                 "OpDecorate %f32arr ArrayStride 4\n"
1533                 "OpMemberDecorate %buf 0 Offset 0\n"
1534
1535                 + string(getComputeAsmCommonTypes()) +
1536
1537                 "%buf        = OpTypeStruct %f32arr\n"
1538                 "%bufptr     = OpTypePointer Uniform %buf\n"
1539                 "%indata1    = OpVariable %bufptr Uniform\n"
1540                 "%indata2    = OpVariable %bufptr Uniform\n"
1541                 "%indata3    = OpVariable %bufptr Uniform\n"
1542                 "%outdata    = OpVariable %bufptr Uniform\n"
1543
1544                 "%id        = OpVariable %uvec3ptr Input\n"
1545                 "%zero      = OpConstant %i32 0\n"
1546
1547                 "%main      = OpFunction %void None %voidf\n"
1548                 "%label     = OpLabel\n"
1549                 "%idval     = OpLoad %uvec3 %id\n"
1550                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1551                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1552                 "%inval1    = OpLoad %f32 %inloc1\n"
1553                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1554                 "%inval2    = OpLoad %f32 %inloc2\n"
1555                 "%inloc3    = OpAccessChain %f32ptr %indata3 %zero %x\n"
1556                 "%inval3    = OpLoad %f32 %inloc3\n"
1557                 "%rem       = OpExtInst %f32 %std450 NClamp %inval1 %inval2 %inval3\n"
1558                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1559                 "             OpStore %outloc %rem\n"
1560                 "             OpReturn\n"
1561                 "             OpFunctionEnd\n";
1562
1563         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1564         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1565         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
1566         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1567         spec.numWorkGroups = IVec3(numElements, 1, 1);
1568         spec.verifyIO = &compareNClamp;
1569
1570         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1571
1572         return group.release();
1573 }
1574
1575 tcu::TestCaseGroup* createOpSRemComputeGroup (tcu::TestContext& testCtx, qpTestResult negFailResult)
1576 {
1577         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsrem", "Test the OpSRem instruction"));
1578         de::Random                                              rnd                             (deStringHash(group->getName()));
1579         const int                                               numElements             = 200;
1580
1581         const struct CaseParams
1582         {
1583                 const char*             name;
1584                 const char*             failMessage;            // customized status message
1585                 qpTestResult    failResult;                     // override status on failure
1586                 int                             op1Min, op1Max;         // operand ranges
1587                 int                             op2Min, op2Max;
1588         } cases[] =
1589         {
1590                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    0,              65536,  0,              100 },
1591                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  -65536, 65536,  -100,   100 },  // see below
1592         };
1593         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1594
1595         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1596         {
1597                 const CaseParams&       params          = cases[caseNdx];
1598                 ComputeShaderSpec       spec;
1599                 vector<deInt32>         inputInts1      (numElements, 0);
1600                 vector<deInt32>         inputInts2      (numElements, 0);
1601                 vector<deInt32>         outputInts      (numElements, 0);
1602
1603                 fillRandomScalars(rnd, params.op1Min, params.op1Max, &inputInts1[0], numElements);
1604                 fillRandomScalars(rnd, params.op2Min, params.op2Max, &inputInts2[0], numElements, filterNotZero);
1605
1606                 for (int ndx = 0; ndx < numElements; ++ndx)
1607                 {
1608                         // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1609                         outputInts[ndx] = inputInts1[ndx] % inputInts2[ndx];
1610                 }
1611
1612                 spec.assembly =
1613                         string(getComputeAsmShaderPreamble()) +
1614
1615                         "OpName %main           \"main\"\n"
1616                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1617
1618                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1619
1620                         "OpDecorate %buf BufferBlock\n"
1621                         "OpDecorate %indata1 DescriptorSet 0\n"
1622                         "OpDecorate %indata1 Binding 0\n"
1623                         "OpDecorate %indata2 DescriptorSet 0\n"
1624                         "OpDecorate %indata2 Binding 1\n"
1625                         "OpDecorate %outdata DescriptorSet 0\n"
1626                         "OpDecorate %outdata Binding 2\n"
1627                         "OpDecorate %i32arr ArrayStride 4\n"
1628                         "OpMemberDecorate %buf 0 Offset 0\n"
1629
1630                         + string(getComputeAsmCommonTypes()) +
1631
1632                         "%buf        = OpTypeStruct %i32arr\n"
1633                         "%bufptr     = OpTypePointer Uniform %buf\n"
1634                         "%indata1    = OpVariable %bufptr Uniform\n"
1635                         "%indata2    = OpVariable %bufptr Uniform\n"
1636                         "%outdata    = OpVariable %bufptr Uniform\n"
1637
1638                         "%id        = OpVariable %uvec3ptr Input\n"
1639                         "%zero      = OpConstant %i32 0\n"
1640
1641                         "%main      = OpFunction %void None %voidf\n"
1642                         "%label     = OpLabel\n"
1643                         "%idval     = OpLoad %uvec3 %id\n"
1644                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1645                         "%inloc1    = OpAccessChain %i32ptr %indata1 %zero %x\n"
1646                         "%inval1    = OpLoad %i32 %inloc1\n"
1647                         "%inloc2    = OpAccessChain %i32ptr %indata2 %zero %x\n"
1648                         "%inval2    = OpLoad %i32 %inloc2\n"
1649                         "%rem       = OpSRem %i32 %inval1 %inval2\n"
1650                         "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
1651                         "             OpStore %outloc %rem\n"
1652                         "             OpReturn\n"
1653                         "             OpFunctionEnd\n";
1654
1655                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts1)));
1656                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts2)));
1657                 spec.outputs.push_back  (BufferSp(new Int32Buffer(outputInts)));
1658                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1659                 spec.failResult                 = params.failResult;
1660                 spec.failMessage                = params.failMessage;
1661
1662                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1663         }
1664
1665         return group.release();
1666 }
1667
1668 tcu::TestCaseGroup* createOpSRemComputeGroup64 (tcu::TestContext& testCtx, qpTestResult negFailResult)
1669 {
1670         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsrem64", "Test the 64-bit OpSRem instruction"));
1671         de::Random                                              rnd                             (deStringHash(group->getName()));
1672         const int                                               numElements             = 200;
1673
1674         const struct CaseParams
1675         {
1676                 const char*             name;
1677                 const char*             failMessage;            // customized status message
1678                 qpTestResult    failResult;                     // override status on failure
1679                 bool                    positive;
1680         } cases[] =
1681         {
1682                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    true },
1683                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  false },        // see below
1684         };
1685         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1686
1687         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1688         {
1689                 const CaseParams&       params          = cases[caseNdx];
1690                 ComputeShaderSpec       spec;
1691                 vector<deInt64>         inputInts1      (numElements, 0);
1692                 vector<deInt64>         inputInts2      (numElements, 0);
1693                 vector<deInt64>         outputInts      (numElements, 0);
1694
1695                 if (params.positive)
1696                 {
1697                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements, filterNonNegative);
1698                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterPositive);
1699                 }
1700                 else
1701                 {
1702                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements);
1703                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterNotZero);
1704                 }
1705
1706                 for (int ndx = 0; ndx < numElements; ++ndx)
1707                 {
1708                         // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1709                         outputInts[ndx] = inputInts1[ndx] % inputInts2[ndx];
1710                 }
1711
1712                 spec.assembly =
1713                         "OpCapability Int64\n"
1714
1715                         + string(getComputeAsmShaderPreamble()) +
1716
1717                         "OpName %main           \"main\"\n"
1718                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1719
1720                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1721
1722                         "OpDecorate %buf BufferBlock\n"
1723                         "OpDecorate %indata1 DescriptorSet 0\n"
1724                         "OpDecorate %indata1 Binding 0\n"
1725                         "OpDecorate %indata2 DescriptorSet 0\n"
1726                         "OpDecorate %indata2 Binding 1\n"
1727                         "OpDecorate %outdata DescriptorSet 0\n"
1728                         "OpDecorate %outdata Binding 2\n"
1729                         "OpDecorate %i64arr ArrayStride 8\n"
1730                         "OpMemberDecorate %buf 0 Offset 0\n"
1731
1732                         + string(getComputeAsmCommonTypes())
1733                         + string(getComputeAsmCommonInt64Types()) +
1734
1735                         "%buf        = OpTypeStruct %i64arr\n"
1736                         "%bufptr     = OpTypePointer Uniform %buf\n"
1737                         "%indata1    = OpVariable %bufptr Uniform\n"
1738                         "%indata2    = OpVariable %bufptr Uniform\n"
1739                         "%outdata    = OpVariable %bufptr Uniform\n"
1740
1741                         "%id        = OpVariable %uvec3ptr Input\n"
1742                         "%zero      = OpConstant %i64 0\n"
1743
1744                         "%main      = OpFunction %void None %voidf\n"
1745                         "%label     = OpLabel\n"
1746                         "%idval     = OpLoad %uvec3 %id\n"
1747                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1748                         "%inloc1    = OpAccessChain %i64ptr %indata1 %zero %x\n"
1749                         "%inval1    = OpLoad %i64 %inloc1\n"
1750                         "%inloc2    = OpAccessChain %i64ptr %indata2 %zero %x\n"
1751                         "%inval2    = OpLoad %i64 %inloc2\n"
1752                         "%rem       = OpSRem %i64 %inval1 %inval2\n"
1753                         "%outloc    = OpAccessChain %i64ptr %outdata %zero %x\n"
1754                         "             OpStore %outloc %rem\n"
1755                         "             OpReturn\n"
1756                         "             OpFunctionEnd\n";
1757
1758                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts1)));
1759                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts2)));
1760                 spec.outputs.push_back  (BufferSp(new Int64Buffer(outputInts)));
1761                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1762                 spec.failResult                 = params.failResult;
1763                 spec.failMessage                = params.failMessage;
1764
1765                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec, COMPUTE_TEST_USES_INT64));
1766         }
1767
1768         return group.release();
1769 }
1770
1771 tcu::TestCaseGroup* createOpSModComputeGroup (tcu::TestContext& testCtx, qpTestResult negFailResult)
1772 {
1773         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsmod", "Test the OpSMod instruction"));
1774         de::Random                                              rnd                             (deStringHash(group->getName()));
1775         const int                                               numElements             = 200;
1776
1777         const struct CaseParams
1778         {
1779                 const char*             name;
1780                 const char*             failMessage;            // customized status message
1781                 qpTestResult    failResult;                     // override status on failure
1782                 int                             op1Min, op1Max;         // operand ranges
1783                 int                             op2Min, op2Max;
1784         } cases[] =
1785         {
1786                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    0,              65536,  0,              100 },
1787                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  -65536, 65536,  -100,   100 },  // see below
1788         };
1789         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1790
1791         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1792         {
1793                 const CaseParams&       params          = cases[caseNdx];
1794
1795                 ComputeShaderSpec       spec;
1796                 vector<deInt32>         inputInts1      (numElements, 0);
1797                 vector<deInt32>         inputInts2      (numElements, 0);
1798                 vector<deInt32>         outputInts      (numElements, 0);
1799
1800                 fillRandomScalars(rnd, params.op1Min, params.op1Max, &inputInts1[0], numElements);
1801                 fillRandomScalars(rnd, params.op2Min, params.op2Max, &inputInts2[0], numElements, filterNotZero);
1802
1803                 for (int ndx = 0; ndx < numElements; ++ndx)
1804                 {
1805                         deInt32 rem = inputInts1[ndx] % inputInts2[ndx];
1806                         if (rem == 0)
1807                         {
1808                                 outputInts[ndx] = 0;
1809                         }
1810                         else if ((inputInts1[ndx] >= 0) == (inputInts2[ndx] >= 0))
1811                         {
1812                                 // They have the same sign
1813                                 outputInts[ndx] = rem;
1814                         }
1815                         else
1816                         {
1817                                 // They have opposite sign.  The remainder operation takes the
1818                                 // sign inputInts1[ndx] but OpSMod is supposed to take ths sign
1819                                 // of inputInts2[ndx].  Adding inputInts2[ndx] will ensure that
1820                                 // the result has the correct sign and that it is still
1821                                 // congruent to inputInts1[ndx] modulo inputInts2[ndx]
1822                                 //
1823                                 // See also http://mathforum.org/library/drmath/view/52343.html
1824                                 outputInts[ndx] = rem + inputInts2[ndx];
1825                         }
1826                 }
1827
1828                 spec.assembly =
1829                         string(getComputeAsmShaderPreamble()) +
1830
1831                         "OpName %main           \"main\"\n"
1832                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1833
1834                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1835
1836                         "OpDecorate %buf BufferBlock\n"
1837                         "OpDecorate %indata1 DescriptorSet 0\n"
1838                         "OpDecorate %indata1 Binding 0\n"
1839                         "OpDecorate %indata2 DescriptorSet 0\n"
1840                         "OpDecorate %indata2 Binding 1\n"
1841                         "OpDecorate %outdata DescriptorSet 0\n"
1842                         "OpDecorate %outdata Binding 2\n"
1843                         "OpDecorate %i32arr ArrayStride 4\n"
1844                         "OpMemberDecorate %buf 0 Offset 0\n"
1845
1846                         + string(getComputeAsmCommonTypes()) +
1847
1848                         "%buf        = OpTypeStruct %i32arr\n"
1849                         "%bufptr     = OpTypePointer Uniform %buf\n"
1850                         "%indata1    = OpVariable %bufptr Uniform\n"
1851                         "%indata2    = OpVariable %bufptr Uniform\n"
1852                         "%outdata    = OpVariable %bufptr Uniform\n"
1853
1854                         "%id        = OpVariable %uvec3ptr Input\n"
1855                         "%zero      = OpConstant %i32 0\n"
1856
1857                         "%main      = OpFunction %void None %voidf\n"
1858                         "%label     = OpLabel\n"
1859                         "%idval     = OpLoad %uvec3 %id\n"
1860                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1861                         "%inloc1    = OpAccessChain %i32ptr %indata1 %zero %x\n"
1862                         "%inval1    = OpLoad %i32 %inloc1\n"
1863                         "%inloc2    = OpAccessChain %i32ptr %indata2 %zero %x\n"
1864                         "%inval2    = OpLoad %i32 %inloc2\n"
1865                         "%rem       = OpSMod %i32 %inval1 %inval2\n"
1866                         "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
1867                         "             OpStore %outloc %rem\n"
1868                         "             OpReturn\n"
1869                         "             OpFunctionEnd\n";
1870
1871                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts1)));
1872                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts2)));
1873                 spec.outputs.push_back  (BufferSp(new Int32Buffer(outputInts)));
1874                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1875                 spec.failResult                 = params.failResult;
1876                 spec.failMessage                = params.failMessage;
1877
1878                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1879         }
1880
1881         return group.release();
1882 }
1883
1884 tcu::TestCaseGroup* createOpSModComputeGroup64 (tcu::TestContext& testCtx, qpTestResult negFailResult)
1885 {
1886         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsmod64", "Test the OpSMod instruction"));
1887         de::Random                                              rnd                             (deStringHash(group->getName()));
1888         const int                                               numElements             = 200;
1889
1890         const struct CaseParams
1891         {
1892                 const char*             name;
1893                 const char*             failMessage;            // customized status message
1894                 qpTestResult    failResult;                     // override status on failure
1895                 bool                    positive;
1896         } cases[] =
1897         {
1898                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    true },
1899                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  false },        // see below
1900         };
1901         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1902
1903         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1904         {
1905                 const CaseParams&       params          = cases[caseNdx];
1906
1907                 ComputeShaderSpec       spec;
1908                 vector<deInt64>         inputInts1      (numElements, 0);
1909                 vector<deInt64>         inputInts2      (numElements, 0);
1910                 vector<deInt64>         outputInts      (numElements, 0);
1911
1912
1913                 if (params.positive)
1914                 {
1915                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements, filterNonNegative);
1916                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterPositive);
1917                 }
1918                 else
1919                 {
1920                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements);
1921                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterNotZero);
1922                 }
1923
1924                 for (int ndx = 0; ndx < numElements; ++ndx)
1925                 {
1926                         deInt64 rem = inputInts1[ndx] % inputInts2[ndx];
1927                         if (rem == 0)
1928                         {
1929                                 outputInts[ndx] = 0;
1930                         }
1931                         else if ((inputInts1[ndx] >= 0) == (inputInts2[ndx] >= 0))
1932                         {
1933                                 // They have the same sign
1934                                 outputInts[ndx] = rem;
1935                         }
1936                         else
1937                         {
1938                                 // They have opposite sign.  The remainder operation takes the
1939                                 // sign inputInts1[ndx] but OpSMod is supposed to take ths sign
1940                                 // of inputInts2[ndx].  Adding inputInts2[ndx] will ensure that
1941                                 // the result has the correct sign and that it is still
1942                                 // congruent to inputInts1[ndx] modulo inputInts2[ndx]
1943                                 //
1944                                 // See also http://mathforum.org/library/drmath/view/52343.html
1945                                 outputInts[ndx] = rem + inputInts2[ndx];
1946                         }
1947                 }
1948
1949                 spec.assembly =
1950                         "OpCapability Int64\n"
1951
1952                         + string(getComputeAsmShaderPreamble()) +
1953
1954                         "OpName %main           \"main\"\n"
1955                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1956
1957                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1958
1959                         "OpDecorate %buf BufferBlock\n"
1960                         "OpDecorate %indata1 DescriptorSet 0\n"
1961                         "OpDecorate %indata1 Binding 0\n"
1962                         "OpDecorate %indata2 DescriptorSet 0\n"
1963                         "OpDecorate %indata2 Binding 1\n"
1964                         "OpDecorate %outdata DescriptorSet 0\n"
1965                         "OpDecorate %outdata Binding 2\n"
1966                         "OpDecorate %i64arr ArrayStride 8\n"
1967                         "OpMemberDecorate %buf 0 Offset 0\n"
1968
1969                         + string(getComputeAsmCommonTypes())
1970                         + string(getComputeAsmCommonInt64Types()) +
1971
1972                         "%buf        = OpTypeStruct %i64arr\n"
1973                         "%bufptr     = OpTypePointer Uniform %buf\n"
1974                         "%indata1    = OpVariable %bufptr Uniform\n"
1975                         "%indata2    = OpVariable %bufptr Uniform\n"
1976                         "%outdata    = OpVariable %bufptr Uniform\n"
1977
1978                         "%id        = OpVariable %uvec3ptr Input\n"
1979                         "%zero      = OpConstant %i64 0\n"
1980
1981                         "%main      = OpFunction %void None %voidf\n"
1982                         "%label     = OpLabel\n"
1983                         "%idval     = OpLoad %uvec3 %id\n"
1984                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1985                         "%inloc1    = OpAccessChain %i64ptr %indata1 %zero %x\n"
1986                         "%inval1    = OpLoad %i64 %inloc1\n"
1987                         "%inloc2    = OpAccessChain %i64ptr %indata2 %zero %x\n"
1988                         "%inval2    = OpLoad %i64 %inloc2\n"
1989                         "%rem       = OpSMod %i64 %inval1 %inval2\n"
1990                         "%outloc    = OpAccessChain %i64ptr %outdata %zero %x\n"
1991                         "             OpStore %outloc %rem\n"
1992                         "             OpReturn\n"
1993                         "             OpFunctionEnd\n";
1994
1995                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts1)));
1996                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts2)));
1997                 spec.outputs.push_back  (BufferSp(new Int64Buffer(outputInts)));
1998                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1999                 spec.failResult                 = params.failResult;
2000                 spec.failMessage                = params.failMessage;
2001
2002                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec, COMPUTE_TEST_USES_INT64));
2003         }
2004
2005         return group.release();
2006 }
2007
2008 // Copy contents in the input buffer to the output buffer.
2009 tcu::TestCaseGroup* createOpCopyMemoryGroup (tcu::TestContext& testCtx)
2010 {
2011         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opcopymemory", "Test the OpCopyMemory instruction"));
2012         de::Random                                              rnd                             (deStringHash(group->getName()));
2013         const int                                               numElements             = 100;
2014
2015         // 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.
2016         ComputeShaderSpec                               spec1;
2017         vector<Vec4>                                    inputFloats1    (numElements);
2018         vector<Vec4>                                    outputFloats1   (numElements);
2019
2020         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats1[0], numElements * 4);
2021
2022         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2023         floorAll(inputFloats1);
2024
2025         for (size_t ndx = 0; ndx < numElements; ++ndx)
2026                 outputFloats1[ndx] = inputFloats1[ndx] + Vec4(0.f, 0.5f, 1.5f, 2.5f);
2027
2028         spec1.assembly =
2029                 string(getComputeAsmShaderPreamble()) +
2030
2031                 "OpName %main           \"main\"\n"
2032                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2033
2034                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2035                 "OpDecorate %vec4arr ArrayStride 16\n"
2036
2037                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2038
2039                 "%vec4       = OpTypeVector %f32 4\n"
2040                 "%vec4ptr_u  = OpTypePointer Uniform %vec4\n"
2041                 "%vec4ptr_f  = OpTypePointer Function %vec4\n"
2042                 "%vec4arr    = OpTypeRuntimeArray %vec4\n"
2043                 "%buf        = OpTypeStruct %vec4arr\n"
2044                 "%bufptr     = OpTypePointer Uniform %buf\n"
2045                 "%indata     = OpVariable %bufptr Uniform\n"
2046                 "%outdata    = OpVariable %bufptr Uniform\n"
2047
2048                 "%id         = OpVariable %uvec3ptr Input\n"
2049                 "%zero       = OpConstant %i32 0\n"
2050                 "%c_f_0      = OpConstant %f32 0.\n"
2051                 "%c_f_0_5    = OpConstant %f32 0.5\n"
2052                 "%c_f_1_5    = OpConstant %f32 1.5\n"
2053                 "%c_f_2_5    = OpConstant %f32 2.5\n"
2054                 "%c_vec4     = OpConstantComposite %vec4 %c_f_0 %c_f_0_5 %c_f_1_5 %c_f_2_5\n"
2055
2056                 "%main       = OpFunction %void None %voidf\n"
2057                 "%label      = OpLabel\n"
2058                 "%v_vec4     = OpVariable %vec4ptr_f Function\n"
2059                 "%idval      = OpLoad %uvec3 %id\n"
2060                 "%x          = OpCompositeExtract %u32 %idval 0\n"
2061                 "%inloc      = OpAccessChain %vec4ptr_u %indata %zero %x\n"
2062                 "%outloc     = OpAccessChain %vec4ptr_u %outdata %zero %x\n"
2063                 "              OpCopyMemory %v_vec4 %inloc\n"
2064                 "%v_vec4_val = OpLoad %vec4 %v_vec4\n"
2065                 "%add        = OpFAdd %vec4 %v_vec4_val %c_vec4\n"
2066                 "              OpStore %outloc %add\n"
2067                 "              OpReturn\n"
2068                 "              OpFunctionEnd\n";
2069
2070         spec1.inputs.push_back(BufferSp(new Vec4Buffer(inputFloats1)));
2071         spec1.outputs.push_back(BufferSp(new Vec4Buffer(outputFloats1)));
2072         spec1.numWorkGroups = IVec3(numElements, 1, 1);
2073
2074         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector", "OpCopyMemory elements of vector type", spec1));
2075
2076         // The following case copies a float[100] variable from the input buffer to the output buffer.
2077         ComputeShaderSpec                               spec2;
2078         vector<float>                                   inputFloats2    (numElements);
2079         vector<float>                                   outputFloats2   (numElements);
2080
2081         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats2[0], numElements);
2082
2083         for (size_t ndx = 0; ndx < numElements; ++ndx)
2084                 outputFloats2[ndx] = inputFloats2[ndx];
2085
2086         spec2.assembly =
2087                 string(getComputeAsmShaderPreamble()) +
2088
2089                 "OpName %main           \"main\"\n"
2090                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2091
2092                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2093                 "OpDecorate %f32arr100 ArrayStride 4\n"
2094
2095                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2096
2097                 "%hundred        = OpConstant %u32 100\n"
2098                 "%f32arr100      = OpTypeArray %f32 %hundred\n"
2099                 "%f32arr100ptr_f = OpTypePointer Function %f32arr100\n"
2100                 "%f32arr100ptr_u = OpTypePointer Uniform %f32arr100\n"
2101                 "%buf            = OpTypeStruct %f32arr100\n"
2102                 "%bufptr         = OpTypePointer Uniform %buf\n"
2103                 "%indata         = OpVariable %bufptr Uniform\n"
2104                 "%outdata        = OpVariable %bufptr Uniform\n"
2105
2106                 "%id             = OpVariable %uvec3ptr Input\n"
2107                 "%zero           = OpConstant %i32 0\n"
2108
2109                 "%main           = OpFunction %void None %voidf\n"
2110                 "%label          = OpLabel\n"
2111                 "%var            = OpVariable %f32arr100ptr_f Function\n"
2112                 "%inarr          = OpAccessChain %f32arr100ptr_u %indata %zero\n"
2113                 "%outarr         = OpAccessChain %f32arr100ptr_u %outdata %zero\n"
2114                 "                  OpCopyMemory %var %inarr\n"
2115                 "                  OpCopyMemory %outarr %var\n"
2116                 "                  OpReturn\n"
2117                 "                  OpFunctionEnd\n";
2118
2119         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
2120         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
2121         spec2.numWorkGroups = IVec3(1, 1, 1);
2122
2123         group->addChild(new SpvAsmComputeShaderCase(testCtx, "array", "OpCopyMemory elements of array type", spec2));
2124
2125         // The following case copies a struct{vec4, vec4, vec4, vec4} variable from the input buffer to the output buffer.
2126         ComputeShaderSpec                               spec3;
2127         vector<float>                                   inputFloats3    (16);
2128         vector<float>                                   outputFloats3   (16);
2129
2130         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats3[0], 16);
2131
2132         for (size_t ndx = 0; ndx < 16; ++ndx)
2133                 outputFloats3[ndx] = inputFloats3[ndx];
2134
2135         spec3.assembly =
2136                 string(getComputeAsmShaderPreamble()) +
2137
2138                 "OpName %main           \"main\"\n"
2139                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2140
2141                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2142                 "OpMemberDecorate %buf 0 Offset 0\n"
2143                 "OpMemberDecorate %buf 1 Offset 16\n"
2144                 "OpMemberDecorate %buf 2 Offset 32\n"
2145                 "OpMemberDecorate %buf 3 Offset 48\n"
2146
2147                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2148
2149                 "%vec4      = OpTypeVector %f32 4\n"
2150                 "%buf       = OpTypeStruct %vec4 %vec4 %vec4 %vec4\n"
2151                 "%bufptr    = OpTypePointer Uniform %buf\n"
2152                 "%indata    = OpVariable %bufptr Uniform\n"
2153                 "%outdata   = OpVariable %bufptr Uniform\n"
2154                 "%vec4stptr = OpTypePointer Function %buf\n"
2155
2156                 "%id        = OpVariable %uvec3ptr Input\n"
2157                 "%zero      = OpConstant %i32 0\n"
2158
2159                 "%main      = OpFunction %void None %voidf\n"
2160                 "%label     = OpLabel\n"
2161                 "%var       = OpVariable %vec4stptr Function\n"
2162                 "             OpCopyMemory %var %indata\n"
2163                 "             OpCopyMemory %outdata %var\n"
2164                 "             OpReturn\n"
2165                 "             OpFunctionEnd\n";
2166
2167         spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
2168         spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
2169         spec3.numWorkGroups = IVec3(1, 1, 1);
2170
2171         group->addChild(new SpvAsmComputeShaderCase(testCtx, "struct", "OpCopyMemory elements of struct type", spec3));
2172
2173         // The following case negates multiple float variables from the input buffer and stores the results to the output buffer.
2174         ComputeShaderSpec                               spec4;
2175         vector<float>                                   inputFloats4    (numElements);
2176         vector<float>                                   outputFloats4   (numElements);
2177
2178         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats4[0], numElements);
2179
2180         for (size_t ndx = 0; ndx < numElements; ++ndx)
2181                 outputFloats4[ndx] = -inputFloats4[ndx];
2182
2183         spec4.assembly =
2184                 string(getComputeAsmShaderPreamble()) +
2185
2186                 "OpName %main           \"main\"\n"
2187                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2188
2189                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2190
2191                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2192
2193                 "%f32ptr_f  = OpTypePointer Function %f32\n"
2194                 "%id        = OpVariable %uvec3ptr Input\n"
2195                 "%zero      = OpConstant %i32 0\n"
2196
2197                 "%main      = OpFunction %void None %voidf\n"
2198                 "%label     = OpLabel\n"
2199                 "%var       = OpVariable %f32ptr_f Function\n"
2200                 "%idval     = OpLoad %uvec3 %id\n"
2201                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2202                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
2203                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
2204                 "             OpCopyMemory %var %inloc\n"
2205                 "%val       = OpLoad %f32 %var\n"
2206                 "%neg       = OpFNegate %f32 %val\n"
2207                 "             OpStore %outloc %neg\n"
2208                 "             OpReturn\n"
2209                 "             OpFunctionEnd\n";
2210
2211         spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
2212         spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
2213         spec4.numWorkGroups = IVec3(numElements, 1, 1);
2214
2215         group->addChild(new SpvAsmComputeShaderCase(testCtx, "float", "OpCopyMemory elements of float type", spec4));
2216
2217         return group.release();
2218 }
2219
2220 tcu::TestCaseGroup* createOpCopyObjectGroup (tcu::TestContext& testCtx)
2221 {
2222         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opcopyobject", "Test the OpCopyObject instruction"));
2223         ComputeShaderSpec                               spec;
2224         de::Random                                              rnd                             (deStringHash(group->getName()));
2225         const int                                               numElements             = 100;
2226         vector<float>                                   inputFloats             (numElements, 0);
2227         vector<float>                                   outputFloats    (numElements, 0);
2228
2229         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
2230
2231         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2232         floorAll(inputFloats);
2233
2234         for (size_t ndx = 0; ndx < numElements; ++ndx)
2235                 outputFloats[ndx] = inputFloats[ndx] + 7.5f;
2236
2237         spec.assembly =
2238                 string(getComputeAsmShaderPreamble()) +
2239
2240                 "OpName %main           \"main\"\n"
2241                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2242
2243                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2244
2245                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2246
2247                 "%fmat     = OpTypeMatrix %fvec3 3\n"
2248                 "%three    = OpConstant %u32 3\n"
2249                 "%farr     = OpTypeArray %f32 %three\n"
2250                 "%fst      = OpTypeStruct %f32 %f32\n"
2251
2252                 + string(getComputeAsmInputOutputBuffer()) +
2253
2254                 "%id            = OpVariable %uvec3ptr Input\n"
2255                 "%zero          = OpConstant %i32 0\n"
2256                 "%c_f           = OpConstant %f32 1.5\n"
2257                 "%c_fvec3       = OpConstantComposite %fvec3 %c_f %c_f %c_f\n"
2258                 "%c_fmat        = OpConstantComposite %fmat %c_fvec3 %c_fvec3 %c_fvec3\n"
2259                 "%c_farr        = OpConstantComposite %farr %c_f %c_f %c_f\n"
2260                 "%c_fst         = OpConstantComposite %fst %c_f %c_f\n"
2261
2262                 "%main          = OpFunction %void None %voidf\n"
2263                 "%label         = OpLabel\n"
2264                 "%c_f_copy      = OpCopyObject %f32   %c_f\n"
2265                 "%c_fvec3_copy  = OpCopyObject %fvec3 %c_fvec3\n"
2266                 "%c_fmat_copy   = OpCopyObject %fmat  %c_fmat\n"
2267                 "%c_farr_copy   = OpCopyObject %farr  %c_farr\n"
2268                 "%c_fst_copy    = OpCopyObject %fst   %c_fst\n"
2269                 "%fvec3_elem    = OpCompositeExtract %f32 %c_fvec3_copy 0\n"
2270                 "%fmat_elem     = OpCompositeExtract %f32 %c_fmat_copy 1 2\n"
2271                 "%farr_elem     = OpCompositeExtract %f32 %c_farr_copy 2\n"
2272                 "%fst_elem      = OpCompositeExtract %f32 %c_fst_copy 1\n"
2273                 // Add up. 1.5 * 5 = 7.5.
2274                 "%add1          = OpFAdd %f32 %c_f_copy %fvec3_elem\n"
2275                 "%add2          = OpFAdd %f32 %add1     %fmat_elem\n"
2276                 "%add3          = OpFAdd %f32 %add2     %farr_elem\n"
2277                 "%add4          = OpFAdd %f32 %add3     %fst_elem\n"
2278
2279                 "%idval         = OpLoad %uvec3 %id\n"
2280                 "%x             = OpCompositeExtract %u32 %idval 0\n"
2281                 "%inloc         = OpAccessChain %f32ptr %indata %zero %x\n"
2282                 "%outloc        = OpAccessChain %f32ptr %outdata %zero %x\n"
2283                 "%inval         = OpLoad %f32 %inloc\n"
2284                 "%add           = OpFAdd %f32 %add4 %inval\n"
2285                 "                 OpStore %outloc %add\n"
2286                 "                 OpReturn\n"
2287                 "                 OpFunctionEnd\n";
2288         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2289         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2290         spec.numWorkGroups = IVec3(numElements, 1, 1);
2291
2292         group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "OpCopyObject on different types", spec));
2293
2294         return group.release();
2295 }
2296 // Assembly code used for testing OpUnreachable is based on GLSL source code:
2297 //
2298 // #version 430
2299 //
2300 // layout(std140, set = 0, binding = 0) readonly buffer Input {
2301 //   float elements[];
2302 // } input_data;
2303 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
2304 //   float elements[];
2305 // } output_data;
2306 //
2307 // void not_called_func() {
2308 //   // place OpUnreachable here
2309 // }
2310 //
2311 // uint modulo4(uint val) {
2312 //   switch (val % uint(4)) {
2313 //     case 0:  return 3;
2314 //     case 1:  return 2;
2315 //     case 2:  return 1;
2316 //     case 3:  return 0;
2317 //     default: return 100; // place OpUnreachable here
2318 //   }
2319 // }
2320 //
2321 // uint const5() {
2322 //   return 5;
2323 //   // place OpUnreachable here
2324 // }
2325 //
2326 // void main() {
2327 //   uint x = gl_GlobalInvocationID.x;
2328 //   if (const5() > modulo4(1000)) {
2329 //     output_data.elements[x] = -input_data.elements[x];
2330 //   } else {
2331 //     // place OpUnreachable here
2332 //     output_data.elements[x] = input_data.elements[x];
2333 //   }
2334 // }
2335
2336 tcu::TestCaseGroup* createOpUnreachableGroup (tcu::TestContext& testCtx)
2337 {
2338         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opunreachable", "Test the OpUnreachable instruction"));
2339         ComputeShaderSpec                               spec;
2340         de::Random                                              rnd                             (deStringHash(group->getName()));
2341         const int                                               numElements             = 100;
2342         vector<float>                                   positiveFloats  (numElements, 0);
2343         vector<float>                                   negativeFloats  (numElements, 0);
2344
2345         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
2346
2347         for (size_t ndx = 0; ndx < numElements; ++ndx)
2348                 negativeFloats[ndx] = -positiveFloats[ndx];
2349
2350         spec.assembly =
2351                 string(getComputeAsmShaderPreamble()) +
2352
2353                 "OpSource GLSL 430\n"
2354                 "OpName %main            \"main\"\n"
2355                 "OpName %func_not_called_func \"not_called_func(\"\n"
2356                 "OpName %func_modulo4         \"modulo4(u1;\"\n"
2357                 "OpName %func_const5          \"const5(\"\n"
2358                 "OpName %id                   \"gl_GlobalInvocationID\"\n"
2359
2360                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2361
2362                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2363
2364                 "%u32ptr    = OpTypePointer Function %u32\n"
2365                 "%uintfuint = OpTypeFunction %u32 %u32ptr\n"
2366                 "%unitf     = OpTypeFunction %u32\n"
2367
2368                 "%id        = OpVariable %uvec3ptr Input\n"
2369                 "%zero      = OpConstant %u32 0\n"
2370                 "%one       = OpConstant %u32 1\n"
2371                 "%two       = OpConstant %u32 2\n"
2372                 "%three     = OpConstant %u32 3\n"
2373                 "%four      = OpConstant %u32 4\n"
2374                 "%five      = OpConstant %u32 5\n"
2375                 "%hundred   = OpConstant %u32 100\n"
2376                 "%thousand  = OpConstant %u32 1000\n"
2377
2378                 + string(getComputeAsmInputOutputBuffer()) +
2379
2380                 // Main()
2381                 "%main   = OpFunction %void None %voidf\n"
2382                 "%main_entry  = OpLabel\n"
2383                 "%v_thousand  = OpVariable %u32ptr Function %thousand\n"
2384                 "%idval       = OpLoad %uvec3 %id\n"
2385                 "%x           = OpCompositeExtract %u32 %idval 0\n"
2386                 "%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
2387                 "%inval       = OpLoad %f32 %inloc\n"
2388                 "%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
2389                 "%ret_const5  = OpFunctionCall %u32 %func_const5\n"
2390                 "%ret_modulo4 = OpFunctionCall %u32 %func_modulo4 %v_thousand\n"
2391                 "%cmp_gt      = OpUGreaterThan %bool %ret_const5 %ret_modulo4\n"
2392                 "               OpSelectionMerge %if_end None\n"
2393                 "               OpBranchConditional %cmp_gt %if_true %if_false\n"
2394                 "%if_true     = OpLabel\n"
2395                 "%negate      = OpFNegate %f32 %inval\n"
2396                 "               OpStore %outloc %negate\n"
2397                 "               OpBranch %if_end\n"
2398                 "%if_false    = OpLabel\n"
2399                 "               OpUnreachable\n" // Unreachable else branch for if statement
2400                 "%if_end      = OpLabel\n"
2401                 "               OpReturn\n"
2402                 "               OpFunctionEnd\n"
2403
2404                 // not_called_function()
2405                 "%func_not_called_func  = OpFunction %void None %voidf\n"
2406                 "%not_called_func_entry = OpLabel\n"
2407                 "                         OpUnreachable\n" // Unreachable entry block in not called static function
2408                 "                         OpFunctionEnd\n"
2409
2410                 // modulo4()
2411                 "%func_modulo4  = OpFunction %u32 None %uintfuint\n"
2412                 "%valptr        = OpFunctionParameter %u32ptr\n"
2413                 "%modulo4_entry = OpLabel\n"
2414                 "%val           = OpLoad %u32 %valptr\n"
2415                 "%modulo        = OpUMod %u32 %val %four\n"
2416                 "                 OpSelectionMerge %switch_merge None\n"
2417                 "                 OpSwitch %modulo %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
2418                 "%case0         = OpLabel\n"
2419                 "                 OpReturnValue %three\n"
2420                 "%case1         = OpLabel\n"
2421                 "                 OpReturnValue %two\n"
2422                 "%case2         = OpLabel\n"
2423                 "                 OpReturnValue %one\n"
2424                 "%case3         = OpLabel\n"
2425                 "                 OpReturnValue %zero\n"
2426                 "%default       = OpLabel\n"
2427                 "                 OpUnreachable\n" // Unreachable default case for switch statement
2428                 "%switch_merge  = OpLabel\n"
2429                 "                 OpUnreachable\n" // Unreachable merge block for switch statement
2430                 "                 OpFunctionEnd\n"
2431
2432                 // const5()
2433                 "%func_const5  = OpFunction %u32 None %unitf\n"
2434                 "%const5_entry = OpLabel\n"
2435                 "                OpReturnValue %five\n"
2436                 "%unreachable  = OpLabel\n"
2437                 "                OpUnreachable\n" // Unreachable block in function
2438                 "                OpFunctionEnd\n";
2439         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
2440         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
2441         spec.numWorkGroups = IVec3(numElements, 1, 1);
2442
2443         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpUnreachable appearing at different places", spec));
2444
2445         return group.release();
2446 }
2447
2448 // Assembly code used for testing decoration group is based on GLSL source code:
2449 //
2450 // #version 430
2451 //
2452 // layout(std140, set = 0, binding = 0) readonly buffer Input0 {
2453 //   float elements[];
2454 // } input_data0;
2455 // layout(std140, set = 0, binding = 1) readonly buffer Input1 {
2456 //   float elements[];
2457 // } input_data1;
2458 // layout(std140, set = 0, binding = 2) readonly buffer Input2 {
2459 //   float elements[];
2460 // } input_data2;
2461 // layout(std140, set = 0, binding = 3) readonly buffer Input3 {
2462 //   float elements[];
2463 // } input_data3;
2464 // layout(std140, set = 0, binding = 4) readonly buffer Input4 {
2465 //   float elements[];
2466 // } input_data4;
2467 // layout(std140, set = 0, binding = 5) writeonly buffer Output {
2468 //   float elements[];
2469 // } output_data;
2470 //
2471 // void main() {
2472 //   uint x = gl_GlobalInvocationID.x;
2473 //   output_data.elements[x] = input_data0.elements[x] + input_data1.elements[x] + input_data2.elements[x] + input_data3.elements[x] + input_data4.elements[x];
2474 // }
2475 tcu::TestCaseGroup* createDecorationGroupGroup (tcu::TestContext& testCtx)
2476 {
2477         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "decoration_group", "Test the OpDecorationGroup & OpGroupDecorate instruction"));
2478         ComputeShaderSpec                               spec;
2479         de::Random                                              rnd                             (deStringHash(group->getName()));
2480         const int                                               numElements             = 100;
2481         vector<float>                                   inputFloats0    (numElements, 0);
2482         vector<float>                                   inputFloats1    (numElements, 0);
2483         vector<float>                                   inputFloats2    (numElements, 0);
2484         vector<float>                                   inputFloats3    (numElements, 0);
2485         vector<float>                                   inputFloats4    (numElements, 0);
2486         vector<float>                                   outputFloats    (numElements, 0);
2487
2488         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats0[0], numElements);
2489         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats1[0], numElements);
2490         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats2[0], numElements);
2491         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats3[0], numElements);
2492         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats4[0], numElements);
2493
2494         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2495         floorAll(inputFloats0);
2496         floorAll(inputFloats1);
2497         floorAll(inputFloats2);
2498         floorAll(inputFloats3);
2499         floorAll(inputFloats4);
2500
2501         for (size_t ndx = 0; ndx < numElements; ++ndx)
2502                 outputFloats[ndx] = inputFloats0[ndx] + inputFloats1[ndx] + inputFloats2[ndx] + inputFloats3[ndx] + inputFloats4[ndx];
2503
2504         spec.assembly =
2505                 string(getComputeAsmShaderPreamble()) +
2506
2507                 "OpSource GLSL 430\n"
2508                 "OpName %main \"main\"\n"
2509                 "OpName %id \"gl_GlobalInvocationID\"\n"
2510
2511                 // Not using group decoration on variable.
2512                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2513                 // Not using group decoration on type.
2514                 "OpDecorate %f32arr ArrayStride 4\n"
2515
2516                 "OpDecorate %groups BufferBlock\n"
2517                 "OpDecorate %groupm Offset 0\n"
2518                 "%groups = OpDecorationGroup\n"
2519                 "%groupm = OpDecorationGroup\n"
2520
2521                 // Group decoration on multiple structs.
2522                 "OpGroupDecorate %groups %outbuf %inbuf0 %inbuf1 %inbuf2 %inbuf3 %inbuf4\n"
2523                 // Group decoration on multiple struct members.
2524                 "OpGroupMemberDecorate %groupm %outbuf 0 %inbuf0 0 %inbuf1 0 %inbuf2 0 %inbuf3 0 %inbuf4 0\n"
2525
2526                 "OpDecorate %group1 DescriptorSet 0\n"
2527                 "OpDecorate %group3 DescriptorSet 0\n"
2528                 "OpDecorate %group3 NonWritable\n"
2529                 "OpDecorate %group3 Restrict\n"
2530                 "%group0 = OpDecorationGroup\n"
2531                 "%group1 = OpDecorationGroup\n"
2532                 "%group3 = OpDecorationGroup\n"
2533
2534                 // Applying the same decoration group multiple times.
2535                 "OpGroupDecorate %group1 %outdata\n"
2536                 "OpGroupDecorate %group1 %outdata\n"
2537                 "OpGroupDecorate %group1 %outdata\n"
2538                 "OpDecorate %outdata DescriptorSet 0\n"
2539                 "OpDecorate %outdata Binding 5\n"
2540                 // Applying decoration group containing nothing.
2541                 "OpGroupDecorate %group0 %indata0\n"
2542                 "OpDecorate %indata0 DescriptorSet 0\n"
2543                 "OpDecorate %indata0 Binding 0\n"
2544                 // Applying decoration group containing one decoration.
2545                 "OpGroupDecorate %group1 %indata1\n"
2546                 "OpDecorate %indata1 Binding 1\n"
2547                 // Applying decoration group containing multiple decorations.
2548                 "OpGroupDecorate %group3 %indata2 %indata3\n"
2549                 "OpDecorate %indata2 Binding 2\n"
2550                 "OpDecorate %indata3 Binding 3\n"
2551                 // Applying multiple decoration groups (with overlapping).
2552                 "OpGroupDecorate %group0 %indata4\n"
2553                 "OpGroupDecorate %group1 %indata4\n"
2554                 "OpGroupDecorate %group3 %indata4\n"
2555                 "OpDecorate %indata4 Binding 4\n"
2556
2557                 + string(getComputeAsmCommonTypes()) +
2558
2559                 "%id   = OpVariable %uvec3ptr Input\n"
2560                 "%zero = OpConstant %i32 0\n"
2561
2562                 "%outbuf    = OpTypeStruct %f32arr\n"
2563                 "%outbufptr = OpTypePointer Uniform %outbuf\n"
2564                 "%outdata   = OpVariable %outbufptr Uniform\n"
2565                 "%inbuf0    = OpTypeStruct %f32arr\n"
2566                 "%inbuf0ptr = OpTypePointer Uniform %inbuf0\n"
2567                 "%indata0   = OpVariable %inbuf0ptr Uniform\n"
2568                 "%inbuf1    = OpTypeStruct %f32arr\n"
2569                 "%inbuf1ptr = OpTypePointer Uniform %inbuf1\n"
2570                 "%indata1   = OpVariable %inbuf1ptr Uniform\n"
2571                 "%inbuf2    = OpTypeStruct %f32arr\n"
2572                 "%inbuf2ptr = OpTypePointer Uniform %inbuf2\n"
2573                 "%indata2   = OpVariable %inbuf2ptr Uniform\n"
2574                 "%inbuf3    = OpTypeStruct %f32arr\n"
2575                 "%inbuf3ptr = OpTypePointer Uniform %inbuf3\n"
2576                 "%indata3   = OpVariable %inbuf3ptr Uniform\n"
2577                 "%inbuf4    = OpTypeStruct %f32arr\n"
2578                 "%inbufptr  = OpTypePointer Uniform %inbuf4\n"
2579                 "%indata4   = OpVariable %inbufptr Uniform\n"
2580
2581                 "%main   = OpFunction %void None %voidf\n"
2582                 "%label  = OpLabel\n"
2583                 "%idval  = OpLoad %uvec3 %id\n"
2584                 "%x      = OpCompositeExtract %u32 %idval 0\n"
2585                 "%inloc0 = OpAccessChain %f32ptr %indata0 %zero %x\n"
2586                 "%inloc1 = OpAccessChain %f32ptr %indata1 %zero %x\n"
2587                 "%inloc2 = OpAccessChain %f32ptr %indata2 %zero %x\n"
2588                 "%inloc3 = OpAccessChain %f32ptr %indata3 %zero %x\n"
2589                 "%inloc4 = OpAccessChain %f32ptr %indata4 %zero %x\n"
2590                 "%outloc = OpAccessChain %f32ptr %outdata %zero %x\n"
2591                 "%inval0 = OpLoad %f32 %inloc0\n"
2592                 "%inval1 = OpLoad %f32 %inloc1\n"
2593                 "%inval2 = OpLoad %f32 %inloc2\n"
2594                 "%inval3 = OpLoad %f32 %inloc3\n"
2595                 "%inval4 = OpLoad %f32 %inloc4\n"
2596                 "%add0   = OpFAdd %f32 %inval0 %inval1\n"
2597                 "%add1   = OpFAdd %f32 %add0 %inval2\n"
2598                 "%add2   = OpFAdd %f32 %add1 %inval3\n"
2599                 "%add    = OpFAdd %f32 %add2 %inval4\n"
2600                 "          OpStore %outloc %add\n"
2601                 "          OpReturn\n"
2602                 "          OpFunctionEnd\n";
2603         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats0)));
2604         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
2605         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
2606         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
2607         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
2608         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2609         spec.numWorkGroups = IVec3(numElements, 1, 1);
2610
2611         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "decoration group cases", spec));
2612
2613         return group.release();
2614 }
2615
2616 struct SpecConstantTwoIntCase
2617 {
2618         const char*             caseName;
2619         const char*             scDefinition0;
2620         const char*             scDefinition1;
2621         const char*             scResultType;
2622         const char*             scOperation;
2623         deInt32                 scActualValue0;
2624         deInt32                 scActualValue1;
2625         const char*             resultOperation;
2626         vector<deInt32> expectedOutput;
2627
2628                                         SpecConstantTwoIntCase (const char* name,
2629                                                                                         const char* definition0,
2630                                                                                         const char* definition1,
2631                                                                                         const char* resultType,
2632                                                                                         const char* operation,
2633                                                                                         deInt32 value0,
2634                                                                                         deInt32 value1,
2635                                                                                         const char* resultOp,
2636                                                                                         const vector<deInt32>& output)
2637                                                 : caseName                      (name)
2638                                                 , scDefinition0         (definition0)
2639                                                 , scDefinition1         (definition1)
2640                                                 , scResultType          (resultType)
2641                                                 , scOperation           (operation)
2642                                                 , scActualValue0        (value0)
2643                                                 , scActualValue1        (value1)
2644                                                 , resultOperation       (resultOp)
2645                                                 , expectedOutput        (output) {}
2646 };
2647
2648 tcu::TestCaseGroup* createSpecConstantGroup (tcu::TestContext& testCtx)
2649 {
2650         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
2651         vector<SpecConstantTwoIntCase>  cases;
2652         de::Random                                              rnd                             (deStringHash(group->getName()));
2653         const int                                               numElements             = 100;
2654         vector<deInt32>                                 inputInts               (numElements, 0);
2655         vector<deInt32>                                 outputInts1             (numElements, 0);
2656         vector<deInt32>                                 outputInts2             (numElements, 0);
2657         vector<deInt32>                                 outputInts3             (numElements, 0);
2658         vector<deInt32>                                 outputInts4             (numElements, 0);
2659         const StringTemplate                    shaderTemplate  (
2660                 "${CAPABILITIES:opt}"
2661                 + string(getComputeAsmShaderPreamble()) +
2662
2663                 "OpName %main           \"main\"\n"
2664                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2665
2666                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2667                 "OpDecorate %sc_0  SpecId 0\n"
2668                 "OpDecorate %sc_1  SpecId 1\n"
2669                 "OpDecorate %i32arr ArrayStride 4\n"
2670
2671                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2672
2673                 "${OPTYPE_DEFINITIONS:opt}"
2674                 "%buf     = OpTypeStruct %i32arr\n"
2675                 "%bufptr  = OpTypePointer Uniform %buf\n"
2676                 "%indata    = OpVariable %bufptr Uniform\n"
2677                 "%outdata   = OpVariable %bufptr Uniform\n"
2678
2679                 "%id        = OpVariable %uvec3ptr Input\n"
2680                 "%zero      = OpConstant %i32 0\n"
2681
2682                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
2683                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
2684                 "%sc_final  = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n"
2685
2686                 "%main      = OpFunction %void None %voidf\n"
2687                 "%label     = OpLabel\n"
2688                 "${TYPE_CONVERT:opt}"
2689                 "%idval     = OpLoad %uvec3 %id\n"
2690                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2691                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
2692                 "%inval     = OpLoad %i32 %inloc\n"
2693                 "%final     = ${GEN_RESULT}\n"
2694                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2695                 "             OpStore %outloc %final\n"
2696                 "             OpReturn\n"
2697                 "             OpFunctionEnd\n");
2698
2699         fillRandomScalars(rnd, -65536, 65536, &inputInts[0], numElements);
2700
2701         for (size_t ndx = 0; ndx < numElements; ++ndx)
2702         {
2703                 outputInts1[ndx] = inputInts[ndx] + 42;
2704                 outputInts2[ndx] = inputInts[ndx];
2705                 outputInts3[ndx] = inputInts[ndx] - 11200;
2706                 outputInts4[ndx] = inputInts[ndx] + 1;
2707         }
2708
2709         const char addScToInput[]               = "OpIAdd %i32 %inval %sc_final";
2710         const char addSc32ToInput[]             = "OpIAdd %i32 %inval %sc_final32";
2711         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_final %inval %zero";
2712         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_final %zero %inval";
2713
2714         cases.push_back(SpecConstantTwoIntCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                     62,             -20,    addScToInput,           outputInts1));
2715         cases.push_back(SpecConstantTwoIntCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                     100,    58,             addScToInput,           outputInts1));
2716         cases.push_back(SpecConstantTwoIntCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                     -2,             -21,    addScToInput,           outputInts1));
2717         cases.push_back(SpecConstantTwoIntCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                     -126,   -3,             addScToInput,           outputInts1));
2718         cases.push_back(SpecConstantTwoIntCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                     126,    3,              addScToInput,           outputInts1));
2719         cases.push_back(SpecConstantTwoIntCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
2720         cases.push_back(SpecConstantTwoIntCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
2721         cases.push_back(SpecConstantTwoIntCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                     342,    50,             addScToInput,           outputInts1));
2722         cases.push_back(SpecConstantTwoIntCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                     42,             63,             addScToInput,           outputInts1));
2723         cases.push_back(SpecConstantTwoIntCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                     34,             8,              addScToInput,           outputInts1));
2724         cases.push_back(SpecConstantTwoIntCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                     18,             56,             addScToInput,           outputInts1));
2725         cases.push_back(SpecConstantTwoIntCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
2726         cases.push_back(SpecConstantTwoIntCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
2727         cases.push_back(SpecConstantTwoIntCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                     21,             1,              addScToInput,           outputInts1));
2728         cases.push_back(SpecConstantTwoIntCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                     -20,    -10,    selectTrueUsingSc,      outputInts2));
2729         cases.push_back(SpecConstantTwoIntCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                     10,             20,             selectTrueUsingSc,      outputInts2));
2730         cases.push_back(SpecConstantTwoIntCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
2731         cases.push_back(SpecConstantTwoIntCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                     10,             5,              selectTrueUsingSc,      outputInts2));
2732         cases.push_back(SpecConstantTwoIntCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                     -10,    -10,    selectTrueUsingSc,      outputInts2));
2733         cases.push_back(SpecConstantTwoIntCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                     50,             100,    selectTrueUsingSc,      outputInts2));
2734         cases.push_back(SpecConstantTwoIntCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
2735         cases.push_back(SpecConstantTwoIntCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                     10,             10,             selectTrueUsingSc,      outputInts2));
2736         cases.push_back(SpecConstantTwoIntCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                     42,             24,             selectFalseUsingSc,     outputInts2));
2737         cases.push_back(SpecConstantTwoIntCase("inotequal",                             " %i32 0",              " %i32 0",              "%bool",        "INotEqual            %sc_0 %sc_1",                     42,             24,             selectTrueUsingSc,      outputInts2));
2738         cases.push_back(SpecConstantTwoIntCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
2739         cases.push_back(SpecConstantTwoIntCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
2740         cases.push_back(SpecConstantTwoIntCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
2741         cases.push_back(SpecConstantTwoIntCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
2742         cases.push_back(SpecConstantTwoIntCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                           -42,    0,              addScToInput,           outputInts1));
2743         cases.push_back(SpecConstantTwoIntCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                           -43,    0,              addScToInput,           outputInts1));
2744         cases.push_back(SpecConstantTwoIntCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                           1,              0,              selectFalseUsingSc,     outputInts2));
2745         cases.push_back(SpecConstantTwoIntCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %zero",       1,              42,             addScToInput,           outputInts1));
2746         cases.push_back(SpecConstantTwoIntCase("sconvert",                              " %i32 0",              " %i32 0",              "%i16",         "SConvert             %sc_0",                           -11200, 0,              addSc32ToInput,         outputInts3));
2747         // -969998336 stored as 32-bit two's complement is the binary representation of -11200 as IEEE-754 Float
2748         cases.push_back(SpecConstantTwoIntCase("fconvert",                              " %f32 0",              " %f32 0",              "%f64",         "FConvert             %sc_0",                           -969998336, 0,  addSc32ToInput,         outputInts3));
2749
2750         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
2751         {
2752                 map<string, string>             specializations;
2753                 ComputeShaderSpec               spec;
2754                 ComputeTestFeatures             features = COMPUTE_TEST_USES_NONE;
2755
2756                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
2757                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
2758                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
2759                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
2760                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
2761
2762                 // Special SPIR-V code for SConvert-case
2763                 if (strcmp(cases[caseNdx].caseName, "sconvert") == 0)
2764                 {
2765                         features                                                                = COMPUTE_TEST_USES_INT16;
2766                         specializations["CAPABILITIES"]                 = "OpCapability Int16\n";                                                       // Adds 16-bit integer capability
2767                         specializations["OPTYPE_DEFINITIONS"]   = "%i16 = OpTypeInt 16 1\n";                                            // Adds 16-bit integer type
2768                         specializations["TYPE_CONVERT"]                 = "%sc_final32 = OpSConvert %i32 %sc_final\n";          // Converts 16-bit integer to 32-bit integer
2769                 }
2770
2771                 // Special SPIR-V code for FConvert-case
2772                 if (strcmp(cases[caseNdx].caseName, "fconvert") == 0)
2773                 {
2774                         features                                                                = COMPUTE_TEST_USES_FLOAT64;
2775                         specializations["CAPABILITIES"]                 = "OpCapability Float64\n";                                                     // Adds 64-bit float capability
2776                         specializations["OPTYPE_DEFINITIONS"]   = "%f64 = OpTypeFloat 64\n";                                            // Adds 64-bit float type
2777                         specializations["TYPE_CONVERT"]                 = "%sc_final32 = OpConvertFToS %i32 %sc_final\n";       // Converts 64-bit float to 32-bit integer
2778                 }
2779
2780                 spec.assembly = shaderTemplate.specialize(specializations);
2781                 spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
2782                 spec.outputs.push_back(BufferSp(new Int32Buffer(cases[caseNdx].expectedOutput)));
2783                 spec.numWorkGroups = IVec3(numElements, 1, 1);
2784                 spec.specConstants.append(cases[caseNdx].scActualValue0);
2785                 spec.specConstants.append(cases[caseNdx].scActualValue1);
2786
2787                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].caseName, cases[caseNdx].caseName, spec, features));
2788         }
2789
2790         ComputeShaderSpec                               spec;
2791
2792         spec.assembly =
2793                 string(getComputeAsmShaderPreamble()) +
2794
2795                 "OpName %main           \"main\"\n"
2796                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2797
2798                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2799                 "OpDecorate %sc_0  SpecId 0\n"
2800                 "OpDecorate %sc_1  SpecId 1\n"
2801                 "OpDecorate %sc_2  SpecId 2\n"
2802                 "OpDecorate %i32arr ArrayStride 4\n"
2803
2804                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2805
2806                 "%ivec3       = OpTypeVector %i32 3\n"
2807                 "%buf         = OpTypeStruct %i32arr\n"
2808                 "%bufptr      = OpTypePointer Uniform %buf\n"
2809                 "%indata      = OpVariable %bufptr Uniform\n"
2810                 "%outdata     = OpVariable %bufptr Uniform\n"
2811
2812                 "%id          = OpVariable %uvec3ptr Input\n"
2813                 "%zero        = OpConstant %i32 0\n"
2814                 "%ivec3_0     = OpConstantComposite %ivec3 %zero %zero %zero\n"
2815                 "%vec3_undef  = OpUndef %ivec3\n"
2816
2817                 "%sc_0        = OpSpecConstant %i32 0\n"
2818                 "%sc_1        = OpSpecConstant %i32 0\n"
2819                 "%sc_2        = OpSpecConstant %i32 0\n"
2820                 "%sc_vec3_0   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_0        %ivec3_0     0\n"                                                 // (sc_0, 0, 0)
2821                 "%sc_vec3_1   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_1        %ivec3_0     1\n"                                                 // (0, sc_1, 0)
2822                 "%sc_vec3_2   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_2        %ivec3_0     2\n"                                                 // (0, 0, sc_2)
2823                 "%sc_vec3_0_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0   %vec3_undef  0          0xFFFFFFFF 2\n"   // (sc_0, ???,  0)
2824                 "%sc_vec3_1_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_1   %vec3_undef  0xFFFFFFFF 1          0\n"   // (???,  sc_1, 0)
2825                 "%sc_vec3_2_s = OpSpecConstantOp %ivec3 VectorShuffle    %vec3_undef  %sc_vec3_2   5          0xFFFFFFFF 5\n"   // (sc_2, ???,  sc_2)
2826                 "%sc_vec3_01  = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0_s %sc_vec3_1_s 1 0 4\n"                                             // (0,    sc_0, sc_1)
2827                 "%sc_vec3_012 = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_01  %sc_vec3_2_s 5 1 2\n"                                             // (sc_2, sc_0, sc_1)
2828                 "%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              0\n"                                                 // sc_2
2829                 "%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              1\n"                                                 // sc_0
2830                 "%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              2\n"                                                 // sc_1
2831                 "%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"                                                              // (sc_2 - sc_0)
2832                 "%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n"                                                              // (sc_2 - sc_0) * sc_1
2833
2834                 "%main      = OpFunction %void None %voidf\n"
2835                 "%label     = OpLabel\n"
2836                 "%idval     = OpLoad %uvec3 %id\n"
2837                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2838                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
2839                 "%inval     = OpLoad %i32 %inloc\n"
2840                 "%final     = OpIAdd %i32 %inval %sc_final\n"
2841                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2842                 "             OpStore %outloc %final\n"
2843                 "             OpReturn\n"
2844                 "             OpFunctionEnd\n";
2845         spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
2846         spec.outputs.push_back(BufferSp(new Int32Buffer(outputInts3)));
2847         spec.numWorkGroups = IVec3(numElements, 1, 1);
2848         spec.specConstants.append<deInt32>(123);
2849         spec.specConstants.append<deInt32>(56);
2850         spec.specConstants.append<deInt32>(-77);
2851
2852         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector_related", "VectorShuffle, CompositeExtract, & CompositeInsert", spec));
2853
2854         return group.release();
2855 }
2856
2857 void createOpPhiVartypeTests (de::MovePtr<tcu::TestCaseGroup>& group, tcu::TestContext& testCtx)
2858 {
2859         ComputeShaderSpec       specInt;
2860         ComputeShaderSpec       specFloat;
2861         ComputeShaderSpec       specVec3;
2862         ComputeShaderSpec       specMat4;
2863         ComputeShaderSpec       specArray;
2864         ComputeShaderSpec       specStruct;
2865         de::Random                      rnd                             (deStringHash(group->getName()));
2866         const int                       numElements             = 100;
2867         vector<float>           inputFloats             (numElements, 0);
2868         vector<float>           outputFloats    (numElements, 0);
2869
2870         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
2871
2872         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2873         floorAll(inputFloats);
2874
2875         for (size_t ndx = 0; ndx < numElements; ++ndx)
2876         {
2877                 // Just check if the value is positive or not
2878                 outputFloats[ndx] = (inputFloats[ndx] > 0) ? 1.0f : -1.0f;
2879         }
2880
2881         // All of the tests are of the form:
2882         //
2883         // testtype r
2884         //
2885         // if (inputdata > 0)
2886         //   r = 1
2887         // else
2888         //   r = -1
2889         //
2890         // return (float)r
2891
2892         specFloat.assembly =
2893                 string(getComputeAsmShaderPreamble()) +
2894
2895                 "OpSource GLSL 430\n"
2896                 "OpName %main \"main\"\n"
2897                 "OpName %id \"gl_GlobalInvocationID\"\n"
2898
2899                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2900
2901                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2902
2903                 "%id = OpVariable %uvec3ptr Input\n"
2904                 "%zero       = OpConstant %i32 0\n"
2905                 "%float_0    = OpConstant %f32 0.0\n"
2906                 "%float_1    = OpConstant %f32 1.0\n"
2907                 "%float_n1   = OpConstant %f32 -1.0\n"
2908
2909                 "%main     = OpFunction %void None %voidf\n"
2910                 "%entry    = OpLabel\n"
2911                 "%idval    = OpLoad %uvec3 %id\n"
2912                 "%x        = OpCompositeExtract %u32 %idval 0\n"
2913                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
2914                 "%inval    = OpLoad %f32 %inloc\n"
2915
2916                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
2917                 "            OpSelectionMerge %cm None\n"
2918                 "            OpBranchConditional %comp %tb %fb\n"
2919                 "%tb       = OpLabel\n"
2920                 "            OpBranch %cm\n"
2921                 "%fb       = OpLabel\n"
2922                 "            OpBranch %cm\n"
2923                 "%cm       = OpLabel\n"
2924                 "%res      = OpPhi %f32 %float_1 %tb %float_n1 %fb\n"
2925
2926                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
2927                 "            OpStore %outloc %res\n"
2928                 "            OpReturn\n"
2929
2930                 "            OpFunctionEnd\n";
2931         specFloat.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2932         specFloat.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2933         specFloat.numWorkGroups = IVec3(numElements, 1, 1);
2934
2935         specMat4.assembly =
2936                 string(getComputeAsmShaderPreamble()) +
2937
2938                 "OpSource GLSL 430\n"
2939                 "OpName %main \"main\"\n"
2940                 "OpName %id \"gl_GlobalInvocationID\"\n"
2941
2942                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2943
2944                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2945
2946                 "%id = OpVariable %uvec3ptr Input\n"
2947                 "%v4f32      = OpTypeVector %f32 4\n"
2948                 "%mat4v4f32  = OpTypeMatrix %v4f32 4\n"
2949                 "%zero       = OpConstant %i32 0\n"
2950                 "%float_0    = OpConstant %f32 0.0\n"
2951                 "%float_1    = OpConstant %f32 1.0\n"
2952                 "%float_n1   = OpConstant %f32 -1.0\n"
2953                 "%m11        = OpConstantComposite %v4f32 %float_1 %float_0 %float_0 %float_0\n"
2954                 "%m12        = OpConstantComposite %v4f32 %float_0 %float_1 %float_0 %float_0\n"
2955                 "%m13        = OpConstantComposite %v4f32 %float_0 %float_0 %float_1 %float_0\n"
2956                 "%m14        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_1\n"
2957                 "%m1         = OpConstantComposite %mat4v4f32 %m11 %m12 %m13 %m14\n"
2958                 "%m21        = OpConstantComposite %v4f32 %float_n1 %float_0 %float_0 %float_0\n"
2959                 "%m22        = OpConstantComposite %v4f32 %float_0 %float_n1 %float_0 %float_0\n"
2960                 "%m23        = OpConstantComposite %v4f32 %float_0 %float_0 %float_n1 %float_0\n"
2961                 "%m24        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_n1\n"
2962                 "%m2         = OpConstantComposite %mat4v4f32 %m21 %m22 %m23 %m24\n"
2963
2964                 "%main     = OpFunction %void None %voidf\n"
2965                 "%entry    = OpLabel\n"
2966                 "%idval    = OpLoad %uvec3 %id\n"
2967                 "%x        = OpCompositeExtract %u32 %idval 0\n"
2968                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
2969                 "%inval    = OpLoad %f32 %inloc\n"
2970
2971                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
2972                 "            OpSelectionMerge %cm None\n"
2973                 "            OpBranchConditional %comp %tb %fb\n"
2974                 "%tb       = OpLabel\n"
2975                 "            OpBranch %cm\n"
2976                 "%fb       = OpLabel\n"
2977                 "            OpBranch %cm\n"
2978                 "%cm       = OpLabel\n"
2979                 "%mres     = OpPhi %mat4v4f32 %m1 %tb %m2 %fb\n"
2980                 "%res      = OpCompositeExtract %f32 %mres 2 2\n"
2981
2982                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
2983                 "            OpStore %outloc %res\n"
2984                 "            OpReturn\n"
2985
2986                 "            OpFunctionEnd\n";
2987         specMat4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2988         specMat4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2989         specMat4.numWorkGroups = IVec3(numElements, 1, 1);
2990
2991         specVec3.assembly =
2992                 string(getComputeAsmShaderPreamble()) +
2993
2994                 "OpSource GLSL 430\n"
2995                 "OpName %main \"main\"\n"
2996                 "OpName %id \"gl_GlobalInvocationID\"\n"
2997
2998                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2999
3000                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3001
3002                 "%id = OpVariable %uvec3ptr Input\n"
3003                 "%zero       = OpConstant %i32 0\n"
3004                 "%float_0    = OpConstant %f32 0.0\n"
3005                 "%float_1    = OpConstant %f32 1.0\n"
3006                 "%float_n1   = OpConstant %f32 -1.0\n"
3007                 "%v1         = OpConstantComposite %fvec3 %float_1 %float_1 %float_1\n"
3008                 "%v2         = OpConstantComposite %fvec3 %float_n1 %float_n1 %float_n1\n"
3009
3010                 "%main     = OpFunction %void None %voidf\n"
3011                 "%entry    = OpLabel\n"
3012                 "%idval    = OpLoad %uvec3 %id\n"
3013                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3014                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3015                 "%inval    = OpLoad %f32 %inloc\n"
3016
3017                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3018                 "            OpSelectionMerge %cm None\n"
3019                 "            OpBranchConditional %comp %tb %fb\n"
3020                 "%tb       = OpLabel\n"
3021                 "            OpBranch %cm\n"
3022                 "%fb       = OpLabel\n"
3023                 "            OpBranch %cm\n"
3024                 "%cm       = OpLabel\n"
3025                 "%vres     = OpPhi %fvec3 %v1 %tb %v2 %fb\n"
3026                 "%res      = OpCompositeExtract %f32 %vres 2\n"
3027
3028                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3029                 "            OpStore %outloc %res\n"
3030                 "            OpReturn\n"
3031
3032                 "            OpFunctionEnd\n";
3033         specVec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3034         specVec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3035         specVec3.numWorkGroups = IVec3(numElements, 1, 1);
3036
3037         specInt.assembly =
3038                 string(getComputeAsmShaderPreamble()) +
3039
3040                 "OpSource GLSL 430\n"
3041                 "OpName %main \"main\"\n"
3042                 "OpName %id \"gl_GlobalInvocationID\"\n"
3043
3044                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3045
3046                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3047
3048                 "%id = OpVariable %uvec3ptr Input\n"
3049                 "%zero       = OpConstant %i32 0\n"
3050                 "%float_0    = OpConstant %f32 0.0\n"
3051                 "%i1         = OpConstant %i32 1\n"
3052                 "%i2         = OpConstant %i32 -1\n"
3053
3054                 "%main     = OpFunction %void None %voidf\n"
3055                 "%entry    = OpLabel\n"
3056                 "%idval    = OpLoad %uvec3 %id\n"
3057                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3058                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3059                 "%inval    = OpLoad %f32 %inloc\n"
3060
3061                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3062                 "            OpSelectionMerge %cm None\n"
3063                 "            OpBranchConditional %comp %tb %fb\n"
3064                 "%tb       = OpLabel\n"
3065                 "            OpBranch %cm\n"
3066                 "%fb       = OpLabel\n"
3067                 "            OpBranch %cm\n"
3068                 "%cm       = OpLabel\n"
3069                 "%ires     = OpPhi %i32 %i1 %tb %i2 %fb\n"
3070                 "%res      = OpConvertSToF %f32 %ires\n"
3071
3072                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3073                 "            OpStore %outloc %res\n"
3074                 "            OpReturn\n"
3075
3076                 "            OpFunctionEnd\n";
3077         specInt.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3078         specInt.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3079         specInt.numWorkGroups = IVec3(numElements, 1, 1);
3080
3081         specArray.assembly =
3082                 string(getComputeAsmShaderPreamble()) +
3083
3084                 "OpSource GLSL 430\n"
3085                 "OpName %main \"main\"\n"
3086                 "OpName %id \"gl_GlobalInvocationID\"\n"
3087
3088                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3089
3090                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3091
3092                 "%id = OpVariable %uvec3ptr Input\n"
3093                 "%zero       = OpConstant %i32 0\n"
3094                 "%u7         = OpConstant %u32 7\n"
3095                 "%float_0    = OpConstant %f32 0.0\n"
3096                 "%float_1    = OpConstant %f32 1.0\n"
3097                 "%float_n1   = OpConstant %f32 -1.0\n"
3098                 "%f32a7      = OpTypeArray %f32 %u7\n"
3099                 "%a1         = OpConstantComposite %f32a7 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1\n"
3100                 "%a2         = OpConstantComposite %f32a7 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1\n"
3101                 "%main     = OpFunction %void None %voidf\n"
3102                 "%entry    = OpLabel\n"
3103                 "%idval    = OpLoad %uvec3 %id\n"
3104                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3105                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3106                 "%inval    = OpLoad %f32 %inloc\n"
3107
3108                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3109                 "            OpSelectionMerge %cm None\n"
3110                 "            OpBranchConditional %comp %tb %fb\n"
3111                 "%tb       = OpLabel\n"
3112                 "            OpBranch %cm\n"
3113                 "%fb       = OpLabel\n"
3114                 "            OpBranch %cm\n"
3115                 "%cm       = OpLabel\n"
3116                 "%ares     = OpPhi %f32a7 %a1 %tb %a2 %fb\n"
3117                 "%res      = OpCompositeExtract %f32 %ares 5\n"
3118
3119                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3120                 "            OpStore %outloc %res\n"
3121                 "            OpReturn\n"
3122
3123                 "            OpFunctionEnd\n";
3124         specArray.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3125         specArray.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3126         specArray.numWorkGroups = IVec3(numElements, 1, 1);
3127
3128         specStruct.assembly =
3129                 string(getComputeAsmShaderPreamble()) +
3130
3131                 "OpSource GLSL 430\n"
3132                 "OpName %main \"main\"\n"
3133                 "OpName %id \"gl_GlobalInvocationID\"\n"
3134
3135                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3136
3137                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3138
3139                 "%id = OpVariable %uvec3ptr Input\n"
3140                 "%zero       = OpConstant %i32 0\n"
3141                 "%float_0    = OpConstant %f32 0.0\n"
3142                 "%float_1    = OpConstant %f32 1.0\n"
3143                 "%float_n1   = OpConstant %f32 -1.0\n"
3144
3145                 "%v2f32      = OpTypeVector %f32 2\n"
3146                 "%Data2      = OpTypeStruct %f32 %v2f32\n"
3147                 "%Data       = OpTypeStruct %Data2 %f32\n"
3148
3149                 "%in1a       = OpConstantComposite %v2f32 %float_1 %float_1\n"
3150                 "%in1b       = OpConstantComposite %Data2 %float_1 %in1a\n"
3151                 "%s1         = OpConstantComposite %Data %in1b %float_1\n"
3152                 "%in2a       = OpConstantComposite %v2f32 %float_n1 %float_n1\n"
3153                 "%in2b       = OpConstantComposite %Data2 %float_n1 %in2a\n"
3154                 "%s2         = OpConstantComposite %Data %in2b %float_n1\n"
3155
3156                 "%main     = OpFunction %void None %voidf\n"
3157                 "%entry    = OpLabel\n"
3158                 "%idval    = OpLoad %uvec3 %id\n"
3159                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3160                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3161                 "%inval    = OpLoad %f32 %inloc\n"
3162
3163                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3164                 "            OpSelectionMerge %cm None\n"
3165                 "            OpBranchConditional %comp %tb %fb\n"
3166                 "%tb       = OpLabel\n"
3167                 "            OpBranch %cm\n"
3168                 "%fb       = OpLabel\n"
3169                 "            OpBranch %cm\n"
3170                 "%cm       = OpLabel\n"
3171                 "%sres     = OpPhi %Data %s1 %tb %s2 %fb\n"
3172                 "%res      = OpCompositeExtract %f32 %sres 0 0\n"
3173
3174                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3175                 "            OpStore %outloc %res\n"
3176                 "            OpReturn\n"
3177
3178                 "            OpFunctionEnd\n";
3179         specStruct.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3180         specStruct.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3181         specStruct.numWorkGroups = IVec3(numElements, 1, 1);
3182
3183         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_int", "OpPhi with int variables", specInt));
3184         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_float", "OpPhi with float variables", specFloat));
3185         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_vec3", "OpPhi with vec3 variables", specVec3));
3186         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_mat4", "OpPhi with mat4 variables", specMat4));
3187         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_array", "OpPhi with array variables", specArray));
3188         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_struct", "OpPhi with struct variables", specStruct));
3189 }
3190
3191 string generateConstantDefinitions (int count)
3192 {
3193         std::ostringstream      r;
3194         for (int i = 0; i < count; i++)
3195                 r << "%cf" << (i * 10 + 5) << " = OpConstant %f32 " <<(i * 10 + 5) << ".0\n";
3196         r << "\n";
3197         return r.str();
3198 }
3199
3200 string generateSwitchCases (int count)
3201 {
3202         std::ostringstream      r;
3203         for (int i = 0; i < count; i++)
3204                 r << " " << i << " %case" << i;
3205         r << "\n";
3206         return r.str();
3207 }
3208
3209 string generateSwitchTargets (int count)
3210 {
3211         std::ostringstream      r;
3212         for (int i = 0; i < count; i++)
3213                 r << "%case" << i << " = OpLabel\n            OpBranch %phi\n";
3214         r << "\n";
3215         return r.str();
3216 }
3217
3218 string generateOpPhiParams (int count)
3219 {
3220         std::ostringstream      r;
3221         for (int i = 0; i < count; i++)
3222                 r << " %cf" << (i * 10 + 5) << " %case" << i;
3223         r << "\n";
3224         return r.str();
3225 }
3226
3227 string generateIntWidth (int value)
3228 {
3229         std::ostringstream      r;
3230         r << value;
3231         return r.str();
3232 }
3233
3234 // Expand input string by injecting "ABC" between the input
3235 // string characters. The acc/add/treshold parameters are used
3236 // to skip some of the injections to make the result less
3237 // uniform (and a lot shorter).
3238 string expandOpPhiCase5 (const string& s, int &acc, int add, int treshold)
3239 {
3240         std::ostringstream      res;
3241         const char*                     p = s.c_str();
3242
3243         while (*p)
3244         {
3245                 res << *p;
3246                 acc += add;
3247                 if (acc > treshold)
3248                 {
3249                         acc -= treshold;
3250                         res << "ABC";
3251                 }
3252                 p++;
3253         }
3254         return res.str();
3255 }
3256
3257 // Calculate expected result based on the code string
3258 float calcOpPhiCase5 (float val, const string& s)
3259 {
3260         const char*             p               = s.c_str();
3261         float                   x[8];
3262         bool                    b[8];
3263         const float             tv[8]   = { 0.5f, 1.5f, 3.5f, 7.5f, 15.5f, 31.5f, 63.5f, 127.5f };
3264         const float             v               = deFloatAbs(val);
3265         float                   res             = 0;
3266         int                             depth   = -1;
3267         int                             skip    = 0;
3268
3269         for (int i = 7; i >= 0; --i)
3270                 x[i] = std::fmod((float)v, (float)(2 << i));
3271         for (int i = 7; i >= 0; --i)
3272                 b[i] = x[i] > tv[i];
3273
3274         while (*p)
3275         {
3276                 if (*p == 'A')
3277                 {
3278                         depth++;
3279                         if (skip == 0 && b[depth])
3280                         {
3281                                 res++;
3282                         }
3283                         else
3284                                 skip++;
3285                 }
3286                 if (*p == 'B')
3287                 {
3288                         if (skip)
3289                                 skip--;
3290                         if (b[depth] || skip)
3291                                 skip++;
3292                 }
3293                 if (*p == 'C')
3294                 {
3295                         depth--;
3296                         if (skip)
3297                                 skip--;
3298                 }
3299                 p++;
3300         }
3301         return res;
3302 }
3303
3304 // In the code string, the letters represent the following:
3305 //
3306 // A:
3307 //     if (certain bit is set)
3308 //     {
3309 //       result++;
3310 //
3311 // B:
3312 //     } else {
3313 //
3314 // C:
3315 //     }
3316 //
3317 // examples:
3318 // AABCBC leads to if(){r++;if(){r++;}else{}}else{}
3319 // ABABCC leads to if(){r++;}else{if(){r++;}else{}}
3320 // ABCABC leads to if(){r++;}else{}if(){r++;}else{}
3321 //
3322 // Code generation gets a bit complicated due to the else-branches,
3323 // which do not generate new values. Thus, the generator needs to
3324 // keep track of the previous variable change seen by the else
3325 // branch.
3326 string generateOpPhiCase5 (const string& s)
3327 {
3328         std::stack<int>                         idStack;
3329         std::stack<std::string>         value;
3330         std::stack<std::string>         valueLabel;
3331         std::stack<std::string>         mergeLeft;
3332         std::stack<std::string>         mergeRight;
3333         std::ostringstream                      res;
3334         const char*                                     p                       = s.c_str();
3335         int                                                     depth           = -1;
3336         int                                                     currId          = 0;
3337         int                                                     iter            = 0;
3338
3339         idStack.push(-1);
3340         value.push("%f32_0");
3341         valueLabel.push("%f32_0 %entry");
3342
3343         while (*p)
3344         {
3345                 if (*p == 'A')
3346                 {
3347                         depth++;
3348                         currId = iter;
3349                         idStack.push(currId);
3350                         res << "\tOpSelectionMerge %m" << currId << " None\n";
3351                         res << "\tOpBranchConditional %b" << depth << " %t" << currId << " %f" << currId << "\n";
3352                         res << "%t" << currId << " = OpLabel\n";
3353                         res << "%rt" << currId << " = OpFAdd %f32 " << value.top() << " %f32_1\n";
3354                         std::ostringstream tag;
3355                         tag << "%rt" << currId;
3356                         value.push(tag.str());
3357                         tag << " %t" << currId;
3358                         valueLabel.push(tag.str());
3359                 }
3360
3361                 if (*p == 'B')
3362                 {
3363                         mergeLeft.push(valueLabel.top());
3364                         value.pop();
3365                         valueLabel.pop();
3366                         res << "\tOpBranch %m" << currId << "\n";
3367                         res << "%f" << currId << " = OpLabel\n";
3368                         std::ostringstream tag;
3369                         tag << value.top() << " %f" << currId;
3370                         valueLabel.pop();
3371                         valueLabel.push(tag.str());
3372                 }
3373
3374                 if (*p == 'C')
3375                 {
3376                         mergeRight.push(valueLabel.top());
3377                         res << "\tOpBranch %m" << currId << "\n";
3378                         res << "%m" << currId << " = OpLabel\n";
3379                         if (*(p + 1) == 0)
3380                                 res << "%res"; // last result goes to %res
3381                         else
3382                                 res << "%rm" << currId;
3383                         res << " = OpPhi %f32  " << mergeLeft.top() << "  " << mergeRight.top() << "\n";
3384                         std::ostringstream tag;
3385                         tag << "%rm" << currId;
3386                         value.pop();
3387                         value.push(tag.str());
3388                         tag << " %m" << currId;
3389                         valueLabel.pop();
3390                         valueLabel.push(tag.str());
3391                         mergeLeft.pop();
3392                         mergeRight.pop();
3393                         depth--;
3394                         idStack.pop();
3395                         currId = idStack.top();
3396                 }
3397                 p++;
3398                 iter++;
3399         }
3400         return res.str();
3401 }
3402
3403 tcu::TestCaseGroup* createOpPhiGroup (tcu::TestContext& testCtx)
3404 {
3405         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
3406         ComputeShaderSpec                               spec1;
3407         ComputeShaderSpec                               spec2;
3408         ComputeShaderSpec                               spec3;
3409         ComputeShaderSpec                               spec4;
3410         ComputeShaderSpec                               spec5;
3411         de::Random                                              rnd                             (deStringHash(group->getName()));
3412         const int                                               numElements             = 100;
3413         vector<float>                                   inputFloats             (numElements, 0);
3414         vector<float>                                   outputFloats1   (numElements, 0);
3415         vector<float>                                   outputFloats2   (numElements, 0);
3416         vector<float>                                   outputFloats3   (numElements, 0);
3417         vector<float>                                   outputFloats4   (numElements, 0);
3418         vector<float>                                   outputFloats5   (numElements, 0);
3419         std::string                                             codestring              = "ABC";
3420         const int                                               test4Width              = 1024;
3421
3422         // Build case 5 code string. Each iteration makes the hierarchy more complicated.
3423         // 9 iterations with (7, 24) parameters makes the hierarchy 8 deep with about 1500 lines of
3424         // shader code.
3425         for (int i = 0, acc = 0; i < 9; i++)
3426                 codestring = expandOpPhiCase5(codestring, acc, 7, 24);
3427
3428         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
3429
3430         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3431         floorAll(inputFloats);
3432
3433         for (size_t ndx = 0; ndx < numElements; ++ndx)
3434         {
3435                 switch (ndx % 3)
3436                 {
3437                         case 0:         outputFloats1[ndx] = inputFloats[ndx] + 5.5f;   break;
3438                         case 1:         outputFloats1[ndx] = inputFloats[ndx] + 20.5f;  break;
3439                         case 2:         outputFloats1[ndx] = inputFloats[ndx] + 1.75f;  break;
3440                         default:        break;
3441                 }
3442                 outputFloats2[ndx] = inputFloats[ndx] + 6.5f * 3;
3443                 outputFloats3[ndx] = 8.5f - inputFloats[ndx];
3444
3445                 int index4 = (int)deFloor(deAbs((float)ndx * inputFloats[ndx]));
3446                 outputFloats4[ndx] = (float)(index4 % test4Width) * 10.0f + 5.0f;
3447
3448                 outputFloats5[ndx] = calcOpPhiCase5(inputFloats[ndx], codestring);
3449         }
3450
3451         spec1.assembly =
3452                 string(getComputeAsmShaderPreamble()) +
3453
3454                 "OpSource GLSL 430\n"
3455                 "OpName %main \"main\"\n"
3456                 "OpName %id \"gl_GlobalInvocationID\"\n"
3457
3458                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3459
3460                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3461
3462                 "%id = OpVariable %uvec3ptr Input\n"
3463                 "%zero       = OpConstant %i32 0\n"
3464                 "%three      = OpConstant %u32 3\n"
3465                 "%constf5p5  = OpConstant %f32 5.5\n"
3466                 "%constf20p5 = OpConstant %f32 20.5\n"
3467                 "%constf1p75 = OpConstant %f32 1.75\n"
3468                 "%constf8p5  = OpConstant %f32 8.5\n"
3469                 "%constf6p5  = OpConstant %f32 6.5\n"
3470
3471                 "%main     = OpFunction %void None %voidf\n"
3472                 "%entry    = OpLabel\n"
3473                 "%idval    = OpLoad %uvec3 %id\n"
3474                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3475                 "%selector = OpUMod %u32 %x %three\n"
3476                 "            OpSelectionMerge %phi None\n"
3477                 "            OpSwitch %selector %default 0 %case0 1 %case1 2 %case2\n"
3478
3479                 // Case 1 before OpPhi.
3480                 "%case1    = OpLabel\n"
3481                 "            OpBranch %phi\n"
3482
3483                 "%default  = OpLabel\n"
3484                 "            OpUnreachable\n"
3485
3486                 "%phi      = OpLabel\n"
3487                 "%operand  = OpPhi %f32   %constf1p75 %case2   %constf20p5 %case1   %constf5p5 %case0\n" // not in the order of blocks
3488                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3489                 "%inval    = OpLoad %f32 %inloc\n"
3490                 "%add      = OpFAdd %f32 %inval %operand\n"
3491                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3492                 "            OpStore %outloc %add\n"
3493                 "            OpReturn\n"
3494
3495                 // Case 0 after OpPhi.
3496                 "%case0    = OpLabel\n"
3497                 "            OpBranch %phi\n"
3498
3499
3500                 // Case 2 after OpPhi.
3501                 "%case2    = OpLabel\n"
3502                 "            OpBranch %phi\n"
3503
3504                 "            OpFunctionEnd\n";
3505         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3506         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
3507         spec1.numWorkGroups = IVec3(numElements, 1, 1);
3508
3509         group->addChild(new SpvAsmComputeShaderCase(testCtx, "block", "out-of-order and unreachable blocks for OpPhi", spec1));
3510
3511         spec2.assembly =
3512                 string(getComputeAsmShaderPreamble()) +
3513
3514                 "OpName %main \"main\"\n"
3515                 "OpName %id \"gl_GlobalInvocationID\"\n"
3516
3517                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3518
3519                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3520
3521                 "%id         = OpVariable %uvec3ptr Input\n"
3522                 "%zero       = OpConstant %i32 0\n"
3523                 "%one        = OpConstant %i32 1\n"
3524                 "%three      = OpConstant %i32 3\n"
3525                 "%constf6p5  = OpConstant %f32 6.5\n"
3526
3527                 "%main       = OpFunction %void None %voidf\n"
3528                 "%entry      = OpLabel\n"
3529                 "%idval      = OpLoad %uvec3 %id\n"
3530                 "%x          = OpCompositeExtract %u32 %idval 0\n"
3531                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3532                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3533                 "%inval      = OpLoad %f32 %inloc\n"
3534                 "              OpBranch %phi\n"
3535
3536                 "%phi        = OpLabel\n"
3537                 "%step       = OpPhi %i32 %zero  %entry %step_next  %phi\n"
3538                 "%accum      = OpPhi %f32 %inval %entry %accum_next %phi\n"
3539                 "%step_next  = OpIAdd %i32 %step %one\n"
3540                 "%accum_next = OpFAdd %f32 %accum %constf6p5\n"
3541                 "%still_loop = OpSLessThan %bool %step %three\n"
3542                 "              OpLoopMerge %exit %phi None\n"
3543                 "              OpBranchConditional %still_loop %phi %exit\n"
3544
3545                 "%exit       = OpLabel\n"
3546                 "              OpStore %outloc %accum\n"
3547                 "              OpReturn\n"
3548                 "              OpFunctionEnd\n";
3549         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3550         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
3551         spec2.numWorkGroups = IVec3(numElements, 1, 1);
3552
3553         group->addChild(new SpvAsmComputeShaderCase(testCtx, "induction", "The usual way induction variables are handled in LLVM IR", spec2));
3554
3555         spec3.assembly =
3556                 string(getComputeAsmShaderPreamble()) +
3557
3558                 "OpName %main \"main\"\n"
3559                 "OpName %id \"gl_GlobalInvocationID\"\n"
3560
3561                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3562
3563                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3564
3565                 "%f32ptr_f   = OpTypePointer Function %f32\n"
3566                 "%id         = OpVariable %uvec3ptr Input\n"
3567                 "%true       = OpConstantTrue %bool\n"
3568                 "%false      = OpConstantFalse %bool\n"
3569                 "%zero       = OpConstant %i32 0\n"
3570                 "%constf8p5  = OpConstant %f32 8.5\n"
3571
3572                 "%main       = OpFunction %void None %voidf\n"
3573                 "%entry      = OpLabel\n"
3574                 "%b          = OpVariable %f32ptr_f Function %constf8p5\n"
3575                 "%idval      = OpLoad %uvec3 %id\n"
3576                 "%x          = OpCompositeExtract %u32 %idval 0\n"
3577                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3578                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3579                 "%a_init     = OpLoad %f32 %inloc\n"
3580                 "%b_init     = OpLoad %f32 %b\n"
3581                 "              OpBranch %phi\n"
3582
3583                 "%phi        = OpLabel\n"
3584                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
3585                 "%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
3586                 "%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
3587                 "              OpLoopMerge %exit %phi None\n"
3588                 "              OpBranchConditional %still_loop %phi %exit\n"
3589
3590                 "%exit       = OpLabel\n"
3591                 "%sub        = OpFSub %f32 %a_next %b_next\n"
3592                 "              OpStore %outloc %sub\n"
3593                 "              OpReturn\n"
3594                 "              OpFunctionEnd\n";
3595         spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3596         spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
3597         spec3.numWorkGroups = IVec3(numElements, 1, 1);
3598
3599         group->addChild(new SpvAsmComputeShaderCase(testCtx, "swap", "Swap the values of two variables using OpPhi", spec3));
3600
3601         spec4.assembly =
3602                 "OpCapability Shader\n"
3603                 "%ext = OpExtInstImport \"GLSL.std.450\"\n"
3604                 "OpMemoryModel Logical GLSL450\n"
3605                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3606                 "OpExecutionMode %main LocalSize 1 1 1\n"
3607
3608                 "OpSource GLSL 430\n"
3609                 "OpName %main \"main\"\n"
3610                 "OpName %id \"gl_GlobalInvocationID\"\n"
3611
3612                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3613
3614                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3615
3616                 "%id       = OpVariable %uvec3ptr Input\n"
3617                 "%zero     = OpConstant %i32 0\n"
3618                 "%cimod    = OpConstant %u32 " + generateIntWidth(test4Width) + "\n"
3619
3620                 + generateConstantDefinitions(test4Width) +
3621
3622                 "%main     = OpFunction %void None %voidf\n"
3623                 "%entry    = OpLabel\n"
3624                 "%idval    = OpLoad %uvec3 %id\n"
3625                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3626                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3627                 "%inval    = OpLoad %f32 %inloc\n"
3628                 "%xf       = OpConvertUToF %f32 %x\n"
3629                 "%xm       = OpFMul %f32 %xf %inval\n"
3630                 "%xa       = OpExtInst %f32 %ext FAbs %xm\n"
3631                 "%xi       = OpConvertFToU %u32 %xa\n"
3632                 "%selector = OpUMod %u32 %xi %cimod\n"
3633                 "            OpSelectionMerge %phi None\n"
3634                 "            OpSwitch %selector %default "
3635
3636                 + generateSwitchCases(test4Width) +
3637
3638                 "%default  = OpLabel\n"
3639                 "            OpUnreachable\n"
3640
3641                 + generateSwitchTargets(test4Width) +
3642
3643                 "%phi      = OpLabel\n"
3644                 "%result   = OpPhi %f32"
3645
3646                 + generateOpPhiParams(test4Width) +
3647
3648                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3649                 "            OpStore %outloc %result\n"
3650                 "            OpReturn\n"
3651
3652                 "            OpFunctionEnd\n";
3653         spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3654         spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
3655         spec4.numWorkGroups = IVec3(numElements, 1, 1);
3656
3657         group->addChild(new SpvAsmComputeShaderCase(testCtx, "wide", "OpPhi with a lot of parameters", spec4));
3658
3659         spec5.assembly =
3660                 "OpCapability Shader\n"
3661                 "%ext      = OpExtInstImport \"GLSL.std.450\"\n"
3662                 "OpMemoryModel Logical GLSL450\n"
3663                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3664                 "OpExecutionMode %main LocalSize 1 1 1\n"
3665                 "%code     = OpString \"" + codestring + "\"\n"
3666
3667                 "OpSource GLSL 430\n"
3668                 "OpName %main \"main\"\n"
3669                 "OpName %id \"gl_GlobalInvocationID\"\n"
3670
3671                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3672
3673                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3674
3675                 "%id       = OpVariable %uvec3ptr Input\n"
3676                 "%zero     = OpConstant %i32 0\n"
3677                 "%f32_0    = OpConstant %f32 0.0\n"
3678                 "%f32_0_5  = OpConstant %f32 0.5\n"
3679                 "%f32_1    = OpConstant %f32 1.0\n"
3680                 "%f32_1_5  = OpConstant %f32 1.5\n"
3681                 "%f32_2    = OpConstant %f32 2.0\n"
3682                 "%f32_3_5  = OpConstant %f32 3.5\n"
3683                 "%f32_4    = OpConstant %f32 4.0\n"
3684                 "%f32_7_5  = OpConstant %f32 7.5\n"
3685                 "%f32_8    = OpConstant %f32 8.0\n"
3686                 "%f32_15_5 = OpConstant %f32 15.5\n"
3687                 "%f32_16   = OpConstant %f32 16.0\n"
3688                 "%f32_31_5 = OpConstant %f32 31.5\n"
3689                 "%f32_32   = OpConstant %f32 32.0\n"
3690                 "%f32_63_5 = OpConstant %f32 63.5\n"
3691                 "%f32_64   = OpConstant %f32 64.0\n"
3692                 "%f32_127_5 = OpConstant %f32 127.5\n"
3693                 "%f32_128  = OpConstant %f32 128.0\n"
3694                 "%f32_256  = OpConstant %f32 256.0\n"
3695
3696                 "%main     = OpFunction %void None %voidf\n"
3697                 "%entry    = OpLabel\n"
3698                 "%idval    = OpLoad %uvec3 %id\n"
3699                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3700                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3701                 "%inval    = OpLoad %f32 %inloc\n"
3702
3703                 "%xabs     = OpExtInst %f32 %ext FAbs %inval\n"
3704                 "%x8       = OpFMod %f32 %xabs %f32_256\n"
3705                 "%x7       = OpFMod %f32 %xabs %f32_128\n"
3706                 "%x6       = OpFMod %f32 %xabs %f32_64\n"
3707                 "%x5       = OpFMod %f32 %xabs %f32_32\n"
3708                 "%x4       = OpFMod %f32 %xabs %f32_16\n"
3709                 "%x3       = OpFMod %f32 %xabs %f32_8\n"
3710                 "%x2       = OpFMod %f32 %xabs %f32_4\n"
3711                 "%x1       = OpFMod %f32 %xabs %f32_2\n"
3712
3713                 "%b7       = OpFOrdGreaterThanEqual %bool %x8 %f32_127_5\n"
3714                 "%b6       = OpFOrdGreaterThanEqual %bool %x7 %f32_63_5\n"
3715                 "%b5       = OpFOrdGreaterThanEqual %bool %x6 %f32_31_5\n"
3716                 "%b4       = OpFOrdGreaterThanEqual %bool %x5 %f32_15_5\n"
3717                 "%b3       = OpFOrdGreaterThanEqual %bool %x4 %f32_7_5\n"
3718                 "%b2       = OpFOrdGreaterThanEqual %bool %x3 %f32_3_5\n"
3719                 "%b1       = OpFOrdGreaterThanEqual %bool %x2 %f32_1_5\n"
3720                 "%b0       = OpFOrdGreaterThanEqual %bool %x1 %f32_0_5\n"
3721
3722                 + generateOpPhiCase5(codestring) +
3723
3724                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3725                 "            OpStore %outloc %res\n"
3726                 "            OpReturn\n"
3727
3728                 "            OpFunctionEnd\n";
3729         spec5.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3730         spec5.outputs.push_back(BufferSp(new Float32Buffer(outputFloats5)));
3731         spec5.numWorkGroups = IVec3(numElements, 1, 1);
3732
3733         group->addChild(new SpvAsmComputeShaderCase(testCtx, "nested", "Stress OpPhi with a lot of nesting", spec5));
3734
3735         createOpPhiVartypeTests(group, testCtx);
3736
3737         return group.release();
3738 }
3739
3740 // Assembly code used for testing block order is based on GLSL source code:
3741 //
3742 // #version 430
3743 //
3744 // layout(std140, set = 0, binding = 0) readonly buffer Input {
3745 //   float elements[];
3746 // } input_data;
3747 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
3748 //   float elements[];
3749 // } output_data;
3750 //
3751 // void main() {
3752 //   uint x = gl_GlobalInvocationID.x;
3753 //   output_data.elements[x] = input_data.elements[x];
3754 //   if (x > uint(50)) {
3755 //     switch (x % uint(3)) {
3756 //       case 0: output_data.elements[x] += 1.5f; break;
3757 //       case 1: output_data.elements[x] += 42.f; break;
3758 //       case 2: output_data.elements[x] -= 27.f; break;
3759 //       default: break;
3760 //     }
3761 //   } else {
3762 //     output_data.elements[x] = -input_data.elements[x];
3763 //   }
3764 // }
3765 tcu::TestCaseGroup* createBlockOrderGroup (tcu::TestContext& testCtx)
3766 {
3767         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "block_order", "Test block orders"));
3768         ComputeShaderSpec                               spec;
3769         de::Random                                              rnd                             (deStringHash(group->getName()));
3770         const int                                               numElements             = 100;
3771         vector<float>                                   inputFloats             (numElements, 0);
3772         vector<float>                                   outputFloats    (numElements, 0);
3773
3774         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
3775
3776         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3777         floorAll(inputFloats);
3778
3779         for (size_t ndx = 0; ndx <= 50; ++ndx)
3780                 outputFloats[ndx] = -inputFloats[ndx];
3781
3782         for (size_t ndx = 51; ndx < numElements; ++ndx)
3783         {
3784                 switch (ndx % 3)
3785                 {
3786                         case 0:         outputFloats[ndx] = inputFloats[ndx] + 1.5f; break;
3787                         case 1:         outputFloats[ndx] = inputFloats[ndx] + 42.f; break;
3788                         case 2:         outputFloats[ndx] = inputFloats[ndx] - 27.f; break;
3789                         default:        break;
3790                 }
3791         }
3792
3793         spec.assembly =
3794                 string(getComputeAsmShaderPreamble()) +
3795
3796                 "OpSource GLSL 430\n"
3797                 "OpName %main \"main\"\n"
3798                 "OpName %id \"gl_GlobalInvocationID\"\n"
3799
3800                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3801
3802                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
3803
3804                 "%u32ptr       = OpTypePointer Function %u32\n"
3805                 "%u32ptr_input = OpTypePointer Input %u32\n"
3806
3807                 + string(getComputeAsmInputOutputBuffer()) +
3808
3809                 "%id        = OpVariable %uvec3ptr Input\n"
3810                 "%zero      = OpConstant %i32 0\n"
3811                 "%const3    = OpConstant %u32 3\n"
3812                 "%const50   = OpConstant %u32 50\n"
3813                 "%constf1p5 = OpConstant %f32 1.5\n"
3814                 "%constf27  = OpConstant %f32 27.0\n"
3815                 "%constf42  = OpConstant %f32 42.0\n"
3816
3817                 "%main = OpFunction %void None %voidf\n"
3818
3819                 // entry block.
3820                 "%entry    = OpLabel\n"
3821
3822                 // Create a temporary variable to hold the value of gl_GlobalInvocationID.x.
3823                 "%xvar     = OpVariable %u32ptr Function\n"
3824                 "%xptr     = OpAccessChain %u32ptr_input %id %zero\n"
3825                 "%x        = OpLoad %u32 %xptr\n"
3826                 "            OpStore %xvar %x\n"
3827
3828                 "%cmp      = OpUGreaterThan %bool %x %const50\n"
3829                 "            OpSelectionMerge %if_merge None\n"
3830                 "            OpBranchConditional %cmp %if_true %if_false\n"
3831
3832                 // False branch for if-statement: placed in the middle of switch cases and before true branch.
3833                 "%if_false = OpLabel\n"
3834                 "%x_f      = OpLoad %u32 %xvar\n"
3835                 "%inloc_f  = OpAccessChain %f32ptr %indata %zero %x_f\n"
3836                 "%inval_f  = OpLoad %f32 %inloc_f\n"
3837                 "%negate   = OpFNegate %f32 %inval_f\n"
3838                 "%outloc_f = OpAccessChain %f32ptr %outdata %zero %x_f\n"
3839                 "            OpStore %outloc_f %negate\n"
3840                 "            OpBranch %if_merge\n"
3841
3842                 // Merge block for if-statement: placed in the middle of true and false branch.
3843                 "%if_merge = OpLabel\n"
3844                 "            OpReturn\n"
3845
3846                 // True branch for if-statement: placed in the middle of swtich cases and after the false branch.
3847                 "%if_true  = OpLabel\n"
3848                 "%xval_t   = OpLoad %u32 %xvar\n"
3849                 "%mod      = OpUMod %u32 %xval_t %const3\n"
3850                 "            OpSelectionMerge %switch_merge None\n"
3851                 "            OpSwitch %mod %default 0 %case0 1 %case1 2 %case2\n"
3852
3853                 // Merge block for switch-statement: placed before the case
3854                 // bodies.  But it must follow OpSwitch which dominates it.
3855                 "%switch_merge = OpLabel\n"
3856                 "                OpBranch %if_merge\n"
3857
3858                 // Case 1 for switch-statement: placed before case 0.
3859                 // It must follow the OpSwitch that dominates it.
3860                 "%case1    = OpLabel\n"
3861                 "%x_1      = OpLoad %u32 %xvar\n"
3862                 "%inloc_1  = OpAccessChain %f32ptr %indata %zero %x_1\n"
3863                 "%inval_1  = OpLoad %f32 %inloc_1\n"
3864                 "%addf42   = OpFAdd %f32 %inval_1 %constf42\n"
3865                 "%outloc_1 = OpAccessChain %f32ptr %outdata %zero %x_1\n"
3866                 "            OpStore %outloc_1 %addf42\n"
3867                 "            OpBranch %switch_merge\n"
3868
3869                 // Case 2 for switch-statement.
3870                 "%case2    = OpLabel\n"
3871                 "%x_2      = OpLoad %u32 %xvar\n"
3872                 "%inloc_2  = OpAccessChain %f32ptr %indata %zero %x_2\n"
3873                 "%inval_2  = OpLoad %f32 %inloc_2\n"
3874                 "%subf27   = OpFSub %f32 %inval_2 %constf27\n"
3875                 "%outloc_2 = OpAccessChain %f32ptr %outdata %zero %x_2\n"
3876                 "            OpStore %outloc_2 %subf27\n"
3877                 "            OpBranch %switch_merge\n"
3878
3879                 // Default case for switch-statement: placed in the middle of normal cases.
3880                 "%default = OpLabel\n"
3881                 "           OpBranch %switch_merge\n"
3882
3883                 // Case 0 for switch-statement: out of order.
3884                 "%case0    = OpLabel\n"
3885                 "%x_0      = OpLoad %u32 %xvar\n"
3886                 "%inloc_0  = OpAccessChain %f32ptr %indata %zero %x_0\n"
3887                 "%inval_0  = OpLoad %f32 %inloc_0\n"
3888                 "%addf1p5  = OpFAdd %f32 %inval_0 %constf1p5\n"
3889                 "%outloc_0 = OpAccessChain %f32ptr %outdata %zero %x_0\n"
3890                 "            OpStore %outloc_0 %addf1p5\n"
3891                 "            OpBranch %switch_merge\n"
3892
3893                 "            OpFunctionEnd\n";
3894         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3895         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3896         spec.numWorkGroups = IVec3(numElements, 1, 1);
3897
3898         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "various out-of-order blocks", spec));
3899
3900         return group.release();
3901 }
3902
3903 tcu::TestCaseGroup* createMultipleShaderGroup (tcu::TestContext& testCtx)
3904 {
3905         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "multiple_shaders", "Test multiple shaders in the same module"));
3906         ComputeShaderSpec                               spec1;
3907         ComputeShaderSpec                               spec2;
3908         de::Random                                              rnd                             (deStringHash(group->getName()));
3909         const int                                               numElements             = 100;
3910         vector<float>                                   inputFloats             (numElements, 0);
3911         vector<float>                                   outputFloats1   (numElements, 0);
3912         vector<float>                                   outputFloats2   (numElements, 0);
3913         fillRandomScalars(rnd, -500.f, 500.f, &inputFloats[0], numElements);
3914
3915         for (size_t ndx = 0; ndx < numElements; ++ndx)
3916         {
3917                 outputFloats1[ndx] = inputFloats[ndx] + inputFloats[ndx];
3918                 outputFloats2[ndx] = -inputFloats[ndx];
3919         }
3920
3921         const string assembly(
3922                 "OpCapability Shader\n"
3923                 "OpCapability ClipDistance\n"
3924                 "OpMemoryModel Logical GLSL450\n"
3925                 "OpEntryPoint GLCompute %comp_main1 \"entrypoint1\" %id\n"
3926                 "OpEntryPoint GLCompute %comp_main2 \"entrypoint2\" %id\n"
3927                 // A module cannot have two OpEntryPoint instructions with the same Execution Model and the same Name string.
3928                 "OpEntryPoint Vertex    %vert_main  \"entrypoint2\" %vert_builtins %vertexIndex %instanceIndex\n"
3929                 "OpExecutionMode %comp_main1 LocalSize 1 1 1\n"
3930                 "OpExecutionMode %comp_main2 LocalSize 1 1 1\n"
3931
3932                 "OpName %comp_main1              \"entrypoint1\"\n"
3933                 "OpName %comp_main2              \"entrypoint2\"\n"
3934                 "OpName %vert_main               \"entrypoint2\"\n"
3935                 "OpName %id                      \"gl_GlobalInvocationID\"\n"
3936                 "OpName %vert_builtin_st         \"gl_PerVertex\"\n"
3937                 "OpName %vertexIndex             \"gl_VertexIndex\"\n"
3938                 "OpName %instanceIndex           \"gl_InstanceIndex\"\n"
3939                 "OpMemberName %vert_builtin_st 0 \"gl_Position\"\n"
3940                 "OpMemberName %vert_builtin_st 1 \"gl_PointSize\"\n"
3941                 "OpMemberName %vert_builtin_st 2 \"gl_ClipDistance\"\n"
3942
3943                 "OpDecorate %id                      BuiltIn GlobalInvocationId\n"
3944                 "OpDecorate %vertexIndex             BuiltIn VertexIndex\n"
3945                 "OpDecorate %instanceIndex           BuiltIn InstanceIndex\n"
3946                 "OpDecorate %vert_builtin_st         Block\n"
3947                 "OpMemberDecorate %vert_builtin_st 0 BuiltIn Position\n"
3948                 "OpMemberDecorate %vert_builtin_st 1 BuiltIn PointSize\n"
3949                 "OpMemberDecorate %vert_builtin_st 2 BuiltIn ClipDistance\n"
3950
3951                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3952
3953                 "%zero       = OpConstant %i32 0\n"
3954                 "%one        = OpConstant %u32 1\n"
3955                 "%c_f32_1    = OpConstant %f32 1\n"
3956
3957                 "%i32inputptr         = OpTypePointer Input %i32\n"
3958                 "%vec4                = OpTypeVector %f32 4\n"
3959                 "%vec4ptr             = OpTypePointer Output %vec4\n"
3960                 "%f32arr1             = OpTypeArray %f32 %one\n"
3961                 "%vert_builtin_st     = OpTypeStruct %vec4 %f32 %f32arr1\n"
3962                 "%vert_builtin_st_ptr = OpTypePointer Output %vert_builtin_st\n"
3963                 "%vert_builtins       = OpVariable %vert_builtin_st_ptr Output\n"
3964
3965                 "%id         = OpVariable %uvec3ptr Input\n"
3966                 "%vertexIndex = OpVariable %i32inputptr Input\n"
3967                 "%instanceIndex = OpVariable %i32inputptr Input\n"
3968                 "%c_vec4_1   = OpConstantComposite %vec4 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
3969
3970                 // gl_Position = vec4(1.);
3971                 "%vert_main  = OpFunction %void None %voidf\n"
3972                 "%vert_entry = OpLabel\n"
3973                 "%position   = OpAccessChain %vec4ptr %vert_builtins %zero\n"
3974                 "              OpStore %position %c_vec4_1\n"
3975                 "              OpReturn\n"
3976                 "              OpFunctionEnd\n"
3977
3978                 // Double inputs.
3979                 "%comp_main1  = OpFunction %void None %voidf\n"
3980                 "%comp1_entry = OpLabel\n"
3981                 "%idval1      = OpLoad %uvec3 %id\n"
3982                 "%x1          = OpCompositeExtract %u32 %idval1 0\n"
3983                 "%inloc1      = OpAccessChain %f32ptr %indata %zero %x1\n"
3984                 "%inval1      = OpLoad %f32 %inloc1\n"
3985                 "%add         = OpFAdd %f32 %inval1 %inval1\n"
3986                 "%outloc1     = OpAccessChain %f32ptr %outdata %zero %x1\n"
3987                 "               OpStore %outloc1 %add\n"
3988                 "               OpReturn\n"
3989                 "               OpFunctionEnd\n"
3990
3991                 // Negate inputs.
3992                 "%comp_main2  = OpFunction %void None %voidf\n"
3993                 "%comp2_entry = OpLabel\n"
3994                 "%idval2      = OpLoad %uvec3 %id\n"
3995                 "%x2          = OpCompositeExtract %u32 %idval2 0\n"
3996                 "%inloc2      = OpAccessChain %f32ptr %indata %zero %x2\n"
3997                 "%inval2      = OpLoad %f32 %inloc2\n"
3998                 "%neg         = OpFNegate %f32 %inval2\n"
3999                 "%outloc2     = OpAccessChain %f32ptr %outdata %zero %x2\n"
4000                 "               OpStore %outloc2 %neg\n"
4001                 "               OpReturn\n"
4002                 "               OpFunctionEnd\n");
4003
4004         spec1.assembly = assembly;
4005         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4006         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
4007         spec1.numWorkGroups = IVec3(numElements, 1, 1);
4008         spec1.entryPoint = "entrypoint1";
4009
4010         spec2.assembly = assembly;
4011         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4012         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
4013         spec2.numWorkGroups = IVec3(numElements, 1, 1);
4014         spec2.entryPoint = "entrypoint2";
4015
4016         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader1", "multiple shaders in the same module", spec1));
4017         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader2", "multiple shaders in the same module", spec2));
4018
4019         return group.release();
4020 }
4021
4022 inline std::string makeLongUTF8String (size_t num4ByteChars)
4023 {
4024         // An example of a longest valid UTF-8 character.  Be explicit about the
4025         // character type because Microsoft compilers can otherwise interpret the
4026         // character string as being over wide (16-bit) characters. Ideally, we
4027         // would just use a C++11 UTF-8 string literal, but we want to support older
4028         // Microsoft compilers.
4029         const std::basic_string<char> earthAfrica("\xF0\x9F\x8C\x8D");
4030         std::string longString;
4031         longString.reserve(num4ByteChars * 4);
4032         for (size_t count = 0; count < num4ByteChars; count++)
4033         {
4034                 longString += earthAfrica;
4035         }
4036         return longString;
4037 }
4038
4039 tcu::TestCaseGroup* createOpSourceGroup (tcu::TestContext& testCtx)
4040 {
4041         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsource", "Tests the OpSource & OpSourceContinued instruction"));
4042         vector<CaseParameter>                   cases;
4043         de::Random                                              rnd                             (deStringHash(group->getName()));
4044         const int                                               numElements             = 100;
4045         vector<float>                                   positiveFloats  (numElements, 0);
4046         vector<float>                                   negativeFloats  (numElements, 0);
4047         const StringTemplate                    shaderTemplate  (
4048                 "OpCapability Shader\n"
4049                 "OpMemoryModel Logical GLSL450\n"
4050
4051                 "OpEntryPoint GLCompute %main \"main\" %id\n"
4052                 "OpExecutionMode %main LocalSize 1 1 1\n"
4053
4054                 "${SOURCE}\n"
4055
4056                 "OpName %main           \"main\"\n"
4057                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4058
4059                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4060
4061                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4062
4063                 "%id        = OpVariable %uvec3ptr Input\n"
4064                 "%zero      = OpConstant %i32 0\n"
4065
4066                 "%main      = OpFunction %void None %voidf\n"
4067                 "%label     = OpLabel\n"
4068                 "%idval     = OpLoad %uvec3 %id\n"
4069                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4070                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4071                 "%inval     = OpLoad %f32 %inloc\n"
4072                 "%neg       = OpFNegate %f32 %inval\n"
4073                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4074                 "             OpStore %outloc %neg\n"
4075                 "             OpReturn\n"
4076                 "             OpFunctionEnd\n");
4077
4078         cases.push_back(CaseParameter("unknown_source",                                                 "OpSource Unknown 0"));
4079         cases.push_back(CaseParameter("wrong_source",                                                   "OpSource OpenCL_C 210"));
4080         cases.push_back(CaseParameter("normal_filename",                                                "%fname = OpString \"filename\"\n"
4081                                                                                                                                                         "OpSource GLSL 430 %fname"));
4082         cases.push_back(CaseParameter("empty_filename",                                                 "%fname = OpString \"\"\n"
4083                                                                                                                                                         "OpSource GLSL 430 %fname"));
4084         cases.push_back(CaseParameter("normal_source_code",                                             "%fname = OpString \"filename\"\n"
4085                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\""));
4086         cases.push_back(CaseParameter("empty_source_code",                                              "%fname = OpString \"filename\"\n"
4087                                                                                                                                                         "OpSource GLSL 430 %fname \"\""));
4088         cases.push_back(CaseParameter("long_source_code",                                               "%fname = OpString \"filename\"\n"
4089                                                                                                                                                         "OpSource GLSL 430 %fname \"" + makeLongUTF8String(65530) + "ccc\"")); // word count: 65535
4090         cases.push_back(CaseParameter("utf8_source_code",                                               "%fname = OpString \"filename\"\n"
4091                                                                                                                                                         "OpSource GLSL 430 %fname \"\xE2\x98\x82\xE2\x98\x85\"")); // umbrella & black star symbol
4092         cases.push_back(CaseParameter("normal_sourcecontinued",                                 "%fname = OpString \"filename\"\n"
4093                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvo\"\n"
4094                                                                                                                                                         "OpSourceContinued \"id main() {}\""));
4095         cases.push_back(CaseParameter("empty_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
4096                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4097                                                                                                                                                         "OpSourceContinued \"\""));
4098         cases.push_back(CaseParameter("long_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
4099                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4100                                                                                                                                                         "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\"")); // word count: 65535
4101         cases.push_back(CaseParameter("utf8_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
4102                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4103                                                                                                                                                         "OpSourceContinued \"\xE2\x98\x8E\xE2\x9A\x91\"")); // white telephone & black flag symbol
4104         cases.push_back(CaseParameter("multi_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
4105                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\n\"\n"
4106                                                                                                                                                         "OpSourceContinued \"void\"\n"
4107                                                                                                                                                         "OpSourceContinued \"main()\"\n"
4108                                                                                                                                                         "OpSourceContinued \"{}\""));
4109         cases.push_back(CaseParameter("empty_source_before_sourcecontinued",    "%fname = OpString \"filename\"\n"
4110                                                                                                                                                         "OpSource GLSL 430 %fname \"\"\n"
4111                                                                                                                                                         "OpSourceContinued \"#version 430\nvoid main() {}\""));
4112
4113         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4114
4115         for (size_t ndx = 0; ndx < numElements; ++ndx)
4116                 negativeFloats[ndx] = -positiveFloats[ndx];
4117
4118         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4119         {
4120                 map<string, string>             specializations;
4121                 ComputeShaderSpec               spec;
4122
4123                 specializations["SOURCE"] = cases[caseNdx].param;
4124                 spec.assembly = shaderTemplate.specialize(specializations);
4125                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4126                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4127                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4128
4129                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4130         }
4131
4132         return group.release();
4133 }
4134
4135 tcu::TestCaseGroup* createOpSourceExtensionGroup (tcu::TestContext& testCtx)
4136 {
4137         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsourceextension", "Tests the OpSource instruction"));
4138         vector<CaseParameter>                   cases;
4139         de::Random                                              rnd                             (deStringHash(group->getName()));
4140         const int                                               numElements             = 100;
4141         vector<float>                                   inputFloats             (numElements, 0);
4142         vector<float>                                   outputFloats    (numElements, 0);
4143         const StringTemplate                    shaderTemplate  (
4144                 string(getComputeAsmShaderPreamble()) +
4145
4146                 "OpSourceExtension \"${EXTENSION}\"\n"
4147
4148                 "OpName %main           \"main\"\n"
4149                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4150
4151                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4152
4153                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4154
4155                 "%id        = OpVariable %uvec3ptr Input\n"
4156                 "%zero      = OpConstant %i32 0\n"
4157
4158                 "%main      = OpFunction %void None %voidf\n"
4159                 "%label     = OpLabel\n"
4160                 "%idval     = OpLoad %uvec3 %id\n"
4161                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4162                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4163                 "%inval     = OpLoad %f32 %inloc\n"
4164                 "%neg       = OpFNegate %f32 %inval\n"
4165                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4166                 "             OpStore %outloc %neg\n"
4167                 "             OpReturn\n"
4168                 "             OpFunctionEnd\n");
4169
4170         cases.push_back(CaseParameter("empty_extension",        ""));
4171         cases.push_back(CaseParameter("real_extension",         "GL_ARB_texture_rectangle"));
4172         cases.push_back(CaseParameter("fake_extension",         "GL_ARB_im_the_ultimate_extension"));
4173         cases.push_back(CaseParameter("utf8_extension",         "GL_ARB_\xE2\x98\x82\xE2\x98\x85"));
4174         cases.push_back(CaseParameter("long_extension",         makeLongUTF8String(65533) + "ccc")); // word count: 65535
4175
4176         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
4177
4178         for (size_t ndx = 0; ndx < numElements; ++ndx)
4179                 outputFloats[ndx] = -inputFloats[ndx];
4180
4181         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4182         {
4183                 map<string, string>             specializations;
4184                 ComputeShaderSpec               spec;
4185
4186                 specializations["EXTENSION"] = cases[caseNdx].param;
4187                 spec.assembly = shaderTemplate.specialize(specializations);
4188                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4189                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
4190                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4191
4192                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4193         }
4194
4195         return group.release();
4196 }
4197
4198 // Checks that a compute shader can generate a constant null value of various types, without exercising a computation on it.
4199 tcu::TestCaseGroup* createOpConstantNullGroup (tcu::TestContext& testCtx)
4200 {
4201         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnull", "Tests the OpConstantNull instruction"));
4202         vector<CaseParameter>                   cases;
4203         de::Random                                              rnd                             (deStringHash(group->getName()));
4204         const int                                               numElements             = 100;
4205         vector<float>                                   positiveFloats  (numElements, 0);
4206         vector<float>                                   negativeFloats  (numElements, 0);
4207         const StringTemplate                    shaderTemplate  (
4208                 string(getComputeAsmShaderPreamble()) +
4209
4210                 "OpSource GLSL 430\n"
4211                 "OpName %main           \"main\"\n"
4212                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4213
4214                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4215
4216                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4217                 "%uvec2     = OpTypeVector %u32 2\n"
4218                 "%bvec3     = OpTypeVector %bool 3\n"
4219                 "%fvec4     = OpTypeVector %f32 4\n"
4220                 "%fmat33    = OpTypeMatrix %fvec3 3\n"
4221                 "%const100  = OpConstant %u32 100\n"
4222                 "%uarr100   = OpTypeArray %i32 %const100\n"
4223                 "%struct    = OpTypeStruct %f32 %i32 %u32\n"
4224                 "%pointer   = OpTypePointer Function %i32\n"
4225                 + string(getComputeAsmInputOutputBuffer()) +
4226
4227                 "%null      = OpConstantNull ${TYPE}\n"
4228
4229                 "%id        = OpVariable %uvec3ptr Input\n"
4230                 "%zero      = OpConstant %i32 0\n"
4231
4232                 "%main      = OpFunction %void None %voidf\n"
4233                 "%label     = OpLabel\n"
4234                 "%idval     = OpLoad %uvec3 %id\n"
4235                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4236                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4237                 "%inval     = OpLoad %f32 %inloc\n"
4238                 "%neg       = OpFNegate %f32 %inval\n"
4239                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4240                 "             OpStore %outloc %neg\n"
4241                 "             OpReturn\n"
4242                 "             OpFunctionEnd\n");
4243
4244         cases.push_back(CaseParameter("bool",                   "%bool"));
4245         cases.push_back(CaseParameter("sint32",                 "%i32"));
4246         cases.push_back(CaseParameter("uint32",                 "%u32"));
4247         cases.push_back(CaseParameter("float32",                "%f32"));
4248         cases.push_back(CaseParameter("vec4float32",    "%fvec4"));
4249         cases.push_back(CaseParameter("vec3bool",               "%bvec3"));
4250         cases.push_back(CaseParameter("vec2uint32",             "%uvec2"));
4251         cases.push_back(CaseParameter("matrix",                 "%fmat33"));
4252         cases.push_back(CaseParameter("array",                  "%uarr100"));
4253         cases.push_back(CaseParameter("struct",                 "%struct"));
4254         cases.push_back(CaseParameter("pointer",                "%pointer"));
4255
4256         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4257
4258         for (size_t ndx = 0; ndx < numElements; ++ndx)
4259                 negativeFloats[ndx] = -positiveFloats[ndx];
4260
4261         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4262         {
4263                 map<string, string>             specializations;
4264                 ComputeShaderSpec               spec;
4265
4266                 specializations["TYPE"] = cases[caseNdx].param;
4267                 spec.assembly = shaderTemplate.specialize(specializations);
4268                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4269                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4270                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4271
4272                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4273         }
4274
4275         return group.release();
4276 }
4277
4278 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
4279 tcu::TestCaseGroup* createOpConstantCompositeGroup (tcu::TestContext& testCtx)
4280 {
4281         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "Tests the OpConstantComposite instruction"));
4282         vector<CaseParameter>                   cases;
4283         de::Random                                              rnd                             (deStringHash(group->getName()));
4284         const int                                               numElements             = 100;
4285         vector<float>                                   positiveFloats  (numElements, 0);
4286         vector<float>                                   negativeFloats  (numElements, 0);
4287         const StringTemplate                    shaderTemplate  (
4288                 string(getComputeAsmShaderPreamble()) +
4289
4290                 "OpSource GLSL 430\n"
4291                 "OpName %main           \"main\"\n"
4292                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4293
4294                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4295
4296                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4297
4298                 "%id        = OpVariable %uvec3ptr Input\n"
4299                 "%zero      = OpConstant %i32 0\n"
4300
4301                 "${CONSTANT}\n"
4302
4303                 "%main      = OpFunction %void None %voidf\n"
4304                 "%label     = OpLabel\n"
4305                 "%idval     = OpLoad %uvec3 %id\n"
4306                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4307                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4308                 "%inval     = OpLoad %f32 %inloc\n"
4309                 "%neg       = OpFNegate %f32 %inval\n"
4310                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4311                 "             OpStore %outloc %neg\n"
4312                 "             OpReturn\n"
4313                 "             OpFunctionEnd\n");
4314
4315         cases.push_back(CaseParameter("vector",                 "%five = OpConstant %u32 5\n"
4316                                                                                                         "%const = OpConstantComposite %uvec3 %five %zero %five"));
4317         cases.push_back(CaseParameter("matrix",                 "%m3fvec3 = OpTypeMatrix %fvec3 3\n"
4318                                                                                                         "%ten = OpConstant %f32 10.\n"
4319                                                                                                         "%fzero = OpConstant %f32 0.\n"
4320                                                                                                         "%vec = OpConstantComposite %fvec3 %ten %fzero %ten\n"
4321                                                                                                         "%mat = OpConstantComposite %m3fvec3 %vec %vec %vec"));
4322         cases.push_back(CaseParameter("struct",                 "%m2vec3 = OpTypeMatrix %fvec3 2\n"
4323                                                                                                         "%struct = OpTypeStruct %i32 %f32 %fvec3 %m2vec3\n"
4324                                                                                                         "%fzero = OpConstant %f32 0.\n"
4325                                                                                                         "%one = OpConstant %f32 1.\n"
4326                                                                                                         "%point5 = OpConstant %f32 0.5\n"
4327                                                                                                         "%vec = OpConstantComposite %fvec3 %one %one %fzero\n"
4328                                                                                                         "%mat = OpConstantComposite %m2vec3 %vec %vec\n"
4329                                                                                                         "%const = OpConstantComposite %struct %zero %point5 %vec %mat"));
4330         cases.push_back(CaseParameter("nested_struct",  "%st1 = OpTypeStruct %u32 %f32\n"
4331                                                                                                         "%st2 = OpTypeStruct %i32 %i32\n"
4332                                                                                                         "%struct = OpTypeStruct %st1 %st2\n"
4333                                                                                                         "%point5 = OpConstant %f32 0.5\n"
4334                                                                                                         "%one = OpConstant %u32 1\n"
4335                                                                                                         "%ten = OpConstant %i32 10\n"
4336                                                                                                         "%st1val = OpConstantComposite %st1 %one %point5\n"
4337                                                                                                         "%st2val = OpConstantComposite %st2 %ten %ten\n"
4338                                                                                                         "%const = OpConstantComposite %struct %st1val %st2val"));
4339
4340         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4341
4342         for (size_t ndx = 0; ndx < numElements; ++ndx)
4343                 negativeFloats[ndx] = -positiveFloats[ndx];
4344
4345         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4346         {
4347                 map<string, string>             specializations;
4348                 ComputeShaderSpec               spec;
4349
4350                 specializations["CONSTANT"] = cases[caseNdx].param;
4351                 spec.assembly = shaderTemplate.specialize(specializations);
4352                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4353                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4354                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4355
4356                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4357         }
4358
4359         return group.release();
4360 }
4361
4362 // Creates a floating point number with the given exponent, and significand
4363 // bits set. It can only create normalized numbers. Only the least significant
4364 // 24 bits of the significand will be examined. The final bit of the
4365 // significand will also be ignored. This allows alignment to be written
4366 // similarly to C99 hex-floats.
4367 // For example if you wanted to write 0x1.7f34p-12 you would call
4368 // constructNormalizedFloat(-12, 0x7f3400)
4369 float constructNormalizedFloat (deInt32 exponent, deUint32 significand)
4370 {
4371         float f = 1.0f;
4372
4373         for (deInt32 idx = 0; idx < 23; ++idx)
4374         {
4375                 f += ((significand & 0x800000) == 0) ? 0.f : std::ldexp(1.0f, -(idx + 1));
4376                 significand <<= 1;
4377         }
4378
4379         return std::ldexp(f, exponent);
4380 }
4381
4382 // Compare instruction for the OpQuantizeF16 compute exact case.
4383 // Returns true if the output is what is expected from the test case.
4384 bool compareOpQuantizeF16ComputeExactCase (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
4385 {
4386         if (outputAllocs.size() != 1)
4387                 return false;
4388
4389         // Only size is needed because we cannot compare Nans.
4390         size_t byteSize = expectedOutputs[0].getByteSize();
4391
4392         const float*    outputAsFloat   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
4393
4394         if (byteSize != 4*sizeof(float)) {
4395                 return false;
4396         }
4397
4398         if (*outputAsFloat != constructNormalizedFloat(8, 0x304000) &&
4399                 *outputAsFloat != constructNormalizedFloat(8, 0x300000)) {
4400                 return false;
4401         }
4402         outputAsFloat++;
4403
4404         if (*outputAsFloat != -constructNormalizedFloat(-7, 0x600000) &&
4405                 *outputAsFloat != -constructNormalizedFloat(-7, 0x604000)) {
4406                 return false;
4407         }
4408         outputAsFloat++;
4409
4410         if (*outputAsFloat != constructNormalizedFloat(2, 0x01C000) &&
4411                 *outputAsFloat != constructNormalizedFloat(2, 0x020000)) {
4412                 return false;
4413         }
4414         outputAsFloat++;
4415
4416         if (*outputAsFloat != constructNormalizedFloat(1, 0xFFC000) &&
4417                 *outputAsFloat != constructNormalizedFloat(2, 0x000000)) {
4418                 return false;
4419         }
4420
4421         return true;
4422 }
4423
4424 // Checks that every output from a test-case is a float NaN.
4425 bool compareNan (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
4426 {
4427         if (outputAllocs.size() != 1)
4428                 return false;
4429
4430         // Only size is needed because we cannot compare Nans.
4431         size_t byteSize = expectedOutputs[0].getByteSize();
4432
4433         const float* const      output_as_float = static_cast<const float*>(outputAllocs[0]->getHostPtr());
4434
4435         for (size_t idx = 0; idx < byteSize / sizeof(float); ++idx)
4436         {
4437                 if (!deFloatIsNaN(output_as_float[idx]))
4438                 {
4439                         return false;
4440                 }
4441         }
4442
4443         return true;
4444 }
4445
4446 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
4447 tcu::TestCaseGroup* createOpQuantizeToF16Group (tcu::TestContext& testCtx)
4448 {
4449         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opquantize", "Tests the OpQuantizeToF16 instruction"));
4450
4451         const std::string shader (
4452                 string(getComputeAsmShaderPreamble()) +
4453
4454                 "OpSource GLSL 430\n"
4455                 "OpName %main           \"main\"\n"
4456                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4457
4458                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4459
4460                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4461
4462                 "%id        = OpVariable %uvec3ptr Input\n"
4463                 "%zero      = OpConstant %i32 0\n"
4464
4465                 "%main      = OpFunction %void None %voidf\n"
4466                 "%label     = OpLabel\n"
4467                 "%idval     = OpLoad %uvec3 %id\n"
4468                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4469                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4470                 "%inval     = OpLoad %f32 %inloc\n"
4471                 "%quant     = OpQuantizeToF16 %f32 %inval\n"
4472                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4473                 "             OpStore %outloc %quant\n"
4474                 "             OpReturn\n"
4475                 "             OpFunctionEnd\n");
4476
4477         {
4478                 ComputeShaderSpec       spec;
4479                 const deUint32          numElements             = 100;
4480                 vector<float>           infinities;
4481                 vector<float>           results;
4482
4483                 infinities.reserve(numElements);
4484                 results.reserve(numElements);
4485
4486                 for (size_t idx = 0; idx < numElements; ++idx)
4487                 {
4488                         switch(idx % 4)
4489                         {
4490                                 case 0:
4491                                         infinities.push_back(std::numeric_limits<float>::infinity());
4492                                         results.push_back(std::numeric_limits<float>::infinity());
4493                                         break;
4494                                 case 1:
4495                                         infinities.push_back(-std::numeric_limits<float>::infinity());
4496                                         results.push_back(-std::numeric_limits<float>::infinity());
4497                                         break;
4498                                 case 2:
4499                                         infinities.push_back(std::ldexp(1.0f, 16));
4500                                         results.push_back(std::numeric_limits<float>::infinity());
4501                                         break;
4502                                 case 3:
4503                                         infinities.push_back(std::ldexp(-1.0f, 32));
4504                                         results.push_back(-std::numeric_limits<float>::infinity());
4505                                         break;
4506                         }
4507                 }
4508
4509                 spec.assembly = shader;
4510                 spec.inputs.push_back(BufferSp(new Float32Buffer(infinities)));
4511                 spec.outputs.push_back(BufferSp(new Float32Buffer(results)));
4512                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4513
4514                 group->addChild(new SpvAsmComputeShaderCase(
4515                         testCtx, "infinities", "Check that infinities propagated and created", spec));
4516         }
4517
4518         {
4519                 ComputeShaderSpec       spec;
4520                 vector<float>           nans;
4521                 const deUint32          numElements             = 100;
4522
4523                 nans.reserve(numElements);
4524
4525                 for (size_t idx = 0; idx < numElements; ++idx)
4526                 {
4527                         if (idx % 2 == 0)
4528                         {
4529                                 nans.push_back(std::numeric_limits<float>::quiet_NaN());
4530                         }
4531                         else
4532                         {
4533                                 nans.push_back(-std::numeric_limits<float>::quiet_NaN());
4534                         }
4535                 }
4536
4537                 spec.assembly = shader;
4538                 spec.inputs.push_back(BufferSp(new Float32Buffer(nans)));
4539                 spec.outputs.push_back(BufferSp(new Float32Buffer(nans)));
4540                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4541                 spec.verifyIO = &compareNan;
4542
4543                 group->addChild(new SpvAsmComputeShaderCase(
4544                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
4545         }
4546
4547         {
4548                 ComputeShaderSpec       spec;
4549                 vector<float>           small;
4550                 vector<float>           zeros;
4551                 const deUint32          numElements             = 100;
4552
4553                 small.reserve(numElements);
4554                 zeros.reserve(numElements);
4555
4556                 for (size_t idx = 0; idx < numElements; ++idx)
4557                 {
4558                         switch(idx % 6)
4559                         {
4560                                 case 0:
4561                                         small.push_back(0.f);
4562                                         zeros.push_back(0.f);
4563                                         break;
4564                                 case 1:
4565                                         small.push_back(-0.f);
4566                                         zeros.push_back(-0.f);
4567                                         break;
4568                                 case 2:
4569                                         small.push_back(std::ldexp(1.0f, -16));
4570                                         zeros.push_back(0.f);
4571                                         break;
4572                                 case 3:
4573                                         small.push_back(std::ldexp(-1.0f, -32));
4574                                         zeros.push_back(-0.f);
4575                                         break;
4576                                 case 4:
4577                                         small.push_back(std::ldexp(1.0f, -127));
4578                                         zeros.push_back(0.f);
4579                                         break;
4580                                 case 5:
4581                                         small.push_back(-std::ldexp(1.0f, -128));
4582                                         zeros.push_back(-0.f);
4583                                         break;
4584                         }
4585                 }
4586
4587                 spec.assembly = shader;
4588                 spec.inputs.push_back(BufferSp(new Float32Buffer(small)));
4589                 spec.outputs.push_back(BufferSp(new Float32Buffer(zeros)));
4590                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4591
4592                 group->addChild(new SpvAsmComputeShaderCase(
4593                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
4594         }
4595
4596         {
4597                 ComputeShaderSpec       spec;
4598                 vector<float>           exact;
4599                 const deUint32          numElements             = 200;
4600
4601                 exact.reserve(numElements);
4602
4603                 for (size_t idx = 0; idx < numElements; ++idx)
4604                         exact.push_back(static_cast<float>(static_cast<int>(idx) - 100));
4605
4606                 spec.assembly = shader;
4607                 spec.inputs.push_back(BufferSp(new Float32Buffer(exact)));
4608                 spec.outputs.push_back(BufferSp(new Float32Buffer(exact)));
4609                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4610
4611                 group->addChild(new SpvAsmComputeShaderCase(
4612                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
4613         }
4614
4615         {
4616                 ComputeShaderSpec       spec;
4617                 vector<float>           inputs;
4618                 const deUint32          numElements             = 4;
4619
4620                 inputs.push_back(constructNormalizedFloat(8,    0x300300));
4621                 inputs.push_back(-constructNormalizedFloat(-7,  0x600800));
4622                 inputs.push_back(constructNormalizedFloat(2,    0x01E000));
4623                 inputs.push_back(constructNormalizedFloat(1,    0xFFE000));
4624
4625                 spec.assembly = shader;
4626                 spec.verifyIO = &compareOpQuantizeF16ComputeExactCase;
4627                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4628                 spec.outputs.push_back(BufferSp(new Float32Buffer(inputs)));
4629                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4630
4631                 group->addChild(new SpvAsmComputeShaderCase(
4632                         testCtx, "rounded", "Check that are rounded when needed", spec));
4633         }
4634
4635         return group.release();
4636 }
4637
4638 tcu::TestCaseGroup* createSpecConstantOpQuantizeToF16Group (tcu::TestContext& testCtx)
4639 {
4640         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opspecconstantop_opquantize", "Tests the OpQuantizeToF16 opcode for the OpSpecConstantOp instruction"));
4641
4642         const std::string shader (
4643                 string(getComputeAsmShaderPreamble()) +
4644
4645                 "OpName %main           \"main\"\n"
4646                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4647
4648                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4649
4650                 "OpDecorate %sc_0  SpecId 0\n"
4651                 "OpDecorate %sc_1  SpecId 1\n"
4652                 "OpDecorate %sc_2  SpecId 2\n"
4653                 "OpDecorate %sc_3  SpecId 3\n"
4654                 "OpDecorate %sc_4  SpecId 4\n"
4655                 "OpDecorate %sc_5  SpecId 5\n"
4656
4657                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4658
4659                 "%id        = OpVariable %uvec3ptr Input\n"
4660                 "%zero      = OpConstant %i32 0\n"
4661                 "%c_u32_6   = OpConstant %u32 6\n"
4662
4663                 "%sc_0      = OpSpecConstant %f32 0.\n"
4664                 "%sc_1      = OpSpecConstant %f32 0.\n"
4665                 "%sc_2      = OpSpecConstant %f32 0.\n"
4666                 "%sc_3      = OpSpecConstant %f32 0.\n"
4667                 "%sc_4      = OpSpecConstant %f32 0.\n"
4668                 "%sc_5      = OpSpecConstant %f32 0.\n"
4669
4670                 "%sc_0_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_0\n"
4671                 "%sc_1_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_1\n"
4672                 "%sc_2_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_2\n"
4673                 "%sc_3_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_3\n"
4674                 "%sc_4_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_4\n"
4675                 "%sc_5_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_5\n"
4676
4677                 "%main      = OpFunction %void None %voidf\n"
4678                 "%label     = OpLabel\n"
4679                 "%idval     = OpLoad %uvec3 %id\n"
4680                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4681                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4682                 "%selector  = OpUMod %u32 %x %c_u32_6\n"
4683                 "            OpSelectionMerge %exit None\n"
4684                 "            OpSwitch %selector %exit 0 %case0 1 %case1 2 %case2 3 %case3 4 %case4 5 %case5\n"
4685
4686                 "%case0     = OpLabel\n"
4687                 "             OpStore %outloc %sc_0_quant\n"
4688                 "             OpBranch %exit\n"
4689
4690                 "%case1     = OpLabel\n"
4691                 "             OpStore %outloc %sc_1_quant\n"
4692                 "             OpBranch %exit\n"
4693
4694                 "%case2     = OpLabel\n"
4695                 "             OpStore %outloc %sc_2_quant\n"
4696                 "             OpBranch %exit\n"
4697
4698                 "%case3     = OpLabel\n"
4699                 "             OpStore %outloc %sc_3_quant\n"
4700                 "             OpBranch %exit\n"
4701
4702                 "%case4     = OpLabel\n"
4703                 "             OpStore %outloc %sc_4_quant\n"
4704                 "             OpBranch %exit\n"
4705
4706                 "%case5     = OpLabel\n"
4707                 "             OpStore %outloc %sc_5_quant\n"
4708                 "             OpBranch %exit\n"
4709
4710                 "%exit      = OpLabel\n"
4711                 "             OpReturn\n"
4712
4713                 "             OpFunctionEnd\n");
4714
4715         {
4716                 ComputeShaderSpec       spec;
4717                 const deUint8           numCases        = 4;
4718                 vector<float>           inputs          (numCases, 0.f);
4719                 vector<float>           outputs;
4720
4721                 spec.assembly           = shader;
4722                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4723
4724                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::numeric_limits<float>::infinity()));
4725                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-std::numeric_limits<float>::infinity()));
4726                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, 16)));
4727                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(-1.0f, 32)));
4728
4729                 outputs.push_back(std::numeric_limits<float>::infinity());
4730                 outputs.push_back(-std::numeric_limits<float>::infinity());
4731                 outputs.push_back(std::numeric_limits<float>::infinity());
4732                 outputs.push_back(-std::numeric_limits<float>::infinity());
4733
4734                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4735                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4736
4737                 group->addChild(new SpvAsmComputeShaderCase(
4738                         testCtx, "infinities", "Check that infinities propagated and created", spec));
4739         }
4740
4741         {
4742                 ComputeShaderSpec       spec;
4743                 const deUint8           numCases        = 2;
4744                 vector<float>           inputs          (numCases, 0.f);
4745                 vector<float>           outputs;
4746
4747                 spec.assembly           = shader;
4748                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4749                 spec.verifyIO           = &compareNan;
4750
4751                 outputs.push_back(std::numeric_limits<float>::quiet_NaN());
4752                 outputs.push_back(-std::numeric_limits<float>::quiet_NaN());
4753
4754                 for (deUint8 idx = 0; idx < numCases; ++idx)
4755                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(outputs[idx]));
4756
4757                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4758                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4759
4760                 group->addChild(new SpvAsmComputeShaderCase(
4761                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
4762         }
4763
4764         {
4765                 ComputeShaderSpec       spec;
4766                 const deUint8           numCases        = 6;
4767                 vector<float>           inputs          (numCases, 0.f);
4768                 vector<float>           outputs;
4769
4770                 spec.assembly           = shader;
4771                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4772
4773                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(0.f));
4774                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-0.f));
4775                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, -16)));
4776                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(-1.0f, -32)));
4777                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, -127)));
4778                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-std::ldexp(1.0f, -128)));
4779
4780                 outputs.push_back(0.f);
4781                 outputs.push_back(-0.f);
4782                 outputs.push_back(0.f);
4783                 outputs.push_back(-0.f);
4784                 outputs.push_back(0.f);
4785                 outputs.push_back(-0.f);
4786
4787                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4788                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4789
4790                 group->addChild(new SpvAsmComputeShaderCase(
4791                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
4792         }
4793
4794         {
4795                 ComputeShaderSpec       spec;
4796                 const deUint8           numCases        = 6;
4797                 vector<float>           inputs          (numCases, 0.f);
4798                 vector<float>           outputs;
4799
4800                 spec.assembly           = shader;
4801                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4802
4803                 for (deUint8 idx = 0; idx < 6; ++idx)
4804                 {
4805                         const float f = static_cast<float>(idx * 10 - 30) / 4.f;
4806                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(f));
4807                         outputs.push_back(f);
4808                 }
4809
4810                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4811                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4812
4813                 group->addChild(new SpvAsmComputeShaderCase(
4814                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
4815         }
4816
4817         {
4818                 ComputeShaderSpec       spec;
4819                 const deUint8           numCases        = 4;
4820                 vector<float>           inputs          (numCases, 0.f);
4821                 vector<float>           outputs;
4822
4823                 spec.assembly           = shader;
4824                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4825                 spec.verifyIO           = &compareOpQuantizeF16ComputeExactCase;
4826
4827                 outputs.push_back(constructNormalizedFloat(8, 0x300300));
4828                 outputs.push_back(-constructNormalizedFloat(-7, 0x600800));
4829                 outputs.push_back(constructNormalizedFloat(2, 0x01E000));
4830                 outputs.push_back(constructNormalizedFloat(1, 0xFFE000));
4831
4832                 for (deUint8 idx = 0; idx < numCases; ++idx)
4833                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(outputs[idx]));
4834
4835                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4836                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4837
4838                 group->addChild(new SpvAsmComputeShaderCase(
4839                         testCtx, "rounded", "Check that are rounded when needed", spec));
4840         }
4841
4842         return group.release();
4843 }
4844
4845 // Checks that constant null/composite values can be used in computation.
4846 tcu::TestCaseGroup* createOpConstantUsageGroup (tcu::TestContext& testCtx)
4847 {
4848         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnullcomposite", "Spotcheck the OpConstantNull & OpConstantComposite instruction"));
4849         ComputeShaderSpec                               spec;
4850         de::Random                                              rnd                             (deStringHash(group->getName()));
4851         const int                                               numElements             = 100;
4852         vector<float>                                   positiveFloats  (numElements, 0);
4853         vector<float>                                   negativeFloats  (numElements, 0);
4854
4855         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4856
4857         for (size_t ndx = 0; ndx < numElements; ++ndx)
4858                 negativeFloats[ndx] = -positiveFloats[ndx];
4859
4860         spec.assembly =
4861                 "OpCapability Shader\n"
4862                 "%std450 = OpExtInstImport \"GLSL.std.450\"\n"
4863                 "OpMemoryModel Logical GLSL450\n"
4864                 "OpEntryPoint GLCompute %main \"main\" %id\n"
4865                 "OpExecutionMode %main LocalSize 1 1 1\n"
4866
4867                 "OpSource GLSL 430\n"
4868                 "OpName %main           \"main\"\n"
4869                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4870
4871                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4872
4873                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4874
4875                 "%fmat      = OpTypeMatrix %fvec3 3\n"
4876                 "%ten       = OpConstant %u32 10\n"
4877                 "%f32arr10  = OpTypeArray %f32 %ten\n"
4878                 "%fst       = OpTypeStruct %f32 %f32\n"
4879
4880                 + string(getComputeAsmInputOutputBuffer()) +
4881
4882                 "%id        = OpVariable %uvec3ptr Input\n"
4883                 "%zero      = OpConstant %i32 0\n"
4884
4885                 // Create a bunch of null values
4886                 "%unull     = OpConstantNull %u32\n"
4887                 "%fnull     = OpConstantNull %f32\n"
4888                 "%vnull     = OpConstantNull %fvec3\n"
4889                 "%mnull     = OpConstantNull %fmat\n"
4890                 "%anull     = OpConstantNull %f32arr10\n"
4891                 "%snull     = OpConstantComposite %fst %fnull %fnull\n"
4892
4893                 "%main      = OpFunction %void None %voidf\n"
4894                 "%label     = OpLabel\n"
4895                 "%idval     = OpLoad %uvec3 %id\n"
4896                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4897                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4898                 "%inval     = OpLoad %f32 %inloc\n"
4899                 "%neg       = OpFNegate %f32 %inval\n"
4900
4901                 // Get the abs() of (a certain element of) those null values
4902                 "%unull_cov = OpConvertUToF %f32 %unull\n"
4903                 "%unull_abs = OpExtInst %f32 %std450 FAbs %unull_cov\n"
4904                 "%fnull_abs = OpExtInst %f32 %std450 FAbs %fnull\n"
4905                 "%vnull_0   = OpCompositeExtract %f32 %vnull 0\n"
4906                 "%vnull_abs = OpExtInst %f32 %std450 FAbs %vnull_0\n"
4907                 "%mnull_12  = OpCompositeExtract %f32 %mnull 1 2\n"
4908                 "%mnull_abs = OpExtInst %f32 %std450 FAbs %mnull_12\n"
4909                 "%anull_3   = OpCompositeExtract %f32 %anull 3\n"
4910                 "%anull_abs = OpExtInst %f32 %std450 FAbs %anull_3\n"
4911                 "%snull_1   = OpCompositeExtract %f32 %snull 1\n"
4912                 "%snull_abs = OpExtInst %f32 %std450 FAbs %snull_1\n"
4913
4914                 // Add them all
4915                 "%add1      = OpFAdd %f32 %neg  %unull_abs\n"
4916                 "%add2      = OpFAdd %f32 %add1 %fnull_abs\n"
4917                 "%add3      = OpFAdd %f32 %add2 %vnull_abs\n"
4918                 "%add4      = OpFAdd %f32 %add3 %mnull_abs\n"
4919                 "%add5      = OpFAdd %f32 %add4 %anull_abs\n"
4920                 "%final     = OpFAdd %f32 %add5 %snull_abs\n"
4921
4922                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4923                 "             OpStore %outloc %final\n" // write to output
4924                 "             OpReturn\n"
4925                 "             OpFunctionEnd\n";
4926         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4927         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4928         spec.numWorkGroups = IVec3(numElements, 1, 1);
4929
4930         group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "Check that values constructed via OpConstantNull & OpConstantComposite can be used", spec));
4931
4932         return group.release();
4933 }
4934
4935 // Assembly code used for testing loop control is based on GLSL source code:
4936 // #version 430
4937 //
4938 // layout(std140, set = 0, binding = 0) readonly buffer Input {
4939 //   float elements[];
4940 // } input_data;
4941 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
4942 //   float elements[];
4943 // } output_data;
4944 //
4945 // void main() {
4946 //   uint x = gl_GlobalInvocationID.x;
4947 //   output_data.elements[x] = input_data.elements[x];
4948 //   for (uint i = 0; i < 4; ++i)
4949 //     output_data.elements[x] += 1.f;
4950 // }
4951 tcu::TestCaseGroup* createLoopControlGroup (tcu::TestContext& testCtx)
4952 {
4953         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "loop_control", "Tests loop control cases"));
4954         vector<CaseParameter>                   cases;
4955         de::Random                                              rnd                             (deStringHash(group->getName()));
4956         const int                                               numElements             = 100;
4957         vector<float>                                   inputFloats             (numElements, 0);
4958         vector<float>                                   outputFloats    (numElements, 0);
4959         const StringTemplate                    shaderTemplate  (
4960                 string(getComputeAsmShaderPreamble()) +
4961
4962                 "OpSource GLSL 430\n"
4963                 "OpName %main \"main\"\n"
4964                 "OpName %id \"gl_GlobalInvocationID\"\n"
4965
4966                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4967
4968                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4969
4970                 "%u32ptr      = OpTypePointer Function %u32\n"
4971
4972                 "%id          = OpVariable %uvec3ptr Input\n"
4973                 "%zero        = OpConstant %i32 0\n"
4974                 "%uzero       = OpConstant %u32 0\n"
4975                 "%one         = OpConstant %i32 1\n"
4976                 "%constf1     = OpConstant %f32 1.0\n"
4977                 "%four        = OpConstant %u32 4\n"
4978
4979                 "%main        = OpFunction %void None %voidf\n"
4980                 "%entry       = OpLabel\n"
4981                 "%i           = OpVariable %u32ptr Function\n"
4982                 "               OpStore %i %uzero\n"
4983
4984                 "%idval       = OpLoad %uvec3 %id\n"
4985                 "%x           = OpCompositeExtract %u32 %idval 0\n"
4986                 "%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
4987                 "%inval       = OpLoad %f32 %inloc\n"
4988                 "%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
4989                 "               OpStore %outloc %inval\n"
4990                 "               OpBranch %loop_entry\n"
4991
4992                 "%loop_entry  = OpLabel\n"
4993                 "%i_val       = OpLoad %u32 %i\n"
4994                 "%cmp_lt      = OpULessThan %bool %i_val %four\n"
4995                 "               OpLoopMerge %loop_merge %loop_body ${CONTROL}\n"
4996                 "               OpBranchConditional %cmp_lt %loop_body %loop_merge\n"
4997                 "%loop_body   = OpLabel\n"
4998                 "%outval      = OpLoad %f32 %outloc\n"
4999                 "%addf1       = OpFAdd %f32 %outval %constf1\n"
5000                 "               OpStore %outloc %addf1\n"
5001                 "%new_i       = OpIAdd %u32 %i_val %one\n"
5002                 "               OpStore %i %new_i\n"
5003                 "               OpBranch %loop_entry\n"
5004                 "%loop_merge  = OpLabel\n"
5005                 "               OpReturn\n"
5006                 "               OpFunctionEnd\n");
5007
5008         cases.push_back(CaseParameter("none",                           "None"));
5009         cases.push_back(CaseParameter("unroll",                         "Unroll"));
5010         cases.push_back(CaseParameter("dont_unroll",            "DontUnroll"));
5011         cases.push_back(CaseParameter("unroll_dont_unroll",     "Unroll|DontUnroll"));
5012
5013         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5014
5015         for (size_t ndx = 0; ndx < numElements; ++ndx)
5016                 outputFloats[ndx] = inputFloats[ndx] + 4.f;
5017
5018         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5019         {
5020                 map<string, string>             specializations;
5021                 ComputeShaderSpec               spec;
5022
5023                 specializations["CONTROL"] = cases[caseNdx].param;
5024                 spec.assembly = shaderTemplate.specialize(specializations);
5025                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5026                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5027                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5028
5029                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5030         }
5031
5032         group->addChild(new SpvAsmLoopControlDependencyLengthCase(testCtx, "dependency_length", "dependency_length"));
5033         group->addChild(new SpvAsmLoopControlDependencyInfiniteCase(testCtx, "dependency_infinite", "dependency_infinite"));
5034
5035         return group.release();
5036 }
5037
5038 // Assembly code used for testing selection control is based on GLSL source code:
5039 // #version 430
5040 //
5041 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5042 //   float elements[];
5043 // } input_data;
5044 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5045 //   float elements[];
5046 // } output_data;
5047 //
5048 // void main() {
5049 //   uint x = gl_GlobalInvocationID.x;
5050 //   float val = input_data.elements[x];
5051 //   if (val > 10.f)
5052 //     output_data.elements[x] = val + 1.f;
5053 //   else
5054 //     output_data.elements[x] = val - 1.f;
5055 // }
5056 tcu::TestCaseGroup* createSelectionControlGroup (tcu::TestContext& testCtx)
5057 {
5058         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "selection_control", "Tests selection control cases"));
5059         vector<CaseParameter>                   cases;
5060         de::Random                                              rnd                             (deStringHash(group->getName()));
5061         const int                                               numElements             = 100;
5062         vector<float>                                   inputFloats             (numElements, 0);
5063         vector<float>                                   outputFloats    (numElements, 0);
5064         const StringTemplate                    shaderTemplate  (
5065                 string(getComputeAsmShaderPreamble()) +
5066
5067                 "OpSource GLSL 430\n"
5068                 "OpName %main \"main\"\n"
5069                 "OpName %id \"gl_GlobalInvocationID\"\n"
5070
5071                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5072
5073                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5074
5075                 "%id       = OpVariable %uvec3ptr Input\n"
5076                 "%zero     = OpConstant %i32 0\n"
5077                 "%constf1  = OpConstant %f32 1.0\n"
5078                 "%constf10 = OpConstant %f32 10.0\n"
5079
5080                 "%main     = OpFunction %void None %voidf\n"
5081                 "%entry    = OpLabel\n"
5082                 "%idval    = OpLoad %uvec3 %id\n"
5083                 "%x        = OpCompositeExtract %u32 %idval 0\n"
5084                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
5085                 "%inval    = OpLoad %f32 %inloc\n"
5086                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
5087                 "%cmp_gt   = OpFOrdGreaterThan %bool %inval %constf10\n"
5088
5089                 "            OpSelectionMerge %if_end ${CONTROL}\n"
5090                 "            OpBranchConditional %cmp_gt %if_true %if_false\n"
5091                 "%if_true  = OpLabel\n"
5092                 "%addf1    = OpFAdd %f32 %inval %constf1\n"
5093                 "            OpStore %outloc %addf1\n"
5094                 "            OpBranch %if_end\n"
5095                 "%if_false = OpLabel\n"
5096                 "%subf1    = OpFSub %f32 %inval %constf1\n"
5097                 "            OpStore %outloc %subf1\n"
5098                 "            OpBranch %if_end\n"
5099                 "%if_end   = OpLabel\n"
5100                 "            OpReturn\n"
5101                 "            OpFunctionEnd\n");
5102
5103         cases.push_back(CaseParameter("none",                                   "None"));
5104         cases.push_back(CaseParameter("flatten",                                "Flatten"));
5105         cases.push_back(CaseParameter("dont_flatten",                   "DontFlatten"));
5106         cases.push_back(CaseParameter("flatten_dont_flatten",   "DontFlatten|Flatten"));
5107
5108         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5109
5110         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
5111         floorAll(inputFloats);
5112
5113         for (size_t ndx = 0; ndx < numElements; ++ndx)
5114                 outputFloats[ndx] = inputFloats[ndx] + (inputFloats[ndx] > 10.f ? 1.f : -1.f);
5115
5116         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5117         {
5118                 map<string, string>             specializations;
5119                 ComputeShaderSpec               spec;
5120
5121                 specializations["CONTROL"] = cases[caseNdx].param;
5122                 spec.assembly = shaderTemplate.specialize(specializations);
5123                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5124                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5125                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5126
5127                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5128         }
5129
5130         return group.release();
5131 }
5132
5133 void getOpNameAbuseCases (vector<CaseParameter> &abuseCases)
5134 {
5135         // Generate a long name.
5136         std::string longname;
5137         longname.resize(65535, 'k'); // max string literal, spir-v 2.17
5138
5139         // Some bad names, abusing utf-8 encoding. This may also cause problems
5140         // with the logs.
5141         // 1. Various illegal code points in utf-8
5142         std::string utf8illegal =
5143                 "Illegal bytes in UTF-8: "
5144                 "\xc0 \xc1 \xf5 \xf6 \xf7 \xf8 \xf9 \xfa \xfb \xfc \xfd \xfe \xff"
5145                 "illegal surrogates: \xed\xad\xbf \xed\xbe\x80";
5146
5147         // 2. Zero encoded as overlong, not exactly legal but often supported to differentiate from terminating zero
5148         std::string utf8nul = "UTF-8 encoded nul \xC0\x80 (should not end name)";
5149
5150         // 3. Some overlong encodings
5151         std::string utf8overlong =
5152                 "UTF-8 overlong \xF0\x82\x82\xAC \xfc\x83\xbf\xbf\xbf\xbf \xf8\x87\xbf\xbf\xbf "
5153                 "\xf0\x8f\xbf\xbf";
5154
5155         // 4. Internet "zalgo" meme "bleeding text"
5156         std::string utf8zalgo =
5157                 "\x56\xcc\xb5\xcc\x85\xcc\x94\xcc\x88\xcd\x8a\xcc\x91\xcc\x88\xcd\x91\xcc\x83\xcd\x82"
5158                 "\xcc\x83\xcd\x90\xcc\x8a\xcc\x92\xcc\x92\xcd\x8b\xcc\x94\xcd\x9d\xcc\x98\xcc\xab\xcc"
5159                 "\xae\xcc\xa9\xcc\xad\xcc\x97\xcc\xb0\x75\xcc\xb6\xcc\xbe\xcc\x80\xcc\x82\xcc\x84\xcd"
5160                 "\x84\xcc\x90\xcd\x86\xcc\x9a\xcd\x84\xcc\x9b\xcd\x86\xcd\x92\xcc\x9a\xcd\x99\xcd\x99"
5161                 "\xcc\xbb\xcc\x98\xcd\x8e\xcd\x88\xcd\x9a\xcc\xa6\xcc\x9c\xcc\xab\xcc\x99\xcd\x94\xcd"
5162                 "\x99\xcd\x95\xcc\xa5\xcc\xab\xcd\x89\x6c\xcc\xb8\xcc\x8e\xcc\x8b\xcc\x8b\xcc\x9a\xcc"
5163                 "\x8e\xcd\x9d\xcc\x80\xcc\xa1\xcc\xad\xcd\x9c\xcc\xba\xcc\x96\xcc\xb3\xcc\xa2\xcd\x8e"
5164                 "\xcc\xa2\xcd\x96\x6b\xcc\xb8\xcc\x84\xcd\x81\xcc\xbf\xcc\x8d\xcc\x89\xcc\x85\xcc\x92"
5165                 "\xcc\x84\xcc\x90\xcd\x81\xcc\x93\xcd\x90\xcd\x92\xcd\x9d\xcc\x84\xcd\x98\xcd\x9d\xcd"
5166                 "\xa0\xcd\x91\xcc\x94\xcc\xb9\xcd\x93\xcc\xa5\xcd\x87\xcc\xad\xcc\xa7\xcd\x96\xcd\x99"
5167                 "\xcc\x9d\xcc\xbc\xcd\x96\xcd\x93\xcc\x9d\xcc\x99\xcc\xa8\xcc\xb1\xcd\x85\xcc\xba\xcc"
5168                 "\xa7\x61\xcc\xb8\xcc\x8e\xcc\x81\xcd\x90\xcd\x84\xcd\x8c\xcc\x8c\xcc\x85\xcd\x86\xcc"
5169                 "\x84\xcd\x84\xcc\x90\xcc\x84\xcc\x8d\xcd\x99\xcd\x8d\xcc\xb0\xcc\xa3\xcc\xa6\xcd\x89"
5170                 "\xcd\x8d\xcd\x87\xcc\x98\xcd\x8d\xcc\xa4\xcd\x9a\xcd\x8e\xcc\xab\xcc\xb9\xcc\xac\xcc"
5171                 "\xa2\xcd\x87\xcc\xa0\xcc\xb3\xcd\x89\xcc\xb9\xcc\xa7\xcc\xa6\xcd\x89\xcd\x95\x6e\xcc"
5172                 "\xb8\xcd\x8a\xcc\x8a\xcd\x82\xcc\x9b\xcd\x81\xcd\x90\xcc\x85\xcc\x9b\xcd\x80\xcd\x91"
5173                 "\xcd\x9b\xcc\x81\xcd\x81\xcc\x9a\xcc\xb3\xcd\x9c\xcc\x9e\xcc\x9d\xcd\x99\xcc\xa2\xcd"
5174                 "\x93\xcd\x96\xcc\x97\xff";
5175
5176         // General name abuses
5177         abuseCases.push_back(CaseParameter("_has_very_long_name", longname));
5178         abuseCases.push_back(CaseParameter("_utf8_illegal", utf8illegal));
5179         abuseCases.push_back(CaseParameter("_utf8_nul", utf8nul));
5180         abuseCases.push_back(CaseParameter("_utf8_overlong", utf8overlong));
5181         abuseCases.push_back(CaseParameter("_utf8_zalgo", utf8zalgo));
5182
5183         // GL keywords
5184         abuseCases.push_back(CaseParameter("_is_gl_Position", "gl_Position"));
5185         abuseCases.push_back(CaseParameter("_is_gl_InstanceID", "gl_InstanceID"));
5186         abuseCases.push_back(CaseParameter("_is_gl_PrimitiveID", "gl_PrimitiveID"));
5187         abuseCases.push_back(CaseParameter("_is_gl_TessCoord", "gl_TessCoord"));
5188         abuseCases.push_back(CaseParameter("_is_gl_PerVertex", "gl_PerVertex"));
5189         abuseCases.push_back(CaseParameter("_is_gl_InvocationID", "gl_InvocationID"));
5190         abuseCases.push_back(CaseParameter("_is_gl_PointSize", "gl_PointSize"));
5191         abuseCases.push_back(CaseParameter("_is_gl_PointCoord", "gl_PointCoord"));
5192         abuseCases.push_back(CaseParameter("_is_gl_Layer", "gl_Layer"));
5193         abuseCases.push_back(CaseParameter("_is_gl_FragDepth", "gl_FragDepth"));
5194         abuseCases.push_back(CaseParameter("_is_gl_NumWorkGroups", "gl_NumWorkGroups"));
5195         abuseCases.push_back(CaseParameter("_is_gl_WorkGroupID", "gl_WorkGroupID"));
5196         abuseCases.push_back(CaseParameter("_is_gl_LocalInvocationID", "gl_LocalInvocationID"));
5197         abuseCases.push_back(CaseParameter("_is_gl_GlobalInvocationID", "gl_GlobalInvocationID"));
5198         abuseCases.push_back(CaseParameter("_is_gl_MaxVertexAttribs", "gl_MaxVertexAttribs"));
5199         abuseCases.push_back(CaseParameter("_is_gl_MaxViewports", "gl_MaxViewports"));
5200         abuseCases.push_back(CaseParameter("_is_gl_MaxComputeWorkGroupCount", "gl_MaxComputeWorkGroupCount"));
5201         abuseCases.push_back(CaseParameter("_is_mat3", "mat3"));
5202         abuseCases.push_back(CaseParameter("_is_volatile", "volatile"));
5203         abuseCases.push_back(CaseParameter("_is_inout", "inout"));
5204         abuseCases.push_back(CaseParameter("_is_isampler3d", "isampler3d"));
5205 }
5206
5207 tcu::TestCaseGroup* createOpNameGroup (tcu::TestContext& testCtx)
5208 {
5209         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opname", "Tests OpName cases"));
5210         de::MovePtr<tcu::TestCaseGroup> entryMainGroup  (new tcu::TestCaseGroup(testCtx, "entry_main", "OpName tests with entry main"));
5211         de::MovePtr<tcu::TestCaseGroup> entryNotGroup   (new tcu::TestCaseGroup(testCtx, "entry_rdc", "OpName tests with entry rdc"));
5212         de::MovePtr<tcu::TestCaseGroup> abuseGroup              (new tcu::TestCaseGroup(testCtx, "abuse", "OpName abuse tests"));
5213         vector<CaseParameter>                   cases;
5214         vector<CaseParameter>                   abuseCases;
5215         vector<string>                                  testFunc;
5216         de::Random                                              rnd                             (deStringHash(group->getName()));
5217         const int                                               numElements             = 128;
5218         vector<float>                                   inputFloats             (numElements, 0);
5219         vector<float>                                   outputFloats    (numElements, 0);
5220
5221         getOpNameAbuseCases(abuseCases);
5222
5223         fillRandomScalars(rnd, -100.0f, 100.0f, &inputFloats[0], numElements);
5224
5225         for(size_t ndx = 0; ndx < numElements; ++ndx)
5226                 outputFloats[ndx] = -inputFloats[ndx];
5227
5228         const string commonShaderHeader =
5229                 "OpCapability Shader\n"
5230                 "OpMemoryModel Logical GLSL450\n"
5231                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5232                 "OpExecutionMode %main LocalSize 1 1 1\n";
5233
5234         const string commonShaderFooter =
5235                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5236
5237                 + string(getComputeAsmInputOutputBufferTraits())
5238                 + string(getComputeAsmCommonTypes())
5239                 + string(getComputeAsmInputOutputBuffer()) +
5240
5241                 "%id        = OpVariable %uvec3ptr Input\n"
5242                 "%zero      = OpConstant %i32 0\n"
5243
5244                 "%func      = OpFunction %void None %voidf\n"
5245                 "%5         = OpLabel\n"
5246                 "             OpReturn\n"
5247                 "             OpFunctionEnd\n"
5248
5249                 "%main      = OpFunction %void None %voidf\n"
5250                 "%entry     = OpLabel\n"
5251                 "%7         = OpFunctionCall %void %func\n"
5252
5253                 "%idval     = OpLoad %uvec3 %id\n"
5254                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5255
5256                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5257                 "%inval     = OpLoad %f32 %inloc\n"
5258                 "%neg       = OpFNegate %f32 %inval\n"
5259                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5260                 "             OpStore %outloc %neg\n"
5261
5262                 "             OpReturn\n"
5263                 "             OpFunctionEnd\n";
5264
5265         const StringTemplate shaderTemplate (
5266                 "OpCapability Shader\n"
5267                 "OpMemoryModel Logical GLSL450\n"
5268                 "OpEntryPoint GLCompute %main \"${ENTRY}\" %id\n"
5269                 "OpExecutionMode %main LocalSize 1 1 1\n"
5270                 "OpName %${ID} \"${NAME}\"\n" +
5271                 commonShaderFooter);
5272
5273         const std::string multipleNames =
5274                 commonShaderHeader +
5275                 "OpName %main \"to_be\"\n"
5276                 "OpName %id   \"or_not\"\n"
5277                 "OpName %main \"to_be\"\n"
5278                 "OpName %main \"makes_no\"\n"
5279                 "OpName %func \"difference\"\n"
5280                 "OpName %5    \"to_me\"\n" +
5281                 commonShaderFooter;
5282
5283         {
5284                 ComputeShaderSpec       spec;
5285
5286                 spec.assembly           = multipleNames;
5287                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5288                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5289                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5290
5291                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "main_has_multiple_names", "multiple_names", spec));
5292         }
5293
5294         const std::string everythingNamed =
5295                 commonShaderHeader +
5296                 "OpName %main   \"name1\"\n"
5297                 "OpName %id     \"name2\"\n"
5298                 "OpName %zero   \"name3\"\n"
5299                 "OpName %entry  \"name4\"\n"
5300                 "OpName %func   \"name5\"\n"
5301                 "OpName %5      \"name6\"\n"
5302                 "OpName %7      \"name7\"\n"
5303                 "OpName %idval  \"name8\"\n"
5304                 "OpName %inloc  \"name9\"\n"
5305                 "OpName %inval  \"name10\"\n"
5306                 "OpName %neg    \"name11\"\n"
5307                 "OpName %outloc \"name12\"\n"+
5308                 commonShaderFooter;
5309         {
5310                 ComputeShaderSpec       spec;
5311
5312                 spec.assembly           = everythingNamed;
5313                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5314                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5315                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5316
5317                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named", "everything_named", spec));
5318         }
5319
5320         const std::string everythingNamedTheSame =
5321                 commonShaderHeader +
5322                 "OpName %main   \"the_same\"\n"
5323                 "OpName %id     \"the_same\"\n"
5324                 "OpName %zero   \"the_same\"\n"
5325                 "OpName %entry  \"the_same\"\n"
5326                 "OpName %func   \"the_same\"\n"
5327                 "OpName %5      \"the_same\"\n"
5328                 "OpName %7      \"the_same\"\n"
5329                 "OpName %idval  \"the_same\"\n"
5330                 "OpName %inloc  \"the_same\"\n"
5331                 "OpName %inval  \"the_same\"\n"
5332                 "OpName %neg    \"the_same\"\n"
5333                 "OpName %outloc \"the_same\"\n"+
5334                 commonShaderFooter;
5335         {
5336                 ComputeShaderSpec       spec;
5337
5338                 spec.assembly           = everythingNamedTheSame;
5339                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5340                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5341                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5342
5343                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named_the_same", "everything_named_the_same", spec));
5344         }
5345
5346         // main_is_...
5347         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5348         {
5349                 map<string, string>     specializations;
5350                 ComputeShaderSpec       spec;
5351
5352                 specializations["ENTRY"]        = "main";
5353                 specializations["ID"]           = "main";
5354                 specializations["NAME"]         = abuseCases[ndx].param;
5355                 spec.assembly                           = shaderTemplate.specialize(specializations);
5356                 spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5357                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5358                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5359
5360                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("main") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5361         }
5362
5363         // x_is_....
5364         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5365         {
5366                 map<string, string>     specializations;
5367                 ComputeShaderSpec       spec;
5368
5369                 specializations["ENTRY"]        = "main";
5370                 specializations["ID"]           = "x";
5371                 specializations["NAME"]         = abuseCases[ndx].param;
5372                 spec.assembly                           = shaderTemplate.specialize(specializations);
5373                 spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5374                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5375                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5376
5377                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("x") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5378         }
5379
5380         cases.push_back(CaseParameter("_is_main", "main"));
5381         cases.push_back(CaseParameter("_is_not_main", "not_main"));
5382         testFunc.push_back("main");
5383         testFunc.push_back("func");
5384
5385         for(size_t fNdx = 0; fNdx < testFunc.size(); ++fNdx)
5386         {
5387                 for(size_t ndx = 0; ndx < cases.size(); ++ndx)
5388                 {
5389                         map<string, string>     specializations;
5390                         ComputeShaderSpec       spec;
5391
5392                         specializations["ENTRY"]        = "main";
5393                         specializations["ID"]           = testFunc[fNdx];
5394                         specializations["NAME"]         = cases[ndx].param;
5395                         spec.assembly                           = shaderTemplate.specialize(specializations);
5396                         spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5397                         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5398                         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5399
5400                         entryMainGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (testFunc[fNdx] + cases[ndx].name).c_str(), cases[ndx].name, spec));
5401                 }
5402         }
5403
5404         cases.push_back(CaseParameter("_is_entry", "rdc"));
5405
5406         for(size_t fNdx = 0; fNdx < testFunc.size(); ++fNdx)
5407         {
5408                 for(size_t ndx = 0; ndx < cases.size(); ++ndx)
5409                 {
5410                         map<string, string>     specializations;
5411                         ComputeShaderSpec       spec;
5412
5413                         specializations["ENTRY"]        = "rdc";
5414                         specializations["ID"]           = testFunc[fNdx];
5415                         specializations["NAME"]         = cases[ndx].param;
5416                         spec.assembly                           = shaderTemplate.specialize(specializations);
5417                         spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5418                         spec.entryPoint                         = "rdc";
5419                         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5420                         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5421
5422                         entryNotGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (testFunc[fNdx] + cases[ndx].name).c_str(), cases[ndx].name, spec));
5423                 }
5424         }
5425
5426         group->addChild(entryMainGroup.release());
5427         group->addChild(entryNotGroup.release());
5428         group->addChild(abuseGroup.release());
5429
5430         return group.release();
5431 }
5432
5433 tcu::TestCaseGroup* createOpMemberNameGroup (tcu::TestContext& testCtx)
5434 {
5435         de::MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "opmembername", "Tests OpMemberName cases"));
5436         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "abuse", "OpMemberName abuse tests"));
5437         vector<CaseParameter>                   abuseCases;
5438         vector<string>                                  testFunc;
5439         de::Random                                              rnd(deStringHash(group->getName()));
5440         const int                                               numElements = 128;
5441         vector<float>                                   inputFloats(numElements, 0);
5442         vector<float>                                   outputFloats(numElements, 0);
5443
5444         getOpNameAbuseCases(abuseCases);
5445
5446         fillRandomScalars(rnd, -100.0f, 100.0f, &inputFloats[0], numElements);
5447
5448         for (size_t ndx = 0; ndx < numElements; ++ndx)
5449                 outputFloats[ndx] = -inputFloats[ndx];
5450
5451         const string commonShaderHeader =
5452                 "OpCapability Shader\n"
5453                 "OpMemoryModel Logical GLSL450\n"
5454                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5455                 "OpExecutionMode %main LocalSize 1 1 1\n";
5456
5457         const string commonShaderFooter =
5458                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5459
5460                 + string(getComputeAsmInputOutputBufferTraits())
5461                 + string(getComputeAsmCommonTypes())
5462                 + string(getComputeAsmInputOutputBuffer()) +
5463
5464                 "%u3str     = OpTypeStruct %u32 %u32 %u32\n"
5465
5466                 "%id        = OpVariable %uvec3ptr Input\n"
5467                 "%zero      = OpConstant %i32 0\n"
5468
5469                 "%main      = OpFunction %void None %voidf\n"
5470                 "%entry     = OpLabel\n"
5471
5472                 "%idval     = OpLoad %uvec3 %id\n"
5473                 "%x0        = OpCompositeExtract %u32 %idval 0\n"
5474
5475                 "%idstr     = OpCompositeConstruct %u3str %x0 %x0 %x0\n"
5476                 "%x         = OpCompositeExtract %u32 %idstr 0\n"
5477
5478                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5479                 "%inval     = OpLoad %f32 %inloc\n"
5480                 "%neg       = OpFNegate %f32 %inval\n"
5481                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5482                 "             OpStore %outloc %neg\n"
5483
5484                 "             OpReturn\n"
5485                 "             OpFunctionEnd\n";
5486
5487         const StringTemplate shaderTemplate(
5488                 commonShaderHeader +
5489                 "OpMemberName %u3str 0 \"${NAME}\"\n" +
5490                 commonShaderFooter);
5491
5492         const std::string multipleNames =
5493                 commonShaderHeader +
5494                 "OpMemberName %u3str 0 \"to_be\"\n"
5495                 "OpMemberName %u3str 1 \"or_not\"\n"
5496                 "OpMemberName %u3str 0 \"to_be\"\n"
5497                 "OpMemberName %u3str 2 \"makes_no\"\n"
5498                 "OpMemberName %u3str 0 \"difference\"\n"
5499                 "OpMemberName %u3str 0 \"to_me\"\n" +
5500                 commonShaderFooter;
5501         {
5502                 ComputeShaderSpec       spec;
5503
5504                 spec.assembly = multipleNames;
5505                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5506                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5507                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5508
5509                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "u3str_x_has_multiple_names", "multiple_names", spec));
5510         }
5511
5512         const std::string everythingNamedTheSame =
5513                 commonShaderHeader +
5514                 "OpMemberName %u3str 0 \"the_same\"\n"
5515                 "OpMemberName %u3str 1 \"the_same\"\n"
5516                 "OpMemberName %u3str 2 \"the_same\"\n" +
5517                 commonShaderFooter;
5518
5519         {
5520                 ComputeShaderSpec       spec;
5521
5522                 spec.assembly = everythingNamedTheSame;
5523                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5524                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5525                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5526
5527                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named_the_same", "everything_named_the_same", spec));
5528         }
5529
5530         // u3str_x_is_....
5531         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5532         {
5533                 map<string, string>     specializations;
5534                 ComputeShaderSpec       spec;
5535
5536                 specializations["NAME"] = abuseCases[ndx].param;
5537                 spec.assembly = shaderTemplate.specialize(specializations);
5538                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5539                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5540                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5541
5542                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("u3str_x") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5543         }
5544
5545         group->addChild(abuseGroup.release());
5546
5547         return group.release();
5548 }
5549
5550 // Assembly code used for testing function control is based on GLSL source code:
5551 //
5552 // #version 430
5553 //
5554 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5555 //   float elements[];
5556 // } input_data;
5557 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5558 //   float elements[];
5559 // } output_data;
5560 //
5561 // float const10() { return 10.f; }
5562 //
5563 // void main() {
5564 //   uint x = gl_GlobalInvocationID.x;
5565 //   output_data.elements[x] = input_data.elements[x] + const10();
5566 // }
5567 tcu::TestCaseGroup* createFunctionControlGroup (tcu::TestContext& testCtx)
5568 {
5569         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "function_control", "Tests function control cases"));
5570         vector<CaseParameter>                   cases;
5571         de::Random                                              rnd                             (deStringHash(group->getName()));
5572         const int                                               numElements             = 100;
5573         vector<float>                                   inputFloats             (numElements, 0);
5574         vector<float>                                   outputFloats    (numElements, 0);
5575         const StringTemplate                    shaderTemplate  (
5576                 string(getComputeAsmShaderPreamble()) +
5577
5578                 "OpSource GLSL 430\n"
5579                 "OpName %main \"main\"\n"
5580                 "OpName %func_const10 \"const10(\"\n"
5581                 "OpName %id \"gl_GlobalInvocationID\"\n"
5582
5583                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5584
5585                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5586
5587                 "%f32f = OpTypeFunction %f32\n"
5588                 "%id = OpVariable %uvec3ptr Input\n"
5589                 "%zero = OpConstant %i32 0\n"
5590                 "%constf10 = OpConstant %f32 10.0\n"
5591
5592                 "%main         = OpFunction %void None %voidf\n"
5593                 "%entry        = OpLabel\n"
5594                 "%idval        = OpLoad %uvec3 %id\n"
5595                 "%x            = OpCompositeExtract %u32 %idval 0\n"
5596                 "%inloc        = OpAccessChain %f32ptr %indata %zero %x\n"
5597                 "%inval        = OpLoad %f32 %inloc\n"
5598                 "%ret_10       = OpFunctionCall %f32 %func_const10\n"
5599                 "%fadd         = OpFAdd %f32 %inval %ret_10\n"
5600                 "%outloc       = OpAccessChain %f32ptr %outdata %zero %x\n"
5601                 "                OpStore %outloc %fadd\n"
5602                 "                OpReturn\n"
5603                 "                OpFunctionEnd\n"
5604
5605                 "%func_const10 = OpFunction %f32 ${CONTROL} %f32f\n"
5606                 "%label        = OpLabel\n"
5607                 "                OpReturnValue %constf10\n"
5608                 "                OpFunctionEnd\n");
5609
5610         cases.push_back(CaseParameter("none",                                           "None"));
5611         cases.push_back(CaseParameter("inline",                                         "Inline"));
5612         cases.push_back(CaseParameter("dont_inline",                            "DontInline"));
5613         cases.push_back(CaseParameter("pure",                                           "Pure"));
5614         cases.push_back(CaseParameter("const",                                          "Const"));
5615         cases.push_back(CaseParameter("inline_pure",                            "Inline|Pure"));
5616         cases.push_back(CaseParameter("const_dont_inline",                      "Const|DontInline"));
5617         cases.push_back(CaseParameter("inline_dont_inline",                     "Inline|DontInline"));
5618         cases.push_back(CaseParameter("pure_inline_dont_inline",        "Pure|Inline|DontInline"));
5619
5620         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5621
5622         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
5623         floorAll(inputFloats);
5624
5625         for (size_t ndx = 0; ndx < numElements; ++ndx)
5626                 outputFloats[ndx] = inputFloats[ndx] + 10.f;
5627
5628         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5629         {
5630                 map<string, string>             specializations;
5631                 ComputeShaderSpec               spec;
5632
5633                 specializations["CONTROL"] = cases[caseNdx].param;
5634                 spec.assembly = shaderTemplate.specialize(specializations);
5635                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5636                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5637                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5638
5639                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5640         }
5641
5642         return group.release();
5643 }
5644
5645 tcu::TestCaseGroup* createMemoryAccessGroup (tcu::TestContext& testCtx)
5646 {
5647         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "memory_access", "Tests memory access cases"));
5648         vector<CaseParameter>                   cases;
5649         de::Random                                              rnd                             (deStringHash(group->getName()));
5650         const int                                               numElements             = 100;
5651         vector<float>                                   inputFloats             (numElements, 0);
5652         vector<float>                                   outputFloats    (numElements, 0);
5653         const StringTemplate                    shaderTemplate  (
5654                 string(getComputeAsmShaderPreamble()) +
5655
5656                 "OpSource GLSL 430\n"
5657                 "OpName %main           \"main\"\n"
5658                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5659
5660                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5661
5662                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5663
5664                 "%f32ptr_f  = OpTypePointer Function %f32\n"
5665
5666                 "%id        = OpVariable %uvec3ptr Input\n"
5667                 "%zero      = OpConstant %i32 0\n"
5668                 "%four      = OpConstant %i32 4\n"
5669
5670                 "%main      = OpFunction %void None %voidf\n"
5671                 "%label     = OpLabel\n"
5672                 "%copy      = OpVariable %f32ptr_f Function\n"
5673                 "%idval     = OpLoad %uvec3 %id ${ACCESS}\n"
5674                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5675                 "%inloc     = OpAccessChain %f32ptr %indata  %zero %x\n"
5676                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5677                 "             OpCopyMemory %copy %inloc ${ACCESS}\n"
5678                 "%val1      = OpLoad %f32 %copy\n"
5679                 "%val2      = OpLoad %f32 %inloc\n"
5680                 "%add       = OpFAdd %f32 %val1 %val2\n"
5681                 "             OpStore %outloc %add ${ACCESS}\n"
5682                 "             OpReturn\n"
5683                 "             OpFunctionEnd\n");
5684
5685         cases.push_back(CaseParameter("null",                                   ""));
5686         cases.push_back(CaseParameter("none",                                   "None"));
5687         cases.push_back(CaseParameter("volatile",                               "Volatile"));
5688         cases.push_back(CaseParameter("aligned",                                "Aligned 4"));
5689         cases.push_back(CaseParameter("nontemporal",                    "Nontemporal"));
5690         cases.push_back(CaseParameter("aligned_nontemporal",    "Aligned|Nontemporal 4"));
5691         cases.push_back(CaseParameter("aligned_volatile",               "Volatile|Aligned 4"));
5692
5693         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5694
5695         for (size_t ndx = 0; ndx < numElements; ++ndx)
5696                 outputFloats[ndx] = inputFloats[ndx] + inputFloats[ndx];
5697
5698         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5699         {
5700                 map<string, string>             specializations;
5701                 ComputeShaderSpec               spec;
5702
5703                 specializations["ACCESS"] = cases[caseNdx].param;
5704                 spec.assembly = shaderTemplate.specialize(specializations);
5705                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5706                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5707                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5708
5709                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5710         }
5711
5712         return group.release();
5713 }
5714
5715 // Checks that we can get undefined values for various types, without exercising a computation with it.
5716 tcu::TestCaseGroup* createOpUndefGroup (tcu::TestContext& testCtx)
5717 {
5718         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opundef", "Tests the OpUndef instruction"));
5719         vector<CaseParameter>                   cases;
5720         de::Random                                              rnd                             (deStringHash(group->getName()));
5721         const int                                               numElements             = 100;
5722         vector<float>                                   positiveFloats  (numElements, 0);
5723         vector<float>                                   negativeFloats  (numElements, 0);
5724         const StringTemplate                    shaderTemplate  (
5725                 string(getComputeAsmShaderPreamble()) +
5726
5727                 "OpSource GLSL 430\n"
5728                 "OpName %main           \"main\"\n"
5729                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5730
5731                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5732
5733                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
5734                 "%uvec2     = OpTypeVector %u32 2\n"
5735                 "%fvec4     = OpTypeVector %f32 4\n"
5736                 "%fmat33    = OpTypeMatrix %fvec3 3\n"
5737                 "%image     = OpTypeImage %f32 2D 0 0 0 1 Unknown\n"
5738                 "%sampler   = OpTypeSampler\n"
5739                 "%simage    = OpTypeSampledImage %image\n"
5740                 "%const100  = OpConstant %u32 100\n"
5741                 "%uarr100   = OpTypeArray %i32 %const100\n"
5742                 "%struct    = OpTypeStruct %f32 %i32 %u32\n"
5743                 "%pointer   = OpTypePointer Function %i32\n"
5744                 + string(getComputeAsmInputOutputBuffer()) +
5745
5746                 "%id        = OpVariable %uvec3ptr Input\n"
5747                 "%zero      = OpConstant %i32 0\n"
5748
5749                 "%main      = OpFunction %void None %voidf\n"
5750                 "%label     = OpLabel\n"
5751
5752                 "%undef     = OpUndef ${TYPE}\n"
5753
5754                 "%idval     = OpLoad %uvec3 %id\n"
5755                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5756
5757                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5758                 "%inval     = OpLoad %f32 %inloc\n"
5759                 "%neg       = OpFNegate %f32 %inval\n"
5760                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5761                 "             OpStore %outloc %neg\n"
5762                 "             OpReturn\n"
5763                 "             OpFunctionEnd\n");
5764
5765         cases.push_back(CaseParameter("bool",                   "%bool"));
5766         cases.push_back(CaseParameter("sint32",                 "%i32"));
5767         cases.push_back(CaseParameter("uint32",                 "%u32"));
5768         cases.push_back(CaseParameter("float32",                "%f32"));
5769         cases.push_back(CaseParameter("vec4float32",    "%fvec4"));
5770         cases.push_back(CaseParameter("vec2uint32",             "%uvec2"));
5771         cases.push_back(CaseParameter("matrix",                 "%fmat33"));
5772         cases.push_back(CaseParameter("image",                  "%image"));
5773         cases.push_back(CaseParameter("sampler",                "%sampler"));
5774         cases.push_back(CaseParameter("sampledimage",   "%simage"));
5775         cases.push_back(CaseParameter("array",                  "%uarr100"));
5776         cases.push_back(CaseParameter("runtimearray",   "%f32arr"));
5777         cases.push_back(CaseParameter("struct",                 "%struct"));
5778         cases.push_back(CaseParameter("pointer",                "%pointer"));
5779
5780         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
5781
5782         for (size_t ndx = 0; ndx < numElements; ++ndx)
5783                 negativeFloats[ndx] = -positiveFloats[ndx];
5784
5785         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5786         {
5787                 map<string, string>             specializations;
5788                 ComputeShaderSpec               spec;
5789
5790                 specializations["TYPE"] = cases[caseNdx].param;
5791                 spec.assembly = shaderTemplate.specialize(specializations);
5792                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
5793                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
5794                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5795
5796                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5797         }
5798
5799                 return group.release();
5800 }
5801 } // anonymous
5802
5803 tcu::TestCaseGroup* createOpSourceTests (tcu::TestContext& testCtx)
5804 {
5805         struct NameCodePair { string name, code; };
5806         RGBA                                                    defaultColors[4];
5807         de::MovePtr<tcu::TestCaseGroup> opSourceTests                   (new tcu::TestCaseGroup(testCtx, "opsource", "OpSource instruction"));
5808         const std::string                               opsourceGLSLWithFile    = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile ";
5809         map<string, string>                             fragments                               = passthruFragments();
5810         const NameCodePair                              tests[]                                 =
5811         {
5812                 {"unknown", "OpSource Unknown 321"},
5813                 {"essl", "OpSource ESSL 310"},
5814                 {"glsl", "OpSource GLSL 450"},
5815                 {"opencl_cpp", "OpSource OpenCL_CPP 120"},
5816                 {"opencl_c", "OpSource OpenCL_C 120"},
5817                 {"multiple", "OpSource GLSL 450\nOpSource GLSL 450"},
5818                 {"file", opsourceGLSLWithFile},
5819                 {"source", opsourceGLSLWithFile + "\"void main(){}\""},
5820                 // Longest possible source string: SPIR-V limits instructions to 65535
5821                 // words, of which the first 4 are opsourceGLSLWithFile; the rest will
5822                 // contain 65530 UTF8 characters (one word each) plus one last word
5823                 // containing 3 ASCII characters and \0.
5824                 {"longsource", opsourceGLSLWithFile + '"' + makeLongUTF8String(65530) + "ccc" + '"'}
5825         };
5826
5827         getDefaultColors(defaultColors);
5828         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
5829         {
5830                 fragments["debug"] = tests[testNdx].code;
5831                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
5832         }
5833
5834         return opSourceTests.release();
5835 }
5836
5837 tcu::TestCaseGroup* createOpSourceContinuedTests (tcu::TestContext& testCtx)
5838 {
5839         struct NameCodePair { string name, code; };
5840         RGBA                                                            defaultColors[4];
5841         de::MovePtr<tcu::TestCaseGroup>         opSourceTests           (new tcu::TestCaseGroup(testCtx, "opsourcecontinued", "OpSourceContinued instruction"));
5842         map<string, string>                                     fragments                       = passthruFragments();
5843         const std::string                                       opsource                        = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile \"void main(){}\"\n";
5844         const NameCodePair                                      tests[]                         =
5845         {
5846                 {"empty", opsource + "OpSourceContinued \"\""},
5847                 {"short", opsource + "OpSourceContinued \"abcde\""},
5848                 {"multiple", opsource + "OpSourceContinued \"abcde\"\nOpSourceContinued \"fghij\""},
5849                 // Longest possible source string: SPIR-V limits instructions to 65535
5850                 // words, of which the first one is OpSourceContinued/length; the rest
5851                 // will contain 65533 UTF8 characters (one word each) plus one last word
5852                 // containing 3 ASCII characters and \0.
5853                 {"long", opsource + "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\""}
5854         };
5855
5856         getDefaultColors(defaultColors);
5857         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
5858         {
5859                 fragments["debug"] = tests[testNdx].code;
5860                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
5861         }
5862
5863         return opSourceTests.release();
5864 }
5865 tcu::TestCaseGroup* createOpNoLineTests(tcu::TestContext& testCtx)
5866 {
5867         RGBA                                                             defaultColors[4];
5868         de::MovePtr<tcu::TestCaseGroup>          opLineTests             (new tcu::TestCaseGroup(testCtx, "opnoline", "OpNoLine instruction"));
5869         map<string, string>                                      fragments;
5870         getDefaultColors(defaultColors);
5871         fragments["debug"]                      =
5872                 "%name = OpString \"name\"\n";
5873
5874         fragments["pre_main"]   =
5875                 "OpNoLine\n"
5876                 "OpNoLine\n"
5877                 "OpLine %name 1 1\n"
5878                 "OpNoLine\n"
5879                 "OpLine %name 1 1\n"
5880                 "OpLine %name 1 1\n"
5881                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
5882                 "OpNoLine\n"
5883                 "OpLine %name 1 1\n"
5884                 "OpNoLine\n"
5885                 "OpLine %name 1 1\n"
5886                 "OpLine %name 1 1\n"
5887                 "%second_param1 = OpFunctionParameter %v4f32\n"
5888                 "OpNoLine\n"
5889                 "OpNoLine\n"
5890                 "%label_secondfunction = OpLabel\n"
5891                 "OpNoLine\n"
5892                 "OpReturnValue %second_param1\n"
5893                 "OpFunctionEnd\n"
5894                 "OpNoLine\n"
5895                 "OpNoLine\n";
5896
5897         fragments["testfun"]            =
5898                 // A %test_code function that returns its argument unchanged.
5899                 "OpNoLine\n"
5900                 "OpNoLine\n"
5901                 "OpLine %name 1 1\n"
5902                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
5903                 "OpNoLine\n"
5904                 "%param1 = OpFunctionParameter %v4f32\n"
5905                 "OpNoLine\n"
5906                 "OpNoLine\n"
5907                 "%label_testfun = OpLabel\n"
5908                 "OpNoLine\n"
5909                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
5910                 "OpReturnValue %val1\n"
5911                 "OpFunctionEnd\n"
5912                 "OpLine %name 1 1\n"
5913                 "OpNoLine\n";
5914
5915         createTestsForAllStages("opnoline", defaultColors, defaultColors, fragments, opLineTests.get());
5916
5917         return opLineTests.release();
5918 }
5919
5920 tcu::TestCaseGroup* createOpModuleProcessedTests(tcu::TestContext& testCtx)
5921 {
5922         RGBA                                                            defaultColors[4];
5923         de::MovePtr<tcu::TestCaseGroup>         opModuleProcessedTests                  (new tcu::TestCaseGroup(testCtx, "opmoduleprocessed", "OpModuleProcessed instruction"));
5924         map<string, string>                                     fragments;
5925         std::vector<std::string>                        noExtensions;
5926         GraphicsResources                                       resources;
5927
5928         getDefaultColors(defaultColors);
5929         resources.verifyBinary = veryfiBinaryShader;
5930         resources.spirvVersion = SPIRV_VERSION_1_3;
5931
5932         fragments["moduleprocessed"]                                                    =
5933                 "OpModuleProcessed \"VULKAN CTS\"\n"
5934                 "OpModuleProcessed \"Negative values\"\n"
5935                 "OpModuleProcessed \"Date: 2017/09/21\"\n";
5936
5937         fragments["pre_main"]   =
5938                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
5939                 "%second_param1 = OpFunctionParameter %v4f32\n"
5940                 "%label_secondfunction = OpLabel\n"
5941                 "OpReturnValue %second_param1\n"
5942                 "OpFunctionEnd\n";
5943
5944         fragments["testfun"]            =
5945                 // A %test_code function that returns its argument unchanged.
5946                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
5947                 "%param1 = OpFunctionParameter %v4f32\n"
5948                 "%label_testfun = OpLabel\n"
5949                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
5950                 "OpReturnValue %val1\n"
5951                 "OpFunctionEnd\n";
5952
5953         createTestsForAllStages ("opmoduleprocessed", defaultColors, defaultColors, fragments, resources, noExtensions, opModuleProcessedTests.get());
5954
5955         return opModuleProcessedTests.release();
5956 }
5957
5958
5959 tcu::TestCaseGroup* createOpLineTests(tcu::TestContext& testCtx)
5960 {
5961         RGBA                                                                                                    defaultColors[4];
5962         de::MovePtr<tcu::TestCaseGroup>                                                 opLineTests                     (new tcu::TestCaseGroup(testCtx, "opline", "OpLine instruction"));
5963         map<string, string>                                                                             fragments;
5964         std::vector<std::pair<std::string, std::string> >               problemStrings;
5965
5966         problemStrings.push_back(std::make_pair<std::string, std::string>("empty_name", ""));
5967         problemStrings.push_back(std::make_pair<std::string, std::string>("short_name", "short_name"));
5968         problemStrings.push_back(std::make_pair<std::string, std::string>("long_name", makeLongUTF8String(65530) + "ccc"));
5969         getDefaultColors(defaultColors);
5970
5971         fragments["debug"]                      =
5972                 "%other_name = OpString \"other_name\"\n";
5973
5974         fragments["pre_main"]   =
5975                 "OpLine %file_name 32 0\n"
5976                 "OpLine %file_name 32 32\n"
5977                 "OpLine %file_name 32 40\n"
5978                 "OpLine %other_name 32 40\n"
5979                 "OpLine %other_name 0 100\n"
5980                 "OpLine %other_name 0 4294967295\n"
5981                 "OpLine %other_name 4294967295 0\n"
5982                 "OpLine %other_name 32 40\n"
5983                 "OpLine %file_name 0 0\n"
5984                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
5985                 "OpLine %file_name 1 0\n"
5986                 "%second_param1 = OpFunctionParameter %v4f32\n"
5987                 "OpLine %file_name 1 3\n"
5988                 "OpLine %file_name 1 2\n"
5989                 "%label_secondfunction = OpLabel\n"
5990                 "OpLine %file_name 0 2\n"
5991                 "OpReturnValue %second_param1\n"
5992                 "OpFunctionEnd\n"
5993                 "OpLine %file_name 0 2\n"
5994                 "OpLine %file_name 0 2\n";
5995
5996         fragments["testfun"]            =
5997                 // A %test_code function that returns its argument unchanged.
5998                 "OpLine %file_name 1 0\n"
5999                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6000                 "OpLine %file_name 16 330\n"
6001                 "%param1 = OpFunctionParameter %v4f32\n"
6002                 "OpLine %file_name 14 442\n"
6003                 "%label_testfun = OpLabel\n"
6004                 "OpLine %file_name 11 1024\n"
6005                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6006                 "OpLine %file_name 2 97\n"
6007                 "OpReturnValue %val1\n"
6008                 "OpFunctionEnd\n"
6009                 "OpLine %file_name 5 32\n";
6010
6011         for (size_t i = 0; i < problemStrings.size(); ++i)
6012         {
6013                 map<string, string> testFragments = fragments;
6014                 testFragments["debug"] += "%file_name = OpString \"" + problemStrings[i].second + "\"\n";
6015                 createTestsForAllStages(string("opline") + "_" + problemStrings[i].first, defaultColors, defaultColors, testFragments, opLineTests.get());
6016         }
6017
6018         return opLineTests.release();
6019 }
6020
6021 tcu::TestCaseGroup* createOpConstantNullTests(tcu::TestContext& testCtx)
6022 {
6023         de::MovePtr<tcu::TestCaseGroup> opConstantNullTests             (new tcu::TestCaseGroup(testCtx, "opconstantnull", "OpConstantNull instruction"));
6024         RGBA                                                    colors[4];
6025
6026
6027         const char                                              functionStart[] =
6028                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6029                 "%param1 = OpFunctionParameter %v4f32\n"
6030                 "%lbl    = OpLabel\n";
6031
6032         const char                                              functionEnd[]   =
6033                 "OpReturnValue %transformed_param\n"
6034                 "OpFunctionEnd\n";
6035
6036         struct NameConstantsCode
6037         {
6038                 string name;
6039                 string constants;
6040                 string code;
6041         };
6042
6043         NameConstantsCode tests[] =
6044         {
6045                 {
6046                         "vec4",
6047                         "%cnull = OpConstantNull %v4f32\n",
6048                         "%transformed_param = OpFAdd %v4f32 %param1 %cnull\n"
6049                 },
6050                 {
6051                         "float",
6052                         "%cnull = OpConstantNull %f32\n",
6053                         "%vp = OpVariable %fp_v4f32 Function\n"
6054                         "%v  = OpLoad %v4f32 %vp\n"
6055                         "%v0 = OpVectorInsertDynamic %v4f32 %v %cnull %c_i32_0\n"
6056                         "%v1 = OpVectorInsertDynamic %v4f32 %v0 %cnull %c_i32_1\n"
6057                         "%v2 = OpVectorInsertDynamic %v4f32 %v1 %cnull %c_i32_2\n"
6058                         "%v3 = OpVectorInsertDynamic %v4f32 %v2 %cnull %c_i32_3\n"
6059                         "%transformed_param = OpFAdd %v4f32 %param1 %v3\n"
6060                 },
6061                 {
6062                         "bool",
6063                         "%cnull             = OpConstantNull %bool\n",
6064                         "%v                 = OpVariable %fp_v4f32 Function\n"
6065                         "                     OpStore %v %param1\n"
6066                         "                     OpSelectionMerge %false_label None\n"
6067                         "                     OpBranchConditional %cnull %true_label %false_label\n"
6068                         "%true_label        = OpLabel\n"
6069                         "                     OpStore %v %c_v4f32_0_5_0_5_0_5_0_5\n"
6070                         "                     OpBranch %false_label\n"
6071                         "%false_label       = OpLabel\n"
6072                         "%transformed_param = OpLoad %v4f32 %v\n"
6073                 },
6074                 {
6075                         "i32",
6076                         "%cnull             = OpConstantNull %i32\n",
6077                         "%v                 = OpVariable %fp_v4f32 Function %c_v4f32_0_5_0_5_0_5_0_5\n"
6078                         "%b                 = OpIEqual %bool %cnull %c_i32_0\n"
6079                         "                     OpSelectionMerge %false_label None\n"
6080                         "                     OpBranchConditional %b %true_label %false_label\n"
6081                         "%true_label        = OpLabel\n"
6082                         "                     OpStore %v %param1\n"
6083                         "                     OpBranch %false_label\n"
6084                         "%false_label       = OpLabel\n"
6085                         "%transformed_param = OpLoad %v4f32 %v\n"
6086                 },
6087                 {
6088                         "struct",
6089                         "%stype             = OpTypeStruct %f32 %v4f32\n"
6090                         "%fp_stype          = OpTypePointer Function %stype\n"
6091                         "%cnull             = OpConstantNull %stype\n",
6092                         "%v                 = OpVariable %fp_stype Function %cnull\n"
6093                         "%f                 = OpAccessChain %fp_v4f32 %v %c_i32_1\n"
6094                         "%f_val             = OpLoad %v4f32 %f\n"
6095                         "%transformed_param = OpFAdd %v4f32 %param1 %f_val\n"
6096                 },
6097                 {
6098                         "array",
6099                         "%a4_v4f32          = OpTypeArray %v4f32 %c_u32_4\n"
6100                         "%fp_a4_v4f32       = OpTypePointer Function %a4_v4f32\n"
6101                         "%cnull             = OpConstantNull %a4_v4f32\n",
6102                         "%v                 = OpVariable %fp_a4_v4f32 Function %cnull\n"
6103                         "%f                 = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
6104                         "%f1                = OpAccessChain %fp_v4f32 %v %c_u32_1\n"
6105                         "%f2                = OpAccessChain %fp_v4f32 %v %c_u32_2\n"
6106                         "%f3                = OpAccessChain %fp_v4f32 %v %c_u32_3\n"
6107                         "%f_val             = OpLoad %v4f32 %f\n"
6108                         "%f1_val            = OpLoad %v4f32 %f1\n"
6109                         "%f2_val            = OpLoad %v4f32 %f2\n"
6110                         "%f3_val            = OpLoad %v4f32 %f3\n"
6111                         "%t0                = OpFAdd %v4f32 %param1 %f_val\n"
6112                         "%t1                = OpFAdd %v4f32 %t0 %f1_val\n"
6113                         "%t2                = OpFAdd %v4f32 %t1 %f2_val\n"
6114                         "%transformed_param = OpFAdd %v4f32 %t2 %f3_val\n"
6115                 },
6116                 {
6117                         "matrix",
6118                         "%mat4x4_f32        = OpTypeMatrix %v4f32 4\n"
6119                         "%cnull             = OpConstantNull %mat4x4_f32\n",
6120                         // Our null matrix * any vector should result in a zero vector.
6121                         "%v                 = OpVectorTimesMatrix %v4f32 %param1 %cnull\n"
6122                         "%transformed_param = OpFAdd %v4f32 %param1 %v\n"
6123                 }
6124         };
6125
6126         getHalfColorsFullAlpha(colors);
6127
6128         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
6129         {
6130                 map<string, string> fragments;
6131                 fragments["pre_main"] = tests[testNdx].constants;
6132                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
6133                 createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, opConstantNullTests.get());
6134         }
6135         return opConstantNullTests.release();
6136 }
6137 tcu::TestCaseGroup* createOpConstantCompositeTests(tcu::TestContext& testCtx)
6138 {
6139         de::MovePtr<tcu::TestCaseGroup> opConstantCompositeTests                (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "OpConstantComposite instruction"));
6140         RGBA                                                    inputColors[4];
6141         RGBA                                                    outputColors[4];
6142
6143
6144         const char                                              functionStart[]  =
6145                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6146                 "%param1 = OpFunctionParameter %v4f32\n"
6147                 "%lbl    = OpLabel\n";
6148
6149         const char                                              functionEnd[]           =
6150                 "OpReturnValue %transformed_param\n"
6151                 "OpFunctionEnd\n";
6152
6153         struct NameConstantsCode
6154         {
6155                 string name;
6156                 string constants;
6157                 string code;
6158         };
6159
6160         NameConstantsCode tests[] =
6161         {
6162                 {
6163                         "vec4",
6164
6165                         "%cval              = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0\n",
6166                         "%transformed_param = OpFAdd %v4f32 %param1 %cval\n"
6167                 },
6168                 {
6169                         "struct",
6170
6171                         "%stype             = OpTypeStruct %v4f32 %f32\n"
6172                         "%fp_stype          = OpTypePointer Function %stype\n"
6173                         "%f32_n_1           = OpConstant %f32 -1.0\n"
6174                         "%f32_1_5           = OpConstant %f32 !0x3fc00000\n" // +1.5
6175                         "%cvec              = OpConstantComposite %v4f32 %f32_1_5 %f32_1_5 %f32_1_5 %c_f32_1\n"
6176                         "%cval              = OpConstantComposite %stype %cvec %f32_n_1\n",
6177
6178                         "%v                 = OpVariable %fp_stype Function %cval\n"
6179                         "%vec_ptr           = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
6180                         "%f32_ptr           = OpAccessChain %fp_f32 %v %c_u32_1\n"
6181                         "%vec_val           = OpLoad %v4f32 %vec_ptr\n"
6182                         "%f32_val           = OpLoad %f32 %f32_ptr\n"
6183                         "%tmp1              = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_1 %f32_val\n" // vec4(-1)
6184                         "%tmp2              = OpFAdd %v4f32 %tmp1 %param1\n" // param1 + vec4(-1)
6185                         "%transformed_param = OpFAdd %v4f32 %tmp2 %vec_val\n" // param1 + vec4(-1) + vec4(1.5, 1.5, 1.5, 1.0)
6186                 },
6187                 {
6188                         // [1|0|0|0.5] [x] = x + 0.5
6189                         // [0|1|0|0.5] [y] = y + 0.5
6190                         // [0|0|1|0.5] [z] = z + 0.5
6191                         // [0|0|0|1  ] [1] = 1
6192                         "matrix",
6193
6194                         "%mat4x4_f32          = OpTypeMatrix %v4f32 4\n"
6195                         "%v4f32_1_0_0_0       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_0 %c_f32_0 %c_f32_0\n"
6196                         "%v4f32_0_1_0_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_1 %c_f32_0 %c_f32_0\n"
6197                         "%v4f32_0_0_1_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_1 %c_f32_0\n"
6198                         "%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"
6199                         "%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",
6200
6201                         "%transformed_param   = OpMatrixTimesVector %v4f32 %cval %param1\n"
6202                 },
6203                 {
6204                         "array",
6205
6206                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
6207                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
6208                         "%f32_n_1             = OpConstant %f32 -1.0\n"
6209                         "%f32_1_5             = OpConstant %f32 !0x3fc00000\n" // +1.5
6210                         "%carr                = OpConstantComposite %a4f32 %c_f32_0 %f32_n_1 %f32_1_5 %c_f32_0\n",
6211
6212                         "%v                   = OpVariable %fp_a4f32 Function %carr\n"
6213                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_0\n"
6214                         "%f1                  = OpAccessChain %fp_f32 %v %c_u32_1\n"
6215                         "%f2                  = OpAccessChain %fp_f32 %v %c_u32_2\n"
6216                         "%f3                  = OpAccessChain %fp_f32 %v %c_u32_3\n"
6217                         "%f_val               = OpLoad %f32 %f\n"
6218                         "%f1_val              = OpLoad %f32 %f1\n"
6219                         "%f2_val              = OpLoad %f32 %f2\n"
6220                         "%f3_val              = OpLoad %f32 %f3\n"
6221                         "%ftot1               = OpFAdd %f32 %f_val %f1_val\n"
6222                         "%ftot2               = OpFAdd %f32 %ftot1 %f2_val\n"
6223                         "%ftot3               = OpFAdd %f32 %ftot2 %f3_val\n"  // 0 - 1 + 1.5 + 0
6224                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %ftot3\n"
6225                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
6226                 },
6227                 {
6228                         //
6229                         // [
6230                         //   {
6231                         //      0.0,
6232                         //      [ 1.0, 1.0, 1.0, 1.0]
6233                         //   },
6234                         //   {
6235                         //      1.0,
6236                         //      [ 0.0, 0.5, 0.0, 0.0]
6237                         //   }, //     ^^^
6238                         //   {
6239                         //      0.0,
6240                         //      [ 1.0, 1.0, 1.0, 1.0]
6241                         //   }
6242                         // ]
6243                         "array_of_struct_of_array",
6244
6245                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
6246                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
6247                         "%stype               = OpTypeStruct %f32 %a4f32\n"
6248                         "%a3stype             = OpTypeArray %stype %c_u32_3\n"
6249                         "%fp_a3stype          = OpTypePointer Function %a3stype\n"
6250                         "%ca4f32_0            = OpConstantComposite %a4f32 %c_f32_0 %c_f32_0_5 %c_f32_0 %c_f32_0\n"
6251                         "%ca4f32_1            = OpConstantComposite %a4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
6252                         "%cstype1             = OpConstantComposite %stype %c_f32_0 %ca4f32_1\n"
6253                         "%cstype2             = OpConstantComposite %stype %c_f32_1 %ca4f32_0\n"
6254                         "%carr                = OpConstantComposite %a3stype %cstype1 %cstype2 %cstype1",
6255
6256                         "%v                   = OpVariable %fp_a3stype Function %carr\n"
6257                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_1 %c_u32_1 %c_u32_1\n"
6258                         "%f_l                 = OpLoad %f32 %f\n"
6259                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %f_l\n"
6260                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
6261                 }
6262         };
6263
6264         getHalfColorsFullAlpha(inputColors);
6265         outputColors[0] = RGBA(255, 255, 255, 255);
6266         outputColors[1] = RGBA(255, 127, 127, 255);
6267         outputColors[2] = RGBA(127, 255, 127, 255);
6268         outputColors[3] = RGBA(127, 127, 255, 255);
6269
6270         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
6271         {
6272                 map<string, string> fragments;
6273                 fragments["pre_main"] = tests[testNdx].constants;
6274                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
6275                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, opConstantCompositeTests.get());
6276         }
6277         return opConstantCompositeTests.release();
6278 }
6279
6280 tcu::TestCaseGroup* createSelectionBlockOrderTests(tcu::TestContext& testCtx)
6281 {
6282         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "selection_block_order", "Out-of-order blocks for selection"));
6283         RGBA                                                    inputColors[4];
6284         RGBA                                                    outputColors[4];
6285         map<string, string>                             fragments;
6286
6287         // vec4 test_code(vec4 param) {
6288         //   vec4 result = param;
6289         //   for (int i = 0; i < 4; ++i) {
6290         //     if (i == 0) result[i] = 0.;
6291         //     else        result[i] = 1. - result[i];
6292         //   }
6293         //   return result;
6294         // }
6295         const char                                              function[]                      =
6296                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6297                 "%param1    = OpFunctionParameter %v4f32\n"
6298                 "%lbl       = OpLabel\n"
6299                 "%iptr      = OpVariable %fp_i32 Function\n"
6300                 "%result    = OpVariable %fp_v4f32 Function\n"
6301                 "             OpStore %iptr %c_i32_0\n"
6302                 "             OpStore %result %param1\n"
6303                 "             OpBranch %loop\n"
6304
6305                 // Loop entry block.
6306                 "%loop      = OpLabel\n"
6307                 "%ival      = OpLoad %i32 %iptr\n"
6308                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6309                 "             OpLoopMerge %exit %if_entry None\n"
6310                 "             OpBranchConditional %lt_4 %if_entry %exit\n"
6311
6312                 // Merge block for loop.
6313                 "%exit      = OpLabel\n"
6314                 "%ret       = OpLoad %v4f32 %result\n"
6315                 "             OpReturnValue %ret\n"
6316
6317                 // If-statement entry block.
6318                 "%if_entry  = OpLabel\n"
6319                 "%loc       = OpAccessChain %fp_f32 %result %ival\n"
6320                 "%eq_0      = OpIEqual %bool %ival %c_i32_0\n"
6321                 "             OpSelectionMerge %if_exit None\n"
6322                 "             OpBranchConditional %eq_0 %if_true %if_false\n"
6323
6324                 // False branch for if-statement.
6325                 "%if_false  = OpLabel\n"
6326                 "%val       = OpLoad %f32 %loc\n"
6327                 "%sub       = OpFSub %f32 %c_f32_1 %val\n"
6328                 "             OpStore %loc %sub\n"
6329                 "             OpBranch %if_exit\n"
6330
6331                 // Merge block for if-statement.
6332                 "%if_exit   = OpLabel\n"
6333                 "%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
6334                 "             OpStore %iptr %ival_next\n"
6335                 "             OpBranch %loop\n"
6336
6337                 // True branch for if-statement.
6338                 "%if_true   = OpLabel\n"
6339                 "             OpStore %loc %c_f32_0\n"
6340                 "             OpBranch %if_exit\n"
6341
6342                 "             OpFunctionEnd\n";
6343
6344         fragments["testfun"]    = function;
6345
6346         inputColors[0]                  = RGBA(127, 127, 127, 0);
6347         inputColors[1]                  = RGBA(127, 0,   0,   0);
6348         inputColors[2]                  = RGBA(0,   127, 0,   0);
6349         inputColors[3]                  = RGBA(0,   0,   127, 0);
6350
6351         outputColors[0]                 = RGBA(0, 128, 128, 255);
6352         outputColors[1]                 = RGBA(0, 255, 255, 255);
6353         outputColors[2]                 = RGBA(0, 128, 255, 255);
6354         outputColors[3]                 = RGBA(0, 255, 128, 255);
6355
6356         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
6357
6358         return group.release();
6359 }
6360
6361 tcu::TestCaseGroup* createSwitchBlockOrderTests(tcu::TestContext& testCtx)
6362 {
6363         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "switch_block_order", "Out-of-order blocks for switch"));
6364         RGBA                                                    inputColors[4];
6365         RGBA                                                    outputColors[4];
6366         map<string, string>                             fragments;
6367
6368         const char                                              typesAndConstants[]     =
6369                 "%c_f32_p2  = OpConstant %f32 0.2\n"
6370                 "%c_f32_p4  = OpConstant %f32 0.4\n"
6371                 "%c_f32_p6  = OpConstant %f32 0.6\n"
6372                 "%c_f32_p8  = OpConstant %f32 0.8\n";
6373
6374         // vec4 test_code(vec4 param) {
6375         //   vec4 result = param;
6376         //   for (int i = 0; i < 4; ++i) {
6377         //     switch (i) {
6378         //       case 0: result[i] += .2; break;
6379         //       case 1: result[i] += .6; break;
6380         //       case 2: result[i] += .4; break;
6381         //       case 3: result[i] += .8; break;
6382         //       default: break; // unreachable
6383         //     }
6384         //   }
6385         //   return result;
6386         // }
6387         const char                                              function[]                      =
6388                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6389                 "%param1    = OpFunctionParameter %v4f32\n"
6390                 "%lbl       = OpLabel\n"
6391                 "%iptr      = OpVariable %fp_i32 Function\n"
6392                 "%result    = OpVariable %fp_v4f32 Function\n"
6393                 "             OpStore %iptr %c_i32_0\n"
6394                 "             OpStore %result %param1\n"
6395                 "             OpBranch %loop\n"
6396
6397                 // Loop entry block.
6398                 "%loop      = OpLabel\n"
6399                 "%ival      = OpLoad %i32 %iptr\n"
6400                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6401                 "             OpLoopMerge %exit %switch_exit None\n"
6402                 "             OpBranchConditional %lt_4 %switch_entry %exit\n"
6403
6404                 // Merge block for loop.
6405                 "%exit      = OpLabel\n"
6406                 "%ret       = OpLoad %v4f32 %result\n"
6407                 "             OpReturnValue %ret\n"
6408
6409                 // Switch-statement entry block.
6410                 "%switch_entry   = OpLabel\n"
6411                 "%loc            = OpAccessChain %fp_f32 %result %ival\n"
6412                 "%val            = OpLoad %f32 %loc\n"
6413                 "                  OpSelectionMerge %switch_exit None\n"
6414                 "                  OpSwitch %ival %switch_default 0 %case0 1 %case1 2 %case2 3 %case3\n"
6415
6416                 "%case2          = OpLabel\n"
6417                 "%addp4          = OpFAdd %f32 %val %c_f32_p4\n"
6418                 "                  OpStore %loc %addp4\n"
6419                 "                  OpBranch %switch_exit\n"
6420
6421                 "%switch_default = OpLabel\n"
6422                 "                  OpUnreachable\n"
6423
6424                 "%case3          = OpLabel\n"
6425                 "%addp8          = OpFAdd %f32 %val %c_f32_p8\n"
6426                 "                  OpStore %loc %addp8\n"
6427                 "                  OpBranch %switch_exit\n"
6428
6429                 "%case0          = OpLabel\n"
6430                 "%addp2          = OpFAdd %f32 %val %c_f32_p2\n"
6431                 "                  OpStore %loc %addp2\n"
6432                 "                  OpBranch %switch_exit\n"
6433
6434                 // Merge block for switch-statement.
6435                 "%switch_exit    = OpLabel\n"
6436                 "%ival_next      = OpIAdd %i32 %ival %c_i32_1\n"
6437                 "                  OpStore %iptr %ival_next\n"
6438                 "                  OpBranch %loop\n"
6439
6440                 "%case1          = OpLabel\n"
6441                 "%addp6          = OpFAdd %f32 %val %c_f32_p6\n"
6442                 "                  OpStore %loc %addp6\n"
6443                 "                  OpBranch %switch_exit\n"
6444
6445                 "                  OpFunctionEnd\n";
6446
6447         fragments["pre_main"]   = typesAndConstants;
6448         fragments["testfun"]    = function;
6449
6450         inputColors[0]                  = RGBA(127, 27,  127, 51);
6451         inputColors[1]                  = RGBA(127, 0,   0,   51);
6452         inputColors[2]                  = RGBA(0,   27,  0,   51);
6453         inputColors[3]                  = RGBA(0,   0,   127, 51);
6454
6455         outputColors[0]                 = RGBA(178, 180, 229, 255);
6456         outputColors[1]                 = RGBA(178, 153, 102, 255);
6457         outputColors[2]                 = RGBA(51,  180, 102, 255);
6458         outputColors[3]                 = RGBA(51,  153, 229, 255);
6459
6460         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
6461
6462         return group.release();
6463 }
6464
6465 tcu::TestCaseGroup* createDecorationGroupTests(tcu::TestContext& testCtx)
6466 {
6467         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "decoration_group", "Decoration group tests"));
6468         RGBA                                                    inputColors[4];
6469         RGBA                                                    outputColors[4];
6470         map<string, string>                             fragments;
6471
6472         const char                                              decorations[]           =
6473                 "OpDecorate %array_group         ArrayStride 4\n"
6474                 "OpDecorate %struct_member_group Offset 0\n"
6475                 "%array_group         = OpDecorationGroup\n"
6476                 "%struct_member_group = OpDecorationGroup\n"
6477
6478                 "OpDecorate %group1 RelaxedPrecision\n"
6479                 "OpDecorate %group3 RelaxedPrecision\n"
6480                 "OpDecorate %group3 Invariant\n"
6481                 "OpDecorate %group3 Restrict\n"
6482                 "%group0 = OpDecorationGroup\n"
6483                 "%group1 = OpDecorationGroup\n"
6484                 "%group3 = OpDecorationGroup\n";
6485
6486         const char                                              typesAndConstants[]     =
6487                 "%a3f32     = OpTypeArray %f32 %c_u32_3\n"
6488                 "%struct1   = OpTypeStruct %a3f32\n"
6489                 "%struct2   = OpTypeStruct %a3f32\n"
6490                 "%fp_struct1 = OpTypePointer Function %struct1\n"
6491                 "%fp_struct2 = OpTypePointer Function %struct2\n"
6492                 "%c_f32_2    = OpConstant %f32 2.\n"
6493                 "%c_f32_n2   = OpConstant %f32 -2.\n"
6494
6495                 "%c_a3f32_1 = OpConstantComposite %a3f32 %c_f32_1 %c_f32_2 %c_f32_1\n"
6496                 "%c_a3f32_2 = OpConstantComposite %a3f32 %c_f32_n1 %c_f32_n2 %c_f32_n1\n"
6497                 "%c_struct1 = OpConstantComposite %struct1 %c_a3f32_1\n"
6498                 "%c_struct2 = OpConstantComposite %struct2 %c_a3f32_2\n";
6499
6500         const char                                              function[]                      =
6501                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6502                 "%param     = OpFunctionParameter %v4f32\n"
6503                 "%entry     = OpLabel\n"
6504                 "%result    = OpVariable %fp_v4f32 Function\n"
6505                 "%v_struct1 = OpVariable %fp_struct1 Function\n"
6506                 "%v_struct2 = OpVariable %fp_struct2 Function\n"
6507                 "             OpStore %result %param\n"
6508                 "             OpStore %v_struct1 %c_struct1\n"
6509                 "             OpStore %v_struct2 %c_struct2\n"
6510                 "%ptr1      = OpAccessChain %fp_f32 %v_struct1 %c_i32_0 %c_i32_2\n"
6511                 "%val1      = OpLoad %f32 %ptr1\n"
6512                 "%ptr2      = OpAccessChain %fp_f32 %v_struct2 %c_i32_0 %c_i32_2\n"
6513                 "%val2      = OpLoad %f32 %ptr2\n"
6514                 "%addvalues = OpFAdd %f32 %val1 %val2\n"
6515                 "%ptr       = OpAccessChain %fp_f32 %result %c_i32_1\n"
6516                 "%val       = OpLoad %f32 %ptr\n"
6517                 "%addresult = OpFAdd %f32 %addvalues %val\n"
6518                 "             OpStore %ptr %addresult\n"
6519                 "%ret       = OpLoad %v4f32 %result\n"
6520                 "             OpReturnValue %ret\n"
6521                 "             OpFunctionEnd\n";
6522
6523         struct CaseNameDecoration
6524         {
6525                 string name;
6526                 string decoration;
6527         };
6528
6529         CaseNameDecoration tests[] =
6530         {
6531                 {
6532                         "same_decoration_group_on_multiple_types",
6533                         "OpGroupMemberDecorate %struct_member_group %struct1 0 %struct2 0\n"
6534                 },
6535                 {
6536                         "empty_decoration_group",
6537                         "OpGroupDecorate %group0      %a3f32\n"
6538                         "OpGroupDecorate %group0      %result\n"
6539                 },
6540                 {
6541                         "one_element_decoration_group",
6542                         "OpGroupDecorate %array_group %a3f32\n"
6543                 },
6544                 {
6545                         "multiple_elements_decoration_group",
6546                         "OpGroupDecorate %group3      %v_struct1\n"
6547                 },
6548                 {
6549                         "multiple_decoration_groups_on_same_variable",
6550                         "OpGroupDecorate %group0      %v_struct2\n"
6551                         "OpGroupDecorate %group1      %v_struct2\n"
6552                         "OpGroupDecorate %group3      %v_struct2\n"
6553                 },
6554                 {
6555                         "same_decoration_group_multiple_times",
6556                         "OpGroupDecorate %group1      %addvalues\n"
6557                         "OpGroupDecorate %group1      %addvalues\n"
6558                         "OpGroupDecorate %group1      %addvalues\n"
6559                 },
6560
6561         };
6562
6563         getHalfColorsFullAlpha(inputColors);
6564         getHalfColorsFullAlpha(outputColors);
6565
6566         for (size_t idx = 0; idx < (sizeof(tests) / sizeof(tests[0])); ++idx)
6567         {
6568                 fragments["decoration"] = decorations + tests[idx].decoration;
6569                 fragments["pre_main"]   = typesAndConstants;
6570                 fragments["testfun"]    = function;
6571
6572                 createTestsForAllStages(tests[idx].name, inputColors, outputColors, fragments, group.get());
6573         }
6574
6575         return group.release();
6576 }
6577
6578 struct SpecConstantTwoIntGraphicsCase
6579 {
6580         const char*             caseName;
6581         const char*             scDefinition0;
6582         const char*             scDefinition1;
6583         const char*             scResultType;
6584         const char*             scOperation;
6585         deInt32                 scActualValue0;
6586         deInt32                 scActualValue1;
6587         const char*             resultOperation;
6588         RGBA                    expectedColors[4];
6589
6590                                         SpecConstantTwoIntGraphicsCase (const char* name,
6591                                                                                         const char* definition0,
6592                                                                                         const char* definition1,
6593                                                                                         const char* resultType,
6594                                                                                         const char* operation,
6595                                                                                         deInt32         value0,
6596                                                                                         deInt32         value1,
6597                                                                                         const char* resultOp,
6598                                                                                         const RGBA      (&output)[4])
6599                                                 : caseName                      (name)
6600                                                 , scDefinition0         (definition0)
6601                                                 , scDefinition1         (definition1)
6602                                                 , scResultType          (resultType)
6603                                                 , scOperation           (operation)
6604                                                 , scActualValue0        (value0)
6605                                                 , scActualValue1        (value1)
6606                                                 , resultOperation       (resultOp)
6607         {
6608                 expectedColors[0] = output[0];
6609                 expectedColors[1] = output[1];
6610                 expectedColors[2] = output[2];
6611                 expectedColors[3] = output[3];
6612         }
6613 };
6614
6615 tcu::TestCaseGroup* createSpecConstantTests (tcu::TestContext& testCtx)
6616 {
6617         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
6618         vector<SpecConstantTwoIntGraphicsCase>  cases;
6619         RGBA                                                    inputColors[4];
6620         RGBA                                                    outputColors0[4];
6621         RGBA                                                    outputColors1[4];
6622         RGBA                                                    outputColors2[4];
6623
6624         const char      decorations1[]                  =
6625                 "OpDecorate %sc_0  SpecId 0\n"
6626                 "OpDecorate %sc_1  SpecId 1\n";
6627
6628         const char      typesAndConstants1[]    =
6629                 "${OPTYPE_DEFINITIONS:opt}"
6630                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
6631                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
6632                 "%sc_op     = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n";
6633
6634         const char      function1[]                             =
6635                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6636                 "%param     = OpFunctionParameter %v4f32\n"
6637                 "%label     = OpLabel\n"
6638                 "%result    = OpVariable %fp_v4f32 Function\n"
6639                 "${TYPE_CONVERT:opt}"
6640                 "             OpStore %result %param\n"
6641                 "%gen       = ${GEN_RESULT}\n"
6642                 "%index     = OpIAdd %i32 %gen %c_i32_1\n"
6643                 "%loc       = OpAccessChain %fp_f32 %result %index\n"
6644                 "%val       = OpLoad %f32 %loc\n"
6645                 "%add       = OpFAdd %f32 %val %c_f32_0_5\n"
6646                 "             OpStore %loc %add\n"
6647                 "%ret       = OpLoad %v4f32 %result\n"
6648                 "             OpReturnValue %ret\n"
6649                 "             OpFunctionEnd\n";
6650
6651         inputColors[0] = RGBA(127, 127, 127, 255);
6652         inputColors[1] = RGBA(127, 0,   0,   255);
6653         inputColors[2] = RGBA(0,   127, 0,   255);
6654         inputColors[3] = RGBA(0,   0,   127, 255);
6655
6656         // Derived from inputColors[x] by adding 128 to inputColors[x][0].
6657         outputColors0[0] = RGBA(255, 127, 127, 255);
6658         outputColors0[1] = RGBA(255, 0,   0,   255);
6659         outputColors0[2] = RGBA(128, 127, 0,   255);
6660         outputColors0[3] = RGBA(128, 0,   127, 255);
6661
6662         // Derived from inputColors[x] by adding 128 to inputColors[x][1].
6663         outputColors1[0] = RGBA(127, 255, 127, 255);
6664         outputColors1[1] = RGBA(127, 128, 0,   255);
6665         outputColors1[2] = RGBA(0,   255, 0,   255);
6666         outputColors1[3] = RGBA(0,   128, 127, 255);
6667
6668         // Derived from inputColors[x] by adding 128 to inputColors[x][2].
6669         outputColors2[0] = RGBA(127, 127, 255, 255);
6670         outputColors2[1] = RGBA(127, 0,   128, 255);
6671         outputColors2[2] = RGBA(0,   127, 128, 255);
6672         outputColors2[3] = RGBA(0,   0,   255, 255);
6673
6674         const char addZeroToSc[]                = "OpIAdd %i32 %c_i32_0 %sc_op";
6675         const char addZeroToSc32[]              = "OpIAdd %i32 %c_i32_0 %sc_op32";
6676         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_op %c_i32_1 %c_i32_0";
6677         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_op %c_i32_0 %c_i32_1";
6678
6679         cases.push_back(SpecConstantTwoIntGraphicsCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                             19,             -20,    addZeroToSc,            outputColors0));
6680         cases.push_back(SpecConstantTwoIntGraphicsCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                             19,             20,             addZeroToSc,            outputColors0));
6681         cases.push_back(SpecConstantTwoIntGraphicsCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                             -1,             -1,             addZeroToSc,            outputColors2));
6682         cases.push_back(SpecConstantTwoIntGraphicsCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                             -126,   126,    addZeroToSc,            outputColors0));
6683         cases.push_back(SpecConstantTwoIntGraphicsCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                             126,    126,    addZeroToSc,            outputColors2));
6684         cases.push_back(SpecConstantTwoIntGraphicsCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
6685         cases.push_back(SpecConstantTwoIntGraphicsCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
6686         cases.push_back(SpecConstantTwoIntGraphicsCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                             1001,   500,    addZeroToSc,            outputColors2));
6687         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                             0x33,   0x0d,   addZeroToSc,            outputColors2));
6688         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                             0,              1,              addZeroToSc,            outputColors2));
6689         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                             0x2e,   0x2f,   addZeroToSc,            outputColors2));
6690         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                             2,              1,              addZeroToSc,            outputColors2));
6691         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                             -4,             2,              addZeroToSc,            outputColors0));
6692         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                             1,              0,              addZeroToSc,            outputColors2));
6693         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                             -20,    -10,    selectTrueUsingSc,      outputColors2));
6694         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                             10,             20,             selectTrueUsingSc,      outputColors2));
6695         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
6696         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                             10,             5,              selectTrueUsingSc,      outputColors2));
6697         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                             -10,    -10,    selectTrueUsingSc,      outputColors2));
6698         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                             50,             100,    selectTrueUsingSc,      outputColors2));
6699         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
6700         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                             10,             10,             selectTrueUsingSc,      outputColors2));
6701         cases.push_back(SpecConstantTwoIntGraphicsCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                             42,             24,             selectFalseUsingSc,     outputColors2));
6702         cases.push_back(SpecConstantTwoIntGraphicsCase("inotequal",                             " %i32 0",              " %i32 0",              "%bool",        "INotEqual            %sc_0 %sc_1",                             42,             24,             selectTrueUsingSc,      outputColors2));
6703         cases.push_back(SpecConstantTwoIntGraphicsCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
6704         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
6705         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
6706         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
6707         cases.push_back(SpecConstantTwoIntGraphicsCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                                   -1,             0,              addZeroToSc,            outputColors2));
6708         cases.push_back(SpecConstantTwoIntGraphicsCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                                   -2,             0,              addZeroToSc,            outputColors2));
6709         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                                   1,              0,              selectFalseUsingSc,     outputColors2));
6710         cases.push_back(SpecConstantTwoIntGraphicsCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %c_i32_0",    1,              1,              addZeroToSc,            outputColors2));
6711         cases.push_back(SpecConstantTwoIntGraphicsCase("sconvert",                              " %i32 0",              " %i32 0",              "%i16",         "SConvert             %sc_0",                                   -1,             0,              addZeroToSc32,          outputColors0));
6712         // -1082130432 stored as 32-bit two's complement is the binary representation of -1 as IEEE-754 Float
6713         cases.push_back(SpecConstantTwoIntGraphicsCase("fconvert",                              " %f32 0",              " %f32 0",              "%f64",         "FConvert             %sc_0",                                   -1082130432, 0, addZeroToSc32,          outputColors0));
6714         // \todo[2015-12-1 antiagainst] OpQuantizeToF16
6715
6716         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
6717         {
6718                 map<string, string>                     specializations;
6719                 map<string, string>                     fragments;
6720                 SpecConstants                           specConstants;
6721                 vector<string>                          features;
6722                 PushConstants                           noPushConstants;
6723                 GraphicsResources                       noResources;
6724                 GraphicsInterfaces                      noInterfaces;
6725                 std::vector<std::string>        noExtensions;
6726
6727                 // Special SPIR-V code for SConvert-case
6728                 if (strcmp(cases[caseNdx].caseName, "sconvert") == 0)
6729                 {
6730                         features.push_back("shaderInt16");
6731                         fragments["capability"]                                 = "OpCapability Int16\n";                                       // Adds 16-bit integer capability
6732                         specializations["OPTYPE_DEFINITIONS"]   = "%i16 = OpTypeInt 16 1\n";                            // Adds 16-bit integer type
6733                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpSConvert %i32 %sc_op\n";        // Converts 16-bit integer to 32-bit integer
6734                 }
6735
6736                 // Special SPIR-V code for FConvert-case
6737                 if (strcmp(cases[caseNdx].caseName, "fconvert") == 0)
6738                 {
6739                         features.push_back("shaderFloat64");
6740                         fragments["capability"]                                 = "OpCapability Float64\n";                                     // Adds 64-bit float capability
6741                         specializations["OPTYPE_DEFINITIONS"]   = "%f64 = OpTypeFloat 64\n";                            // Adds 64-bit float type
6742                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpConvertFToS %i32 %sc_op\n";     // Converts 64-bit float to 32-bit integer
6743                 }
6744
6745                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
6746                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
6747                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
6748                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
6749                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
6750
6751                 fragments["decoration"]                         = tcu::StringTemplate(decorations1).specialize(specializations);
6752                 fragments["pre_main"]                           = tcu::StringTemplate(typesAndConstants1).specialize(specializations);
6753                 fragments["testfun"]                            = tcu::StringTemplate(function1).specialize(specializations);
6754
6755                 specConstants.append(cases[caseNdx].scActualValue0);
6756                 specConstants.append(cases[caseNdx].scActualValue1);
6757
6758                 createTestsForAllStages(
6759                         cases[caseNdx].caseName, inputColors, cases[caseNdx].expectedColors, fragments, specConstants,
6760                         noPushConstants, noResources, noInterfaces, noExtensions, features, VulkanFeatures(), group.get());
6761         }
6762
6763         const char      decorations2[]                  =
6764                 "OpDecorate %sc_0  SpecId 0\n"
6765                 "OpDecorate %sc_1  SpecId 1\n"
6766                 "OpDecorate %sc_2  SpecId 2\n";
6767
6768         const char      typesAndConstants2[]    =
6769                 "%vec3_0      = OpConstantComposite %v3i32 %c_i32_0 %c_i32_0 %c_i32_0\n"
6770                 "%vec3_undef  = OpUndef %v3i32\n"
6771
6772                 "%sc_0        = OpSpecConstant %i32 0\n"
6773                 "%sc_1        = OpSpecConstant %i32 0\n"
6774                 "%sc_2        = OpSpecConstant %i32 0\n"
6775                 "%sc_vec3_0   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_0        %vec3_0      0\n"                                                 // (sc_0, 0,    0)
6776                 "%sc_vec3_1   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_1        %vec3_0      1\n"                                                 // (0,    sc_1, 0)
6777                 "%sc_vec3_2   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_2        %vec3_0      2\n"                                                 // (0,    0,    sc_2)
6778                 "%sc_vec3_0_s = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_0   %vec3_undef  0          0xFFFFFFFF 2\n"   // (sc_0, ???,  0)
6779                 "%sc_vec3_1_s = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_1   %vec3_undef  0xFFFFFFFF 1          0\n"   // (???,  sc_1, 0)
6780                 "%sc_vec3_2_s = OpSpecConstantOp %v3i32 VectorShuffle    %vec3_undef  %sc_vec3_2   5          0xFFFFFFFF 5\n"   // (sc_2, ???,  sc_2)
6781                 "%sc_vec3_01  = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_0_s %sc_vec3_1_s 1 0 4\n"                                             // (0,    sc_0, sc_1)
6782                 "%sc_vec3_012 = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_01  %sc_vec3_2_s 5 1 2\n"                                             // (sc_2, sc_0, sc_1)
6783                 "%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              0\n"                                                 // sc_2
6784                 "%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              1\n"                                                 // sc_0
6785                 "%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              2\n"                                                 // sc_1
6786                 "%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"                                                              // (sc_2 - sc_0)
6787                 "%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n";                                                             // (sc_2 - sc_0) * sc_1
6788
6789         const char      function2[]                             =
6790                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6791                 "%param     = OpFunctionParameter %v4f32\n"
6792                 "%label     = OpLabel\n"
6793                 "%result    = OpVariable %fp_v4f32 Function\n"
6794                 "             OpStore %result %param\n"
6795                 "%loc       = OpAccessChain %fp_f32 %result %sc_final\n"
6796                 "%val       = OpLoad %f32 %loc\n"
6797                 "%add       = OpFAdd %f32 %val %c_f32_0_5\n"
6798                 "             OpStore %loc %add\n"
6799                 "%ret       = OpLoad %v4f32 %result\n"
6800                 "             OpReturnValue %ret\n"
6801                 "             OpFunctionEnd\n";
6802
6803         map<string, string>     fragments;
6804         SpecConstants           specConstants;
6805
6806         fragments["decoration"] = decorations2;
6807         fragments["pre_main"]   = typesAndConstants2;
6808         fragments["testfun"]    = function2;
6809
6810         specConstants.append<deInt32>(56789);
6811         specConstants.append<deInt32>(-2);
6812         specConstants.append<deInt32>(56788);
6813
6814         createTestsForAllStages("vector_related", inputColors, outputColors2, fragments, specConstants, group.get());
6815
6816         return group.release();
6817 }
6818
6819 tcu::TestCaseGroup* createOpPhiTests(tcu::TestContext& testCtx)
6820 {
6821         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
6822         RGBA                                                    inputColors[4];
6823         RGBA                                                    outputColors1[4];
6824         RGBA                                                    outputColors2[4];
6825         RGBA                                                    outputColors3[4];
6826         map<string, string>                             fragments1;
6827         map<string, string>                             fragments2;
6828         map<string, string>                             fragments3;
6829
6830         const char      typesAndConstants1[]    =
6831                 "%c_f32_p2  = OpConstant %f32 0.2\n"
6832                 "%c_f32_p4  = OpConstant %f32 0.4\n"
6833                 "%c_f32_p5  = OpConstant %f32 0.5\n"
6834                 "%c_f32_p8  = OpConstant %f32 0.8\n";
6835
6836         // vec4 test_code(vec4 param) {
6837         //   vec4 result = param;
6838         //   for (int i = 0; i < 4; ++i) {
6839         //     float operand;
6840         //     switch (i) {
6841         //       case 0: operand = .2; break;
6842         //       case 1: operand = .5; break;
6843         //       case 2: operand = .4; break;
6844         //       case 3: operand = .0; break;
6845         //       default: break; // unreachable
6846         //     }
6847         //     result[i] += operand;
6848         //   }
6849         //   return result;
6850         // }
6851         const char      function1[]                             =
6852                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6853                 "%param1    = OpFunctionParameter %v4f32\n"
6854                 "%lbl       = OpLabel\n"
6855                 "%iptr      = OpVariable %fp_i32 Function\n"
6856                 "%result    = OpVariable %fp_v4f32 Function\n"
6857                 "             OpStore %iptr %c_i32_0\n"
6858                 "             OpStore %result %param1\n"
6859                 "             OpBranch %loop\n"
6860
6861                 "%loop      = OpLabel\n"
6862                 "%ival      = OpLoad %i32 %iptr\n"
6863                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6864                 "             OpLoopMerge %exit %phi None\n"
6865                 "             OpBranchConditional %lt_4 %entry %exit\n"
6866
6867                 "%entry     = OpLabel\n"
6868                 "%loc       = OpAccessChain %fp_f32 %result %ival\n"
6869                 "%val       = OpLoad %f32 %loc\n"
6870                 "             OpSelectionMerge %phi None\n"
6871                 "             OpSwitch %ival %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
6872
6873                 "%case0     = OpLabel\n"
6874                 "             OpBranch %phi\n"
6875                 "%case1     = OpLabel\n"
6876                 "             OpBranch %phi\n"
6877                 "%case2     = OpLabel\n"
6878                 "             OpBranch %phi\n"
6879                 "%case3     = OpLabel\n"
6880                 "             OpBranch %phi\n"
6881
6882                 "%default   = OpLabel\n"
6883                 "             OpUnreachable\n"
6884
6885                 "%phi       = OpLabel\n"
6886                 "%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
6887                 "%add       = OpFAdd %f32 %val %operand\n"
6888                 "             OpStore %loc %add\n"
6889                 "%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
6890                 "             OpStore %iptr %ival_next\n"
6891                 "             OpBranch %loop\n"
6892
6893                 "%exit      = OpLabel\n"
6894                 "%ret       = OpLoad %v4f32 %result\n"
6895                 "             OpReturnValue %ret\n"
6896
6897                 "             OpFunctionEnd\n";
6898
6899         fragments1["pre_main"]  = typesAndConstants1;
6900         fragments1["testfun"]   = function1;
6901
6902         getHalfColorsFullAlpha(inputColors);
6903
6904         outputColors1[0]                = RGBA(178, 255, 229, 255);
6905         outputColors1[1]                = RGBA(178, 127, 102, 255);
6906         outputColors1[2]                = RGBA(51,  255, 102, 255);
6907         outputColors1[3]                = RGBA(51,  127, 229, 255);
6908
6909         createTestsForAllStages("out_of_order", inputColors, outputColors1, fragments1, group.get());
6910
6911         const char      typesAndConstants2[]    =
6912                 "%c_f32_p2  = OpConstant %f32 0.2\n";
6913
6914         // Add .4 to the second element of the given parameter.
6915         const char      function2[]                             =
6916                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6917                 "%param     = OpFunctionParameter %v4f32\n"
6918                 "%entry     = OpLabel\n"
6919                 "%result    = OpVariable %fp_v4f32 Function\n"
6920                 "             OpStore %result %param\n"
6921                 "%loc       = OpAccessChain %fp_f32 %result %c_i32_1\n"
6922                 "%val       = OpLoad %f32 %loc\n"
6923                 "             OpBranch %phi\n"
6924
6925                 "%phi        = OpLabel\n"
6926                 "%step       = OpPhi %i32 %c_i32_0  %entry %step_next  %phi\n"
6927                 "%accum      = OpPhi %f32 %val      %entry %accum_next %phi\n"
6928                 "%step_next  = OpIAdd %i32 %step  %c_i32_1\n"
6929                 "%accum_next = OpFAdd %f32 %accum %c_f32_p2\n"
6930                 "%still_loop = OpSLessThan %bool %step %c_i32_2\n"
6931                 "              OpLoopMerge %exit %phi None\n"
6932                 "              OpBranchConditional %still_loop %phi %exit\n"
6933
6934                 "%exit       = OpLabel\n"
6935                 "              OpStore %loc %accum\n"
6936                 "%ret        = OpLoad %v4f32 %result\n"
6937                 "              OpReturnValue %ret\n"
6938
6939                 "              OpFunctionEnd\n";
6940
6941         fragments2["pre_main"]  = typesAndConstants2;
6942         fragments2["testfun"]   = function2;
6943
6944         outputColors2[0]                        = RGBA(127, 229, 127, 255);
6945         outputColors2[1]                        = RGBA(127, 102, 0,   255);
6946         outputColors2[2]                        = RGBA(0,   229, 0,   255);
6947         outputColors2[3]                        = RGBA(0,   102, 127, 255);
6948
6949         createTestsForAllStages("induction", inputColors, outputColors2, fragments2, group.get());
6950
6951         const char      typesAndConstants3[]    =
6952                 "%true      = OpConstantTrue %bool\n"
6953                 "%false     = OpConstantFalse %bool\n"
6954                 "%c_f32_p2  = OpConstant %f32 0.2\n";
6955
6956         // Swap the second and the third element of the given parameter.
6957         const char      function3[]                             =
6958                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6959                 "%param     = OpFunctionParameter %v4f32\n"
6960                 "%entry     = OpLabel\n"
6961                 "%result    = OpVariable %fp_v4f32 Function\n"
6962                 "             OpStore %result %param\n"
6963                 "%a_loc     = OpAccessChain %fp_f32 %result %c_i32_1\n"
6964                 "%a_init    = OpLoad %f32 %a_loc\n"
6965                 "%b_loc     = OpAccessChain %fp_f32 %result %c_i32_2\n"
6966                 "%b_init    = OpLoad %f32 %b_loc\n"
6967                 "             OpBranch %phi\n"
6968
6969                 "%phi        = OpLabel\n"
6970                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
6971                 "%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
6972                 "%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
6973                 "              OpLoopMerge %exit %phi None\n"
6974                 "              OpBranchConditional %still_loop %phi %exit\n"
6975
6976                 "%exit       = OpLabel\n"
6977                 "              OpStore %a_loc %a_next\n"
6978                 "              OpStore %b_loc %b_next\n"
6979                 "%ret        = OpLoad %v4f32 %result\n"
6980                 "              OpReturnValue %ret\n"
6981
6982                 "              OpFunctionEnd\n";
6983
6984         fragments3["pre_main"]  = typesAndConstants3;
6985         fragments3["testfun"]   = function3;
6986
6987         outputColors3[0]                        = RGBA(127, 127, 127, 255);
6988         outputColors3[1]                        = RGBA(127, 0,   0,   255);
6989         outputColors3[2]                        = RGBA(0,   0,   127, 255);
6990         outputColors3[3]                        = RGBA(0,   127, 0,   255);
6991
6992         createTestsForAllStages("swap", inputColors, outputColors3, fragments3, group.get());
6993
6994         return group.release();
6995 }
6996
6997 tcu::TestCaseGroup* createNoContractionTests(tcu::TestContext& testCtx)
6998 {
6999         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
7000         RGBA                                                    inputColors[4];
7001         RGBA                                                    outputColors[4];
7002
7003         // With NoContraction, (1 + 2^-23) * (1 - 2^-23) - 1 should be conducted as a multiplication and an addition separately.
7004         // For the multiplication, the result is 1 - 2^-46, which is out of the precision range for 32-bit float. (32-bit float
7005         // only have 23-bit fraction.) So it will be rounded to 1. Or 0x1.fffffc. Then the final result is 0 or -0x1p-24.
7006         // On the contrary, the result will be 2^-46, which is a normalized number perfectly representable as 32-bit float.
7007         const char                                              constantsAndTypes[]      =
7008                 "%c_vec4_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_0 %c_f32_1\n"
7009                 "%c_vec4_1       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
7010                 "%c_f32_1pl2_23  = OpConstant %f32 0x1.000002p+0\n" // 1 + 2^-23
7011                 "%c_f32_1mi2_23  = OpConstant %f32 0x1.fffffcp-1\n" // 1 - 2^-23
7012                 "%c_f32_n1pn24   = OpConstant %f32 -0x1p-24\n";
7013
7014         const char                                              function[]       =
7015                 "%test_code      = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7016                 "%param          = OpFunctionParameter %v4f32\n"
7017                 "%label          = OpLabel\n"
7018                 "%var1           = OpVariable %fp_f32 Function %c_f32_1pl2_23\n"
7019                 "%var2           = OpVariable %fp_f32 Function\n"
7020                 "%red            = OpCompositeExtract %f32 %param 0\n"
7021                 "%plus_red       = OpFAdd %f32 %c_f32_1mi2_23 %red\n"
7022                 "                  OpStore %var2 %plus_red\n"
7023                 "%val1           = OpLoad %f32 %var1\n"
7024                 "%val2           = OpLoad %f32 %var2\n"
7025                 "%mul            = OpFMul %f32 %val1 %val2\n"
7026                 "%add            = OpFAdd %f32 %mul %c_f32_n1\n"
7027                 "%is0            = OpFOrdEqual %bool %add %c_f32_0\n"
7028                 "%isn1n24         = OpFOrdEqual %bool %add %c_f32_n1pn24\n"
7029                 "%success        = OpLogicalOr %bool %is0 %isn1n24\n"
7030                 "%v4success      = OpCompositeConstruct %v4bool %success %success %success %success\n"
7031                 "%ret            = OpSelect %v4f32 %v4success %c_vec4_0 %c_vec4_1\n"
7032                 "                  OpReturnValue %ret\n"
7033                 "                  OpFunctionEnd\n";
7034
7035         struct CaseNameDecoration
7036         {
7037                 string name;
7038                 string decoration;
7039         };
7040
7041
7042         CaseNameDecoration tests[] = {
7043                 {"multiplication",      "OpDecorate %mul NoContraction"},
7044                 {"addition",            "OpDecorate %add NoContraction"},
7045                 {"both",                        "OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"},
7046         };
7047
7048         getHalfColorsFullAlpha(inputColors);
7049
7050         for (deUint8 idx = 0; idx < 4; ++idx)
7051         {
7052                 inputColors[idx].setRed(0);
7053                 outputColors[idx] = RGBA(0, 0, 0, 255);
7054         }
7055
7056         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(CaseNameDecoration); ++testNdx)
7057         {
7058                 map<string, string> fragments;
7059
7060                 fragments["decoration"] = tests[testNdx].decoration;
7061                 fragments["pre_main"] = constantsAndTypes;
7062                 fragments["testfun"] = function;
7063
7064                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, group.get());
7065         }
7066
7067         return group.release();
7068 }
7069
7070 tcu::TestCaseGroup* createMemoryAccessTests(tcu::TestContext& testCtx)
7071 {
7072         de::MovePtr<tcu::TestCaseGroup> memoryAccessTests (new tcu::TestCaseGroup(testCtx, "opmemoryaccess", "Memory Semantics"));
7073         RGBA                                                    colors[4];
7074
7075         const char                                              constantsAndTypes[]      =
7076                 "%c_a2f32_1         = OpConstantComposite %a2f32 %c_f32_1 %c_f32_1\n"
7077                 "%fp_a2f32          = OpTypePointer Function %a2f32\n"
7078                 "%stype             = OpTypeStruct  %v4f32 %a2f32 %f32\n"
7079                 "%fp_stype          = OpTypePointer Function %stype\n";
7080
7081         const char                                              function[]       =
7082                 "%test_code         = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7083                 "%param1            = OpFunctionParameter %v4f32\n"
7084                 "%lbl               = OpLabel\n"
7085                 "%v1                = OpVariable %fp_v4f32 Function\n"
7086                 "%v2                = OpVariable %fp_a2f32 Function\n"
7087                 "%v3                = OpVariable %fp_f32 Function\n"
7088                 "%v                 = OpVariable %fp_stype Function\n"
7089                 "%vv                = OpVariable %fp_stype Function\n"
7090                 "%vvv               = OpVariable %fp_f32 Function\n"
7091
7092                 "                     OpStore %v1 %c_v4f32_1_1_1_1\n"
7093                 "                     OpStore %v2 %c_a2f32_1\n"
7094                 "                     OpStore %v3 %c_f32_1\n"
7095
7096                 "%p_v4f32          = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
7097                 "%p_a2f32          = OpAccessChain %fp_a2f32 %v %c_u32_1\n"
7098                 "%p_f32            = OpAccessChain %fp_f32 %v %c_u32_2\n"
7099                 "%v1_v             = OpLoad %v4f32 %v1 ${access_type}\n"
7100                 "%v2_v             = OpLoad %a2f32 %v2 ${access_type}\n"
7101                 "%v3_v             = OpLoad %f32 %v3 ${access_type}\n"
7102
7103                 "                    OpStore %p_v4f32 %v1_v ${access_type}\n"
7104                 "                    OpStore %p_a2f32 %v2_v ${access_type}\n"
7105                 "                    OpStore %p_f32 %v3_v ${access_type}\n"
7106
7107                 "                    OpCopyMemory %vv %v ${access_type}\n"
7108                 "                    OpCopyMemory %vvv %p_f32 ${access_type}\n"
7109
7110                 "%p_f32_2          = OpAccessChain %fp_f32 %vv %c_u32_2\n"
7111                 "%v_f32_2          = OpLoad %f32 %p_f32_2\n"
7112                 "%v_f32_3          = OpLoad %f32 %vvv\n"
7113
7114                 "%ret1             = OpVectorTimesScalar %v4f32 %param1 %v_f32_2\n"
7115                 "%ret2             = OpVectorTimesScalar %v4f32 %ret1 %v_f32_3\n"
7116                 "                    OpReturnValue %ret2\n"
7117                 "                    OpFunctionEnd\n";
7118
7119         struct NameMemoryAccess
7120         {
7121                 string name;
7122                 string accessType;
7123         };
7124
7125
7126         NameMemoryAccess tests[] =
7127         {
7128                 { "none", "" },
7129                 { "volatile", "Volatile" },
7130                 { "aligned",  "Aligned 1" },
7131                 { "volatile_aligned",  "Volatile|Aligned 1" },
7132                 { "nontemporal_aligned",  "Nontemporal|Aligned 1" },
7133                 { "volatile_nontemporal",  "Volatile|Nontemporal" },
7134                 { "volatile_nontermporal_aligned",  "Volatile|Nontemporal|Aligned 1" },
7135         };
7136
7137         getHalfColorsFullAlpha(colors);
7138
7139         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameMemoryAccess); ++testNdx)
7140         {
7141                 map<string, string> fragments;
7142                 map<string, string> memoryAccess;
7143                 memoryAccess["access_type"] = tests[testNdx].accessType;
7144
7145                 fragments["pre_main"] = constantsAndTypes;
7146                 fragments["testfun"] = tcu::StringTemplate(function).specialize(memoryAccess);
7147                 createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, memoryAccessTests.get());
7148         }
7149         return memoryAccessTests.release();
7150 }
7151 tcu::TestCaseGroup* createOpUndefTests(tcu::TestContext& testCtx)
7152 {
7153         de::MovePtr<tcu::TestCaseGroup>         opUndefTests             (new tcu::TestCaseGroup(testCtx, "opundef", "Test OpUndef"));
7154         RGBA                                                            defaultColors[4];
7155         map<string, string>                                     fragments;
7156         getDefaultColors(defaultColors);
7157
7158         // First, simple cases that don't do anything with the OpUndef result.
7159         struct NameCodePair { string name, decl, type; };
7160         const NameCodePair tests[] =
7161         {
7162                 {"bool", "", "%bool"},
7163                 {"vec2uint32", "", "%v2u32"},
7164                 {"image", "%type = OpTypeImage %f32 2D 0 0 0 1 Unknown", "%type"},
7165                 {"sampler", "%type = OpTypeSampler", "%type"},
7166                 {"sampledimage", "%img = OpTypeImage %f32 2D 0 0 0 1 Unknown\n" "%type = OpTypeSampledImage %img", "%type"},
7167                 {"pointer", "", "%fp_i32"},
7168                 {"runtimearray", "%type = OpTypeRuntimeArray %f32", "%type"},
7169                 {"array", "%c_u32_100 = OpConstant %u32 100\n" "%type = OpTypeArray %i32 %c_u32_100", "%type"},
7170                 {"struct", "%type = OpTypeStruct %f32 %i32 %u32", "%type"}};
7171         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
7172         {
7173                 fragments["undef_type"] = tests[testNdx].type;
7174                 fragments["testfun"] = StringTemplate(
7175                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7176                         "%param1 = OpFunctionParameter %v4f32\n"
7177                         "%label_testfun = OpLabel\n"
7178                         "%undef = OpUndef ${undef_type}\n"
7179                         "OpReturnValue %param1\n"
7180                         "OpFunctionEnd\n").specialize(fragments);
7181                 fragments["pre_main"] = tests[testNdx].decl;
7182                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opUndefTests.get());
7183         }
7184         fragments.clear();
7185
7186         fragments["testfun"] =
7187                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7188                 "%param1 = OpFunctionParameter %v4f32\n"
7189                 "%label_testfun = OpLabel\n"
7190                 "%undef = OpUndef %f32\n"
7191                 "%zero = OpFMul %f32 %undef %c_f32_0\n"
7192                 "%is_nan = OpIsNan %bool %zero\n" //OpUndef may result in NaN which may turn %zero into Nan.
7193                 "%actually_zero = OpSelect %f32 %is_nan %c_f32_0 %zero\n"
7194                 "%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7195                 "%b = OpFAdd %f32 %a %actually_zero\n"
7196                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %b %c_i32_0\n"
7197                 "OpReturnValue %ret\n"
7198                 "OpFunctionEnd\n";
7199
7200         createTestsForAllStages("float32", defaultColors, defaultColors, fragments, opUndefTests.get());
7201
7202         fragments["testfun"] =
7203                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7204                 "%param1 = OpFunctionParameter %v4f32\n"
7205                 "%label_testfun = OpLabel\n"
7206                 "%undef = OpUndef %i32\n"
7207                 "%zero = OpIMul %i32 %undef %c_i32_0\n"
7208                 "%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
7209                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
7210                 "OpReturnValue %ret\n"
7211                 "OpFunctionEnd\n";
7212
7213         createTestsForAllStages("sint32", defaultColors, defaultColors, fragments, opUndefTests.get());
7214
7215         fragments["testfun"] =
7216                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7217                 "%param1 = OpFunctionParameter %v4f32\n"
7218                 "%label_testfun = OpLabel\n"
7219                 "%undef = OpUndef %u32\n"
7220                 "%zero = OpIMul %u32 %undef %c_i32_0\n"
7221                 "%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
7222                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
7223                 "OpReturnValue %ret\n"
7224                 "OpFunctionEnd\n";
7225
7226         createTestsForAllStages("uint32", defaultColors, defaultColors, fragments, opUndefTests.get());
7227
7228         fragments["testfun"] =
7229                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7230                 "%param1 = OpFunctionParameter %v4f32\n"
7231                 "%label_testfun = OpLabel\n"
7232                 "%undef = OpUndef %v4f32\n"
7233                 "%vzero = OpVectorTimesScalar %v4f32 %undef %c_f32_0\n"
7234                 "%zero_0 = OpVectorExtractDynamic %f32 %vzero %c_i32_0\n"
7235                 "%zero_1 = OpVectorExtractDynamic %f32 %vzero %c_i32_1\n"
7236                 "%zero_2 = OpVectorExtractDynamic %f32 %vzero %c_i32_2\n"
7237                 "%zero_3 = OpVectorExtractDynamic %f32 %vzero %c_i32_3\n"
7238                 "%is_nan_0 = OpIsNan %bool %zero_0\n"
7239                 "%is_nan_1 = OpIsNan %bool %zero_1\n"
7240                 "%is_nan_2 = OpIsNan %bool %zero_2\n"
7241                 "%is_nan_3 = OpIsNan %bool %zero_3\n"
7242                 "%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
7243                 "%actually_zero_1 = OpSelect %f32 %is_nan_1 %c_f32_0 %zero_1\n"
7244                 "%actually_zero_2 = OpSelect %f32 %is_nan_2 %c_f32_0 %zero_2\n"
7245                 "%actually_zero_3 = OpSelect %f32 %is_nan_3 %c_f32_0 %zero_3\n"
7246                 "%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7247                 "%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
7248                 "%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
7249                 "%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
7250                 "%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
7251                 "%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
7252                 "%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
7253                 "%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
7254                 "%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
7255                 "%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
7256                 "%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
7257                 "%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
7258                 "OpReturnValue %ret\n"
7259                 "OpFunctionEnd\n";
7260
7261         createTestsForAllStages("vec4float32", defaultColors, defaultColors, fragments, opUndefTests.get());
7262
7263         fragments["pre_main"] =
7264                 "%m2x2f32 = OpTypeMatrix %v2f32 2\n";
7265         fragments["testfun"] =
7266                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7267                 "%param1 = OpFunctionParameter %v4f32\n"
7268                 "%label_testfun = OpLabel\n"
7269                 "%undef = OpUndef %m2x2f32\n"
7270                 "%mzero = OpMatrixTimesScalar %m2x2f32 %undef %c_f32_0\n"
7271                 "%zero_0 = OpCompositeExtract %f32 %mzero 0 0\n"
7272                 "%zero_1 = OpCompositeExtract %f32 %mzero 0 1\n"
7273                 "%zero_2 = OpCompositeExtract %f32 %mzero 1 0\n"
7274                 "%zero_3 = OpCompositeExtract %f32 %mzero 1 1\n"
7275                 "%is_nan_0 = OpIsNan %bool %zero_0\n"
7276                 "%is_nan_1 = OpIsNan %bool %zero_1\n"
7277                 "%is_nan_2 = OpIsNan %bool %zero_2\n"
7278                 "%is_nan_3 = OpIsNan %bool %zero_3\n"
7279                 "%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
7280                 "%actually_zero_1 = OpSelect %f32 %is_nan_1 %c_f32_0 %zero_1\n"
7281                 "%actually_zero_2 = OpSelect %f32 %is_nan_2 %c_f32_0 %zero_2\n"
7282                 "%actually_zero_3 = OpSelect %f32 %is_nan_3 %c_f32_0 %zero_3\n"
7283                 "%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7284                 "%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
7285                 "%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
7286                 "%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
7287                 "%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
7288                 "%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
7289                 "%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
7290                 "%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
7291                 "%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
7292                 "%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
7293                 "%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
7294                 "%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
7295                 "OpReturnValue %ret\n"
7296                 "OpFunctionEnd\n";
7297
7298         createTestsForAllStages("matrix", defaultColors, defaultColors, fragments, opUndefTests.get());
7299
7300         return opUndefTests.release();
7301 }
7302
7303 void createOpQuantizeSingleOptionTests(tcu::TestCaseGroup* testCtx)
7304 {
7305         const RGBA              inputColors[4]          =
7306         {
7307                 RGBA(0,         0,              0,              255),
7308                 RGBA(0,         0,              255,    255),
7309                 RGBA(0,         255,    0,              255),
7310                 RGBA(0,         255,    255,    255)
7311         };
7312
7313         const RGBA              expectedColors[4]       =
7314         {
7315                 RGBA(255,        0,              0,              255),
7316                 RGBA(255,        0,              0,              255),
7317                 RGBA(255,        0,              0,              255),
7318                 RGBA(255,        0,              0,              255)
7319         };
7320
7321         const struct SingleFP16Possibility
7322         {
7323                 const char* name;
7324                 const char* constant;  // Value to assign to %test_constant.
7325                 float           valueAsFloat;
7326                 const char* condition; // Must assign to %cond an expression that evaluates to true after %c = OpQuantizeToF16(%test_constant + 0).
7327         }                               tests[]                         =
7328         {
7329                 {
7330                         "negative",
7331                         "-0x1.3p1\n",
7332                         -constructNormalizedFloat(1, 0x300000),
7333                         "%cond = OpFOrdEqual %bool %c %test_constant\n"
7334                 }, // -19
7335                 {
7336                         "positive",
7337                         "0x1.0p7\n",
7338                         constructNormalizedFloat(7, 0x000000),
7339                         "%cond = OpFOrdEqual %bool %c %test_constant\n"
7340                 },  // +128
7341                 // SPIR-V requires that OpQuantizeToF16 flushes
7342                 // any numbers that would end up denormalized in F16 to zero.
7343                 {
7344                         "denorm",
7345                         "0x0.0006p-126\n",
7346                         std::ldexp(1.5f, -140),
7347                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7348                 },  // denorm
7349                 {
7350                         "negative_denorm",
7351                         "-0x0.0006p-126\n",
7352                         -std::ldexp(1.5f, -140),
7353                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7354                 }, // -denorm
7355                 {
7356                         "too_small",
7357                         "0x1.0p-16\n",
7358                         std::ldexp(1.0f, -16),
7359                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7360                 },     // too small positive
7361                 {
7362                         "negative_too_small",
7363                         "-0x1.0p-32\n",
7364                         -std::ldexp(1.0f, -32),
7365                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7366                 },      // too small negative
7367                 {
7368                         "negative_inf",
7369                         "-0x1.0p128\n",
7370                         -std::ldexp(1.0f, 128),
7371
7372                         "%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
7373                         "%inf = OpIsInf %bool %c\n"
7374                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7375                 },     // -inf to -inf
7376                 {
7377                         "inf",
7378                         "0x1.0p128\n",
7379                         std::ldexp(1.0f, 128),
7380
7381                         "%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
7382                         "%inf = OpIsInf %bool %c\n"
7383                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7384                 },     // +inf to +inf
7385                 {
7386                         "round_to_negative_inf",
7387                         "-0x1.0p32\n",
7388                         -std::ldexp(1.0f, 32),
7389
7390                         "%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
7391                         "%inf = OpIsInf %bool %c\n"
7392                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7393                 },     // round to -inf
7394                 {
7395                         "round_to_inf",
7396                         "0x1.0p16\n",
7397                         std::ldexp(1.0f, 16),
7398
7399                         "%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
7400                         "%inf = OpIsInf %bool %c\n"
7401                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7402                 },     // round to +inf
7403                 {
7404                         "nan",
7405                         "0x1.1p128\n",
7406                         std::numeric_limits<float>::quiet_NaN(),
7407
7408                         // Test for any NaN value, as NaNs are not preserved
7409                         "%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
7410                         "%cond = OpIsNan %bool %direct_quant\n"
7411                 }, // nan
7412                 {
7413                         "negative_nan",
7414                         "-0x1.0001p128\n",
7415                         std::numeric_limits<float>::quiet_NaN(),
7416
7417                         // Test for any NaN value, as NaNs are not preserved
7418                         "%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
7419                         "%cond = OpIsNan %bool %direct_quant\n"
7420                 } // -nan
7421         };
7422         const char*             constants                       =
7423                 "%test_constant = OpConstant %f32 ";  // The value will be test.constant.
7424
7425         StringTemplate  function                        (
7426                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7427                 "%param1        = OpFunctionParameter %v4f32\n"
7428                 "%label_testfun = OpLabel\n"
7429                 "%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7430                 "%b             = OpFAdd %f32 %test_constant %a\n"
7431                 "%c             = OpQuantizeToF16 %f32 %b\n"
7432                 "${condition}\n"
7433                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
7434                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
7435                 "                 OpReturnValue %retval\n"
7436                 "OpFunctionEnd\n"
7437         );
7438
7439         const char*             specDecorations         = "OpDecorate %test_constant SpecId 0\n";
7440         const char*             specConstants           =
7441                         "%test_constant = OpSpecConstant %f32 0.\n"
7442                         "%c             = OpSpecConstantOp %f32 QuantizeToF16 %test_constant\n";
7443
7444         StringTemplate  specConstantFunction(
7445                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7446                 "%param1        = OpFunctionParameter %v4f32\n"
7447                 "%label_testfun = OpLabel\n"
7448                 "${condition}\n"
7449                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
7450                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
7451                 "                 OpReturnValue %retval\n"
7452                 "OpFunctionEnd\n"
7453         );
7454
7455         for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
7456         {
7457                 map<string, string>                                                             codeSpecialization;
7458                 map<string, string>                                                             fragments;
7459                 codeSpecialization["condition"]                                 = tests[idx].condition;
7460                 fragments["testfun"]                                                    = function.specialize(codeSpecialization);
7461                 fragments["pre_main"]                                                   = string(constants) + tests[idx].constant + "\n";
7462                 createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
7463         }
7464
7465         for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
7466         {
7467                 map<string, string>                                                             codeSpecialization;
7468                 map<string, string>                                                             fragments;
7469                 SpecConstants                                                                   passConstants;
7470                 deInt32                                                                                 specConstant;
7471
7472                 codeSpecialization["condition"]                                 = tests[idx].condition;
7473                 fragments["testfun"]                                                    = specConstantFunction.specialize(codeSpecialization);
7474                 fragments["decoration"]                                                 = specDecorations;
7475                 fragments["pre_main"]                                                   = specConstants;
7476
7477                 memcpy(&specConstant, &tests[idx].valueAsFloat, sizeof(float));
7478                 passConstants.append(specConstant);
7479
7480                 createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
7481         }
7482 }
7483
7484 void createOpQuantizeTwoPossibilityTests(tcu::TestCaseGroup* testCtx)
7485 {
7486         RGBA inputColors[4] =  {
7487                 RGBA(0,         0,              0,              255),
7488                 RGBA(0,         0,              255,    255),
7489                 RGBA(0,         255,    0,              255),
7490                 RGBA(0,         255,    255,    255)
7491         };
7492
7493         RGBA expectedColors[4] =
7494         {
7495                 RGBA(255,        0,              0,              255),
7496                 RGBA(255,        0,              0,              255),
7497                 RGBA(255,        0,              0,              255),
7498                 RGBA(255,        0,              0,              255)
7499         };
7500
7501         struct DualFP16Possibility
7502         {
7503                 const char* name;
7504                 const char* input;
7505                 float           inputAsFloat;
7506                 const char* possibleOutput1;
7507                 const char* possibleOutput2;
7508         } tests[] = {
7509                 {
7510                         "positive_round_up_or_round_down",
7511                         "0x1.3003p8",
7512                         constructNormalizedFloat(8, 0x300300),
7513                         "0x1.304p8",
7514                         "0x1.3p8"
7515                 },
7516                 {
7517                         "negative_round_up_or_round_down",
7518                         "-0x1.6008p-7",
7519                         -constructNormalizedFloat(-7, 0x600800),
7520                         "-0x1.6p-7",
7521                         "-0x1.604p-7"
7522                 },
7523                 {
7524                         "carry_bit",
7525                         "0x1.01ep2",
7526                         constructNormalizedFloat(2, 0x01e000),
7527                         "0x1.01cp2",
7528                         "0x1.02p2"
7529                 },
7530                 {
7531                         "carry_to_exponent",
7532                         "0x1.ffep1",
7533                         constructNormalizedFloat(1, 0xffe000),
7534                         "0x1.ffcp1",
7535                         "0x1.0p2"
7536                 },
7537         };
7538         StringTemplate constants (
7539                 "%input_const = OpConstant %f32 ${input}\n"
7540                 "%possible_solution1 = OpConstant %f32 ${output1}\n"
7541                 "%possible_solution2 = OpConstant %f32 ${output2}\n"
7542                 );
7543
7544         StringTemplate specConstants (
7545                 "%input_const = OpSpecConstant %f32 0.\n"
7546                 "%possible_solution1 = OpConstant %f32 ${output1}\n"
7547                 "%possible_solution2 = OpConstant %f32 ${output2}\n"
7548         );
7549
7550         const char* specDecorations = "OpDecorate %input_const  SpecId 0\n";
7551
7552         const char* function  =
7553                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7554                 "%param1        = OpFunctionParameter %v4f32\n"
7555                 "%label_testfun = OpLabel\n"
7556                 "%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7557                 // For the purposes of this test we assume that 0.f will always get
7558                 // faithfully passed through the pipeline stages.
7559                 "%b             = OpFAdd %f32 %input_const %a\n"
7560                 "%c             = OpQuantizeToF16 %f32 %b\n"
7561                 "%eq_1          = OpFOrdEqual %bool %c %possible_solution1\n"
7562                 "%eq_2          = OpFOrdEqual %bool %c %possible_solution2\n"
7563                 "%cond          = OpLogicalOr %bool %eq_1 %eq_2\n"
7564                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
7565                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1"
7566                 "                 OpReturnValue %retval\n"
7567                 "OpFunctionEnd\n";
7568
7569         for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
7570                 map<string, string>                                                                     fragments;
7571                 map<string, string>                                                                     constantSpecialization;
7572
7573                 constantSpecialization["input"]                                         = tests[idx].input;
7574                 constantSpecialization["output1"]                                       = tests[idx].possibleOutput1;
7575                 constantSpecialization["output2"]                                       = tests[idx].possibleOutput2;
7576                 fragments["testfun"]                                                            = function;
7577                 fragments["pre_main"]                                                           = constants.specialize(constantSpecialization);
7578                 createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
7579         }
7580
7581         for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
7582                 map<string, string>                                                                     fragments;
7583                 map<string, string>                                                                     constantSpecialization;
7584                 SpecConstants                                                                           passConstants;
7585                 deInt32                                                                                         specConstant;
7586
7587                 constantSpecialization["output1"]                                       = tests[idx].possibleOutput1;
7588                 constantSpecialization["output2"]                                       = tests[idx].possibleOutput2;
7589                 fragments["testfun"]                                                            = function;
7590                 fragments["decoration"]                                                         = specDecorations;
7591                 fragments["pre_main"]                                                           = specConstants.specialize(constantSpecialization);
7592
7593                 memcpy(&specConstant, &tests[idx].inputAsFloat, sizeof(float));
7594                 passConstants.append(specConstant);
7595
7596                 createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
7597         }
7598 }
7599
7600 tcu::TestCaseGroup* createOpQuantizeTests(tcu::TestContext& testCtx)
7601 {
7602         de::MovePtr<tcu::TestCaseGroup> opQuantizeTests (new tcu::TestCaseGroup(testCtx, "opquantize", "Test OpQuantizeToF16"));
7603         createOpQuantizeSingleOptionTests(opQuantizeTests.get());
7604         createOpQuantizeTwoPossibilityTests(opQuantizeTests.get());
7605         return opQuantizeTests.release();
7606 }
7607
7608 struct ShaderPermutation
7609 {
7610         deUint8 vertexPermutation;
7611         deUint8 geometryPermutation;
7612         deUint8 tesscPermutation;
7613         deUint8 tessePermutation;
7614         deUint8 fragmentPermutation;
7615 };
7616
7617 ShaderPermutation getShaderPermutation(deUint8 inputValue)
7618 {
7619         ShaderPermutation       permutation =
7620         {
7621                 static_cast<deUint8>(inputValue & 0x10? 1u: 0u),
7622                 static_cast<deUint8>(inputValue & 0x08? 1u: 0u),
7623                 static_cast<deUint8>(inputValue & 0x04? 1u: 0u),
7624                 static_cast<deUint8>(inputValue & 0x02? 1u: 0u),
7625                 static_cast<deUint8>(inputValue & 0x01? 1u: 0u)
7626         };
7627         return permutation;
7628 }
7629
7630 tcu::TestCaseGroup* createModuleTests(tcu::TestContext& testCtx)
7631 {
7632         RGBA                                                            defaultColors[4];
7633         RGBA                                                            invertedColors[4];
7634         de::MovePtr<tcu::TestCaseGroup>         moduleTests                     (new tcu::TestCaseGroup(testCtx, "module", "Multiple entry points into shaders"));
7635
7636         getDefaultColors(defaultColors);
7637         getInvertedDefaultColors(invertedColors);
7638
7639         // Combined module tests
7640         {
7641                 // Shader stages: vertex and fragment
7642                 {
7643                         const ShaderElement combinedPipeline[]  =
7644                         {
7645                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
7646                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
7647                         };
7648
7649                         addFunctionCaseWithPrograms<InstanceContext>(
7650                                 moduleTests.get(), "same_module", "", createCombinedModule, runAndVerifyDefaultPipeline,
7651                                 createInstanceContext(combinedPipeline, map<string, string>()));
7652                 }
7653
7654                 // Shader stages: vertex, geometry and fragment
7655                 {
7656                         const ShaderElement combinedPipeline[]  =
7657                         {
7658                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
7659                                 ShaderElement("module", "main", VK_SHADER_STAGE_GEOMETRY_BIT),
7660                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
7661                         };
7662
7663                         addFunctionCaseWithPrograms<InstanceContext>(
7664                                 moduleTests.get(), "same_module_geom", "", createCombinedModule, runAndVerifyDefaultPipeline,
7665                                 createInstanceContext(combinedPipeline, map<string, string>()));
7666                 }
7667
7668                 // Shader stages: vertex, tessellation control, tessellation evaluation and fragment
7669                 {
7670                         const ShaderElement combinedPipeline[]  =
7671                         {
7672                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
7673                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
7674                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
7675                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
7676                         };
7677
7678                         addFunctionCaseWithPrograms<InstanceContext>(
7679                                 moduleTests.get(), "same_module_tessc_tesse", "", createCombinedModule, runAndVerifyDefaultPipeline,
7680                                 createInstanceContext(combinedPipeline, map<string, string>()));
7681                 }
7682
7683                 // Shader stages: vertex, tessellation control, tessellation evaluation, geometry and fragment
7684                 {
7685                         const ShaderElement combinedPipeline[]  =
7686                         {
7687                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
7688                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
7689                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
7690                                 ShaderElement("module", "main", VK_SHADER_STAGE_GEOMETRY_BIT),
7691                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
7692                         };
7693
7694                         addFunctionCaseWithPrograms<InstanceContext>(
7695                                 moduleTests.get(), "same_module_tessc_tesse_geom", "", createCombinedModule, runAndVerifyDefaultPipeline,
7696                                 createInstanceContext(combinedPipeline, map<string, string>()));
7697                 }
7698         }
7699
7700         const char* numbers[] =
7701         {
7702                 "1", "2"
7703         };
7704
7705         for (deInt8 idx = 0; idx < 32; ++idx)
7706         {
7707                 ShaderPermutation                       permutation             = getShaderPermutation(idx);
7708                 string                                          name                    = string("vert") + numbers[permutation.vertexPermutation] + "_geom" + numbers[permutation.geometryPermutation] + "_tessc" + numbers[permutation.tesscPermutation] + "_tesse" + numbers[permutation.tessePermutation] + "_frag" + numbers[permutation.fragmentPermutation];
7709                 const ShaderElement                     pipeline[]              =
7710                 {
7711                         ShaderElement("vert",   string("vert") +        numbers[permutation.vertexPermutation],         VK_SHADER_STAGE_VERTEX_BIT),
7712                         ShaderElement("geom",   string("geom") +        numbers[permutation.geometryPermutation],       VK_SHADER_STAGE_GEOMETRY_BIT),
7713                         ShaderElement("tessc",  string("tessc") +       numbers[permutation.tesscPermutation],          VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
7714                         ShaderElement("tesse",  string("tesse") +       numbers[permutation.tessePermutation],          VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
7715                         ShaderElement("frag",   string("frag") +        numbers[permutation.fragmentPermutation],       VK_SHADER_STAGE_FRAGMENT_BIT)
7716                 };
7717
7718                 // If there are an even number of swaps, then it should be no-op.
7719                 // If there are an odd number, the color should be flipped.
7720                 if ((permutation.vertexPermutation + permutation.geometryPermutation + permutation.tesscPermutation + permutation.tessePermutation + permutation.fragmentPermutation) % 2 == 0)
7721                 {
7722                         addFunctionCaseWithPrograms<InstanceContext>(
7723                                         moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline,
7724                                         createInstanceContext(pipeline, defaultColors, defaultColors, map<string, string>()));
7725                 }
7726                 else
7727                 {
7728                         addFunctionCaseWithPrograms<InstanceContext>(
7729                                         moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline,
7730                                         createInstanceContext(pipeline, defaultColors, invertedColors, map<string, string>()));
7731                 }
7732         }
7733         return moduleTests.release();
7734 }
7735
7736 tcu::TestCaseGroup* createLoopTests(tcu::TestContext& testCtx)
7737 {
7738         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "loop", "Looping control flow"));
7739         RGBA defaultColors[4];
7740         getDefaultColors(defaultColors);
7741         map<string, string> fragments;
7742         fragments["pre_main"] =
7743                 "%c_f32_5 = OpConstant %f32 5.\n";
7744
7745         // A loop with a single block. The Continue Target is the loop block
7746         // itself. In SPIR-V terms, the "loop construct" contains no blocks at all
7747         // -- the "continue construct" forms the entire loop.
7748         fragments["testfun"] =
7749                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7750                 "%param1 = OpFunctionParameter %v4f32\n"
7751
7752                 "%entry = OpLabel\n"
7753                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7754                 "OpBranch %loop\n"
7755
7756                 ";adds and subtracts 1.0 to %val in alternate iterations\n"
7757                 "%loop = OpLabel\n"
7758                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
7759                 "%delta = OpPhi %f32 %c_f32_1 %entry %minus_delta %loop\n"
7760                 "%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
7761                 "%val = OpFAdd %f32 %val1 %delta\n"
7762                 "%minus_delta = OpFSub %f32 %c_f32_0 %delta\n"
7763                 "%count__ = OpISub %i32 %count %c_i32_1\n"
7764                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
7765                 "OpLoopMerge %exit %loop None\n"
7766                 "OpBranchConditional %again %loop %exit\n"
7767
7768                 "%exit = OpLabel\n"
7769                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
7770                 "OpReturnValue %result\n"
7771
7772                 "OpFunctionEnd\n";
7773
7774         createTestsForAllStages("single_block", defaultColors, defaultColors, fragments, testGroup.get());
7775
7776         // Body comprised of multiple basic blocks.
7777         const StringTemplate multiBlock(
7778                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7779                 "%param1 = OpFunctionParameter %v4f32\n"
7780
7781                 "%entry = OpLabel\n"
7782                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7783                 "OpBranch %loop\n"
7784
7785                 ";adds and subtracts 1.0 to %val in alternate iterations\n"
7786                 "%loop = OpLabel\n"
7787                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %gather\n"
7788                 "%delta = OpPhi %f32 %c_f32_1 %entry %delta_next %gather\n"
7789                 "%val1 = OpPhi %f32 %val0 %entry %val %gather\n"
7790                 // There are several possibilities for the Continue Target below.  Each
7791                 // will be specialized into a separate test case.
7792                 "OpLoopMerge %exit ${continue_target} None\n"
7793                 "OpBranch %if\n"
7794
7795                 "%if = OpLabel\n"
7796                 ";delta_next = (delta > 0) ? -1 : 1;\n"
7797                 "%gt0 = OpFOrdGreaterThan %bool %delta %c_f32_0\n"
7798                 "OpSelectionMerge %gather DontFlatten\n"
7799                 "OpBranchConditional %gt0 %even %odd ;tells us if %count is even or odd\n"
7800
7801                 "%odd = OpLabel\n"
7802                 "OpBranch %gather\n"
7803
7804                 "%even = OpLabel\n"
7805                 "OpBranch %gather\n"
7806
7807                 "%gather = OpLabel\n"
7808                 "%delta_next = OpPhi %f32 %c_f32_n1 %even %c_f32_1 %odd\n"
7809                 "%val = OpFAdd %f32 %val1 %delta\n"
7810                 "%count__ = OpISub %i32 %count %c_i32_1\n"
7811                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
7812                 "OpBranchConditional %again %loop %exit\n"
7813
7814                 "%exit = OpLabel\n"
7815                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
7816                 "OpReturnValue %result\n"
7817
7818                 "OpFunctionEnd\n");
7819
7820         map<string, string> continue_target;
7821
7822         // The Continue Target is the loop block itself.
7823         continue_target["continue_target"] = "%loop";
7824         fragments["testfun"] = multiBlock.specialize(continue_target);
7825         createTestsForAllStages("multi_block_continue_construct", defaultColors, defaultColors, fragments, testGroup.get());
7826
7827         // The Continue Target is at the end of the loop.
7828         continue_target["continue_target"] = "%gather";
7829         fragments["testfun"] = multiBlock.specialize(continue_target);
7830         createTestsForAllStages("multi_block_loop_construct", defaultColors, defaultColors, fragments, testGroup.get());
7831
7832         // A loop with continue statement.
7833         fragments["testfun"] =
7834                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7835                 "%param1 = OpFunctionParameter %v4f32\n"
7836
7837                 "%entry = OpLabel\n"
7838                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7839                 "OpBranch %loop\n"
7840
7841                 ";adds 4, 3, and 1 to %val0 (skips 2)\n"
7842                 "%loop = OpLabel\n"
7843                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
7844                 "%val1 = OpPhi %f32 %val0 %entry %val %continue\n"
7845                 "OpLoopMerge %exit %continue None\n"
7846                 "OpBranch %if\n"
7847
7848                 "%if = OpLabel\n"
7849                 ";skip if %count==2\n"
7850                 "%eq2 = OpIEqual %bool %count %c_i32_2\n"
7851                 "OpSelectionMerge %continue DontFlatten\n"
7852                 "OpBranchConditional %eq2 %continue %body\n"
7853
7854                 "%body = OpLabel\n"
7855                 "%fcount = OpConvertSToF %f32 %count\n"
7856                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
7857                 "OpBranch %continue\n"
7858
7859                 "%continue = OpLabel\n"
7860                 "%val = OpPhi %f32 %val2 %body %val1 %if\n"
7861                 "%count__ = OpISub %i32 %count %c_i32_1\n"
7862                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
7863                 "OpBranchConditional %again %loop %exit\n"
7864
7865                 "%exit = OpLabel\n"
7866                 "%same = OpFSub %f32 %val %c_f32_8\n"
7867                 "%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
7868                 "OpReturnValue %result\n"
7869                 "OpFunctionEnd\n";
7870         createTestsForAllStages("continue", defaultColors, defaultColors, fragments, testGroup.get());
7871
7872         // A loop with break.
7873         fragments["testfun"] =
7874                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7875                 "%param1 = OpFunctionParameter %v4f32\n"
7876
7877                 "%entry = OpLabel\n"
7878                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
7879                 "%dot = OpDot %f32 %param1 %param1\n"
7880                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
7881                 "%zero = OpConvertFToU %u32 %div\n"
7882                 "%two = OpIAdd %i32 %zero %c_i32_2\n"
7883                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7884                 "OpBranch %loop\n"
7885
7886                 ";adds 4 and 3 to %val0 (exits early)\n"
7887                 "%loop = OpLabel\n"
7888                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
7889                 "%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
7890                 "OpLoopMerge %exit %continue None\n"
7891                 "OpBranch %if\n"
7892
7893                 "%if = OpLabel\n"
7894                 ";end loop if %count==%two\n"
7895                 "%above2 = OpSGreaterThan %bool %count %two\n"
7896                 "OpSelectionMerge %continue DontFlatten\n"
7897                 "OpBranchConditional %above2 %body %exit\n"
7898
7899                 "%body = OpLabel\n"
7900                 "%fcount = OpConvertSToF %f32 %count\n"
7901                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
7902                 "OpBranch %continue\n"
7903
7904                 "%continue = OpLabel\n"
7905                 "%count__ = OpISub %i32 %count %c_i32_1\n"
7906                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
7907                 "OpBranchConditional %again %loop %exit\n"
7908
7909                 "%exit = OpLabel\n"
7910                 "%val_post = OpPhi %f32 %val2 %continue %val1 %if\n"
7911                 "%same = OpFSub %f32 %val_post %c_f32_7\n"
7912                 "%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
7913                 "OpReturnValue %result\n"
7914                 "OpFunctionEnd\n";
7915         createTestsForAllStages("break", defaultColors, defaultColors, fragments, testGroup.get());
7916
7917         // A loop with return.
7918         fragments["testfun"] =
7919                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7920                 "%param1 = OpFunctionParameter %v4f32\n"
7921
7922                 "%entry = OpLabel\n"
7923                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
7924                 "%dot = OpDot %f32 %param1 %param1\n"
7925                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
7926                 "%zero = OpConvertFToU %u32 %div\n"
7927                 "%two = OpIAdd %i32 %zero %c_i32_2\n"
7928                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7929                 "OpBranch %loop\n"
7930
7931                 ";returns early without modifying %param1\n"
7932                 "%loop = OpLabel\n"
7933                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
7934                 "%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
7935                 "OpLoopMerge %exit %continue None\n"
7936                 "OpBranch %if\n"
7937
7938                 "%if = OpLabel\n"
7939                 ";return if %count==%two\n"
7940                 "%above2 = OpSGreaterThan %bool %count %two\n"
7941                 "OpSelectionMerge %continue DontFlatten\n"
7942                 "OpBranchConditional %above2 %body %early_exit\n"
7943
7944                 "%early_exit = OpLabel\n"
7945                 "OpReturnValue %param1\n"
7946
7947                 "%body = OpLabel\n"
7948                 "%fcount = OpConvertSToF %f32 %count\n"
7949                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
7950                 "OpBranch %continue\n"
7951
7952                 "%continue = OpLabel\n"
7953                 "%count__ = OpISub %i32 %count %c_i32_1\n"
7954                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
7955                 "OpBranchConditional %again %loop %exit\n"
7956
7957                 "%exit = OpLabel\n"
7958                 ";should never get here, so return an incorrect result\n"
7959                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val2 %c_i32_0\n"
7960                 "OpReturnValue %result\n"
7961                 "OpFunctionEnd\n";
7962         createTestsForAllStages("return", defaultColors, defaultColors, fragments, testGroup.get());
7963
7964         // Continue inside a switch block to break to enclosing loop's merge block.
7965         // Matches roughly the following GLSL code:
7966         // for (; keep_going; keep_going = false)
7967         // {
7968         //     switch (int(param1.x))
7969         //     {
7970         //         case 0: continue;
7971         //         case 1: continue;
7972         //         default: continue;
7973         //     }
7974         //     dead code: modify return value to invalid result.
7975         // }
7976         fragments["pre_main"] =
7977                 "%fp_bool = OpTypePointer Function %bool\n"
7978                 "%true = OpConstantTrue %bool\n"
7979                 "%false = OpConstantFalse %bool\n";
7980
7981         fragments["testfun"] =
7982                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7983                 "%param1 = OpFunctionParameter %v4f32\n"
7984
7985                 "%entry = OpLabel\n"
7986                 "%keep_going = OpVariable %fp_bool Function\n"
7987                 "%val_ptr = OpVariable %fp_f32 Function\n"
7988                 "%param1_x = OpCompositeExtract %f32 %param1 0\n"
7989                 "OpStore %keep_going %true\n"
7990                 "OpBranch %forloop_begin\n"
7991
7992                 "%forloop_begin = OpLabel\n"
7993                 "OpLoopMerge %forloop_merge %forloop_continue None\n"
7994                 "OpBranch %forloop\n"
7995
7996                 "%forloop = OpLabel\n"
7997                 "%for_condition = OpLoad %bool %keep_going\n"
7998                 "OpBranchConditional %for_condition %forloop_body %forloop_merge\n"
7999
8000                 "%forloop_body = OpLabel\n"
8001                 "OpStore %val_ptr %param1_x\n"
8002                 "%param1_x_int = OpConvertFToS %i32 %param1_x\n"
8003
8004                 "OpSelectionMerge %switch_merge None\n"
8005                 "OpSwitch %param1_x_int %default 0 %case_0 1 %case_1\n"
8006                 "%case_0 = OpLabel\n"
8007                 "OpBranch %forloop_continue\n"
8008                 "%case_1 = OpLabel\n"
8009                 "OpBranch %forloop_continue\n"
8010                 "%default = OpLabel\n"
8011                 "OpBranch %forloop_continue\n"
8012                 "%switch_merge = OpLabel\n"
8013                 ";should never get here, so change the return value to invalid result\n"
8014                 "OpStore %val_ptr %c_f32_1\n"
8015                 "OpBranch %forloop_continue\n"
8016
8017                 "%forloop_continue = OpLabel\n"
8018                 "OpStore %keep_going %false\n"
8019                 "OpBranch %forloop_begin\n"
8020                 "%forloop_merge = OpLabel\n"
8021
8022                 "%val = OpLoad %f32 %val_ptr\n"
8023                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8024                 "OpReturnValue %result\n"
8025                 "OpFunctionEnd\n";
8026         createTestsForAllStages("switch_continue", defaultColors, defaultColors, fragments, testGroup.get());
8027
8028         return testGroup.release();
8029 }
8030
8031 // A collection of tests putting OpControlBarrier in places GLSL forbids but SPIR-V allows.
8032 tcu::TestCaseGroup* createBarrierTests(tcu::TestContext& testCtx)
8033 {
8034         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "barrier", "OpControlBarrier"));
8035         map<string, string> fragments;
8036
8037         // A barrier inside a function body.
8038         fragments["pre_main"] =
8039                 "%Workgroup = OpConstant %i32 2\n"
8040                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n";
8041         fragments["testfun"] =
8042                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8043                 "%param1 = OpFunctionParameter %v4f32\n"
8044                 "%label_testfun = OpLabel\n"
8045                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8046                 "OpReturnValue %param1\n"
8047                 "OpFunctionEnd\n";
8048         addTessCtrlTest(testGroup.get(), "in_function", fragments);
8049
8050         // Common setup code for the following tests.
8051         fragments["pre_main"] =
8052                 "%Workgroup = OpConstant %i32 2\n"
8053                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n"
8054                 "%c_f32_5 = OpConstant %f32 5.\n";
8055         const string setupPercentZero =  // Begins %test_code function with code that sets %zero to 0u but cannot be optimized away.
8056                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8057                 "%param1 = OpFunctionParameter %v4f32\n"
8058                 "%entry = OpLabel\n"
8059                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8060                 "%dot = OpDot %f32 %param1 %param1\n"
8061                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8062                 "%zero = OpConvertFToU %u32 %div\n";
8063
8064         // Barriers inside OpSwitch branches.
8065         fragments["testfun"] =
8066                 setupPercentZero +
8067                 "OpSelectionMerge %switch_exit None\n"
8068                 "OpSwitch %zero %switch_default 0 %case0 1 %case1 ;should always go to %case0\n"
8069
8070                 "%case1 = OpLabel\n"
8071                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8072                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8073                 "%wrong_branch_alert1 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8074                 "OpBranch %switch_exit\n"
8075
8076                 "%switch_default = OpLabel\n"
8077                 "%wrong_branch_alert2 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8078                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8079                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8080                 "OpBranch %switch_exit\n"
8081
8082                 "%case0 = OpLabel\n"
8083                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8084                 "OpBranch %switch_exit\n"
8085
8086                 "%switch_exit = OpLabel\n"
8087                 "%ret = OpPhi %v4f32 %param1 %case0 %wrong_branch_alert1 %case1 %wrong_branch_alert2 %switch_default\n"
8088                 "OpReturnValue %ret\n"
8089                 "OpFunctionEnd\n";
8090         addTessCtrlTest(testGroup.get(), "in_switch", fragments);
8091
8092         // Barriers inside if-then-else.
8093         fragments["testfun"] =
8094                 setupPercentZero +
8095                 "%eq0 = OpIEqual %bool %zero %c_u32_0\n"
8096                 "OpSelectionMerge %exit DontFlatten\n"
8097                 "OpBranchConditional %eq0 %then %else\n"
8098
8099                 "%else = OpLabel\n"
8100                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8101                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8102                 "%wrong_branch_alert = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8103                 "OpBranch %exit\n"
8104
8105                 "%then = OpLabel\n"
8106                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8107                 "OpBranch %exit\n"
8108                 "%exit = OpLabel\n"
8109                 "%ret = OpPhi %v4f32 %param1 %then %wrong_branch_alert %else\n"
8110                 "OpReturnValue %ret\n"
8111                 "OpFunctionEnd\n";
8112         addTessCtrlTest(testGroup.get(), "in_if", fragments);
8113
8114         // A barrier after control-flow reconvergence, tempting the compiler to attempt something like this:
8115         // http://lists.llvm.org/pipermail/llvm-dev/2009-October/026317.html.
8116         fragments["testfun"] =
8117                 setupPercentZero +
8118                 "%thread_id = OpLoad %i32 %BP_gl_InvocationID\n"
8119                 "%thread0 = OpIEqual %bool %thread_id %c_i32_0\n"
8120                 "OpSelectionMerge %exit DontFlatten\n"
8121                 "OpBranchConditional %thread0 %then %else\n"
8122
8123                 "%else = OpLabel\n"
8124                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8125                 "OpBranch %exit\n"
8126
8127                 "%then = OpLabel\n"
8128                 "%val1 = OpVectorExtractDynamic %f32 %param1 %zero\n"
8129                 "OpBranch %exit\n"
8130
8131                 "%exit = OpLabel\n"
8132                 "%val = OpPhi %f32 %val0 %else %val1 %then\n"
8133                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8134                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %val %zero\n"
8135                 "OpReturnValue %ret\n"
8136                 "OpFunctionEnd\n";
8137         addTessCtrlTest(testGroup.get(), "after_divergent_if", fragments);
8138
8139         // A barrier inside a loop.
8140         fragments["pre_main"] =
8141                 "%Workgroup = OpConstant %i32 2\n"
8142                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n"
8143                 "%c_f32_10 = OpConstant %f32 10.\n";
8144         fragments["testfun"] =
8145                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8146                 "%param1 = OpFunctionParameter %v4f32\n"
8147                 "%entry = OpLabel\n"
8148                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8149                 "OpBranch %loop\n"
8150
8151                 ";adds 4, 3, 2, and 1 to %val0\n"
8152                 "%loop = OpLabel\n"
8153                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
8154                 "%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
8155                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8156                 "%fcount = OpConvertSToF %f32 %count\n"
8157                 "%val = OpFAdd %f32 %val1 %fcount\n"
8158                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8159                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8160                 "OpLoopMerge %exit %loop None\n"
8161                 "OpBranchConditional %again %loop %exit\n"
8162
8163                 "%exit = OpLabel\n"
8164                 "%same = OpFSub %f32 %val %c_f32_10\n"
8165                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8166                 "OpReturnValue %ret\n"
8167                 "OpFunctionEnd\n";
8168         addTessCtrlTest(testGroup.get(), "in_loop", fragments);
8169
8170         return testGroup.release();
8171 }
8172
8173 // Test for the OpFRem instruction.
8174 tcu::TestCaseGroup* createFRemTests(tcu::TestContext& testCtx)
8175 {
8176         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "frem", "OpFRem"));
8177         map<string, string>                                     fragments;
8178         RGBA                                                            inputColors[4];
8179         RGBA                                                            outputColors[4];
8180
8181         fragments["pre_main"]                            =
8182                 "%c_f32_3 = OpConstant %f32 3.0\n"
8183                 "%c_f32_n3 = OpConstant %f32 -3.0\n"
8184                 "%c_f32_4 = OpConstant %f32 4.0\n"
8185                 "%c_f32_p75 = OpConstant %f32 0.75\n"
8186                 "%c_v4f32_p75_p75_p75_p75 = OpConstantComposite %v4f32 %c_f32_p75 %c_f32_p75 %c_f32_p75 %c_f32_p75 \n"
8187                 "%c_v4f32_4_4_4_4 = OpConstantComposite %v4f32 %c_f32_4 %c_f32_4 %c_f32_4 %c_f32_4\n"
8188                 "%c_v4f32_3_n3_3_n3 = OpConstantComposite %v4f32 %c_f32_3 %c_f32_n3 %c_f32_3 %c_f32_n3\n";
8189
8190         // The test does the following.
8191         // vec4 result = (param1 * 8.0) - 4.0;
8192         // return (frem(result.x,3) + 0.75, frem(result.y, -3) + 0.75, 0, 1)
8193         fragments["testfun"]                             =
8194                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8195                 "%param1 = OpFunctionParameter %v4f32\n"
8196                 "%label_testfun = OpLabel\n"
8197                 "%v_times_8 = OpVectorTimesScalar %v4f32 %param1 %c_f32_8\n"
8198                 "%minus_4 = OpFSub %v4f32 %v_times_8 %c_v4f32_4_4_4_4\n"
8199                 "%frem = OpFRem %v4f32 %minus_4 %c_v4f32_3_n3_3_n3\n"
8200                 "%added = OpFAdd %v4f32 %frem %c_v4f32_p75_p75_p75_p75\n"
8201                 "%xyz_1 = OpVectorInsertDynamic %v4f32 %added %c_f32_1 %c_i32_3\n"
8202                 "%xy_0_1 = OpVectorInsertDynamic %v4f32 %xyz_1 %c_f32_0 %c_i32_2\n"
8203                 "OpReturnValue %xy_0_1\n"
8204                 "OpFunctionEnd\n";
8205
8206
8207         inputColors[0]          = RGBA(16,      16,             0, 255);
8208         inputColors[1]          = RGBA(232, 232,        0, 255);
8209         inputColors[2]          = RGBA(232, 16,         0, 255);
8210         inputColors[3]          = RGBA(16,      232,    0, 255);
8211
8212         outputColors[0]         = RGBA(64,      64,             0, 255);
8213         outputColors[1]         = RGBA(255, 255,        0, 255);
8214         outputColors[2]         = RGBA(255, 64,         0, 255);
8215         outputColors[3]         = RGBA(64,      255,    0, 255);
8216
8217         createTestsForAllStages("frem", inputColors, outputColors, fragments, testGroup.get());
8218         return testGroup.release();
8219 }
8220
8221 // Test for the OpSRem instruction.
8222 tcu::TestCaseGroup* createOpSRemGraphicsTests(tcu::TestContext& testCtx, qpTestResult negFailResult)
8223 {
8224         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "srem", "OpSRem"));
8225         map<string, string>                                     fragments;
8226
8227         fragments["pre_main"]                            =
8228                 "%c_f32_255 = OpConstant %f32 255.0\n"
8229                 "%c_i32_128 = OpConstant %i32 128\n"
8230                 "%c_i32_255 = OpConstant %i32 255\n"
8231                 "%c_v4f32_255 = OpConstantComposite %v4f32 %c_f32_255 %c_f32_255 %c_f32_255 %c_f32_255 \n"
8232                 "%c_v4f32_0_5 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 \n"
8233                 "%c_v4i32_128 = OpConstantComposite %v4i32 %c_i32_128 %c_i32_128 %c_i32_128 %c_i32_128 \n";
8234
8235         // The test does the following.
8236         // ivec4 ints = int(param1 * 255.0 + 0.5) - 128;
8237         // ivec4 result = ivec4(srem(ints.x, ints.y), srem(ints.y, ints.z), srem(ints.z, ints.x), 255);
8238         // return float(result + 128) / 255.0;
8239         fragments["testfun"]                             =
8240                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8241                 "%param1 = OpFunctionParameter %v4f32\n"
8242                 "%label_testfun = OpLabel\n"
8243                 "%div255 = OpFMul %v4f32 %param1 %c_v4f32_255\n"
8244                 "%add0_5 = OpFAdd %v4f32 %div255 %c_v4f32_0_5\n"
8245                 "%uints_in = OpConvertFToS %v4i32 %add0_5\n"
8246                 "%ints_in = OpISub %v4i32 %uints_in %c_v4i32_128\n"
8247                 "%x_in = OpCompositeExtract %i32 %ints_in 0\n"
8248                 "%y_in = OpCompositeExtract %i32 %ints_in 1\n"
8249                 "%z_in = OpCompositeExtract %i32 %ints_in 2\n"
8250                 "%x_out = OpSRem %i32 %x_in %y_in\n"
8251                 "%y_out = OpSRem %i32 %y_in %z_in\n"
8252                 "%z_out = OpSRem %i32 %z_in %x_in\n"
8253                 "%ints_out = OpCompositeConstruct %v4i32 %x_out %y_out %z_out %c_i32_255\n"
8254                 "%ints_offset = OpIAdd %v4i32 %ints_out %c_v4i32_128\n"
8255                 "%f_ints_offset = OpConvertSToF %v4f32 %ints_offset\n"
8256                 "%float_out = OpFDiv %v4f32 %f_ints_offset %c_v4f32_255\n"
8257                 "OpReturnValue %float_out\n"
8258                 "OpFunctionEnd\n";
8259
8260         const struct CaseParams
8261         {
8262                 const char*             name;
8263                 const char*             failMessageTemplate;    // customized status message
8264                 qpTestResult    failResult;                             // override status on failure
8265                 int                             operands[4][3];                 // four (x, y, z) vectors of operands
8266                 int                             results[4][3];                  // four (x, y, z) vectors of results
8267         } cases[] =
8268         {
8269                 {
8270                         "positive",
8271                         "${reason}",
8272                         QP_TEST_RESULT_FAIL,
8273                         { { 5, 12, 17 }, { 5, 5, 7 }, { 75, 8, 81 }, { 25, 60, 100 } },                 // operands
8274                         { { 5, 12,  2 }, { 0, 5, 2 }, {  3, 8,  6 }, { 25, 60,   0 } },                 // results
8275                 },
8276                 {
8277                         "all",
8278                         "Inconsistent results, but within specification: ${reason}",
8279                         negFailResult,                                                                                                                  // negative operands, not required by the spec
8280                         { { 5, 12, -17 }, { -5, -5, 7 }, { 75, 8, -81 }, { 25, -60, 100 } },    // operands
8281                         { { 5, 12,  -2 }, {  0, -5, 2 }, {  3, 8,  -6 }, { 25, -60,   0 } },    // results
8282                 },
8283         };
8284         // If either operand is negative the result is undefined. Some implementations may still return correct values.
8285
8286         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
8287         {
8288                 const CaseParams&       params                  = cases[caseNdx];
8289                 RGBA                            inputColors[4];
8290                 RGBA                            outputColors[4];
8291
8292                 for (int i = 0; i < 4; ++i)
8293                 {
8294                         inputColors [i] = RGBA(params.operands[i][0] + 128, params.operands[i][1] + 128, params.operands[i][2] + 128, 255);
8295                         outputColors[i] = RGBA(params.results [i][0] + 128, params.results [i][1] + 128, params.results [i][2] + 128, 255);
8296                 }
8297
8298                 createTestsForAllStages(params.name, inputColors, outputColors, fragments, testGroup.get(), params.failResult, params.failMessageTemplate);
8299         }
8300
8301         return testGroup.release();
8302 }
8303
8304 // Test for the OpSMod instruction.
8305 tcu::TestCaseGroup* createOpSModGraphicsTests(tcu::TestContext& testCtx, qpTestResult negFailResult)
8306 {
8307         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "smod", "OpSMod"));
8308         map<string, string>                                     fragments;
8309
8310         fragments["pre_main"]                            =
8311                 "%c_f32_255 = OpConstant %f32 255.0\n"
8312                 "%c_i32_128 = OpConstant %i32 128\n"
8313                 "%c_i32_255 = OpConstant %i32 255\n"
8314                 "%c_v4f32_255 = OpConstantComposite %v4f32 %c_f32_255 %c_f32_255 %c_f32_255 %c_f32_255 \n"
8315                 "%c_v4f32_0_5 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 \n"
8316                 "%c_v4i32_128 = OpConstantComposite %v4i32 %c_i32_128 %c_i32_128 %c_i32_128 %c_i32_128 \n";
8317
8318         // The test does the following.
8319         // ivec4 ints = int(param1 * 255.0 + 0.5) - 128;
8320         // ivec4 result = ivec4(smod(ints.x, ints.y), smod(ints.y, ints.z), smod(ints.z, ints.x), 255);
8321         // return float(result + 128) / 255.0;
8322         fragments["testfun"]                             =
8323                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8324                 "%param1 = OpFunctionParameter %v4f32\n"
8325                 "%label_testfun = OpLabel\n"
8326                 "%div255 = OpFMul %v4f32 %param1 %c_v4f32_255\n"
8327                 "%add0_5 = OpFAdd %v4f32 %div255 %c_v4f32_0_5\n"
8328                 "%uints_in = OpConvertFToS %v4i32 %add0_5\n"
8329                 "%ints_in = OpISub %v4i32 %uints_in %c_v4i32_128\n"
8330                 "%x_in = OpCompositeExtract %i32 %ints_in 0\n"
8331                 "%y_in = OpCompositeExtract %i32 %ints_in 1\n"
8332                 "%z_in = OpCompositeExtract %i32 %ints_in 2\n"
8333                 "%x_out = OpSMod %i32 %x_in %y_in\n"
8334                 "%y_out = OpSMod %i32 %y_in %z_in\n"
8335                 "%z_out = OpSMod %i32 %z_in %x_in\n"
8336                 "%ints_out = OpCompositeConstruct %v4i32 %x_out %y_out %z_out %c_i32_255\n"
8337                 "%ints_offset = OpIAdd %v4i32 %ints_out %c_v4i32_128\n"
8338                 "%f_ints_offset = OpConvertSToF %v4f32 %ints_offset\n"
8339                 "%float_out = OpFDiv %v4f32 %f_ints_offset %c_v4f32_255\n"
8340                 "OpReturnValue %float_out\n"
8341                 "OpFunctionEnd\n";
8342
8343         const struct CaseParams
8344         {
8345                 const char*             name;
8346                 const char*             failMessageTemplate;    // customized status message
8347                 qpTestResult    failResult;                             // override status on failure
8348                 int                             operands[4][3];                 // four (x, y, z) vectors of operands
8349                 int                             results[4][3];                  // four (x, y, z) vectors of results
8350         } cases[] =
8351         {
8352                 {
8353                         "positive",
8354                         "${reason}",
8355                         QP_TEST_RESULT_FAIL,
8356                         { { 5, 12, 17 }, { 5, 5, 7 }, { 75, 8, 81 }, { 25, 60, 100 } },                         // operands
8357                         { { 5, 12,  2 }, { 0, 5, 2 }, {  3, 8,  6 }, { 25, 60,   0 } },                         // results
8358                 },
8359                 {
8360                         "all",
8361                         "Inconsistent results, but within specification: ${reason}",
8362                         negFailResult,                                                                                                                          // negative operands, not required by the spec
8363                         { { 5, 12, -17 }, { -5, -5,  7 }, { 75,   8, -81 }, {  25, -60, 100 } },        // operands
8364                         { { 5, -5,   3 }, {  0,  2, -3 }, {  3, -73,  69 }, { -35,  40,   0 } },        // results
8365                 },
8366         };
8367         // If either operand is negative the result is undefined. Some implementations may still return correct values.
8368
8369         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
8370         {
8371                 const CaseParams&       params                  = cases[caseNdx];
8372                 RGBA                            inputColors[4];
8373                 RGBA                            outputColors[4];
8374
8375                 for (int i = 0; i < 4; ++i)
8376                 {
8377                         inputColors [i] = RGBA(params.operands[i][0] + 128, params.operands[i][1] + 128, params.operands[i][2] + 128, 255);
8378                         outputColors[i] = RGBA(params.results [i][0] + 128, params.results [i][1] + 128, params.results [i][2] + 128, 255);
8379                 }
8380
8381                 createTestsForAllStages(params.name, inputColors, outputColors, fragments, testGroup.get(), params.failResult, params.failMessageTemplate);
8382         }
8383         return testGroup.release();
8384 }
8385
8386 enum ConversionDataType
8387 {
8388         DATA_TYPE_SIGNED_16,
8389         DATA_TYPE_SIGNED_32,
8390         DATA_TYPE_SIGNED_64,
8391         DATA_TYPE_UNSIGNED_16,
8392         DATA_TYPE_UNSIGNED_32,
8393         DATA_TYPE_UNSIGNED_64,
8394         DATA_TYPE_FLOAT_32,
8395         DATA_TYPE_FLOAT_64,
8396         DATA_TYPE_VEC2_SIGNED_16,
8397         DATA_TYPE_VEC2_SIGNED_32
8398 };
8399
8400 const string getBitWidthStr (ConversionDataType type)
8401 {
8402         switch (type)
8403         {
8404                 case DATA_TYPE_SIGNED_16:
8405                 case DATA_TYPE_UNSIGNED_16:
8406                         return "16";
8407
8408                 case DATA_TYPE_SIGNED_32:
8409                 case DATA_TYPE_UNSIGNED_32:
8410                 case DATA_TYPE_FLOAT_32:
8411                 case DATA_TYPE_VEC2_SIGNED_16:
8412                         return "32";
8413
8414                 case DATA_TYPE_SIGNED_64:
8415                 case DATA_TYPE_UNSIGNED_64:
8416                 case DATA_TYPE_FLOAT_64:
8417                 case DATA_TYPE_VEC2_SIGNED_32:
8418                         return "64";
8419
8420                 default:
8421                         DE_ASSERT(false);
8422         }
8423         return "";
8424 }
8425
8426 const string getByteWidthStr (ConversionDataType type)
8427 {
8428         switch (type)
8429         {
8430                 case DATA_TYPE_SIGNED_16:
8431                 case DATA_TYPE_UNSIGNED_16:
8432                         return "2";
8433
8434                 case DATA_TYPE_SIGNED_32:
8435                 case DATA_TYPE_UNSIGNED_32:
8436                 case DATA_TYPE_FLOAT_32:
8437                 case DATA_TYPE_VEC2_SIGNED_16:
8438                         return "4";
8439
8440                 case DATA_TYPE_SIGNED_64:
8441                 case DATA_TYPE_UNSIGNED_64:
8442                 case DATA_TYPE_FLOAT_64:
8443                 case DATA_TYPE_VEC2_SIGNED_32:
8444                         return "8";
8445
8446                 default:
8447                         DE_ASSERT(false);
8448         }
8449         return "";
8450 }
8451
8452 bool isSigned (ConversionDataType type)
8453 {
8454         switch (type)
8455         {
8456                 case DATA_TYPE_SIGNED_16:
8457                 case DATA_TYPE_SIGNED_32:
8458                 case DATA_TYPE_SIGNED_64:
8459                 case DATA_TYPE_FLOAT_32:
8460                 case DATA_TYPE_FLOAT_64:
8461                 case DATA_TYPE_VEC2_SIGNED_16:
8462                 case DATA_TYPE_VEC2_SIGNED_32:
8463                         return true;
8464
8465                 case DATA_TYPE_UNSIGNED_16:
8466                 case DATA_TYPE_UNSIGNED_32:
8467                 case DATA_TYPE_UNSIGNED_64:
8468                         return false;
8469
8470                 default:
8471                         DE_ASSERT(false);
8472         }
8473         return false;
8474 }
8475
8476 bool isInt (ConversionDataType type)
8477 {
8478         switch (type)
8479         {
8480                 case DATA_TYPE_SIGNED_16:
8481                 case DATA_TYPE_SIGNED_32:
8482                 case DATA_TYPE_SIGNED_64:
8483                 case DATA_TYPE_UNSIGNED_16:
8484                 case DATA_TYPE_UNSIGNED_32:
8485                 case DATA_TYPE_UNSIGNED_64:
8486                         return true;
8487
8488                 case DATA_TYPE_FLOAT_32:
8489                 case DATA_TYPE_FLOAT_64:
8490                 case DATA_TYPE_VEC2_SIGNED_16:
8491                 case DATA_TYPE_VEC2_SIGNED_32:
8492                         return false;
8493
8494                 default:
8495                         DE_ASSERT(false);
8496         }
8497         return false;
8498 }
8499
8500 bool isFloat (ConversionDataType type)
8501 {
8502         switch (type)
8503         {
8504                 case DATA_TYPE_SIGNED_16:
8505                 case DATA_TYPE_SIGNED_32:
8506                 case DATA_TYPE_SIGNED_64:
8507                 case DATA_TYPE_UNSIGNED_16:
8508                 case DATA_TYPE_UNSIGNED_32:
8509                 case DATA_TYPE_UNSIGNED_64:
8510                 case DATA_TYPE_VEC2_SIGNED_16:
8511                 case DATA_TYPE_VEC2_SIGNED_32:
8512                         return false;
8513
8514                 case DATA_TYPE_FLOAT_32:
8515                 case DATA_TYPE_FLOAT_64:
8516                         return true;
8517
8518                 default:
8519                         DE_ASSERT(false);
8520         }
8521         return false;
8522 }
8523
8524 const string getTypeName (ConversionDataType type)
8525 {
8526         string prefix = isSigned(type) ? "" : "u";
8527
8528         if              (isInt(type))                                           return prefix + "int"   + getBitWidthStr(type);
8529         else if (isFloat(type))                                         return prefix + "float" + getBitWidthStr(type);
8530         else if (type == DATA_TYPE_VEC2_SIGNED_16)      return "i16vec2";
8531         else if (type == DATA_TYPE_VEC2_SIGNED_32)      return "i32vec2";
8532         else                                                                            DE_ASSERT(false);
8533
8534         return "";
8535 }
8536
8537 const string getTestName (ConversionDataType from, ConversionDataType to, deUint32 caseNumber)
8538 {
8539         return getTypeName(from) + "_to_" + getTypeName(to) + (caseNumber != 0 ? (string("_") + de::toString(caseNumber)) : string(""));
8540 }
8541
8542 const string getAsmTypeName (ConversionDataType type)
8543 {
8544         string prefix;
8545
8546         if              (isInt(type))                                           prefix = isSigned(type) ? "i" : "u";
8547         else if (isFloat(type))                                         prefix = "f";
8548         else if (type == DATA_TYPE_VEC2_SIGNED_16)      return "i16vec2";
8549         else if (type == DATA_TYPE_VEC2_SIGNED_32)      return "v2i32";
8550         else                                                                            DE_ASSERT(false);
8551
8552         return prefix + getBitWidthStr(type);
8553 }
8554
8555 template<typename T>
8556 BufferSp getSpecializedBuffer (deInt64 number)
8557 {
8558         return BufferSp(new Buffer<T>(vector<T>(1, (T)number)));
8559 }
8560
8561 BufferSp getBuffer (ConversionDataType type, deInt64 number)
8562 {
8563         switch (type)
8564         {
8565                 case DATA_TYPE_SIGNED_16:               return getSpecializedBuffer<deInt16>(number);
8566                 case DATA_TYPE_SIGNED_32:               return getSpecializedBuffer<deInt32>(number);
8567                 case DATA_TYPE_SIGNED_64:               return getSpecializedBuffer<deInt64>(number);
8568                 case DATA_TYPE_UNSIGNED_16:             return getSpecializedBuffer<deUint16>(number);
8569                 case DATA_TYPE_UNSIGNED_32:             return getSpecializedBuffer<deUint32>(number);
8570                 case DATA_TYPE_UNSIGNED_64:             return getSpecializedBuffer<deUint64>(number);
8571                 case DATA_TYPE_FLOAT_32:                return getSpecializedBuffer<deUint32>(number);
8572                 case DATA_TYPE_FLOAT_64:                return getSpecializedBuffer<deUint64>(number);
8573                 case DATA_TYPE_VEC2_SIGNED_16:  return getSpecializedBuffer<deUint32>(number);
8574                 case DATA_TYPE_VEC2_SIGNED_32:  return getSpecializedBuffer<deUint64>(number);
8575
8576                 default:                                                DE_ASSERT(false);
8577                                                                                 return BufferSp(new Buffer<deInt32>(vector<deInt32>(1, 0)));
8578         }
8579 }
8580
8581 bool usesInt16 (ConversionDataType from, ConversionDataType to)
8582 {
8583         return (from == DATA_TYPE_SIGNED_16 || from == DATA_TYPE_UNSIGNED_16
8584                         || to == DATA_TYPE_SIGNED_16 || to == DATA_TYPE_UNSIGNED_16
8585                         || from == DATA_TYPE_VEC2_SIGNED_16 || to == DATA_TYPE_VEC2_SIGNED_16);
8586 }
8587
8588 bool usesInt32 (ConversionDataType from, ConversionDataType to)
8589 {
8590         return (from == DATA_TYPE_SIGNED_32 || from == DATA_TYPE_UNSIGNED_32
8591                 || to == DATA_TYPE_SIGNED_32 || to == DATA_TYPE_UNSIGNED_32
8592                 || from == DATA_TYPE_VEC2_SIGNED_32 || to == DATA_TYPE_VEC2_SIGNED_32);
8593 }
8594
8595 bool usesInt64 (ConversionDataType from, ConversionDataType to)
8596 {
8597         return (from == DATA_TYPE_SIGNED_64 || from == DATA_TYPE_UNSIGNED_64
8598                         || to == DATA_TYPE_SIGNED_64 || to == DATA_TYPE_UNSIGNED_64);
8599 }
8600
8601 bool usesFloat64 (ConversionDataType from, ConversionDataType to)
8602 {
8603         return (from == DATA_TYPE_FLOAT_64 || to == DATA_TYPE_FLOAT_64);
8604 }
8605
8606 bool usesFloat32 (ConversionDataType from, ConversionDataType to)
8607 {
8608         return (from == DATA_TYPE_FLOAT_32 || to == DATA_TYPE_FLOAT_32);
8609 }
8610
8611 ComputeTestFeatures getConversionUsedFeatures (ConversionDataType from, ConversionDataType to)
8612 {
8613         if (usesInt16(from, to) && usesInt64(from, to))                 return COMPUTE_TEST_USES_INT16_INT64;
8614         else if (usesInt16(from, to) && usesInt32(from, to))    return COMPUTE_TEST_USES_NONE;
8615         else if (usesInt16(from, to) && usesFloat64(from, to))  return COMPUTE_TEST_USES_INT16_FLOAT64;
8616         else if (usesInt32(from, to) && usesFloat32(from, to))  return COMPUTE_TEST_USES_NONE;
8617         else if (usesInt64(from, to) && usesFloat64(from, to))  return COMPUTE_TEST_USES_INT64_FLOAT64;
8618         else if (usesInt16(from, to))                                                   return COMPUTE_TEST_USES_INT16;                 // This is not set for int16<-->int32 only conversions
8619         else if (usesInt64(from, to))                                                   return COMPUTE_TEST_USES_INT64;
8620         else if (usesFloat64(from, to))                                                 return COMPUTE_TEST_USES_FLOAT64;
8621         else                                                                                                    return COMPUTE_TEST_USES_NONE;
8622 }
8623
8624 vector<string> getFeatureStringVector (ComputeTestFeatures computeTestFeatures)
8625 {
8626         vector<string> features;
8627         if (computeTestFeatures == COMPUTE_TEST_USES_INT16_INT64)
8628         {
8629                 features.push_back("shaderInt16");
8630                 features.push_back("shaderInt64");
8631         }
8632         else if (computeTestFeatures == COMPUTE_TEST_USES_INT64_FLOAT64)
8633         {
8634                 features.push_back("shaderInt64");
8635                 features.push_back("shaderFloat64");
8636         }
8637         else if (computeTestFeatures == COMPUTE_TEST_USES_INT16_FLOAT64)
8638         {
8639                 features.push_back("shaderInt16");
8640                 features.push_back("shaderFloat64");
8641         }
8642         else if (computeTestFeatures == COMPUTE_TEST_USES_INT16)        features.push_back("shaderInt16");
8643         else if (computeTestFeatures == COMPUTE_TEST_USES_INT64)        features.push_back("shaderInt64");
8644         else if (computeTestFeatures == COMPUTE_TEST_USES_FLOAT64)      features.push_back("shaderFloat64");
8645         else if (computeTestFeatures == COMPUTE_TEST_USES_NONE)         {}
8646         else                                                                                                            DE_ASSERT(false);
8647
8648         return features;
8649 }
8650
8651 struct ConvertCase
8652 {
8653         ConvertCase (ConversionDataType from, ConversionDataType to, deInt64 number, bool separateOutput = false, deInt64 outputNumber = 0, deUint32 caseNumber = 0)
8654         : m_fromType            (from)
8655         , m_toType                      (to)
8656         , m_features            (getConversionUsedFeatures(from, to))
8657         , m_name                        (getTestName(from, to, caseNumber))
8658         , m_inputBuffer         (getBuffer(from, number))
8659         {
8660                 m_asmTypes["inputType"]         = getAsmTypeName(from);
8661                 m_asmTypes["outputType"]        = getAsmTypeName(to);
8662
8663                 if (separateOutput)
8664                         m_outputBuffer = getBuffer(to, outputNumber);
8665                 else
8666                         m_outputBuffer = getBuffer(to, number);
8667
8668                 if (m_features == COMPUTE_TEST_USES_INT16)
8669                 {
8670                         m_asmTypes["datatype_capabilities"]             =       "OpCapability Int16\n"
8671                                                                                                                 "OpCapability StorageUniformBufferBlock16\n"
8672                                                                                                                 "OpCapability StorageUniform16\n";
8673                         m_asmTypes["datatype_additional_decl"]  =       "%i16        = OpTypeInt 16 1\n"
8674                                                                                                                 "%u16        = OpTypeInt 16 0\n"
8675                                                                                                                 "%i16vec2    = OpTypeVector %i16 2\n";
8676                         m_asmTypes["datatype_extensions"]               =       "OpExtension \"SPV_KHR_16bit_storage\"\n";
8677                 }
8678                 else if (m_features == COMPUTE_TEST_USES_INT64)
8679                 {
8680                         m_asmTypes["datatype_capabilities"]             =       "OpCapability Int64\n";
8681                         m_asmTypes["datatype_additional_decl"]  =       "%i64        = OpTypeInt 64 1\n"
8682                                                                                                                 "%u64        = OpTypeInt 64 0\n";
8683                         m_asmTypes["datatype_extensions"]               =       "";
8684                 }
8685                 else if (m_features == COMPUTE_TEST_USES_INT16_INT64)
8686                 {
8687                         m_asmTypes["datatype_capabilities"]             =       "OpCapability Int16\n"
8688                                                                                                                 "OpCapability StorageUniformBufferBlock16\n"
8689                                                                                                                 "OpCapability StorageUniform16\n"
8690                                                                                                                 "OpCapability Int64\n";
8691                         m_asmTypes["datatype_additional_decl"]  =       "%i16        = OpTypeInt 16 1\n"
8692                                                                                                                 "%u16        = OpTypeInt 16 0\n"
8693                                                                                                                 "%i64        = OpTypeInt 64 1\n"
8694                                                                                                                 "%u64        = OpTypeInt 64 0\n";
8695                         m_asmTypes["datatype_extensions"]               =       "OpExtension \"SPV_KHR_16bit_storage\"\n";
8696                 }
8697                 else if (m_features == COMPUTE_TEST_USES_FLOAT64)
8698                 {
8699                         m_asmTypes["datatype_capabilities"]             =       "OpCapability Float64\n";
8700                         m_asmTypes["datatype_additional_decl"]  =       "%f64        = OpTypeFloat 64\n";
8701                 }
8702                 else if (usesInt16(from, to) && usesInt32(from, to))
8703                 {
8704                         m_asmTypes["datatype_capabilities"]             =       "OpCapability StorageUniformBufferBlock16\n"
8705                                                                                                                 "OpCapability StorageUniform16\n";
8706                         m_asmTypes["datatype_additional_decl"]  =       "%i16        = OpTypeInt 16 1\n"
8707                                                                                                                 "%u16        = OpTypeInt 16 0\n"
8708                                                                                                                 "%i16vec2    = OpTypeVector %i16 2\n";
8709                         m_asmTypes["datatype_extensions"]               =       "OpExtension \"SPV_KHR_16bit_storage\"\n";
8710                 }
8711                 else if (m_features == COMPUTE_TEST_USES_INT16_FLOAT64)
8712                 {
8713                         m_asmTypes["datatype_capabilities"]             =       "OpCapability Int16\n"
8714                                                                                                                 "OpCapability StorageUniform16\n"
8715                                                                                                                 "OpCapability Float64\n";
8716                         m_asmTypes["datatype_additional_decl"]  =       "%i16        = OpTypeInt 16 1\n"
8717                                                                                                                 "%u16        = OpTypeInt 16 0\n"
8718                                                                                                                 "%f64        = OpTypeFloat 64\n";
8719                         m_asmTypes["datatype_extensions"]               =       "OpExtension \"SPV_KHR_16bit_storage\"\n";
8720                 }
8721                 else if (m_features == COMPUTE_TEST_USES_INT64_FLOAT64)
8722                 {
8723                         m_asmTypes["datatype_capabilities"]             =       "OpCapability Int64\n"
8724                                                                                                                 "OpCapability Float64\n";
8725                         m_asmTypes["datatype_additional_decl"]  =       "%i64        = OpTypeInt 64 1\n"
8726                                                                                                                 "%u64        = OpTypeInt 64 0\n"
8727                                                                                                                 "%f64        = OpTypeFloat 64\n";
8728                         m_asmTypes["datatype_extensions"]               =       "";
8729                 }
8730                 else if (usesInt32(from, to) && usesFloat32(from, to))
8731                 {
8732                         m_asmTypes["datatype_capabilities"]             =       "";
8733                         m_asmTypes["datatype_additional_decl"]  =       "";
8734                         m_asmTypes["datatype_extensions"]               =       "";
8735                 }
8736                 else
8737                 {
8738                         DE_ASSERT(false);
8739                 }
8740         }
8741
8742         ConversionDataType              m_fromType;
8743         ConversionDataType              m_toType;
8744         ComputeTestFeatures             m_features;
8745         string                                  m_name;
8746         map<string, string>             m_asmTypes;
8747         BufferSp                                m_inputBuffer;
8748         BufferSp                                m_outputBuffer;
8749 };
8750
8751 const string getConvertCaseShaderStr (const string& instruction, const ConvertCase& convertCase)
8752 {
8753         map<string, string> params = convertCase.m_asmTypes;
8754
8755         params["instruction"]   = instruction;
8756         params["inDecorator"]   = getByteWidthStr(convertCase.m_fromType);
8757         params["outDecorator"]  = getByteWidthStr(convertCase.m_toType);
8758
8759         const StringTemplate shader (
8760                 "OpCapability Shader\n"
8761                 "${datatype_capabilities}"
8762                 "${datatype_extensions:opt}"
8763                 "OpMemoryModel Logical GLSL450\n"
8764                 "OpEntryPoint GLCompute %main \"main\"\n"
8765                 "OpExecutionMode %main LocalSize 1 1 1\n"
8766                 "OpSource GLSL 430\n"
8767                 "OpName %main           \"main\"\n"
8768                 // Decorators
8769                 "OpDecorate %indata DescriptorSet 0\n"
8770                 "OpDecorate %indata Binding 0\n"
8771                 "OpDecorate %outdata DescriptorSet 0\n"
8772                 "OpDecorate %outdata Binding 1\n"
8773                 "OpDecorate %in_buf BufferBlock\n"
8774                 "OpDecorate %out_buf BufferBlock\n"
8775                 "OpMemberDecorate %in_buf 0 Offset 0\n"
8776                 "OpMemberDecorate %out_buf 0 Offset 0\n"
8777                 // Base types
8778                 "%void       = OpTypeVoid\n"
8779                 "%voidf      = OpTypeFunction %void\n"
8780                 "%u32        = OpTypeInt 32 0\n"
8781                 "%i32        = OpTypeInt 32 1\n"
8782                 "%f32        = OpTypeFloat 32\n"
8783                 "%v2i32      = OpTypeVector %i32 2\n"
8784                 "${datatype_additional_decl}"
8785                 "%uvec3      = OpTypeVector %u32 3\n"
8786                 // Derived types
8787                 "%in_ptr     = OpTypePointer Uniform %${inputType}\n"
8788                 "%out_ptr    = OpTypePointer Uniform %${outputType}\n"
8789                 "%in_buf     = OpTypeStruct %${inputType}\n"
8790                 "%out_buf    = OpTypeStruct %${outputType}\n"
8791                 "%in_bufptr  = OpTypePointer Uniform %in_buf\n"
8792                 "%out_bufptr = OpTypePointer Uniform %out_buf\n"
8793                 "%indata     = OpVariable %in_bufptr Uniform\n"
8794                 "%outdata    = OpVariable %out_bufptr Uniform\n"
8795                 // Constants
8796                 "%zero       = OpConstant %i32 0\n"
8797                 // Main function
8798                 "%main       = OpFunction %void None %voidf\n"
8799                 "%label      = OpLabel\n"
8800                 "%inloc      = OpAccessChain %in_ptr %indata %zero\n"
8801                 "%outloc     = OpAccessChain %out_ptr %outdata %zero\n"
8802                 "%inval      = OpLoad %${inputType} %inloc\n"
8803                 "%conv       = ${instruction} %${outputType} %inval\n"
8804                 "              OpStore %outloc %conv\n"
8805                 "              OpReturn\n"
8806                 "              OpFunctionEnd\n"
8807         );
8808
8809         return shader.specialize(params);
8810 }
8811
8812 void createConvertCases (vector<ConvertCase>& testCases, const string& instruction)
8813 {
8814         if (instruction == "OpUConvert")
8815         {
8816                 // Convert unsigned int to unsigned int
8817                 testCases.push_back(ConvertCase(DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_32,          60653));
8818                 testCases.push_back(ConvertCase(DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_64,          17991));
8819                 testCases.push_back(ConvertCase(DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_64,          904256275));
8820                 testCases.push_back(ConvertCase(DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_16,          6275));
8821                 testCases.push_back(ConvertCase(DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_32,          701256243));
8822                 testCases.push_back(ConvertCase(DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_16,          4741));
8823         }
8824         else if (instruction == "OpSConvert")
8825         {
8826                 // Sign extension int->int
8827                 testCases.push_back(ConvertCase(DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_32,            14669));
8828                 testCases.push_back(ConvertCase(DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_64,            -3341));
8829                 testCases.push_back(ConvertCase(DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_64,            973610259));
8830
8831                 // Truncate for int->int
8832                 testCases.push_back(ConvertCase(DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_16,            12382));
8833                 testCases.push_back(ConvertCase(DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_32,            -972812359));
8834                 testCases.push_back(ConvertCase(DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_16,            -1067742499291926803ll,                         true,   -4371));
8835
8836                 // Sign extension for int->uint
8837                 testCases.push_back(ConvertCase(DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_32,          14669));
8838                 testCases.push_back(ConvertCase(DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_64,          -3341,                                                          true,   18446744073709548275ull));
8839                 testCases.push_back(ConvertCase(DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_64,          973610259));
8840
8841                 // Truncate for int->uint
8842                 testCases.push_back(ConvertCase(DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_16,          12382));
8843                 testCases.push_back(ConvertCase(DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_32,          -972812359,                                                     true,   3322154937u));
8844                 testCases.push_back(ConvertCase(DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_16,          -1067742499291926803ll,                         true,   61165));
8845
8846                 // Sign extension for uint->int
8847                 testCases.push_back(ConvertCase(DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_32,            14669));
8848                 testCases.push_back(ConvertCase(DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_64,            62195,                                                          true,   -3341));
8849                 testCases.push_back(ConvertCase(DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_64,            973610259));
8850
8851                 // Truncate for uint->int
8852                 testCases.push_back(ConvertCase(DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_16,            12382));
8853                 testCases.push_back(ConvertCase(DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_32,            18446744072736739257ull,                        true,   -972812359));
8854                 testCases.push_back(ConvertCase(DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_16,            17379001574417624813ull,                        true,   -4371));
8855
8856                 // Convert i16vec2 to i32vec2 and vice versa
8857                 // Unsigned values are used here to represent negative signed values and to allow defined shifting behaviour.
8858                 // The actual signed value -32123 is used here as uint16 value 33413 and uint32 value 4294935173
8859                 testCases.push_back(ConvertCase(DATA_TYPE_VEC2_SIGNED_16,       DATA_TYPE_VEC2_SIGNED_32,       (33413u << 16)                  | 27593,        true,   (4294935173ull << 32)   | 27593));
8860                 testCases.push_back(ConvertCase(DATA_TYPE_VEC2_SIGNED_32,       DATA_TYPE_VEC2_SIGNED_16,       (4294935173ull << 32)   | 27593,        true,   (33413u << 16)                  | 27593));
8861         }
8862         else if (instruction == "OpFConvert")
8863         {
8864                 // All hexadecimal values below represent 1234.0 as 32/64-bit IEEE 754 float
8865                 testCases.push_back(ConvertCase(DATA_TYPE_FLOAT_32,                     DATA_TYPE_FLOAT_64,                     0x449a4000,                                                     true,   0x4093480000000000));
8866                 testCases.push_back(ConvertCase(DATA_TYPE_FLOAT_64,                     DATA_TYPE_FLOAT_32,                     0x4093480000000000,                                     true,   0x449a4000));
8867         }
8868         else if (instruction == "OpConvertSToF")
8869         {
8870                 testCases.push_back(ConvertCase(DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
8871                 testCases.push_back(ConvertCase(DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
8872                 testCases.push_back(ConvertCase(DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
8873                 testCases.push_back(ConvertCase(DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
8874                 testCases.push_back(ConvertCase(DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
8875                 testCases.push_back(ConvertCase(DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
8876         }
8877         else if (instruction == "OpConvertFToS")
8878         {
8879                 testCases.push_back(ConvertCase(DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0xc49a4000,                                                     true,   -1234));
8880                 testCases.push_back(ConvertCase(DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0x453b9000,                                                     true,    3001, 1));
8881                 testCases.push_back(ConvertCase(DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0xc53b9000,                                                     true,   -3001, 2));
8882                 testCases.push_back(ConvertCase(DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_32,            0xc49a4000,                                                     true,   -1234));
8883                 testCases.push_back(ConvertCase(DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_64,            0xc49a4000,                                                     true,   -1234));
8884                 testCases.push_back(ConvertCase(DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_16,            0xc093480000000000,                                     true,   -1234));
8885                 testCases.push_back(ConvertCase(DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_32,            0xc093480000000000,                                     true,   -1234));
8886                 testCases.push_back(ConvertCase(DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_64,            0xc093480000000000,                                     true,   -1234));
8887         }
8888         else if (instruction == "OpConvertUToF")
8889         {
8890                 testCases.push_back(ConvertCase(DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
8891                 testCases.push_back(ConvertCase(DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
8892                 testCases.push_back(ConvertCase(DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
8893                 testCases.push_back(ConvertCase(DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
8894                 testCases.push_back(ConvertCase(DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
8895                 testCases.push_back(ConvertCase(DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
8896         }
8897         else if (instruction == "OpConvertFToU")
8898         {
8899                 testCases.push_back(ConvertCase(DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_16,          0x449a4000,                                                     true,   1234));
8900                 testCases.push_back(ConvertCase(DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_32,          0x449a4000,                                                     true,   1234));
8901                 testCases.push_back(ConvertCase(DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_64,          0x449a4000,                                                     true,   1234));
8902                 testCases.push_back(ConvertCase(DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_16,          0x4093480000000000,                                     true,   1234));
8903                 testCases.push_back(ConvertCase(DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_32,          0x4093480000000000,                                     true,   1234));
8904                 testCases.push_back(ConvertCase(DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_64,          0x4093480000000000,                                     true,   1234));
8905         }
8906         else
8907                 DE_FATAL("Unknown instruction");
8908 }
8909
8910 const map<string, string> getConvertCaseFragments (string instruction, const ConvertCase& convertCase)
8911 {
8912         map<string, string> params = convertCase.m_asmTypes;
8913         map<string, string> fragments;
8914
8915         params["instruction"] = instruction;
8916         params["inDecorator"] = getByteWidthStr(convertCase.m_fromType);
8917
8918         const StringTemplate decoration (
8919                 "      OpDecorate %SSBOi DescriptorSet 0\n"
8920                 "      OpDecorate %SSBOo DescriptorSet 0\n"
8921                 "      OpDecorate %SSBOi Binding 0\n"
8922                 "      OpDecorate %SSBOo Binding 1\n"
8923                 "      OpDecorate %s_SSBOi Block\n"
8924                 "      OpDecorate %s_SSBOo Block\n"
8925                 "OpMemberDecorate %s_SSBOi 0 Offset 0\n"
8926                 "OpMemberDecorate %s_SSBOo 0 Offset 0\n");
8927
8928         const StringTemplate pre_main (
8929                 "${datatype_additional_decl:opt}"
8930                 "    %ptr_in = OpTypePointer StorageBuffer %${inputType}\n"
8931                 "   %ptr_out = OpTypePointer StorageBuffer %${outputType}\n"
8932                 "   %s_SSBOi = OpTypeStruct %${inputType}\n"
8933                 "   %s_SSBOo = OpTypeStruct %${outputType}\n"
8934                 " %ptr_SSBOi = OpTypePointer StorageBuffer %s_SSBOi\n"
8935                 " %ptr_SSBOo = OpTypePointer StorageBuffer %s_SSBOo\n"
8936                 "     %SSBOi = OpVariable %ptr_SSBOi StorageBuffer\n"
8937                 "     %SSBOo = OpVariable %ptr_SSBOo StorageBuffer\n");
8938
8939         const StringTemplate testfun (
8940                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8941                 "%param     = OpFunctionParameter %v4f32\n"
8942                 "%label     = OpLabel\n"
8943                 "%iLoc      = OpAccessChain %ptr_in %SSBOi %c_u32_0\n"
8944                 "%oLoc      = OpAccessChain %ptr_out %SSBOo %c_u32_0\n"
8945                 "%valIn     = OpLoad %${inputType} %iLoc\n"
8946                 "%valOut    = ${instruction} %${outputType} %valIn\n"
8947                 "             OpStore %oLoc %valOut\n"
8948                 "             OpReturnValue %param\n"
8949                 "             OpFunctionEnd\n");
8950
8951         params["datatype_extensions"] =
8952                 params["datatype_extensions"] +
8953                 "OpExtension \"SPV_KHR_storage_buffer_storage_class\"\n";
8954
8955         fragments["capability"] = params["datatype_capabilities"];
8956         fragments["extension"]  = params["datatype_extensions"];
8957         fragments["decoration"] = decoration.specialize(params);
8958         fragments["pre_main"]   = pre_main.specialize(params);
8959         fragments["testfun"]    = testfun.specialize(params);
8960
8961         return fragments;
8962 }
8963
8964 // Test for OpSConvert, OpUConvert and OpFConvert in compute shaders
8965 tcu::TestCaseGroup* createConvertComputeTests (tcu::TestContext& testCtx, const string& instruction, const string& name)
8966 {
8967         de::MovePtr<tcu::TestCaseGroup>         group(new tcu::TestCaseGroup(testCtx, name.c_str(), instruction.c_str()));
8968         vector<ConvertCase>                                     testCases;
8969         createConvertCases(testCases, instruction);
8970
8971         for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
8972         {
8973                 ComputeShaderSpec spec;
8974                 spec.assembly                   = getConvertCaseShaderStr(instruction, *test);
8975                 spec.numWorkGroups              = IVec3(1, 1, 1);
8976                 spec.inputs.push_back   (test->m_inputBuffer);
8977                 spec.outputs.push_back  (test->m_outputBuffer);
8978
8979                 if (test->m_features == COMPUTE_TEST_USES_INT16 || test->m_features == COMPUTE_TEST_USES_INT16_INT64 || usesInt16(test->m_fromType, test->m_toType)) {
8980                         spec.extensions.push_back("VK_KHR_16bit_storage");
8981                         spec.requestedVulkanFeatures.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
8982                 }
8983
8984                 group->addChild(new SpvAsmComputeShaderCase(testCtx, test->m_name.c_str(), "", spec, test->m_features));
8985         }
8986         return group.release();
8987 }
8988
8989 // Test for OpSConvert, OpUConvert and OpFConvert in graphics shaders
8990 tcu::TestCaseGroup* createConvertGraphicsTests (tcu::TestContext& testCtx, const string& instruction, const string& name)
8991 {
8992         de::MovePtr<tcu::TestCaseGroup>         group(new tcu::TestCaseGroup(testCtx, name.c_str(), instruction.c_str()));
8993         vector<ConvertCase>                                     testCases;
8994         createConvertCases(testCases, instruction);
8995
8996         for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
8997         {
8998                 map<string, string>     fragments               = getConvertCaseFragments(instruction, *test);
8999                 vector<string>          features                = getFeatureStringVector(test->m_features);
9000                 GraphicsResources       resources;
9001                 vector<string>          extensions;
9002                 SpecConstants           noSpecConstants;
9003                 PushConstants           noPushConstants;
9004                 VulkanFeatures          vulkanFeatures;
9005                 GraphicsInterfaces      noInterfaces;
9006                 tcu::RGBA                       defaultColors[4];
9007
9008                 getDefaultColors                        (defaultColors);
9009                 resources.inputs.push_back      (Resource(test->m_inputBuffer, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9010                 resources.outputs.push_back     (Resource(test->m_outputBuffer, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9011                 extensions.push_back            ("VK_KHR_storage_buffer_storage_class");
9012
9013                 if (test->m_features == COMPUTE_TEST_USES_INT16 || test->m_features == COMPUTE_TEST_USES_INT16_INT64 || usesInt16(test->m_fromType, test->m_toType))
9014                 {
9015                         extensions.push_back("VK_KHR_16bit_storage");
9016                         vulkanFeatures.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
9017                 }
9018
9019                 createTestsForAllStages(
9020                         test->m_name, defaultColors, defaultColors, fragments, noSpecConstants,
9021                         noPushConstants, resources, noInterfaces, extensions, features, vulkanFeatures, group.get());
9022         }
9023         return group.release();
9024 }
9025
9026 const string getNumberTypeName (const NumberType type)
9027 {
9028         if (type == NUMBERTYPE_INT32)
9029         {
9030                 return "int";
9031         }
9032         else if (type == NUMBERTYPE_UINT32)
9033         {
9034                 return "uint";
9035         }
9036         else if (type == NUMBERTYPE_FLOAT32)
9037         {
9038                 return "float";
9039         }
9040         else
9041         {
9042                 DE_ASSERT(false);
9043                 return "";
9044         }
9045 }
9046
9047 deInt32 getInt(de::Random& rnd)
9048 {
9049         return rnd.getInt(std::numeric_limits<int>::min(), std::numeric_limits<int>::max());
9050 }
9051
9052 const string repeatString (const string& str, int times)
9053 {
9054         string filler;
9055         for (int i = 0; i < times; ++i)
9056         {
9057                 filler += str;
9058         }
9059         return filler;
9060 }
9061
9062 const string getRandomConstantString (const NumberType type, de::Random& rnd)
9063 {
9064         if (type == NUMBERTYPE_INT32)
9065         {
9066                 return numberToString<deInt32>(getInt(rnd));
9067         }
9068         else if (type == NUMBERTYPE_UINT32)
9069         {
9070                 return numberToString<deUint32>(rnd.getUint32());
9071         }
9072         else if (type == NUMBERTYPE_FLOAT32)
9073         {
9074                 return numberToString<float>(rnd.getFloat());
9075         }
9076         else
9077         {
9078                 DE_ASSERT(false);
9079                 return "";
9080         }
9081 }
9082
9083 void createVectorCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
9084 {
9085         map<string, string> params;
9086
9087         // Vec2 to Vec4
9088         for (int width = 2; width <= 4; ++width)
9089         {
9090                 const string randomConst = numberToString(getInt(rnd));
9091                 const string widthStr = numberToString(width);
9092                 const string composite_type = "${customType}vec" + widthStr;
9093                 const int index = rnd.getInt(0, width-1);
9094
9095                 params["type"]                  = "vec";
9096                 params["name"]                  = params["type"] + "_" + widthStr;
9097                 params["compositeDecl"]         = composite_type + " = OpTypeVector ${customType} " + widthStr +"\n";
9098                 params["compositeType"]         = composite_type;
9099                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
9100                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct " + composite_type + repeatString(" %filler", width) + "\n";
9101                 params["indexes"]               = numberToString(index);
9102                 testCases.push_back(params);
9103         }
9104 }
9105
9106 void createArrayCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
9107 {
9108         const int limit = 10;
9109         map<string, string> params;
9110
9111         for (int width = 2; width <= limit; ++width)
9112         {
9113                 string randomConst = numberToString(getInt(rnd));
9114                 string widthStr = numberToString(width);
9115                 int index = rnd.getInt(0, width-1);
9116
9117                 params["type"]                  = "array";
9118                 params["name"]                  = params["type"] + "_" + widthStr;
9119                 params["compositeDecl"]         = string("%arraywidth = OpConstant %u32 " + widthStr + "\n")
9120                                                                                         +        "%composite = OpTypeArray ${customType} %arraywidth\n";
9121                 params["compositeType"]         = "%composite";
9122                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
9123                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
9124                 params["indexes"]               = numberToString(index);
9125                 testCases.push_back(params);
9126         }
9127 }
9128
9129 void createStructCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
9130 {
9131         const int limit = 10;
9132         map<string, string> params;
9133
9134         for (int width = 2; width <= limit; ++width)
9135         {
9136                 string randomConst = numberToString(getInt(rnd));
9137                 int index = rnd.getInt(0, width-1);
9138
9139                 params["type"]                  = "struct";
9140                 params["name"]                  = params["type"] + "_" + numberToString(width);
9141                 params["compositeDecl"]         = "%composite = OpTypeStruct" + repeatString(" ${customType}", width) + "\n";
9142                 params["compositeType"]         = "%composite";
9143                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
9144                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
9145                 params["indexes"]               = numberToString(index);
9146                 testCases.push_back(params);
9147         }
9148 }
9149
9150 void createMatrixCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
9151 {
9152         map<string, string> params;
9153
9154         // Vec2 to Vec4
9155         for (int width = 2; width <= 4; ++width)
9156         {
9157                 string widthStr = numberToString(width);
9158
9159                 for (int column = 2 ; column <= 4; ++column)
9160                 {
9161                         int index_0 = rnd.getInt(0, column-1);
9162                         int index_1 = rnd.getInt(0, width-1);
9163                         string columnStr = numberToString(column);
9164
9165                         params["type"]          = "matrix";
9166                         params["name"]          = params["type"] + "_" + widthStr + "x" + columnStr;
9167                         params["compositeDecl"] = string("%vectype   = OpTypeVector ${customType} " + widthStr + "\n")
9168                                                                                                 +        "%composite = OpTypeMatrix %vectype " + columnStr + "\n";
9169                         params["compositeType"] = "%composite";
9170
9171                         params["filler"]        = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n"
9172                                                                                                 +        "%fillerVec = OpConstantComposite %vectype" + repeatString(" %filler", width) + "\n";
9173
9174                         params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %fillerVec", column) + "\n";
9175                         params["indexes"]       = numberToString(index_0) + " " + numberToString(index_1);
9176                         testCases.push_back(params);
9177                 }
9178         }
9179 }
9180
9181 void createCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
9182 {
9183         createVectorCompositeCases(testCases, rnd, type);
9184         createArrayCompositeCases(testCases, rnd, type);
9185         createStructCompositeCases(testCases, rnd, type);
9186         // Matrix only supports float types
9187         if (type == NUMBERTYPE_FLOAT32)
9188         {
9189                 createMatrixCompositeCases(testCases, rnd, type);
9190         }
9191 }
9192
9193 const string getAssemblyTypeDeclaration (const NumberType type)
9194 {
9195         switch (type)
9196         {
9197                 case NUMBERTYPE_INT32:          return "OpTypeInt 32 1";
9198                 case NUMBERTYPE_UINT32:         return "OpTypeInt 32 0";
9199                 case NUMBERTYPE_FLOAT32:        return "OpTypeFloat 32";
9200                 default:                        DE_ASSERT(false); return "";
9201         }
9202 }
9203
9204 const string getAssemblyTypeName (const NumberType type)
9205 {
9206         switch (type)
9207         {
9208                 case NUMBERTYPE_INT32:          return "%i32";
9209                 case NUMBERTYPE_UINT32:         return "%u32";
9210                 case NUMBERTYPE_FLOAT32:        return "%f32";
9211                 default:                        DE_ASSERT(false); return "";
9212         }
9213 }
9214
9215 const string specializeCompositeInsertShaderTemplate (const NumberType type, const map<string, string>& params)
9216 {
9217         map<string, string>     parameters(params);
9218
9219         const string customType = getAssemblyTypeName(type);
9220         map<string, string> substCustomType;
9221         substCustomType["customType"] = customType;
9222         parameters["compositeDecl"] = StringTemplate(parameters.at("compositeDecl")).specialize(substCustomType);
9223         parameters["compositeType"] = StringTemplate(parameters.at("compositeType")).specialize(substCustomType);
9224         parameters["compositeConstruct"] = StringTemplate(parameters.at("compositeConstruct")).specialize(substCustomType);
9225         parameters["filler"] = StringTemplate(parameters.at("filler")).specialize(substCustomType);
9226         parameters["customType"] = customType;
9227         parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
9228
9229         if (parameters.at("compositeType") != "%u32vec3")
9230         {
9231                 parameters["u32vec3Decl"] = "%u32vec3   = OpTypeVector %u32 3\n";
9232         }
9233
9234         return StringTemplate(
9235                 "OpCapability Shader\n"
9236                 "OpCapability Matrix\n"
9237                 "OpMemoryModel Logical GLSL450\n"
9238                 "OpEntryPoint GLCompute %main \"main\" %id\n"
9239                 "OpExecutionMode %main LocalSize 1 1 1\n"
9240
9241                 "OpSource GLSL 430\n"
9242                 "OpName %main           \"main\"\n"
9243                 "OpName %id             \"gl_GlobalInvocationID\"\n"
9244
9245                 // Decorators
9246                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
9247                 "OpDecorate %buf BufferBlock\n"
9248                 "OpDecorate %indata DescriptorSet 0\n"
9249                 "OpDecorate %indata Binding 0\n"
9250                 "OpDecorate %outdata DescriptorSet 0\n"
9251                 "OpDecorate %outdata Binding 1\n"
9252                 "OpDecorate %customarr ArrayStride 4\n"
9253                 "${compositeDecorator}"
9254                 "OpMemberDecorate %buf 0 Offset 0\n"
9255
9256                 // General types
9257                 "%void      = OpTypeVoid\n"
9258                 "%voidf     = OpTypeFunction %void\n"
9259                 "%u32       = OpTypeInt 32 0\n"
9260                 "%i32       = OpTypeInt 32 1\n"
9261                 "%f32       = OpTypeFloat 32\n"
9262
9263                 // Composite declaration
9264                 "${compositeDecl}"
9265
9266                 // Constants
9267                 "${filler}"
9268
9269                 "${u32vec3Decl:opt}"
9270                 "%uvec3ptr  = OpTypePointer Input %u32vec3\n"
9271
9272                 // Inherited from custom
9273                 "%customptr = OpTypePointer Uniform ${customType}\n"
9274                 "%customarr = OpTypeRuntimeArray ${customType}\n"
9275                 "%buf       = OpTypeStruct %customarr\n"
9276                 "%bufptr    = OpTypePointer Uniform %buf\n"
9277
9278                 "%indata    = OpVariable %bufptr Uniform\n"
9279                 "%outdata   = OpVariable %bufptr Uniform\n"
9280
9281                 "%id        = OpVariable %uvec3ptr Input\n"
9282                 "%zero      = OpConstant %i32 0\n"
9283
9284                 "%main      = OpFunction %void None %voidf\n"
9285                 "%label     = OpLabel\n"
9286                 "%idval     = OpLoad %u32vec3 %id\n"
9287                 "%x         = OpCompositeExtract %u32 %idval 0\n"
9288
9289                 "%inloc     = OpAccessChain %customptr %indata %zero %x\n"
9290                 "%outloc    = OpAccessChain %customptr %outdata %zero %x\n"
9291                 // Read the input value
9292                 "%inval     = OpLoad ${customType} %inloc\n"
9293                 // Create the composite and fill it
9294                 "${compositeConstruct}"
9295                 // Insert the input value to a place
9296                 "%instance2 = OpCompositeInsert ${compositeType} %inval %instance ${indexes}\n"
9297                 // Read back the value from the position
9298                 "%out_val   = OpCompositeExtract ${customType} %instance2 ${indexes}\n"
9299                 // Store it in the output position
9300                 "             OpStore %outloc %out_val\n"
9301                 "             OpReturn\n"
9302                 "             OpFunctionEnd\n"
9303         ).specialize(parameters);
9304 }
9305
9306 template<typename T>
9307 BufferSp createCompositeBuffer(T number)
9308 {
9309         return BufferSp(new Buffer<T>(vector<T>(1, number)));
9310 }
9311
9312 tcu::TestCaseGroup* createOpCompositeInsertGroup (tcu::TestContext& testCtx)
9313 {
9314         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "opcompositeinsert", "Test the OpCompositeInsert instruction"));
9315         de::Random                                              rnd             (deStringHash(group->getName()));
9316
9317         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
9318         {
9319                 NumberType                                              numberType              = NumberType(type);
9320                 const string                                    typeName                = getNumberTypeName(numberType);
9321                 const string                                    description             = "Test the OpCompositeInsert instruction with " + typeName + "s";
9322                 de::MovePtr<tcu::TestCaseGroup> subGroup                (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
9323                 vector<map<string, string> >    testCases;
9324
9325                 createCompositeCases(testCases, rnd, numberType);
9326
9327                 for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
9328                 {
9329                         ComputeShaderSpec       spec;
9330
9331                         spec.assembly = specializeCompositeInsertShaderTemplate(numberType, *test);
9332
9333                         switch (numberType)
9334                         {
9335                                 case NUMBERTYPE_INT32:
9336                                 {
9337                                         deInt32 number = getInt(rnd);
9338                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
9339                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
9340                                         break;
9341                                 }
9342                                 case NUMBERTYPE_UINT32:
9343                                 {
9344                                         deUint32 number = rnd.getUint32();
9345                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
9346                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
9347                                         break;
9348                                 }
9349                                 case NUMBERTYPE_FLOAT32:
9350                                 {
9351                                         float number = rnd.getFloat();
9352                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
9353                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
9354                                         break;
9355                                 }
9356                                 default:
9357                                         DE_ASSERT(false);
9358                         }
9359
9360                         spec.numWorkGroups = IVec3(1, 1, 1);
9361                         subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpCompositeInsert test", spec));
9362                 }
9363                 group->addChild(subGroup.release());
9364         }
9365         return group.release();
9366 }
9367
9368 tcu::TestCaseGroup* createOpCompositeExtractGroup (tcu::TestContext& testCtx)
9369 {
9370         de::MovePtr<tcu::TestCaseGroup> group           (new tcu::TestCaseGroup(testCtx, "opcompositeextract", "Test the OpCompositeExtract instruction"));
9371         ComputeShaderSpec                               spec;
9372         de::Random                                              rnd                     (deStringHash(group->getName()));
9373         const int                                               numElements = 100;
9374         vector<float>                                   input           (4 * numElements, 0);
9375         vector<float>                                   output          (4 * numElements, 0);
9376
9377         fillRandomScalars(rnd, -100.0f, 100.0f, &input[0], 4 * numElements);
9378
9379         for(size_t ndx = 0; ndx < numElements; ++ndx)
9380         {
9381                 output[ndx * 4]         = input[ndx * 4 + 2];
9382                 output[ndx * 4 + 1] = input[ndx * 4 + 1];
9383                 output[ndx * 4 + 2] = input[ndx * 4];
9384                 output[ndx * 4 + 3] = input[ndx * 4 + 3];
9385         }
9386
9387         const string shader (
9388                 "OpCapability Shader\n"
9389                 "OpMemoryModel Logical GLSL450\n"
9390                 "OpEntryPoint GLCompute %main \"main\" %gl_GlobalInvocationID\n"
9391                 "OpExecutionMode %main LocalSize 1 1 1\n"
9392                 "OpSource OpenCL_C 120\n"
9393
9394                 "OpMemberDecorate %struct_4_f32 0 Offset 0\n"
9395                 "OpMemberDecorate %struct_4_f32 1 Offset 4\n"
9396                 "OpMemberDecorate %struct_4_f32 2 Offset 8\n"
9397                 "OpMemberDecorate %struct_4_f32 3 Offset 12\n"
9398                 "OpDecorate %_runtimearr_struct_4_f32 ArrayStride 16\n"
9399                 "OpMemberDecorate %InStruct 0 Offset 0\n"
9400                 "OpDecorate %InStruct BufferBlock\n"
9401                 "OpDecorate %gl_GlobalInvocationID BuiltIn GlobalInvocationId\n"
9402                 "OpDecorate %output DescriptorSet 0\n"
9403                 "OpDecorate %output Binding 1\n"
9404                 "OpDecorate %input DescriptorSet 0\n"
9405                 "OpDecorate %input Binding 0\n"
9406
9407                 "%f32                       = OpTypeFloat 32\n"
9408                 "%struct_4_f32              = OpTypeStruct %f32 %f32 %f32 %f32\n"
9409                 "%_runtimearr_struct_4_f32  = OpTypeRuntimeArray %struct_4_f32\n"
9410                 "%InStruct                  = OpTypeStruct %_runtimearr_struct_4_f32\n"
9411                 "%_ptr_Uniform__InStruct    = OpTypePointer Uniform %InStruct\n"
9412                 "%uint                      = OpTypeInt 32 0\n"
9413                 "%void                      = OpTypeVoid\n"
9414                 "%voidf                     = OpTypeFunction %void\n"
9415                 "%v3uint                    = OpTypeVector %uint 3\n"
9416                 "%_ptr_Input_v3uint         = OpTypePointer Input %v3uint\n"
9417                 "%_ptr_Input_uint           = OpTypePointer Input %uint\n"
9418                 "%_ptr_Uniform_float        = OpTypePointer Uniform %f32\n"
9419                 "%structf                   = OpTypeFunction %struct_4_f32 %struct_4_f32\n"
9420                 "%_ptr_Private_v3uint       = OpTypePointer Private %v3uint\n"
9421                 "%uint_0                    = OpConstant %uint 0\n"
9422                 "%uint_1                    = OpConstant %uint 1\n"
9423                 "%uint_2                    = OpConstant %uint 2\n"
9424                 "%uint_3                    = OpConstant %uint 3\n"
9425                 "%gl_GlobalInvocationID     = OpVariable %_ptr_Input_v3uint Input\n"
9426                 "%output                    = OpVariable %_ptr_Uniform__InStruct Uniform\n"
9427                 "%input                     = OpVariable %_ptr_Uniform__InStruct Uniform\n"
9428
9429                 "%helper                    = OpFunction %struct_4_f32 Const %structf\n"
9430                 "%param_struct              = OpFunctionParameter %struct_4_f32\n"
9431                 "%label1                    = OpLabel\n"
9432
9433                 "%param_a                   = OpCompositeExtract %f32 %param_struct 0\n"
9434                 "%param_b                   = OpCompositeExtract %f32 %param_struct 1\n"
9435                 "%param_c                   = OpCompositeExtract %f32 %param_struct 2\n"
9436                 "%param_d                   = OpCompositeExtract %f32 %param_struct 3\n"
9437
9438                 "%returnVal                 = OpCompositeConstruct %struct_4_f32 %param_c %param_b %param_a %param_d\n"
9439
9440                 "                             OpReturnValue %returnVal\n"
9441                 "                             OpFunctionEnd\n"
9442
9443                 "%main                      = OpFunction %void None %voidf\n"
9444                 "%label2                    = OpLabel\n"
9445
9446                 "%struct_index              = OpAccessChain %_ptr_Input_uint %gl_GlobalInvocationID %uint_0\n"
9447                 "%struct_loc                = OpLoad %uint %struct_index\n"
9448                 "%input_a_loc               = OpAccessChain %_ptr_Uniform_float %input %uint_0 %struct_loc %uint_0\n"
9449                 "%input_a                   = OpLoad %f32 %input_a_loc\n"
9450                 "%input_b_loc               = OpAccessChain %_ptr_Uniform_float %input %uint_0 %struct_loc %uint_1\n"
9451                 "%input_b                   = OpLoad %f32 %input_b_loc\n"
9452                 "%input_c_loc               = OpAccessChain %_ptr_Uniform_float %input %uint_0 %struct_loc %uint_2\n"
9453                 "%input_c                   = OpLoad %f32 %input_c_loc\n"
9454                 "%input_d_loc               = OpAccessChain %_ptr_Uniform_float %input %uint_0 %struct_loc %uint_3\n"
9455                 "%input_d                   = OpLoad %f32 %input_d_loc\n"
9456
9457                 "%input_struct              = OpCompositeConstruct %struct_4_f32 %input_a %input_b %input_c %input_d\n"
9458
9459                 "%output_struct             = OpFunctionCall %struct_4_f32 %helper %input_struct\n"
9460
9461                 "%output_a                  = OpCompositeExtract %f32 %output_struct 0\n"
9462                 "%output_b                  = OpCompositeExtract %f32 %output_struct 1\n"
9463                 "%output_c                  = OpCompositeExtract %f32 %output_struct 2\n"
9464                 "%output_d                  = OpCompositeExtract %f32 %output_struct 3\n"
9465
9466                 "%output_a_loc              = OpAccessChain %_ptr_Uniform_float %output %uint_0 %struct_loc %uint_0\n"
9467                 "                             OpStore %output_a_loc %output_a\n"
9468                 "%output_b_loc              = OpAccessChain %_ptr_Uniform_float %output %uint_0 %struct_loc %uint_1\n"
9469                 "                             OpStore %output_b_loc %output_b\n"
9470                 "%output_c_loc              = OpAccessChain %_ptr_Uniform_float %output %uint_0 %struct_loc %uint_2\n"
9471                 "                             OpStore %output_c_loc %output_c\n"
9472                 "%output_d_loc              = OpAccessChain %_ptr_Uniform_float %output %uint_0 %struct_loc %uint_3\n"
9473                 "                             OpStore %output_d_loc %output_d\n"
9474
9475                 "                             OpReturn\n"
9476                 "                             OpFunctionEnd\n");
9477
9478         spec.inputs.push_back(BufferSp(new Buffer<float>(input)));
9479         spec.outputs.push_back(BufferSp(new Buffer<float>(output)));
9480         spec.assembly = shader;
9481         spec.numWorkGroups = IVec3(numElements, 1, 1);
9482
9483         group->addChild(new SpvAsmComputeShaderCase(testCtx, "basic_test", "OpCompositeExtract test", spec));
9484
9485         return group.release();
9486 }
9487
9488 struct AssemblyStructInfo
9489 {
9490         AssemblyStructInfo (const deUint32 comp, const deUint32 idx)
9491         : components    (comp)
9492         , index                 (idx)
9493         {}
9494
9495         deUint32 components;
9496         deUint32 index;
9497 };
9498
9499 const string specializeInBoundsShaderTemplate (const NumberType type, const AssemblyStructInfo& structInfo, const map<string, string>& params)
9500 {
9501         // Create the full index string
9502         string                          fullIndex       = numberToString(structInfo.index) + " " + params.at("indexes");
9503         // Convert it to list of indexes
9504         vector<string>          indexes         = de::splitString(fullIndex, ' ');
9505
9506         map<string, string>     parameters      (params);
9507         parameters["structType"]        = repeatString(" ${compositeType}", structInfo.components);
9508         parameters["structConstruct"]   = repeatString(" %instance", structInfo.components);
9509         parameters["insertIndexes"]     = fullIndex;
9510
9511         // In matrix cases the last two index is the CompositeExtract indexes
9512         const deUint32 extractIndexes = (parameters["type"] == "matrix") ? 2 : 1;
9513
9514         // Construct the extractIndex
9515         for (vector<string>::const_iterator index = indexes.end() - extractIndexes; index != indexes.end(); ++index)
9516         {
9517                 parameters["extractIndexes"] += " " + *index;
9518         }
9519
9520         // Remove the last 1 or 2 element depends on matrix case or not
9521         indexes.erase(indexes.end() - extractIndexes, indexes.end());
9522
9523         deUint32 id = 0;
9524         // Generate AccessChain index expressions (except for the last one, because we use ptr to the composite)
9525         for (vector<string>::const_iterator index = indexes.begin(); index != indexes.end(); ++index)
9526         {
9527                 string indexId = "%index_" + numberToString(id++);
9528                 parameters["accessChainConstDeclaration"] += indexId + "   = OpConstant %u32 " + *index + "\n";
9529                 parameters["accessChainIndexes"] += " " + indexId;
9530         }
9531
9532         parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
9533
9534         const string customType = getAssemblyTypeName(type);
9535         map<string, string> substCustomType;
9536         substCustomType["customType"] = customType;
9537         parameters["compositeDecl"] = StringTemplate(parameters.at("compositeDecl")).specialize(substCustomType);
9538         parameters["compositeType"] = StringTemplate(parameters.at("compositeType")).specialize(substCustomType);
9539         parameters["compositeConstruct"] = StringTemplate(parameters.at("compositeConstruct")).specialize(substCustomType);
9540         parameters["filler"] = StringTemplate(parameters.at("filler")).specialize(substCustomType);
9541         parameters["customType"] = customType;
9542
9543         const string compositeType = parameters.at("compositeType");
9544         map<string, string> substCompositeType;
9545         substCompositeType["compositeType"] = compositeType;
9546         parameters["structType"] = StringTemplate(parameters.at("structType")).specialize(substCompositeType);
9547         if (compositeType != "%u32vec3")
9548         {
9549                 parameters["u32vec3Decl"] = "%u32vec3   = OpTypeVector %u32 3\n";
9550         }
9551
9552         return StringTemplate(
9553                 "OpCapability Shader\n"
9554                 "OpCapability Matrix\n"
9555                 "OpMemoryModel Logical GLSL450\n"
9556                 "OpEntryPoint GLCompute %main \"main\" %id\n"
9557                 "OpExecutionMode %main LocalSize 1 1 1\n"
9558
9559                 "OpSource GLSL 430\n"
9560                 "OpName %main           \"main\"\n"
9561                 "OpName %id             \"gl_GlobalInvocationID\"\n"
9562                 // Decorators
9563                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
9564                 "OpDecorate %buf BufferBlock\n"
9565                 "OpDecorate %indata DescriptorSet 0\n"
9566                 "OpDecorate %indata Binding 0\n"
9567                 "OpDecorate %outdata DescriptorSet 0\n"
9568                 "OpDecorate %outdata Binding 1\n"
9569                 "OpDecorate %customarr ArrayStride 4\n"
9570                 "${compositeDecorator}"
9571                 "OpMemberDecorate %buf 0 Offset 0\n"
9572                 // General types
9573                 "%void      = OpTypeVoid\n"
9574                 "%voidf     = OpTypeFunction %void\n"
9575                 "%i32       = OpTypeInt 32 1\n"
9576                 "%u32       = OpTypeInt 32 0\n"
9577                 "%f32       = OpTypeFloat 32\n"
9578                 // Custom types
9579                 "${compositeDecl}"
9580                 // %u32vec3 if not already declared in ${compositeDecl}
9581                 "${u32vec3Decl:opt}"
9582                 "%uvec3ptr  = OpTypePointer Input %u32vec3\n"
9583                 // Inherited from composite
9584                 "%composite_p = OpTypePointer Function ${compositeType}\n"
9585                 "%struct_t  = OpTypeStruct${structType}\n"
9586                 "%struct_p  = OpTypePointer Function %struct_t\n"
9587                 // Constants
9588                 "${filler}"
9589                 "${accessChainConstDeclaration}"
9590                 // Inherited from custom
9591                 "%customptr = OpTypePointer Uniform ${customType}\n"
9592                 "%customarr = OpTypeRuntimeArray ${customType}\n"
9593                 "%buf       = OpTypeStruct %customarr\n"
9594                 "%bufptr    = OpTypePointer Uniform %buf\n"
9595                 "%indata    = OpVariable %bufptr Uniform\n"
9596                 "%outdata   = OpVariable %bufptr Uniform\n"
9597
9598                 "%id        = OpVariable %uvec3ptr Input\n"
9599                 "%zero      = OpConstant %u32 0\n"
9600                 "%main      = OpFunction %void None %voidf\n"
9601                 "%label     = OpLabel\n"
9602                 "%struct_v  = OpVariable %struct_p Function\n"
9603                 "%idval     = OpLoad %u32vec3 %id\n"
9604                 "%x         = OpCompositeExtract %u32 %idval 0\n"
9605                 // Create the input/output type
9606                 "%inloc     = OpInBoundsAccessChain %customptr %indata %zero %x\n"
9607                 "%outloc    = OpInBoundsAccessChain %customptr %outdata %zero %x\n"
9608                 // Read the input value
9609                 "%inval     = OpLoad ${customType} %inloc\n"
9610                 // Create the composite and fill it
9611                 "${compositeConstruct}"
9612                 // Create the struct and fill it with the composite
9613                 "%struct    = OpCompositeConstruct %struct_t${structConstruct}\n"
9614                 // Insert the value
9615                 "%comp_obj  = OpCompositeInsert %struct_t %inval %struct ${insertIndexes}\n"
9616                 // Store the object
9617                 "             OpStore %struct_v %comp_obj\n"
9618                 // Get deepest possible composite pointer
9619                 "%inner_ptr = OpInBoundsAccessChain %composite_p %struct_v${accessChainIndexes}\n"
9620                 "%read_obj  = OpLoad ${compositeType} %inner_ptr\n"
9621                 // Read back the stored value
9622                 "%read_val  = OpCompositeExtract ${customType} %read_obj${extractIndexes}\n"
9623                 "             OpStore %outloc %read_val\n"
9624                 "             OpReturn\n"
9625                 "             OpFunctionEnd\n"
9626         ).specialize(parameters);
9627 }
9628
9629 tcu::TestCaseGroup* createOpInBoundsAccessChainGroup (tcu::TestContext& testCtx)
9630 {
9631         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opinboundsaccesschain", "Test the OpInBoundsAccessChain instruction"));
9632         de::Random                                              rnd                             (deStringHash(group->getName()));
9633
9634         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
9635         {
9636                 NumberType                                              numberType      = NumberType(type);
9637                 const string                                    typeName        = getNumberTypeName(numberType);
9638                 const string                                    description     = "Test the OpInBoundsAccessChain instruction with " + typeName + "s";
9639                 de::MovePtr<tcu::TestCaseGroup> subGroup        (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
9640
9641                 vector<map<string, string> >    testCases;
9642                 createCompositeCases(testCases, rnd, numberType);
9643
9644                 for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
9645                 {
9646                         ComputeShaderSpec       spec;
9647
9648                         // Number of components inside of a struct
9649                         deUint32 structComponents = rnd.getInt(2, 8);
9650                         // Component index value
9651                         deUint32 structIndex = rnd.getInt(0, structComponents - 1);
9652                         AssemblyStructInfo structInfo(structComponents, structIndex);
9653
9654                         spec.assembly = specializeInBoundsShaderTemplate(numberType, structInfo, *test);
9655
9656                         switch (numberType)
9657                         {
9658                                 case NUMBERTYPE_INT32:
9659                                 {
9660                                         deInt32 number = getInt(rnd);
9661                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
9662                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
9663                                         break;
9664                                 }
9665                                 case NUMBERTYPE_UINT32:
9666                                 {
9667                                         deUint32 number = rnd.getUint32();
9668                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
9669                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
9670                                         break;
9671                                 }
9672                                 case NUMBERTYPE_FLOAT32:
9673                                 {
9674                                         float number = rnd.getFloat();
9675                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
9676                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
9677                                         break;
9678                                 }
9679                                 default:
9680                                         DE_ASSERT(false);
9681                         }
9682                         spec.numWorkGroups = IVec3(1, 1, 1);
9683                         subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpInBoundsAccessChain test", spec));
9684                 }
9685                 group->addChild(subGroup.release());
9686         }
9687         return group.release();
9688 }
9689
9690 // If the params missing, uninitialized case
9691 const string specializeDefaultOutputShaderTemplate (const NumberType type, const map<string, string>& params = map<string, string>())
9692 {
9693         map<string, string> parameters(params);
9694
9695         parameters["customType"]        = getAssemblyTypeName(type);
9696
9697         // Declare the const value, and use it in the initializer
9698         if (params.find("constValue") != params.end())
9699         {
9700                 parameters["variableInitializer"]       = " %const";
9701         }
9702         // Uninitialized case
9703         else
9704         {
9705                 parameters["commentDecl"]       = ";";
9706         }
9707
9708         return StringTemplate(
9709                 "OpCapability Shader\n"
9710                 "OpMemoryModel Logical GLSL450\n"
9711                 "OpEntryPoint GLCompute %main \"main\" %id\n"
9712                 "OpExecutionMode %main LocalSize 1 1 1\n"
9713                 "OpSource GLSL 430\n"
9714                 "OpName %main           \"main\"\n"
9715                 "OpName %id             \"gl_GlobalInvocationID\"\n"
9716                 // Decorators
9717                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
9718                 "OpDecorate %indata DescriptorSet 0\n"
9719                 "OpDecorate %indata Binding 0\n"
9720                 "OpDecorate %outdata DescriptorSet 0\n"
9721                 "OpDecorate %outdata Binding 1\n"
9722                 "OpDecorate %in_arr ArrayStride 4\n"
9723                 "OpDecorate %in_buf BufferBlock\n"
9724                 "OpMemberDecorate %in_buf 0 Offset 0\n"
9725                 // Base types
9726                 "%void       = OpTypeVoid\n"
9727                 "%voidf      = OpTypeFunction %void\n"
9728                 "%u32        = OpTypeInt 32 0\n"
9729                 "%i32        = OpTypeInt 32 1\n"
9730                 "%f32        = OpTypeFloat 32\n"
9731                 "%uvec3      = OpTypeVector %u32 3\n"
9732                 "%uvec3ptr   = OpTypePointer Input %uvec3\n"
9733                 "${commentDecl:opt}%const      = OpConstant ${customType} ${constValue:opt}\n"
9734                 // Derived types
9735                 "%in_ptr     = OpTypePointer Uniform ${customType}\n"
9736                 "%in_arr     = OpTypeRuntimeArray ${customType}\n"
9737                 "%in_buf     = OpTypeStruct %in_arr\n"
9738                 "%in_bufptr  = OpTypePointer Uniform %in_buf\n"
9739                 "%indata     = OpVariable %in_bufptr Uniform\n"
9740                 "%outdata    = OpVariable %in_bufptr Uniform\n"
9741                 "%id         = OpVariable %uvec3ptr Input\n"
9742                 "%var_ptr    = OpTypePointer Function ${customType}\n"
9743                 // Constants
9744                 "%zero       = OpConstant %i32 0\n"
9745                 // Main function
9746                 "%main       = OpFunction %void None %voidf\n"
9747                 "%label      = OpLabel\n"
9748                 "%out_var    = OpVariable %var_ptr Function${variableInitializer:opt}\n"
9749                 "%idval      = OpLoad %uvec3 %id\n"
9750                 "%x          = OpCompositeExtract %u32 %idval 0\n"
9751                 "%inloc      = OpAccessChain %in_ptr %indata %zero %x\n"
9752                 "%outloc     = OpAccessChain %in_ptr %outdata %zero %x\n"
9753
9754                 "%outval     = OpLoad ${customType} %out_var\n"
9755                 "              OpStore %outloc %outval\n"
9756                 "              OpReturn\n"
9757                 "              OpFunctionEnd\n"
9758         ).specialize(parameters);
9759 }
9760
9761 bool compareFloats (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
9762 {
9763         DE_ASSERT(outputAllocs.size() != 0);
9764         DE_ASSERT(outputAllocs.size() == expectedOutputs.size());
9765
9766         // Use custom epsilon because of the float->string conversion
9767         const float     epsilon = 0.00001f;
9768
9769         for (size_t outputNdx = 0; outputNdx < outputAllocs.size(); ++outputNdx)
9770         {
9771                 vector<deUint8> expectedBytes;
9772                 float                   expected;
9773                 float                   actual;
9774
9775                 expectedOutputs[outputNdx].getBytes(expectedBytes);
9776                 memcpy(&expected, &expectedBytes.front(), expectedBytes.size());
9777                 memcpy(&actual, outputAllocs[outputNdx]->getHostPtr(), expectedBytes.size());
9778
9779                 // Test with epsilon
9780                 if (fabs(expected - actual) > epsilon)
9781                 {
9782                         log << TestLog::Message << "Error: The actual and expected values not matching."
9783                                 << " Expected: " << expected << " Actual: " << actual << " Epsilon: " << epsilon << TestLog::EndMessage;
9784                         return false;
9785                 }
9786         }
9787         return true;
9788 }
9789
9790 // Checks if the driver crash with uninitialized cases
9791 bool passthruVerify (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
9792 {
9793         DE_ASSERT(outputAllocs.size() != 0);
9794         DE_ASSERT(outputAllocs.size() == expectedOutputs.size());
9795
9796         // Copy and discard the result.
9797         for (size_t outputNdx = 0; outputNdx < outputAllocs.size(); ++outputNdx)
9798         {
9799                 vector<deUint8> expectedBytes;
9800                 expectedOutputs[outputNdx].getBytes(expectedBytes);
9801
9802                 const size_t    width                   = expectedBytes.size();
9803                 vector<char>    data                    (width);
9804
9805                 memcpy(&data[0], outputAllocs[outputNdx]->getHostPtr(), width);
9806         }
9807         return true;
9808 }
9809
9810 tcu::TestCaseGroup* createShaderDefaultOutputGroup (tcu::TestContext& testCtx)
9811 {
9812         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "shader_default_output", "Test shader default output."));
9813         de::Random                                              rnd             (deStringHash(group->getName()));
9814
9815         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
9816         {
9817                 NumberType                                              numberType      = NumberType(type);
9818                 const string                                    typeName        = getNumberTypeName(numberType);
9819                 const string                                    description     = "Test the OpVariable initializer with " + typeName + ".";
9820                 de::MovePtr<tcu::TestCaseGroup> subGroup        (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
9821
9822                 // 2 similar subcases (initialized and uninitialized)
9823                 for (int subCase = 0; subCase < 2; ++subCase)
9824                 {
9825                         ComputeShaderSpec spec;
9826                         spec.numWorkGroups = IVec3(1, 1, 1);
9827
9828                         map<string, string>                             params;
9829
9830                         switch (numberType)
9831                         {
9832                                 case NUMBERTYPE_INT32:
9833                                 {
9834                                         deInt32 number = getInt(rnd);
9835                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
9836                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
9837                                         params["constValue"] = numberToString(number);
9838                                         break;
9839                                 }
9840                                 case NUMBERTYPE_UINT32:
9841                                 {
9842                                         deUint32 number = rnd.getUint32();
9843                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
9844                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
9845                                         params["constValue"] = numberToString(number);
9846                                         break;
9847                                 }
9848                                 case NUMBERTYPE_FLOAT32:
9849                                 {
9850                                         float number = rnd.getFloat();
9851                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
9852                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
9853                                         spec.verifyIO = &compareFloats;
9854                                         params["constValue"] = numberToString(number);
9855                                         break;
9856                                 }
9857                                 default:
9858                                         DE_ASSERT(false);
9859                         }
9860
9861                         // Initialized subcase
9862                         if (!subCase)
9863                         {
9864                                 spec.assembly = specializeDefaultOutputShaderTemplate(numberType, params);
9865                                 subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "initialized", "OpVariable initializer tests.", spec));
9866                         }
9867                         // Uninitialized subcase
9868                         else
9869                         {
9870                                 spec.assembly = specializeDefaultOutputShaderTemplate(numberType);
9871                                 spec.verifyIO = &passthruVerify;
9872                                 subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "uninitialized", "OpVariable initializer tests.", spec));
9873                         }
9874                 }
9875                 group->addChild(subGroup.release());
9876         }
9877         return group.release();
9878 }
9879
9880 tcu::TestCaseGroup* createOpNopTests (tcu::TestContext& testCtx)
9881 {
9882         de::MovePtr<tcu::TestCaseGroup> testGroup (new tcu::TestCaseGroup(testCtx, "opnop", "Test OpNop"));
9883         RGBA                                                    defaultColors[4];
9884         map<string, string>                             opNopFragments;
9885
9886         getDefaultColors(defaultColors);
9887
9888         opNopFragments["testfun"]               =
9889                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9890                 "%param1 = OpFunctionParameter %v4f32\n"
9891                 "%label_testfun = OpLabel\n"
9892                 "OpNop\n"
9893                 "OpNop\n"
9894                 "OpNop\n"
9895                 "OpNop\n"
9896                 "OpNop\n"
9897                 "OpNop\n"
9898                 "OpNop\n"
9899                 "OpNop\n"
9900                 "%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
9901                 "%b = OpFAdd %f32 %a %a\n"
9902                 "OpNop\n"
9903                 "%c = OpFSub %f32 %b %a\n"
9904                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
9905                 "OpNop\n"
9906                 "OpNop\n"
9907                 "OpReturnValue %ret\n"
9908                 "OpFunctionEnd\n";
9909
9910         createTestsForAllStages("opnop", defaultColors, defaultColors, opNopFragments, testGroup.get());
9911
9912         return testGroup.release();
9913 }
9914
9915 tcu::TestCaseGroup* createOpNameTests (tcu::TestContext& testCtx)
9916 {
9917         de::MovePtr<tcu::TestCaseGroup> testGroup       (new tcu::TestCaseGroup(testCtx, "opname","Test OpName"));
9918         RGBA                                                    defaultColors[4];
9919         map<string, string>                             opNameFragments;
9920
9921         getDefaultColors(defaultColors);
9922
9923         opNameFragments["testfun"] =
9924                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9925                 "%param1     = OpFunctionParameter %v4f32\n"
9926                 "%label_func = OpLabel\n"
9927                 "%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
9928                 "%b          = OpFAdd %f32 %a %a\n"
9929                 "%c          = OpFSub %f32 %b %a\n"
9930                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
9931                 "OpReturnValue %ret\n"
9932                 "OpFunctionEnd\n";
9933
9934         opNameFragments["debug"] =
9935                 "OpName %BP_main \"not_main\"";
9936
9937         createTestsForAllStages("opname", defaultColors, defaultColors, opNameFragments, testGroup.get());
9938
9939         return testGroup.release();
9940 }
9941
9942 tcu::TestCaseGroup* createOpNameAbuseTests (tcu::TestContext& testCtx)
9943 {
9944         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "opname_abuse", "OpName abuse tests"));
9945         vector<CaseParameter>                   abuseCases;
9946         RGBA                                                    defaultColors[4];
9947         map<string, string>                             opNameFragments;
9948
9949         getOpNameAbuseCases(abuseCases);
9950         getDefaultColors(defaultColors);
9951
9952         opNameFragments["testfun"] =
9953                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9954                 "%param1     = OpFunctionParameter %v4f32\n"
9955                 "%label_func = OpLabel\n"
9956                 "%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
9957                 "%b          = OpFAdd %f32 %a %a\n"
9958                 "%c          = OpFSub %f32 %b %a\n"
9959                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
9960                 "OpReturnValue %ret\n"
9961                 "OpFunctionEnd\n";
9962
9963         for (unsigned int i = 0; i < abuseCases.size(); i++)
9964         {
9965                 string casename;
9966                 casename = string("main") + abuseCases[i].name;
9967
9968                 opNameFragments["debug"] =
9969                         "OpName %BP_main \"" + abuseCases[i].param + "\"";
9970
9971                 createTestsForAllStages(casename, defaultColors, defaultColors, opNameFragments, abuseGroup.get());
9972         }
9973
9974         for (unsigned int i = 0; i < abuseCases.size(); i++)
9975         {
9976                 string casename;
9977                 casename = string("b") + abuseCases[i].name;
9978
9979                 opNameFragments["debug"] =
9980                         "OpName %b \"" + abuseCases[i].param + "\"";
9981
9982                 createTestsForAllStages(casename, defaultColors, defaultColors, opNameFragments, abuseGroup.get());
9983         }
9984
9985         {
9986                 opNameFragments["debug"] =
9987                         "OpName %test_code \"name1\"\n"
9988                         "OpName %param1    \"name2\"\n"
9989                         "OpName %a         \"name3\"\n"
9990                         "OpName %b         \"name4\"\n"
9991                         "OpName %c         \"name5\"\n"
9992                         "OpName %ret       \"name6\"\n";
9993
9994                 createTestsForAllStages("everything_named", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
9995         }
9996
9997         {
9998                 opNameFragments["debug"] =
9999                         "OpName %test_code \"the_same\"\n"
10000                         "OpName %param1    \"the_same\"\n"
10001                         "OpName %a         \"the_same\"\n"
10002                         "OpName %b         \"the_same\"\n"
10003                         "OpName %c         \"the_same\"\n"
10004                         "OpName %ret       \"the_same\"\n";
10005
10006                 createTestsForAllStages("everything_named_the_same", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
10007         }
10008
10009         {
10010                 opNameFragments["debug"] =
10011                         "OpName %BP_main \"to_be\"\n"
10012                         "OpName %BP_main \"or_not\"\n"
10013                         "OpName %BP_main \"to_be\"\n";
10014
10015                 createTestsForAllStages("main_has_multiple_names", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
10016         }
10017
10018         {
10019                 opNameFragments["debug"] =
10020                         "OpName %b \"to_be\"\n"
10021                         "OpName %b \"or_not\"\n"
10022                         "OpName %b \"to_be\"\n";
10023
10024                 createTestsForAllStages("b_has_multiple_names", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
10025         }
10026
10027         return abuseGroup.release();
10028 }
10029
10030
10031 tcu::TestCaseGroup* createOpMemberNameAbuseTests (tcu::TestContext& testCtx)
10032 {
10033         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "opmembername_abuse", "OpName abuse tests"));
10034         vector<CaseParameter>                   abuseCases;
10035         RGBA                                                    defaultColors[4];
10036         map<string, string>                             opMemberNameFragments;
10037
10038         getOpNameAbuseCases(abuseCases);
10039         getDefaultColors(defaultColors);
10040
10041         opMemberNameFragments["pre_main"] =
10042                 "%f3str = OpTypeStruct %f32 %f32 %f32\n";
10043
10044         opMemberNameFragments["testfun"] =
10045                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10046                 "%param1     = OpFunctionParameter %v4f32\n"
10047                 "%label_func = OpLabel\n"
10048                 "%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
10049                 "%b          = OpFAdd %f32 %a %a\n"
10050                 "%c          = OpFSub %f32 %b %a\n"
10051                 "%cstr       = OpCompositeConstruct %f3str %c %c %c\n"
10052                 "%d          = OpCompositeExtract %f32 %cstr 0\n"
10053                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %d %c_i32_0\n"
10054                 "OpReturnValue %ret\n"
10055                 "OpFunctionEnd\n";
10056
10057         for (unsigned int i = 0; i < abuseCases.size(); i++)
10058         {
10059                 string casename;
10060                 casename = string("f3str_x") + abuseCases[i].name;
10061
10062                 opMemberNameFragments["debug"] =
10063                         "OpMemberName %f3str 0 \"" + abuseCases[i].param + "\"";
10064
10065                 createTestsForAllStages(casename, defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
10066         }
10067
10068         {
10069                 opMemberNameFragments["debug"] =
10070                         "OpMemberName %f3str 0 \"name1\"\n"
10071                         "OpMemberName %f3str 1 \"name2\"\n"
10072                         "OpMemberName %f3str 2 \"name3\"\n";
10073
10074                 createTestsForAllStages("everything_named", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
10075         }
10076
10077         {
10078                 opMemberNameFragments["debug"] =
10079                         "OpMemberName %f3str 0 \"the_same\"\n"
10080                         "OpMemberName %f3str 1 \"the_same\"\n"
10081                         "OpMemberName %f3str 2 \"the_same\"\n";
10082
10083                 createTestsForAllStages("everything_named_the_same", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
10084         }
10085
10086         {
10087                 opMemberNameFragments["debug"] =
10088                         "OpMemberName %f3str 0 \"to_be\"\n"
10089                         "OpMemberName %f3str 1 \"or_not\"\n"
10090                         "OpMemberName %f3str 0 \"to_be\"\n"
10091                         "OpMemberName %f3str 2 \"makes_no\"\n"
10092                         "OpMemberName %f3str 0 \"difference\"\n"
10093                         "OpMemberName %f3str 0 \"to_me\"\n";
10094
10095
10096                 createTestsForAllStages("f3str_x_has_multiple_names", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
10097         }
10098
10099         return abuseGroup.release();
10100 }
10101
10102 tcu::TestCaseGroup* createInstructionTests (tcu::TestContext& testCtx)
10103 {
10104         const bool testComputePipeline = true;
10105
10106         de::MovePtr<tcu::TestCaseGroup> instructionTests        (new tcu::TestCaseGroup(testCtx, "instruction", "Instructions with special opcodes/operands"));
10107         de::MovePtr<tcu::TestCaseGroup> computeTests            (new tcu::TestCaseGroup(testCtx, "compute", "Compute Instructions with special opcodes/operands"));
10108         de::MovePtr<tcu::TestCaseGroup> graphicsTests           (new tcu::TestCaseGroup(testCtx, "graphics", "Graphics Instructions with special opcodes/operands"));
10109
10110         computeTests->addChild(createSpivVersionCheckTests(testCtx, testComputePipeline));
10111         computeTests->addChild(createLocalSizeGroup(testCtx));
10112         computeTests->addChild(createOpNopGroup(testCtx));
10113         computeTests->addChild(createOpFUnordGroup(testCtx));
10114         computeTests->addChild(createOpAtomicGroup(testCtx, false));
10115         computeTests->addChild(createOpAtomicGroup(testCtx, true));                                     // Using new StorageBuffer decoration
10116         computeTests->addChild(createOpAtomicGroup(testCtx, false, 1024, true));        // Return value validation
10117         computeTests->addChild(createOpLineGroup(testCtx));
10118         computeTests->addChild(createOpModuleProcessedGroup(testCtx));
10119         computeTests->addChild(createOpNoLineGroup(testCtx));
10120         computeTests->addChild(createOpConstantNullGroup(testCtx));
10121         computeTests->addChild(createOpConstantCompositeGroup(testCtx));
10122         computeTests->addChild(createOpConstantUsageGroup(testCtx));
10123         computeTests->addChild(createSpecConstantGroup(testCtx));
10124         computeTests->addChild(createOpSourceGroup(testCtx));
10125         computeTests->addChild(createOpSourceExtensionGroup(testCtx));
10126         computeTests->addChild(createDecorationGroupGroup(testCtx));
10127         computeTests->addChild(createOpPhiGroup(testCtx));
10128         computeTests->addChild(createLoopControlGroup(testCtx));
10129         computeTests->addChild(createFunctionControlGroup(testCtx));
10130         computeTests->addChild(createSelectionControlGroup(testCtx));
10131         computeTests->addChild(createBlockOrderGroup(testCtx));
10132         computeTests->addChild(createMultipleShaderGroup(testCtx));
10133         computeTests->addChild(createMemoryAccessGroup(testCtx));
10134         computeTests->addChild(createOpCopyMemoryGroup(testCtx));
10135         computeTests->addChild(createOpCopyObjectGroup(testCtx));
10136         computeTests->addChild(createNoContractionGroup(testCtx));
10137         computeTests->addChild(createOpUndefGroup(testCtx));
10138         computeTests->addChild(createOpUnreachableGroup(testCtx));
10139         computeTests->addChild(createOpQuantizeToF16Group(testCtx));
10140         computeTests->addChild(createOpFRemGroup(testCtx));
10141         computeTests->addChild(createOpSRemComputeGroup(testCtx, QP_TEST_RESULT_PASS));
10142         computeTests->addChild(createOpSRemComputeGroup64(testCtx, QP_TEST_RESULT_PASS));
10143         computeTests->addChild(createOpSModComputeGroup(testCtx, QP_TEST_RESULT_PASS));
10144         computeTests->addChild(createOpSModComputeGroup64(testCtx, QP_TEST_RESULT_PASS));
10145         computeTests->addChild(createConvertComputeTests(testCtx, "OpSConvert", "sconvert"));
10146         computeTests->addChild(createConvertComputeTests(testCtx, "OpUConvert", "uconvert"));
10147         computeTests->addChild(createConvertComputeTests(testCtx, "OpFConvert", "fconvert"));
10148         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertSToF", "convertstof"));
10149         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertFToS", "convertftos"));
10150         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertUToF", "convertutof"));
10151         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertFToU", "convertftou"));
10152         computeTests->addChild(createOpCompositeInsertGroup(testCtx));
10153         computeTests->addChild(createOpCompositeExtractGroup(testCtx));
10154         computeTests->addChild(createOpInBoundsAccessChainGroup(testCtx));
10155         computeTests->addChild(createShaderDefaultOutputGroup(testCtx));
10156         computeTests->addChild(createOpNMinGroup(testCtx));
10157         computeTests->addChild(createOpNMaxGroup(testCtx));
10158         computeTests->addChild(createOpNClampGroup(testCtx));
10159         {
10160                 de::MovePtr<tcu::TestCaseGroup> computeAndroidTests     (new tcu::TestCaseGroup(testCtx, "android", "Android CTS Tests"));
10161
10162                 computeAndroidTests->addChild(createOpSRemComputeGroup(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
10163                 computeAndroidTests->addChild(createOpSModComputeGroup(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
10164
10165                 computeTests->addChild(computeAndroidTests.release());
10166         }
10167
10168         computeTests->addChild(create8BitStorageComputeGroup(testCtx));
10169         computeTests->addChild(create16BitStorageComputeGroup(testCtx));
10170         computeTests->addChild(createUboMatrixPaddingComputeGroup(testCtx));
10171         computeTests->addChild(createVariableInitComputeGroup(testCtx));
10172         computeTests->addChild(createConditionalBranchComputeGroup(testCtx));
10173         computeTests->addChild(createIndexingComputeGroup(testCtx));
10174         computeTests->addChild(createVariablePointersComputeGroup(testCtx));
10175         computeTests->addChild(createImageSamplerComputeGroup(testCtx));
10176         computeTests->addChild(createOpNameGroup(testCtx));
10177         computeTests->addChild(createOpMemberNameGroup(testCtx));
10178         computeTests->addChild(createPointerParameterComputeGroup(testCtx));
10179         graphicsTests->addChild(createCrossStageInterfaceTests(testCtx));
10180         graphicsTests->addChild(createSpivVersionCheckTests(testCtx, !testComputePipeline));
10181         graphicsTests->addChild(createOpNopTests(testCtx));
10182         graphicsTests->addChild(createOpSourceTests(testCtx));
10183         graphicsTests->addChild(createOpSourceContinuedTests(testCtx));
10184         graphicsTests->addChild(createOpModuleProcessedTests(testCtx));
10185         graphicsTests->addChild(createOpLineTests(testCtx));
10186         graphicsTests->addChild(createOpNoLineTests(testCtx));
10187         graphicsTests->addChild(createOpConstantNullTests(testCtx));
10188         graphicsTests->addChild(createOpConstantCompositeTests(testCtx));
10189         graphicsTests->addChild(createMemoryAccessTests(testCtx));
10190         graphicsTests->addChild(createOpUndefTests(testCtx));
10191         graphicsTests->addChild(createSelectionBlockOrderTests(testCtx));
10192         graphicsTests->addChild(createModuleTests(testCtx));
10193         graphicsTests->addChild(createSwitchBlockOrderTests(testCtx));
10194         graphicsTests->addChild(createOpPhiTests(testCtx));
10195         graphicsTests->addChild(createNoContractionTests(testCtx));
10196         graphicsTests->addChild(createOpQuantizeTests(testCtx));
10197         graphicsTests->addChild(createLoopTests(testCtx));
10198         graphicsTests->addChild(createSpecConstantTests(testCtx));
10199         graphicsTests->addChild(createSpecConstantOpQuantizeToF16Group(testCtx));
10200         graphicsTests->addChild(createBarrierTests(testCtx));
10201         graphicsTests->addChild(createDecorationGroupTests(testCtx));
10202         graphicsTests->addChild(createFRemTests(testCtx));
10203         graphicsTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
10204         graphicsTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
10205
10206         {
10207                 de::MovePtr<tcu::TestCaseGroup> graphicsAndroidTests    (new tcu::TestCaseGroup(testCtx, "android", "Android CTS Tests"));
10208
10209                 graphicsAndroidTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
10210                 graphicsAndroidTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
10211
10212                 graphicsTests->addChild(graphicsAndroidTests.release());
10213         }
10214         graphicsTests->addChild(createOpNameTests(testCtx));
10215         graphicsTests->addChild(createOpNameAbuseTests(testCtx));
10216         graphicsTests->addChild(createOpMemberNameAbuseTests(testCtx));
10217
10218         graphicsTests->addChild(create8BitStorageGraphicsGroup(testCtx));
10219         graphicsTests->addChild(create16BitStorageGraphicsGroup(testCtx));
10220         graphicsTests->addChild(createUboMatrixPaddingGraphicsGroup(testCtx));
10221         graphicsTests->addChild(createVariableInitGraphicsGroup(testCtx));
10222         graphicsTests->addChild(createConditionalBranchGraphicsGroup(testCtx));
10223         graphicsTests->addChild(createIndexingGraphicsGroup(testCtx));
10224         graphicsTests->addChild(createVariablePointersGraphicsGroup(testCtx));
10225         graphicsTests->addChild(createImageSamplerGraphicsGroup(testCtx));
10226         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpSConvert", "sconvert"));
10227         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpUConvert", "uconvert"));
10228         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpFConvert", "fconvert"));
10229         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertSToF", "convertstof"));
10230         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertFToS", "convertftos"));
10231         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertUToF", "convertutof"));
10232         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertFToU", "convertftou"));
10233         graphicsTests->addChild(createPointerParameterGraphicsGroup(testCtx));
10234
10235         instructionTests->addChild(computeTests.release());
10236         instructionTests->addChild(graphicsTests.release());
10237
10238         return instructionTests.release();
10239 }
10240
10241 } // SpirVAssembly
10242 } // vkt