Merge vk-gl-cts/vulkan-cts-1.1.0 into vk-gl-cts/vulkan-cts-1.1.1
[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 "vktSpvAsm8bitStorageTests.hpp"
53 #include "vktSpvAsm16bitStorageTests.hpp"
54 #include "vktSpvAsmUboMatrixPaddingTests.hpp"
55 #include "vktSpvAsmConditionalBranchTests.hpp"
56 #include "vktSpvAsmIndexingTests.hpp"
57 #include "vktSpvAsmImageSamplerTests.hpp"
58 #include "vktSpvAsmComputeShaderCase.hpp"
59 #include "vktSpvAsmComputeShaderTestUtil.hpp"
60 #include "vktSpvAsmGraphicsShaderTestUtil.hpp"
61 #include "vktSpvAsmVariablePointersTests.hpp"
62 #include "vktSpvAsmSpirvVersionTests.hpp"
63 #include "vktTestCaseUtil.hpp"
64 #include "vktSpvAsmLoopDepLenTests.hpp"
65 #include "vktSpvAsmLoopDepInfTests.hpp"
66
67 #include <cmath>
68 #include <limits>
69 #include <map>
70 #include <string>
71 #include <sstream>
72 #include <utility>
73 #include <stack>
74
75 namespace vkt
76 {
77 namespace SpirVAssembly
78 {
79
80 namespace
81 {
82
83 using namespace vk;
84 using std::map;
85 using std::string;
86 using std::vector;
87 using tcu::IVec3;
88 using tcu::IVec4;
89 using tcu::RGBA;
90 using tcu::TestLog;
91 using tcu::TestStatus;
92 using tcu::Vec4;
93 using de::UniquePtr;
94 using tcu::StringTemplate;
95 using tcu::Vec4;
96
97 template<typename T>
98 static void fillRandomScalars (de::Random& rnd, T minValue, T maxValue, void* dst, int numValues, int offset = 0)
99 {
100         T* const typedPtr = (T*)dst;
101         for (int ndx = 0; ndx < numValues; ndx++)
102                 typedPtr[offset + ndx] = randomScalar<T>(rnd, minValue, maxValue);
103 }
104
105 // Filter is a function that returns true if a value should pass, false otherwise.
106 template<typename T, typename FilterT>
107 static void fillRandomScalars (de::Random& rnd, T minValue, T maxValue, void* dst, int numValues, FilterT filter, int offset = 0)
108 {
109         T* const typedPtr = (T*)dst;
110         T value;
111         for (int ndx = 0; ndx < numValues; ndx++)
112         {
113                 do
114                         value = randomScalar<T>(rnd, minValue, maxValue);
115                 while (!filter(value));
116
117                 typedPtr[offset + ndx] = value;
118         }
119 }
120
121 // Gets a 64-bit integer with a more logarithmic distribution
122 deInt64 randomInt64LogDistributed (de::Random& rnd)
123 {
124         deInt64 val = rnd.getUint64();
125         val &= (1ull << rnd.getInt(1, 63)) - 1;
126         if (rnd.getBool())
127                 val = -val;
128         return val;
129 }
130
131 static void fillRandomInt64sLogDistributed (de::Random& rnd, vector<deInt64>& dst, int numValues)
132 {
133         for (int ndx = 0; ndx < numValues; ndx++)
134                 dst[ndx] = randomInt64LogDistributed(rnd);
135 }
136
137 template<typename FilterT>
138 static void fillRandomInt64sLogDistributed (de::Random& rnd, vector<deInt64>& dst, int numValues, FilterT filter)
139 {
140         for (int ndx = 0; ndx < numValues; ndx++)
141         {
142                 deInt64 value;
143                 do {
144                         value = randomInt64LogDistributed(rnd);
145                 } while (!filter(value));
146                 dst[ndx] = value;
147         }
148 }
149
150 inline bool filterNonNegative (const deInt64 value)
151 {
152         return value >= 0;
153 }
154
155 inline bool filterPositive (const deInt64 value)
156 {
157         return value > 0;
158 }
159
160 inline bool filterNotZero (const deInt64 value)
161 {
162         return value != 0;
163 }
164
165 static void floorAll (vector<float>& values)
166 {
167         for (size_t i = 0; i < values.size(); i++)
168                 values[i] = deFloatFloor(values[i]);
169 }
170
171 static void floorAll (vector<Vec4>& values)
172 {
173         for (size_t i = 0; i < values.size(); i++)
174                 values[i] = floor(values[i]);
175 }
176
177 struct CaseParameter
178 {
179         const char*             name;
180         string                  param;
181
182         CaseParameter   (const char* case_, const string& param_) : name(case_), param(param_) {}
183 };
184
185 // Assembly code used for testing LocalSize, OpNop, OpConstant{Null|Composite}, Op[No]Line, OpSource[Continued], OpSourceExtension, OpUndef is based on GLSL source code:
186 //
187 // #version 430
188 //
189 // layout(std140, set = 0, binding = 0) readonly buffer Input {
190 //   float elements[];
191 // } input_data;
192 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
193 //   float elements[];
194 // } output_data;
195 //
196 // layout (local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
197 //
198 // void main() {
199 //   uint x = gl_GlobalInvocationID.x;
200 //   output_data.elements[x] = -input_data.elements[x];
201 // }
202
203 static string getAsmForLocalSizeTest(bool useLiteralLocalSize, bool useSpecConstantWorkgroupSize, IVec3 workGroupSize, deUint32 ndx)
204 {
205         std::ostringstream out;
206         out << getComputeAsmShaderPreambleWithoutLocalSize();
207
208         if (useLiteralLocalSize)
209         {
210                 out << "OpExecutionMode %main LocalSize "
211                         << workGroupSize.x() << " " << workGroupSize.y() << " " << workGroupSize.z() << "\n";
212         }
213
214         out << "OpSource GLSL 430\n"
215                 "OpName %main           \"main\"\n"
216                 "OpName %id             \"gl_GlobalInvocationID\"\n"
217                 "OpDecorate %id BuiltIn GlobalInvocationId\n";
218
219         if (useSpecConstantWorkgroupSize)
220         {
221                 out << "OpDecorate %spec_0 SpecId 100\n"
222                         << "OpDecorate %spec_1 SpecId 101\n"
223                         << "OpDecorate %spec_2 SpecId 102\n"
224                         << "OpDecorate %gl_WorkGroupSize BuiltIn WorkgroupSize\n";
225         }
226
227         out << getComputeAsmInputOutputBufferTraits()
228                 << getComputeAsmCommonTypes()
229                 << getComputeAsmInputOutputBuffer()
230                 << "%id        = OpVariable %uvec3ptr Input\n"
231                 << "%zero      = OpConstant %i32 0 \n";
232
233         if (useSpecConstantWorkgroupSize)
234         {
235                 out     << "%spec_0   = OpSpecConstant %u32 "<< workGroupSize.x() << "\n"
236                         << "%spec_1   = OpSpecConstant %u32 "<< workGroupSize.y() << "\n"
237                         << "%spec_2   = OpSpecConstant %u32 "<< workGroupSize.z() << "\n"
238                         << "%gl_WorkGroupSize = OpSpecConstantComposite %uvec3 %spec_0 %spec_1 %spec_2\n";
239         }
240
241         out << "%main      = OpFunction %void None %voidf\n"
242                 << "%label     = OpLabel\n"
243                 << "%idval     = OpLoad %uvec3 %id\n"
244                 << "%ndx         = OpCompositeExtract %u32 %idval " << ndx << "\n"
245
246                         "%inloc     = OpAccessChain %f32ptr %indata %zero %ndx\n"
247                         "%inval     = OpLoad %f32 %inloc\n"
248                         "%neg       = OpFNegate %f32 %inval\n"
249                         "%outloc    = OpAccessChain %f32ptr %outdata %zero %ndx\n"
250                         "             OpStore %outloc %neg\n"
251                         "             OpReturn\n"
252                         "             OpFunctionEnd\n";
253         return out.str();
254 }
255
256 tcu::TestCaseGroup* createLocalSizeGroup (tcu::TestContext& testCtx)
257 {
258         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "localsize", ""));
259         ComputeShaderSpec                               spec;
260         de::Random                                              rnd                             (deStringHash(group->getName()));
261         const deUint32                                  numElements             = 64u;
262         vector<float>                                   positiveFloats  (numElements, 0);
263         vector<float>                                   negativeFloats  (numElements, 0);
264
265         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
266
267         for (size_t ndx = 0; ndx < numElements; ++ndx)
268                 negativeFloats[ndx] = -positiveFloats[ndx];
269
270         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
271         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
272
273         spec.numWorkGroups = IVec3(numElements, 1, 1);
274
275         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, 1, 1), 0u);
276         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize", "", spec));
277
278         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, 1, 1), 0u);
279         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize", "", spec));
280
281         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, 1, 1), 0u);
282         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize", "", spec));
283
284         spec.numWorkGroups = IVec3(1, 1, 1);
285
286         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(numElements, 1, 1), 0u);
287         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_x", "", spec));
288
289         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(numElements, 1, 1), 0u);
290         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_x", "", spec));
291
292         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(numElements, 1, 1), 0u);
293         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_x", "", spec));
294
295         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, numElements, 1), 1u);
296         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_y", "", spec));
297
298         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, numElements, 1), 1u);
299         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_y", "", spec));
300
301         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, numElements, 1), 1u);
302         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_y", "", spec));
303
304         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, 1, numElements), 2u);
305         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_z", "", spec));
306
307         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, 1, numElements), 2u);
308         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_z", "", spec));
309
310         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, 1, numElements), 2u);
311         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_z", "", spec));
312
313         return group.release();
314 }
315
316 tcu::TestCaseGroup* createOpNopGroup (tcu::TestContext& testCtx)
317 {
318         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnop", "Test the OpNop instruction"));
319         ComputeShaderSpec                               spec;
320         de::Random                                              rnd                             (deStringHash(group->getName()));
321         const int                                               numElements             = 100;
322         vector<float>                                   positiveFloats  (numElements, 0);
323         vector<float>                                   negativeFloats  (numElements, 0);
324
325         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
326
327         for (size_t ndx = 0; ndx < numElements; ++ndx)
328                 negativeFloats[ndx] = -positiveFloats[ndx];
329
330         spec.assembly =
331                 string(getComputeAsmShaderPreamble()) +
332
333                 "OpSource GLSL 430\n"
334                 "OpName %main           \"main\"\n"
335                 "OpName %id             \"gl_GlobalInvocationID\"\n"
336
337                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
338
339                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes())
340
341                 + string(getComputeAsmInputOutputBuffer()) +
342
343                 "%id        = OpVariable %uvec3ptr Input\n"
344                 "%zero      = OpConstant %i32 0\n"
345
346                 "%main      = OpFunction %void None %voidf\n"
347                 "%label     = OpLabel\n"
348                 "%idval     = OpLoad %uvec3 %id\n"
349                 "%x         = OpCompositeExtract %u32 %idval 0\n"
350
351                 "             OpNop\n" // Inside a function body
352
353                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
354                 "%inval     = OpLoad %f32 %inloc\n"
355                 "%neg       = OpFNegate %f32 %inval\n"
356                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
357                 "             OpStore %outloc %neg\n"
358                 "             OpReturn\n"
359                 "             OpFunctionEnd\n";
360         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
361         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
362         spec.numWorkGroups = IVec3(numElements, 1, 1);
363
364         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpNop appearing at different places", spec));
365
366         return group.release();
367 }
368
369 bool compareFUnord (const std::vector<BufferSp>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<BufferSp>& expectedOutputs, TestLog& log)
370 {
371         if (outputAllocs.size() != 1)
372                 return false;
373
374         vector<deUint8> input1Bytes;
375         vector<deUint8> input2Bytes;
376         vector<deUint8> expectedBytes;
377
378         inputs[0]->getBytes(input1Bytes);
379         inputs[1]->getBytes(input2Bytes);
380         expectedOutputs[0]->getBytes(expectedBytes);
381
382         const deInt32* const    expectedOutputAsInt             = reinterpret_cast<const deInt32* const>(&expectedBytes.front());
383         const deInt32* const    outputAsInt                             = static_cast<const deInt32* const>(outputAllocs[0]->getHostPtr());
384         const float* const              input1AsFloat                   = reinterpret_cast<const float* const>(&input1Bytes.front());
385         const float* const              input2AsFloat                   = reinterpret_cast<const float* const>(&input2Bytes.front());
386         bool returnValue                                                                = true;
387
388         for (size_t idx = 0; idx < expectedBytes.size() / sizeof(deInt32); ++idx)
389         {
390                 if (outputAsInt[idx] != expectedOutputAsInt[idx])
391                 {
392                         log << TestLog::Message << "ERROR: Sub-case failed. inputs: " << input1AsFloat[idx] << "," << input2AsFloat[idx] << " output: " << outputAsInt[idx]<< " expected output: " << expectedOutputAsInt[idx] << TestLog::EndMessage;
393                         returnValue = false;
394                 }
395         }
396         return returnValue;
397 }
398
399 typedef VkBool32 (*compareFuncType) (float, float);
400
401 struct OpFUnordCase
402 {
403         const char*             name;
404         const char*             opCode;
405         compareFuncType compareFunc;
406
407                                         OpFUnordCase                    (const char* _name, const char* _opCode, compareFuncType _compareFunc)
408                                                 : name                          (_name)
409                                                 , opCode                        (_opCode)
410                                                 , compareFunc           (_compareFunc) {}
411 };
412
413 #define ADD_OPFUNORD_CASE(NAME, OPCODE, OPERATOR) \
414 do { \
415     struct compare_##NAME { static VkBool32 compare(float x, float y) { return (x OPERATOR y) ? VK_TRUE : VK_FALSE; } }; \
416     cases.push_back(OpFUnordCase(#NAME, OPCODE, compare_##NAME::compare)); \
417 } while (deGetFalse())
418
419 tcu::TestCaseGroup* createOpFUnordGroup (tcu::TestContext& testCtx)
420 {
421         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opfunord", "Test the OpFUnord* opcodes"));
422         de::Random                                              rnd                             (deStringHash(group->getName()));
423         const int                                               numElements             = 100;
424         vector<OpFUnordCase>                    cases;
425
426         const StringTemplate                    shaderTemplate  (
427
428                 string(getComputeAsmShaderPreamble()) +
429
430                 "OpSource GLSL 430\n"
431                 "OpName %main           \"main\"\n"
432                 "OpName %id             \"gl_GlobalInvocationID\"\n"
433
434                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
435
436                 "OpDecorate %buf BufferBlock\n"
437                 "OpDecorate %buf2 BufferBlock\n"
438                 "OpDecorate %indata1 DescriptorSet 0\n"
439                 "OpDecorate %indata1 Binding 0\n"
440                 "OpDecorate %indata2 DescriptorSet 0\n"
441                 "OpDecorate %indata2 Binding 1\n"
442                 "OpDecorate %outdata DescriptorSet 0\n"
443                 "OpDecorate %outdata Binding 2\n"
444                 "OpDecorate %f32arr ArrayStride 4\n"
445                 "OpDecorate %i32arr ArrayStride 4\n"
446                 "OpMemberDecorate %buf 0 Offset 0\n"
447                 "OpMemberDecorate %buf2 0 Offset 0\n"
448
449                 + string(getComputeAsmCommonTypes()) +
450
451                 "%buf        = OpTypeStruct %f32arr\n"
452                 "%bufptr     = OpTypePointer Uniform %buf\n"
453                 "%indata1    = OpVariable %bufptr Uniform\n"
454                 "%indata2    = OpVariable %bufptr Uniform\n"
455
456                 "%buf2       = OpTypeStruct %i32arr\n"
457                 "%buf2ptr    = OpTypePointer Uniform %buf2\n"
458                 "%outdata    = OpVariable %buf2ptr Uniform\n"
459
460                 "%id        = OpVariable %uvec3ptr Input\n"
461                 "%zero      = OpConstant %i32 0\n"
462                 "%consti1   = OpConstant %i32 1\n"
463                 "%constf1   = OpConstant %f32 1.0\n"
464
465                 "%main      = OpFunction %void None %voidf\n"
466                 "%label     = OpLabel\n"
467                 "%idval     = OpLoad %uvec3 %id\n"
468                 "%x         = OpCompositeExtract %u32 %idval 0\n"
469
470                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
471                 "%inval1    = OpLoad %f32 %inloc1\n"
472                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
473                 "%inval2    = OpLoad %f32 %inloc2\n"
474                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
475
476                 "%result    = ${OPCODE} %bool %inval1 %inval2\n"
477                 "%int_res   = OpSelect %i32 %result %consti1 %zero\n"
478                 "             OpStore %outloc %int_res\n"
479
480                 "             OpReturn\n"
481                 "             OpFunctionEnd\n");
482
483         ADD_OPFUNORD_CASE(equal, "OpFUnordEqual", ==);
484         ADD_OPFUNORD_CASE(less, "OpFUnordLessThan", <);
485         ADD_OPFUNORD_CASE(lessequal, "OpFUnordLessThanEqual", <=);
486         ADD_OPFUNORD_CASE(greater, "OpFUnordGreaterThan", >);
487         ADD_OPFUNORD_CASE(greaterequal, "OpFUnordGreaterThanEqual", >=);
488         ADD_OPFUNORD_CASE(notequal, "OpFUnordNotEqual", !=);
489
490         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
491         {
492                 map<string, string>                     specializations;
493                 ComputeShaderSpec                       spec;
494                 const float                                     NaN                             = std::numeric_limits<float>::quiet_NaN();
495                 vector<float>                           inputFloats1    (numElements, 0);
496                 vector<float>                           inputFloats2    (numElements, 0);
497                 vector<deInt32>                         expectedInts    (numElements, 0);
498
499                 specializations["OPCODE"]       = cases[caseNdx].opCode;
500                 spec.assembly                           = shaderTemplate.specialize(specializations);
501
502                 fillRandomScalars(rnd, 1.f, 100.f, &inputFloats1[0], numElements);
503                 for (size_t ndx = 0; ndx < numElements; ++ndx)
504                 {
505                         switch (ndx % 6)
506                         {
507                                 case 0:         inputFloats2[ndx] = inputFloats1[ndx] + 1.0f; break;
508                                 case 1:         inputFloats2[ndx] = inputFloats1[ndx] - 1.0f; break;
509                                 case 2:         inputFloats2[ndx] = inputFloats1[ndx]; break;
510                                 case 3:         inputFloats2[ndx] = NaN; break;
511                                 case 4:         inputFloats2[ndx] = inputFloats1[ndx];  inputFloats1[ndx] = NaN; break;
512                                 case 5:         inputFloats2[ndx] = NaN;                                inputFloats1[ndx] = NaN; break;
513                         }
514                         expectedInts[ndx] = tcu::Float32(inputFloats1[ndx]).isNaN() || tcu::Float32(inputFloats2[ndx]).isNaN() || cases[caseNdx].compareFunc(inputFloats1[ndx], inputFloats2[ndx]);
515                 }
516
517                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
518                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
519                 spec.outputs.push_back(BufferSp(new Int32Buffer(expectedInts)));
520                 spec.numWorkGroups = IVec3(numElements, 1, 1);
521                 spec.verifyIO = &compareFUnord;
522                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
523         }
524
525         return group.release();
526 }
527
528 struct OpAtomicCase
529 {
530         const char*             name;
531         const char*             assembly;
532         OpAtomicType    opAtomic;
533         deInt32                 numOutputElements;
534
535                                         OpAtomicCase                    (const char* _name, const char* _assembly, OpAtomicType _opAtomic, deInt32 _numOutputElements)
536                                                 : name                          (_name)
537                                                 , assembly                      (_assembly)
538                                                 , opAtomic                      (_opAtomic)
539                                                 , numOutputElements     (_numOutputElements) {}
540 };
541
542 tcu::TestCaseGroup* createOpAtomicGroup (tcu::TestContext& testCtx, bool useStorageBuffer)
543 {
544         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx,
545                                                                                                                                                                 useStorageBuffer ? "opatomic_storage_buffer" : "opatomic",
546                                                                                                                                                                 "Test the OpAtomic* opcodes"));
547         const int                                               numElements                     = 65535;
548         vector<OpAtomicCase>                    cases;
549
550         const StringTemplate                    shaderTemplate  (
551
552                 string("OpCapability Shader\n") +
553                 (useStorageBuffer ? "OpExtension \"SPV_KHR_storage_buffer_storage_class\"\n" : "") +
554                 "OpMemoryModel Logical GLSL450\n"
555                 "OpEntryPoint GLCompute %main \"main\" %id\n"
556                 "OpExecutionMode %main LocalSize 1 1 1\n" +
557
558                 "OpSource GLSL 430\n"
559                 "OpName %main           \"main\"\n"
560                 "OpName %id             \"gl_GlobalInvocationID\"\n"
561
562                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
563
564                 "OpDecorate %buf ${BLOCK_DECORATION}\n"
565                 "OpDecorate %indata DescriptorSet 0\n"
566                 "OpDecorate %indata Binding 0\n"
567                 "OpDecorate %i32arr ArrayStride 4\n"
568                 "OpMemberDecorate %buf 0 Offset 0\n"
569
570                 "OpDecorate %sumbuf ${BLOCK_DECORATION}\n"
571                 "OpDecorate %sum DescriptorSet 0\n"
572                 "OpDecorate %sum Binding 1\n"
573                 "OpMemberDecorate %sumbuf 0 Coherent\n"
574                 "OpMemberDecorate %sumbuf 0 Offset 0\n"
575
576                 + getComputeAsmCommonTypes("${BLOCK_POINTER_TYPE}") +
577
578                 "%buf       = OpTypeStruct %i32arr\n"
579                 "%bufptr    = OpTypePointer ${BLOCK_POINTER_TYPE} %buf\n"
580                 "%indata    = OpVariable %bufptr ${BLOCK_POINTER_TYPE}\n"
581
582                 "%sumbuf    = OpTypeStruct %i32arr\n"
583                 "%sumbufptr = OpTypePointer ${BLOCK_POINTER_TYPE} %sumbuf\n"
584                 "%sum       = OpVariable %sumbufptr ${BLOCK_POINTER_TYPE}\n"
585
586                 "%id        = OpVariable %uvec3ptr Input\n"
587                 "%minusone  = OpConstant %i32 -1\n"
588                 "%zero      = OpConstant %i32 0\n"
589                 "%one       = OpConstant %u32 1\n"
590                 "%two       = OpConstant %i32 2\n"
591
592                 "%main      = OpFunction %void None %voidf\n"
593                 "%label     = OpLabel\n"
594                 "%idval     = OpLoad %uvec3 %id\n"
595                 "%x         = OpCompositeExtract %u32 %idval 0\n"
596
597                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
598                 "%inval     = OpLoad %i32 %inloc\n"
599
600                 "%outloc    = OpAccessChain %i32ptr %sum %zero ${INDEX}\n"
601                 "${INSTRUCTION}"
602
603                 "             OpReturn\n"
604                 "             OpFunctionEnd\n");
605
606         #define ADD_OPATOMIC_CASE(NAME, ASSEMBLY, OPATOMIC, NUM_OUTPUT_ELEMENTS) \
607         do { \
608                 DE_STATIC_ASSERT((NUM_OUTPUT_ELEMENTS) == 1 || (NUM_OUTPUT_ELEMENTS) == numElements); \
609                 cases.push_back(OpAtomicCase(#NAME, ASSEMBLY, OPATOMIC, NUM_OUTPUT_ELEMENTS)); \
610         } while (deGetFalse())
611         #define ADD_OPATOMIC_CASE_1(NAME, ASSEMBLY, OPATOMIC) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, OPATOMIC, 1)
612         #define ADD_OPATOMIC_CASE_N(NAME, ASSEMBLY, OPATOMIC) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, OPATOMIC, numElements)
613
614         ADD_OPATOMIC_CASE_1(iadd,       "%unused    = OpAtomicIAdd %i32 %outloc %one %zero %inval\n", OPATOMIC_IADD );
615         ADD_OPATOMIC_CASE_1(isub,       "%unused    = OpAtomicISub %i32 %outloc %one %zero %inval\n", OPATOMIC_ISUB );
616         ADD_OPATOMIC_CASE_1(iinc,       "%unused    = OpAtomicIIncrement %i32 %outloc %one %zero\n",  OPATOMIC_IINC );
617         ADD_OPATOMIC_CASE_1(idec,       "%unused    = OpAtomicIDecrement %i32 %outloc %one %zero\n",  OPATOMIC_IDEC );
618         ADD_OPATOMIC_CASE_N(load,       "%inval2    = OpAtomicLoad %i32 %inloc %zero %zero\n"
619                                                                 "             OpStore %outloc %inval2\n",  OPATOMIC_LOAD );
620         ADD_OPATOMIC_CASE_N(store,      "             OpAtomicStore %outloc %zero %zero %inval\n",  OPATOMIC_STORE );
621         ADD_OPATOMIC_CASE_N(compex, "%even      = OpSMod %i32 %inval %two\n"
622                                                                 "             OpStore %outloc %even\n"
623                                                                 "%unused    = OpAtomicCompareExchange %i32 %outloc %one %zero %zero %minusone %zero\n",  OPATOMIC_COMPEX );
624
625         #undef ADD_OPATOMIC_CASE
626         #undef ADD_OPATOMIC_CASE_1
627         #undef ADD_OPATOMIC_CASE_N
628
629         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
630         {
631                 map<string, string>                     specializations;
632                 ComputeShaderSpec                       spec;
633                 vector<deInt32>                         inputInts               (numElements, 0);
634                 vector<deInt32>                         expected                (cases[caseNdx].numOutputElements, -1);
635
636                 specializations["INDEX"]                                = (cases[caseNdx].numOutputElements == 1) ? "%zero" : "%x";
637                 specializations["INSTRUCTION"]                  = cases[caseNdx].assembly;
638                 specializations["BLOCK_DECORATION"]             = useStorageBuffer ? "Block" : "BufferBlock";
639                 specializations["BLOCK_POINTER_TYPE"]   = useStorageBuffer ? "StorageBuffer" : "Uniform";
640                 spec.assembly                                                   = shaderTemplate.specialize(specializations);
641
642                 if (useStorageBuffer)
643                         spec.extensions.push_back("VK_KHR_storage_buffer_storage_class");
644
645                 spec.inputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_INPUT)));
646                 spec.outputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_EXPECTED)));
647                 spec.numWorkGroups = IVec3(numElements, 1, 1);
648                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
649         }
650
651         return group.release();
652 }
653
654 tcu::TestCaseGroup* createOpLineGroup (tcu::TestContext& testCtx)
655 {
656         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opline", "Test the OpLine instruction"));
657         ComputeShaderSpec                               spec;
658         de::Random                                              rnd                             (deStringHash(group->getName()));
659         const int                                               numElements             = 100;
660         vector<float>                                   positiveFloats  (numElements, 0);
661         vector<float>                                   negativeFloats  (numElements, 0);
662
663         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
664
665         for (size_t ndx = 0; ndx < numElements; ++ndx)
666                 negativeFloats[ndx] = -positiveFloats[ndx];
667
668         spec.assembly =
669                 string(getComputeAsmShaderPreamble()) +
670
671                 "%fname1 = OpString \"negateInputs.comp\"\n"
672                 "%fname2 = OpString \"negateInputs\"\n"
673
674                 "OpSource GLSL 430\n"
675                 "OpName %main           \"main\"\n"
676                 "OpName %id             \"gl_GlobalInvocationID\"\n"
677
678                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
679
680                 + string(getComputeAsmInputOutputBufferTraits()) +
681
682                 "OpLine %fname1 0 0\n" // At the earliest possible position
683
684                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
685
686                 "OpLine %fname1 0 1\n" // Multiple OpLines in sequence
687                 "OpLine %fname2 1 0\n" // Different filenames
688                 "OpLine %fname1 1000 100000\n"
689
690                 "%id        = OpVariable %uvec3ptr Input\n"
691                 "%zero      = OpConstant %i32 0\n"
692
693                 "OpLine %fname1 1 1\n" // Before a function
694
695                 "%main      = OpFunction %void None %voidf\n"
696                 "%label     = OpLabel\n"
697
698                 "OpLine %fname1 1 1\n" // In a function
699
700                 "%idval     = OpLoad %uvec3 %id\n"
701                 "%x         = OpCompositeExtract %u32 %idval 0\n"
702                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
703                 "%inval     = OpLoad %f32 %inloc\n"
704                 "%neg       = OpFNegate %f32 %inval\n"
705                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
706                 "             OpStore %outloc %neg\n"
707                 "             OpReturn\n"
708                 "             OpFunctionEnd\n";
709         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
710         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
711         spec.numWorkGroups = IVec3(numElements, 1, 1);
712
713         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpLine appearing at different places", spec));
714
715         return group.release();
716 }
717
718 bool veryfiBinaryShader (const ProgramBinary& binary)
719 {
720         const size_t    paternCount                     = 3u;
721         bool paternsCheck[paternCount]          =
722         {
723                 false, false, false
724         };
725         const string patersns[paternCount]      =
726         {
727                 "VULKAN CTS",
728                 "Negative values",
729                 "Date: 2017/09/21"
730         };
731         size_t                  paternNdx               = 0u;
732
733         for (size_t ndx = 0u; ndx < binary.getSize(); ++ndx)
734         {
735                 if (false == paternsCheck[paternNdx] &&
736                         patersns[paternNdx][0] == static_cast<char>(binary.getBinary()[ndx]) &&
737                         deMemoryEqual((const char*)&binary.getBinary()[ndx], &patersns[paternNdx][0], patersns[paternNdx].length()))
738                 {
739                         paternsCheck[paternNdx]= true;
740                         paternNdx++;
741                         if (paternNdx == paternCount)
742                                 break;
743                 }
744         }
745
746         for (size_t ndx = 0u; ndx < paternCount; ++ndx)
747         {
748                 if (!paternsCheck[ndx])
749                         return false;
750         }
751
752         return true;
753 }
754
755 tcu::TestCaseGroup* createOpModuleProcessedGroup (tcu::TestContext& testCtx)
756 {
757         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opmoduleprocessed", "Test the OpModuleProcessed instruction"));
758         ComputeShaderSpec                               spec;
759         de::Random                                              rnd                             (deStringHash(group->getName()));
760         const int                                               numElements             = 10;
761         vector<float>                                   positiveFloats  (numElements, 0);
762         vector<float>                                   negativeFloats  (numElements, 0);
763
764         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
765
766         for (size_t ndx = 0; ndx < numElements; ++ndx)
767                 negativeFloats[ndx] = -positiveFloats[ndx];
768
769         spec.assembly =
770                 string(getComputeAsmShaderPreamble()) +
771                 "%fname = OpString \"negateInputs.comp\"\n"
772
773                 "OpSource GLSL 430\n"
774                 "OpName %main           \"main\"\n"
775                 "OpName %id             \"gl_GlobalInvocationID\"\n"
776                 "OpModuleProcessed \"VULKAN CTS\"\n"                                    //OpModuleProcessed;
777                 "OpModuleProcessed \"Negative values\"\n"
778                 "OpModuleProcessed \"Date: 2017/09/21\"\n"
779                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
780
781                 + string(getComputeAsmInputOutputBufferTraits())
782
783                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
784
785                 "OpLine %fname 0 1\n"
786
787                 "OpLine %fname 1000 1\n"
788
789                 "%id        = OpVariable %uvec3ptr Input\n"
790                 "%zero      = OpConstant %i32 0\n"
791                 "%main      = OpFunction %void None %voidf\n"
792
793                 "%label     = OpLabel\n"
794                 "%idval     = OpLoad %uvec3 %id\n"
795                 "%x         = OpCompositeExtract %u32 %idval 0\n"
796
797                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
798                 "%inval     = OpLoad %f32 %inloc\n"
799                 "%neg       = OpFNegate %f32 %inval\n"
800                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
801                 "             OpStore %outloc %neg\n"
802                 "             OpReturn\n"
803                 "             OpFunctionEnd\n";
804         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
805         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
806         spec.numWorkGroups = IVec3(numElements, 1, 1);
807         spec.verifyBinary = veryfiBinaryShader;
808         spec.spirvVersion = SPIRV_VERSION_1_3;
809
810         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpModuleProcessed Tests", spec));
811
812         return group.release();
813 }
814
815 tcu::TestCaseGroup* createOpNoLineGroup (tcu::TestContext& testCtx)
816 {
817         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnoline", "Test the OpNoLine instruction"));
818         ComputeShaderSpec                               spec;
819         de::Random                                              rnd                             (deStringHash(group->getName()));
820         const int                                               numElements             = 100;
821         vector<float>                                   positiveFloats  (numElements, 0);
822         vector<float>                                   negativeFloats  (numElements, 0);
823
824         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
825
826         for (size_t ndx = 0; ndx < numElements; ++ndx)
827                 negativeFloats[ndx] = -positiveFloats[ndx];
828
829         spec.assembly =
830                 string(getComputeAsmShaderPreamble()) +
831
832                 "%fname = OpString \"negateInputs.comp\"\n"
833
834                 "OpSource GLSL 430\n"
835                 "OpName %main           \"main\"\n"
836                 "OpName %id             \"gl_GlobalInvocationID\"\n"
837
838                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
839
840                 + string(getComputeAsmInputOutputBufferTraits()) +
841
842                 "OpNoLine\n" // At the earliest possible position, without preceding OpLine
843
844                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
845
846                 "OpLine %fname 0 1\n"
847                 "OpNoLine\n" // Immediately following a preceding OpLine
848
849                 "OpLine %fname 1000 1\n"
850
851                 "%id        = OpVariable %uvec3ptr Input\n"
852                 "%zero      = OpConstant %i32 0\n"
853
854                 "OpNoLine\n" // Contents after the previous OpLine
855
856                 "%main      = OpFunction %void None %voidf\n"
857                 "%label     = OpLabel\n"
858                 "%idval     = OpLoad %uvec3 %id\n"
859                 "%x         = OpCompositeExtract %u32 %idval 0\n"
860
861                 "OpNoLine\n" // Multiple OpNoLine
862                 "OpNoLine\n"
863                 "OpNoLine\n"
864
865                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
866                 "%inval     = OpLoad %f32 %inloc\n"
867                 "%neg       = OpFNegate %f32 %inval\n"
868                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
869                 "             OpStore %outloc %neg\n"
870                 "             OpReturn\n"
871                 "             OpFunctionEnd\n";
872         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
873         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
874         spec.numWorkGroups = IVec3(numElements, 1, 1);
875
876         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpNoLine appearing at different places", spec));
877
878         return group.release();
879 }
880
881 // Compare instruction for the contraction compute case.
882 // Returns true if the output is what is expected from the test case.
883 bool compareNoContractCase(const std::vector<BufferSp>&, const vector<AllocationSp>& outputAllocs, const std::vector<BufferSp>& expectedOutputs, TestLog&)
884 {
885         if (outputAllocs.size() != 1)
886                 return false;
887
888         // Only size is needed because we are not comparing the exact values.
889         size_t byteSize = expectedOutputs[0]->getByteSize();
890
891         const float*    outputAsFloat   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
892
893         for(size_t i = 0; i < byteSize / sizeof(float); ++i) {
894                 if (outputAsFloat[i] != 0.f &&
895                         outputAsFloat[i] != -ldexp(1, -24)) {
896                         return false;
897                 }
898         }
899
900         return true;
901 }
902
903 tcu::TestCaseGroup* createNoContractionGroup (tcu::TestContext& testCtx)
904 {
905         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
906         vector<CaseParameter>                   cases;
907         const int                                               numElements             = 100;
908         vector<float>                                   inputFloats1    (numElements, 0);
909         vector<float>                                   inputFloats2    (numElements, 0);
910         vector<float>                                   outputFloats    (numElements, 0);
911         const StringTemplate                    shaderTemplate  (
912                 string(getComputeAsmShaderPreamble()) +
913
914                 "OpName %main           \"main\"\n"
915                 "OpName %id             \"gl_GlobalInvocationID\"\n"
916
917                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
918
919                 "${DECORATION}\n"
920
921                 "OpDecorate %buf BufferBlock\n"
922                 "OpDecorate %indata1 DescriptorSet 0\n"
923                 "OpDecorate %indata1 Binding 0\n"
924                 "OpDecorate %indata2 DescriptorSet 0\n"
925                 "OpDecorate %indata2 Binding 1\n"
926                 "OpDecorate %outdata DescriptorSet 0\n"
927                 "OpDecorate %outdata Binding 2\n"
928                 "OpDecorate %f32arr ArrayStride 4\n"
929                 "OpMemberDecorate %buf 0 Offset 0\n"
930
931                 + string(getComputeAsmCommonTypes()) +
932
933                 "%buf        = OpTypeStruct %f32arr\n"
934                 "%bufptr     = OpTypePointer Uniform %buf\n"
935                 "%indata1    = OpVariable %bufptr Uniform\n"
936                 "%indata2    = OpVariable %bufptr Uniform\n"
937                 "%outdata    = OpVariable %bufptr Uniform\n"
938
939                 "%id         = OpVariable %uvec3ptr Input\n"
940                 "%zero       = OpConstant %i32 0\n"
941                 "%c_f_m1     = OpConstant %f32 -1.\n"
942
943                 "%main       = OpFunction %void None %voidf\n"
944                 "%label      = OpLabel\n"
945                 "%idval      = OpLoad %uvec3 %id\n"
946                 "%x          = OpCompositeExtract %u32 %idval 0\n"
947                 "%inloc1     = OpAccessChain %f32ptr %indata1 %zero %x\n"
948                 "%inval1     = OpLoad %f32 %inloc1\n"
949                 "%inloc2     = OpAccessChain %f32ptr %indata2 %zero %x\n"
950                 "%inval2     = OpLoad %f32 %inloc2\n"
951                 "%mul        = OpFMul %f32 %inval1 %inval2\n"
952                 "%add        = OpFAdd %f32 %mul %c_f_m1\n"
953                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
954                 "              OpStore %outloc %add\n"
955                 "              OpReturn\n"
956                 "              OpFunctionEnd\n");
957
958         cases.push_back(CaseParameter("multiplication", "OpDecorate %mul NoContraction"));
959         cases.push_back(CaseParameter("addition",               "OpDecorate %add NoContraction"));
960         cases.push_back(CaseParameter("both",                   "OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"));
961
962         for (size_t ndx = 0; ndx < numElements; ++ndx)
963         {
964                 inputFloats1[ndx]       = 1.f + std::ldexp(1.f, -23); // 1 + 2^-23.
965                 inputFloats2[ndx]       = 1.f - std::ldexp(1.f, -23); // 1 - 2^-23.
966                 // Result for (1 + 2^-23) * (1 - 2^-23) - 1. With NoContraction, the multiplication will be
967                 // conducted separately and the result is rounded to 1, or 0x1.fffffcp-1
968                 // So the final result will be 0.f or 0x1p-24.
969                 // If the operation is combined into a precise fused multiply-add, then the result would be
970                 // 2^-46 (0xa8800000).
971                 outputFloats[ndx]       = 0.f;
972         }
973
974         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
975         {
976                 map<string, string>             specializations;
977                 ComputeShaderSpec               spec;
978
979                 specializations["DECORATION"] = cases[caseNdx].param;
980                 spec.assembly = shaderTemplate.specialize(specializations);
981                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
982                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
983                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
984                 spec.numWorkGroups = IVec3(numElements, 1, 1);
985                 // Check against the two possible answers based on rounding mode.
986                 spec.verifyIO = &compareNoContractCase;
987
988                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
989         }
990         return group.release();
991 }
992
993 bool compareFRem(const std::vector<BufferSp>&, const vector<AllocationSp>& outputAllocs, const std::vector<BufferSp>& expectedOutputs, TestLog&)
994 {
995         if (outputAllocs.size() != 1)
996                 return false;
997
998         vector<deUint8> expectedBytes;
999         expectedOutputs[0]->getBytes(expectedBytes);
1000
1001         const float*    expectedOutputAsFloat   = reinterpret_cast<const float*>(&expectedBytes.front());
1002         const float*    outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1003
1004         for (size_t idx = 0; idx < expectedBytes.size() / sizeof(float); ++idx)
1005         {
1006                 const float f0 = expectedOutputAsFloat[idx];
1007                 const float f1 = outputAsFloat[idx];
1008                 // \todo relative error needs to be fairly high because FRem may be implemented as
1009                 // (roughly) frac(a/b)*b, so LSB errors can be magnified. But this should be fine for now.
1010                 if (deFloatAbs((f1 - f0) / f0) > 0.02)
1011                         return false;
1012         }
1013
1014         return true;
1015 }
1016
1017 tcu::TestCaseGroup* createOpFRemGroup (tcu::TestContext& testCtx)
1018 {
1019         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opfrem", "Test the OpFRem instruction"));
1020         ComputeShaderSpec                               spec;
1021         de::Random                                              rnd                             (deStringHash(group->getName()));
1022         const int                                               numElements             = 200;
1023         vector<float>                                   inputFloats1    (numElements, 0);
1024         vector<float>                                   inputFloats2    (numElements, 0);
1025         vector<float>                                   outputFloats    (numElements, 0);
1026
1027         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1028         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats2[0], numElements);
1029
1030         for (size_t ndx = 0; ndx < numElements; ++ndx)
1031         {
1032                 // Guard against divisors near zero.
1033                 if (std::fabs(inputFloats2[ndx]) < 1e-3)
1034                         inputFloats2[ndx] = 8.f;
1035
1036                 // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1037                 outputFloats[ndx] = std::fmod(inputFloats1[ndx], inputFloats2[ndx]);
1038         }
1039
1040         spec.assembly =
1041                 string(getComputeAsmShaderPreamble()) +
1042
1043                 "OpName %main           \"main\"\n"
1044                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1045
1046                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1047
1048                 "OpDecorate %buf BufferBlock\n"
1049                 "OpDecorate %indata1 DescriptorSet 0\n"
1050                 "OpDecorate %indata1 Binding 0\n"
1051                 "OpDecorate %indata2 DescriptorSet 0\n"
1052                 "OpDecorate %indata2 Binding 1\n"
1053                 "OpDecorate %outdata DescriptorSet 0\n"
1054                 "OpDecorate %outdata Binding 2\n"
1055                 "OpDecorate %f32arr ArrayStride 4\n"
1056                 "OpMemberDecorate %buf 0 Offset 0\n"
1057
1058                 + string(getComputeAsmCommonTypes()) +
1059
1060                 "%buf        = OpTypeStruct %f32arr\n"
1061                 "%bufptr     = OpTypePointer Uniform %buf\n"
1062                 "%indata1    = OpVariable %bufptr Uniform\n"
1063                 "%indata2    = OpVariable %bufptr Uniform\n"
1064                 "%outdata    = OpVariable %bufptr Uniform\n"
1065
1066                 "%id        = OpVariable %uvec3ptr Input\n"
1067                 "%zero      = OpConstant %i32 0\n"
1068
1069                 "%main      = OpFunction %void None %voidf\n"
1070                 "%label     = OpLabel\n"
1071                 "%idval     = OpLoad %uvec3 %id\n"
1072                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1073                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1074                 "%inval1    = OpLoad %f32 %inloc1\n"
1075                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1076                 "%inval2    = OpLoad %f32 %inloc2\n"
1077                 "%rem       = OpFRem %f32 %inval1 %inval2\n"
1078                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1079                 "             OpStore %outloc %rem\n"
1080                 "             OpReturn\n"
1081                 "             OpFunctionEnd\n";
1082
1083         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1084         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1085         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1086         spec.numWorkGroups = IVec3(numElements, 1, 1);
1087         spec.verifyIO = &compareFRem;
1088
1089         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1090
1091         return group.release();
1092 }
1093
1094 bool compareNMin (const std::vector<BufferSp>&, const vector<AllocationSp>& outputAllocs, const std::vector<BufferSp>& expectedOutputs, TestLog&)
1095 {
1096         if (outputAllocs.size() != 1)
1097                 return false;
1098
1099         const BufferSp&                 expectedOutput                  (expectedOutputs[0]);
1100         std::vector<deUint8>    data;
1101         expectedOutput->getBytes(data);
1102
1103         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1104         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1105
1106         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float); ++idx)
1107         {
1108                 const float f0 = expectedOutputAsFloat[idx];
1109                 const float f1 = outputAsFloat[idx];
1110
1111                 // For NMin, we accept NaN as output if both inputs were NaN.
1112                 // Otherwise the NaN is the wrong choise, as on architectures that
1113                 // do not handle NaN, those are huge values.
1114                 if (!(tcu::Float32(f1).isNaN() && tcu::Float32(f0).isNaN()) && deFloatAbs(f1 - f0) > 0.00001f)
1115                         return false;
1116         }
1117
1118         return true;
1119 }
1120
1121 tcu::TestCaseGroup* createOpNMinGroup (tcu::TestContext& testCtx)
1122 {
1123         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnmin", "Test the OpNMin instruction"));
1124         ComputeShaderSpec                               spec;
1125         de::Random                                              rnd                             (deStringHash(group->getName()));
1126         const int                                               numElements             = 200;
1127         vector<float>                                   inputFloats1    (numElements, 0);
1128         vector<float>                                   inputFloats2    (numElements, 0);
1129         vector<float>                                   outputFloats    (numElements, 0);
1130
1131         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1132         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1133
1134         // Make the first case a full-NAN case.
1135         inputFloats1[0] = TCU_NAN;
1136         inputFloats2[0] = TCU_NAN;
1137
1138         for (size_t ndx = 0; ndx < numElements; ++ndx)
1139         {
1140                 // By default, pick the smallest
1141                 outputFloats[ndx] = std::min(inputFloats1[ndx], inputFloats2[ndx]);
1142
1143                 // Make half of the cases NaN cases
1144                 if ((ndx & 1) == 0)
1145                 {
1146                         // Alternate between the NaN operand
1147                         if ((ndx & 2) == 0)
1148                         {
1149                                 outputFloats[ndx] = inputFloats2[ndx];
1150                                 inputFloats1[ndx] = TCU_NAN;
1151                         }
1152                         else
1153                         {
1154                                 outputFloats[ndx] = inputFloats1[ndx];
1155                                 inputFloats2[ndx] = TCU_NAN;
1156                         }
1157                 }
1158         }
1159
1160         spec.assembly =
1161                 "OpCapability Shader\n"
1162                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1163                 "OpMemoryModel Logical GLSL450\n"
1164                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1165                 "OpExecutionMode %main LocalSize 1 1 1\n"
1166
1167                 "OpName %main           \"main\"\n"
1168                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1169
1170                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1171
1172                 "OpDecorate %buf BufferBlock\n"
1173                 "OpDecorate %indata1 DescriptorSet 0\n"
1174                 "OpDecorate %indata1 Binding 0\n"
1175                 "OpDecorate %indata2 DescriptorSet 0\n"
1176                 "OpDecorate %indata2 Binding 1\n"
1177                 "OpDecorate %outdata DescriptorSet 0\n"
1178                 "OpDecorate %outdata Binding 2\n"
1179                 "OpDecorate %f32arr ArrayStride 4\n"
1180                 "OpMemberDecorate %buf 0 Offset 0\n"
1181
1182                 + string(getComputeAsmCommonTypes()) +
1183
1184                 "%buf        = OpTypeStruct %f32arr\n"
1185                 "%bufptr     = OpTypePointer Uniform %buf\n"
1186                 "%indata1    = OpVariable %bufptr Uniform\n"
1187                 "%indata2    = OpVariable %bufptr Uniform\n"
1188                 "%outdata    = OpVariable %bufptr Uniform\n"
1189
1190                 "%id        = OpVariable %uvec3ptr Input\n"
1191                 "%zero      = OpConstant %i32 0\n"
1192
1193                 "%main      = OpFunction %void None %voidf\n"
1194                 "%label     = OpLabel\n"
1195                 "%idval     = OpLoad %uvec3 %id\n"
1196                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1197                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1198                 "%inval1    = OpLoad %f32 %inloc1\n"
1199                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1200                 "%inval2    = OpLoad %f32 %inloc2\n"
1201                 "%rem       = OpExtInst %f32 %std450 NMin %inval1 %inval2\n"
1202                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1203                 "             OpStore %outloc %rem\n"
1204                 "             OpReturn\n"
1205                 "             OpFunctionEnd\n";
1206
1207         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1208         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1209         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1210         spec.numWorkGroups = IVec3(numElements, 1, 1);
1211         spec.verifyIO = &compareNMin;
1212
1213         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1214
1215         return group.release();
1216 }
1217
1218 bool compareNMax (const std::vector<BufferSp>&, const vector<AllocationSp>& outputAllocs, const std::vector<BufferSp>& expectedOutputs, TestLog&)
1219 {
1220         if (outputAllocs.size() != 1)
1221                 return false;
1222
1223         const BufferSp&                 expectedOutput                  = expectedOutputs[0];
1224         std::vector<deUint8>    data;
1225         expectedOutput->getBytes(data);
1226
1227         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1228         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1229
1230         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float); ++idx)
1231         {
1232                 const float f0 = expectedOutputAsFloat[idx];
1233                 const float f1 = outputAsFloat[idx];
1234
1235                 // For NMax, NaN is considered acceptable result, since in
1236                 // architectures that do not handle NaNs, those are huge values.
1237                 if (!tcu::Float32(f1).isNaN() && deFloatAbs(f1 - f0) > 0.00001f)
1238                         return false;
1239         }
1240
1241         return true;
1242 }
1243
1244 tcu::TestCaseGroup* createOpNMaxGroup (tcu::TestContext& testCtx)
1245 {
1246         de::MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "opnmax", "Test the OpNMax instruction"));
1247         ComputeShaderSpec                               spec;
1248         de::Random                                              rnd                             (deStringHash(group->getName()));
1249         const int                                               numElements             = 200;
1250         vector<float>                                   inputFloats1    (numElements, 0);
1251         vector<float>                                   inputFloats2    (numElements, 0);
1252         vector<float>                                   outputFloats    (numElements, 0);
1253
1254         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1255         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1256
1257         // Make the first case a full-NAN case.
1258         inputFloats1[0] = TCU_NAN;
1259         inputFloats2[0] = TCU_NAN;
1260
1261         for (size_t ndx = 0; ndx < numElements; ++ndx)
1262         {
1263                 // By default, pick the biggest
1264                 outputFloats[ndx] = std::max(inputFloats1[ndx], inputFloats2[ndx]);
1265
1266                 // Make half of the cases NaN cases
1267                 if ((ndx & 1) == 0)
1268                 {
1269                         // Alternate between the NaN operand
1270                         if ((ndx & 2) == 0)
1271                         {
1272                                 outputFloats[ndx] = inputFloats2[ndx];
1273                                 inputFloats1[ndx] = TCU_NAN;
1274                         }
1275                         else
1276                         {
1277                                 outputFloats[ndx] = inputFloats1[ndx];
1278                                 inputFloats2[ndx] = TCU_NAN;
1279                         }
1280                 }
1281         }
1282
1283         spec.assembly =
1284                 "OpCapability Shader\n"
1285                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1286                 "OpMemoryModel Logical GLSL450\n"
1287                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1288                 "OpExecutionMode %main LocalSize 1 1 1\n"
1289
1290                 "OpName %main           \"main\"\n"
1291                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1292
1293                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1294
1295                 "OpDecorate %buf BufferBlock\n"
1296                 "OpDecorate %indata1 DescriptorSet 0\n"
1297                 "OpDecorate %indata1 Binding 0\n"
1298                 "OpDecorate %indata2 DescriptorSet 0\n"
1299                 "OpDecorate %indata2 Binding 1\n"
1300                 "OpDecorate %outdata DescriptorSet 0\n"
1301                 "OpDecorate %outdata Binding 2\n"
1302                 "OpDecorate %f32arr ArrayStride 4\n"
1303                 "OpMemberDecorate %buf 0 Offset 0\n"
1304
1305                 + string(getComputeAsmCommonTypes()) +
1306
1307                 "%buf        = OpTypeStruct %f32arr\n"
1308                 "%bufptr     = OpTypePointer Uniform %buf\n"
1309                 "%indata1    = OpVariable %bufptr Uniform\n"
1310                 "%indata2    = OpVariable %bufptr Uniform\n"
1311                 "%outdata    = OpVariable %bufptr Uniform\n"
1312
1313                 "%id        = OpVariable %uvec3ptr Input\n"
1314                 "%zero      = OpConstant %i32 0\n"
1315
1316                 "%main      = OpFunction %void None %voidf\n"
1317                 "%label     = OpLabel\n"
1318                 "%idval     = OpLoad %uvec3 %id\n"
1319                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1320                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1321                 "%inval1    = OpLoad %f32 %inloc1\n"
1322                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1323                 "%inval2    = OpLoad %f32 %inloc2\n"
1324                 "%rem       = OpExtInst %f32 %std450 NMax %inval1 %inval2\n"
1325                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1326                 "             OpStore %outloc %rem\n"
1327                 "             OpReturn\n"
1328                 "             OpFunctionEnd\n";
1329
1330         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1331         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1332         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1333         spec.numWorkGroups = IVec3(numElements, 1, 1);
1334         spec.verifyIO = &compareNMax;
1335
1336         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1337
1338         return group.release();
1339 }
1340
1341 bool compareNClamp (const std::vector<BufferSp>&, const vector<AllocationSp>& outputAllocs, const std::vector<BufferSp>& expectedOutputs, TestLog&)
1342 {
1343         if (outputAllocs.size() != 1)
1344                 return false;
1345
1346         const BufferSp&                 expectedOutput                  = expectedOutputs[0];
1347         std::vector<deUint8>    data;
1348         expectedOutput->getBytes(data);
1349
1350         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1351         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1352
1353         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float) / 2; ++idx)
1354         {
1355                 const float e0 = expectedOutputAsFloat[idx * 2];
1356                 const float e1 = expectedOutputAsFloat[idx * 2 + 1];
1357                 const float res = outputAsFloat[idx];
1358
1359                 // For NClamp, we have two possible outcomes based on
1360                 // whether NaNs are handled or not.
1361                 // If either min or max value is NaN, the result is undefined,
1362                 // so this test doesn't stress those. If the clamped value is
1363                 // NaN, and NaNs are handled, the result is min; if NaNs are not
1364                 // handled, they are big values that result in max.
1365                 // If all three parameters are NaN, the result should be NaN.
1366                 if (!((tcu::Float32(e0).isNaN() && tcu::Float32(res).isNaN()) ||
1367                          (deFloatAbs(e0 - res) < 0.00001f) ||
1368                          (deFloatAbs(e1 - res) < 0.00001f)))
1369                         return false;
1370         }
1371
1372         return true;
1373 }
1374
1375 tcu::TestCaseGroup* createOpNClampGroup (tcu::TestContext& testCtx)
1376 {
1377         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnclamp", "Test the OpNClamp instruction"));
1378         ComputeShaderSpec                               spec;
1379         de::Random                                              rnd                             (deStringHash(group->getName()));
1380         const int                                               numElements             = 200;
1381         vector<float>                                   inputFloats1    (numElements, 0);
1382         vector<float>                                   inputFloats2    (numElements, 0);
1383         vector<float>                                   inputFloats3    (numElements, 0);
1384         vector<float>                                   outputFloats    (numElements * 2, 0);
1385
1386         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1387         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1388         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats3[0], numElements);
1389
1390         for (size_t ndx = 0; ndx < numElements; ++ndx)
1391         {
1392                 // Results are only defined if max value is bigger than min value.
1393                 if (inputFloats2[ndx] > inputFloats3[ndx])
1394                 {
1395                         float t = inputFloats2[ndx];
1396                         inputFloats2[ndx] = inputFloats3[ndx];
1397                         inputFloats3[ndx] = t;
1398                 }
1399
1400                 // By default, do the clamp, setting both possible answers
1401                 float defaultRes = std::min(std::max(inputFloats1[ndx], inputFloats2[ndx]), inputFloats3[ndx]);
1402
1403                 float maxResA = std::max(inputFloats1[ndx], inputFloats2[ndx]);
1404                 float maxResB = maxResA;
1405
1406                 // Alternate between the NaN cases
1407                 if (ndx & 1)
1408                 {
1409                         inputFloats1[ndx] = TCU_NAN;
1410                         // If NaN is handled, the result should be same as the clamp minimum.
1411                         // If NaN is not handled, the result should clamp to the clamp maximum.
1412                         maxResA = inputFloats2[ndx];
1413                         maxResB = inputFloats3[ndx];
1414                 }
1415                 else
1416                 {
1417                         // Not a NaN case - only one legal result.
1418                         maxResA = defaultRes;
1419                         maxResB = defaultRes;
1420                 }
1421
1422                 outputFloats[ndx * 2] = maxResA;
1423                 outputFloats[ndx * 2 + 1] = maxResB;
1424         }
1425
1426         // Make the first case a full-NAN case.
1427         inputFloats1[0] = TCU_NAN;
1428         inputFloats2[0] = TCU_NAN;
1429         inputFloats3[0] = TCU_NAN;
1430         outputFloats[0] = TCU_NAN;
1431         outputFloats[1] = TCU_NAN;
1432
1433         spec.assembly =
1434                 "OpCapability Shader\n"
1435                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1436                 "OpMemoryModel Logical GLSL450\n"
1437                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1438                 "OpExecutionMode %main LocalSize 1 1 1\n"
1439
1440                 "OpName %main           \"main\"\n"
1441                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1442
1443                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1444
1445                 "OpDecorate %buf BufferBlock\n"
1446                 "OpDecorate %indata1 DescriptorSet 0\n"
1447                 "OpDecorate %indata1 Binding 0\n"
1448                 "OpDecorate %indata2 DescriptorSet 0\n"
1449                 "OpDecorate %indata2 Binding 1\n"
1450                 "OpDecorate %indata3 DescriptorSet 0\n"
1451                 "OpDecorate %indata3 Binding 2\n"
1452                 "OpDecorate %outdata DescriptorSet 0\n"
1453                 "OpDecorate %outdata Binding 3\n"
1454                 "OpDecorate %f32arr ArrayStride 4\n"
1455                 "OpMemberDecorate %buf 0 Offset 0\n"
1456
1457                 + string(getComputeAsmCommonTypes()) +
1458
1459                 "%buf        = OpTypeStruct %f32arr\n"
1460                 "%bufptr     = OpTypePointer Uniform %buf\n"
1461                 "%indata1    = OpVariable %bufptr Uniform\n"
1462                 "%indata2    = OpVariable %bufptr Uniform\n"
1463                 "%indata3    = OpVariable %bufptr Uniform\n"
1464                 "%outdata    = OpVariable %bufptr Uniform\n"
1465
1466                 "%id        = OpVariable %uvec3ptr Input\n"
1467                 "%zero      = OpConstant %i32 0\n"
1468
1469                 "%main      = OpFunction %void None %voidf\n"
1470                 "%label     = OpLabel\n"
1471                 "%idval     = OpLoad %uvec3 %id\n"
1472                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1473                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1474                 "%inval1    = OpLoad %f32 %inloc1\n"
1475                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1476                 "%inval2    = OpLoad %f32 %inloc2\n"
1477                 "%inloc3    = OpAccessChain %f32ptr %indata3 %zero %x\n"
1478                 "%inval3    = OpLoad %f32 %inloc3\n"
1479                 "%rem       = OpExtInst %f32 %std450 NClamp %inval1 %inval2 %inval3\n"
1480                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1481                 "             OpStore %outloc %rem\n"
1482                 "             OpReturn\n"
1483                 "             OpFunctionEnd\n";
1484
1485         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1486         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1487         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
1488         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1489         spec.numWorkGroups = IVec3(numElements, 1, 1);
1490         spec.verifyIO = &compareNClamp;
1491
1492         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1493
1494         return group.release();
1495 }
1496
1497 tcu::TestCaseGroup* createOpSRemComputeGroup (tcu::TestContext& testCtx, qpTestResult negFailResult)
1498 {
1499         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsrem", "Test the OpSRem instruction"));
1500         de::Random                                              rnd                             (deStringHash(group->getName()));
1501         const int                                               numElements             = 200;
1502
1503         const struct CaseParams
1504         {
1505                 const char*             name;
1506                 const char*             failMessage;            // customized status message
1507                 qpTestResult    failResult;                     // override status on failure
1508                 int                             op1Min, op1Max;         // operand ranges
1509                 int                             op2Min, op2Max;
1510         } cases[] =
1511         {
1512                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    0,              65536,  0,              100 },
1513                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  -65536, 65536,  -100,   100 },  // see below
1514         };
1515         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1516
1517         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1518         {
1519                 const CaseParams&       params          = cases[caseNdx];
1520                 ComputeShaderSpec       spec;
1521                 vector<deInt32>         inputInts1      (numElements, 0);
1522                 vector<deInt32>         inputInts2      (numElements, 0);
1523                 vector<deInt32>         outputInts      (numElements, 0);
1524
1525                 fillRandomScalars(rnd, params.op1Min, params.op1Max, &inputInts1[0], numElements);
1526                 fillRandomScalars(rnd, params.op2Min, params.op2Max, &inputInts2[0], numElements, filterNotZero);
1527
1528                 for (int ndx = 0; ndx < numElements; ++ndx)
1529                 {
1530                         // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1531                         outputInts[ndx] = inputInts1[ndx] % inputInts2[ndx];
1532                 }
1533
1534                 spec.assembly =
1535                         string(getComputeAsmShaderPreamble()) +
1536
1537                         "OpName %main           \"main\"\n"
1538                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1539
1540                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1541
1542                         "OpDecorate %buf BufferBlock\n"
1543                         "OpDecorate %indata1 DescriptorSet 0\n"
1544                         "OpDecorate %indata1 Binding 0\n"
1545                         "OpDecorate %indata2 DescriptorSet 0\n"
1546                         "OpDecorate %indata2 Binding 1\n"
1547                         "OpDecorate %outdata DescriptorSet 0\n"
1548                         "OpDecorate %outdata Binding 2\n"
1549                         "OpDecorate %i32arr ArrayStride 4\n"
1550                         "OpMemberDecorate %buf 0 Offset 0\n"
1551
1552                         + string(getComputeAsmCommonTypes()) +
1553
1554                         "%buf        = OpTypeStruct %i32arr\n"
1555                         "%bufptr     = OpTypePointer Uniform %buf\n"
1556                         "%indata1    = OpVariable %bufptr Uniform\n"
1557                         "%indata2    = OpVariable %bufptr Uniform\n"
1558                         "%outdata    = OpVariable %bufptr Uniform\n"
1559
1560                         "%id        = OpVariable %uvec3ptr Input\n"
1561                         "%zero      = OpConstant %i32 0\n"
1562
1563                         "%main      = OpFunction %void None %voidf\n"
1564                         "%label     = OpLabel\n"
1565                         "%idval     = OpLoad %uvec3 %id\n"
1566                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1567                         "%inloc1    = OpAccessChain %i32ptr %indata1 %zero %x\n"
1568                         "%inval1    = OpLoad %i32 %inloc1\n"
1569                         "%inloc2    = OpAccessChain %i32ptr %indata2 %zero %x\n"
1570                         "%inval2    = OpLoad %i32 %inloc2\n"
1571                         "%rem       = OpSRem %i32 %inval1 %inval2\n"
1572                         "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
1573                         "             OpStore %outloc %rem\n"
1574                         "             OpReturn\n"
1575                         "             OpFunctionEnd\n";
1576
1577                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts1)));
1578                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts2)));
1579                 spec.outputs.push_back  (BufferSp(new Int32Buffer(outputInts)));
1580                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1581                 spec.failResult                 = params.failResult;
1582                 spec.failMessage                = params.failMessage;
1583
1584                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1585         }
1586
1587         return group.release();
1588 }
1589
1590 tcu::TestCaseGroup* createOpSRemComputeGroup64 (tcu::TestContext& testCtx, qpTestResult negFailResult)
1591 {
1592         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsrem64", "Test the 64-bit OpSRem instruction"));
1593         de::Random                                              rnd                             (deStringHash(group->getName()));
1594         const int                                               numElements             = 200;
1595
1596         const struct CaseParams
1597         {
1598                 const char*             name;
1599                 const char*             failMessage;            // customized status message
1600                 qpTestResult    failResult;                     // override status on failure
1601                 bool                    positive;
1602         } cases[] =
1603         {
1604                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    true },
1605                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  false },        // see below
1606         };
1607         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1608
1609         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1610         {
1611                 const CaseParams&       params          = cases[caseNdx];
1612                 ComputeShaderSpec       spec;
1613                 vector<deInt64>         inputInts1      (numElements, 0);
1614                 vector<deInt64>         inputInts2      (numElements, 0);
1615                 vector<deInt64>         outputInts      (numElements, 0);
1616
1617                 if (params.positive)
1618                 {
1619                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements, filterNonNegative);
1620                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterPositive);
1621                 }
1622                 else
1623                 {
1624                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements);
1625                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterNotZero);
1626                 }
1627
1628                 for (int ndx = 0; ndx < numElements; ++ndx)
1629                 {
1630                         // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1631                         outputInts[ndx] = inputInts1[ndx] % inputInts2[ndx];
1632                 }
1633
1634                 spec.assembly =
1635                         "OpCapability Int64\n"
1636
1637                         + string(getComputeAsmShaderPreamble()) +
1638
1639                         "OpName %main           \"main\"\n"
1640                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1641
1642                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1643
1644                         "OpDecorate %buf BufferBlock\n"
1645                         "OpDecorate %indata1 DescriptorSet 0\n"
1646                         "OpDecorate %indata1 Binding 0\n"
1647                         "OpDecorate %indata2 DescriptorSet 0\n"
1648                         "OpDecorate %indata2 Binding 1\n"
1649                         "OpDecorate %outdata DescriptorSet 0\n"
1650                         "OpDecorate %outdata Binding 2\n"
1651                         "OpDecorate %i64arr ArrayStride 8\n"
1652                         "OpMemberDecorate %buf 0 Offset 0\n"
1653
1654                         + string(getComputeAsmCommonTypes())
1655                         + string(getComputeAsmCommonInt64Types()) +
1656
1657                         "%buf        = OpTypeStruct %i64arr\n"
1658                         "%bufptr     = OpTypePointer Uniform %buf\n"
1659                         "%indata1    = OpVariable %bufptr Uniform\n"
1660                         "%indata2    = OpVariable %bufptr Uniform\n"
1661                         "%outdata    = OpVariable %bufptr Uniform\n"
1662
1663                         "%id        = OpVariable %uvec3ptr Input\n"
1664                         "%zero      = OpConstant %i64 0\n"
1665
1666                         "%main      = OpFunction %void None %voidf\n"
1667                         "%label     = OpLabel\n"
1668                         "%idval     = OpLoad %uvec3 %id\n"
1669                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1670                         "%inloc1    = OpAccessChain %i64ptr %indata1 %zero %x\n"
1671                         "%inval1    = OpLoad %i64 %inloc1\n"
1672                         "%inloc2    = OpAccessChain %i64ptr %indata2 %zero %x\n"
1673                         "%inval2    = OpLoad %i64 %inloc2\n"
1674                         "%rem       = OpSRem %i64 %inval1 %inval2\n"
1675                         "%outloc    = OpAccessChain %i64ptr %outdata %zero %x\n"
1676                         "             OpStore %outloc %rem\n"
1677                         "             OpReturn\n"
1678                         "             OpFunctionEnd\n";
1679
1680                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts1)));
1681                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts2)));
1682                 spec.outputs.push_back  (BufferSp(new Int64Buffer(outputInts)));
1683                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1684                 spec.failResult                 = params.failResult;
1685                 spec.failMessage                = params.failMessage;
1686
1687                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec, COMPUTE_TEST_USES_INT64));
1688         }
1689
1690         return group.release();
1691 }
1692
1693 tcu::TestCaseGroup* createOpSModComputeGroup (tcu::TestContext& testCtx, qpTestResult negFailResult)
1694 {
1695         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsmod", "Test the OpSMod instruction"));
1696         de::Random                                              rnd                             (deStringHash(group->getName()));
1697         const int                                               numElements             = 200;
1698
1699         const struct CaseParams
1700         {
1701                 const char*             name;
1702                 const char*             failMessage;            // customized status message
1703                 qpTestResult    failResult;                     // override status on failure
1704                 int                             op1Min, op1Max;         // operand ranges
1705                 int                             op2Min, op2Max;
1706         } cases[] =
1707         {
1708                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    0,              65536,  0,              100 },
1709                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  -65536, 65536,  -100,   100 },  // see below
1710         };
1711         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1712
1713         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1714         {
1715                 const CaseParams&       params          = cases[caseNdx];
1716
1717                 ComputeShaderSpec       spec;
1718                 vector<deInt32>         inputInts1      (numElements, 0);
1719                 vector<deInt32>         inputInts2      (numElements, 0);
1720                 vector<deInt32>         outputInts      (numElements, 0);
1721
1722                 fillRandomScalars(rnd, params.op1Min, params.op1Max, &inputInts1[0], numElements);
1723                 fillRandomScalars(rnd, params.op2Min, params.op2Max, &inputInts2[0], numElements, filterNotZero);
1724
1725                 for (int ndx = 0; ndx < numElements; ++ndx)
1726                 {
1727                         deInt32 rem = inputInts1[ndx] % inputInts2[ndx];
1728                         if (rem == 0)
1729                         {
1730                                 outputInts[ndx] = 0;
1731                         }
1732                         else if ((inputInts1[ndx] >= 0) == (inputInts2[ndx] >= 0))
1733                         {
1734                                 // They have the same sign
1735                                 outputInts[ndx] = rem;
1736                         }
1737                         else
1738                         {
1739                                 // They have opposite sign.  The remainder operation takes the
1740                                 // sign inputInts1[ndx] but OpSMod is supposed to take ths sign
1741                                 // of inputInts2[ndx].  Adding inputInts2[ndx] will ensure that
1742                                 // the result has the correct sign and that it is still
1743                                 // congruent to inputInts1[ndx] modulo inputInts2[ndx]
1744                                 //
1745                                 // See also http://mathforum.org/library/drmath/view/52343.html
1746                                 outputInts[ndx] = rem + inputInts2[ndx];
1747                         }
1748                 }
1749
1750                 spec.assembly =
1751                         string(getComputeAsmShaderPreamble()) +
1752
1753                         "OpName %main           \"main\"\n"
1754                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1755
1756                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1757
1758                         "OpDecorate %buf BufferBlock\n"
1759                         "OpDecorate %indata1 DescriptorSet 0\n"
1760                         "OpDecorate %indata1 Binding 0\n"
1761                         "OpDecorate %indata2 DescriptorSet 0\n"
1762                         "OpDecorate %indata2 Binding 1\n"
1763                         "OpDecorate %outdata DescriptorSet 0\n"
1764                         "OpDecorate %outdata Binding 2\n"
1765                         "OpDecorate %i32arr ArrayStride 4\n"
1766                         "OpMemberDecorate %buf 0 Offset 0\n"
1767
1768                         + string(getComputeAsmCommonTypes()) +
1769
1770                         "%buf        = OpTypeStruct %i32arr\n"
1771                         "%bufptr     = OpTypePointer Uniform %buf\n"
1772                         "%indata1    = OpVariable %bufptr Uniform\n"
1773                         "%indata2    = OpVariable %bufptr Uniform\n"
1774                         "%outdata    = OpVariable %bufptr Uniform\n"
1775
1776                         "%id        = OpVariable %uvec3ptr Input\n"
1777                         "%zero      = OpConstant %i32 0\n"
1778
1779                         "%main      = OpFunction %void None %voidf\n"
1780                         "%label     = OpLabel\n"
1781                         "%idval     = OpLoad %uvec3 %id\n"
1782                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1783                         "%inloc1    = OpAccessChain %i32ptr %indata1 %zero %x\n"
1784                         "%inval1    = OpLoad %i32 %inloc1\n"
1785                         "%inloc2    = OpAccessChain %i32ptr %indata2 %zero %x\n"
1786                         "%inval2    = OpLoad %i32 %inloc2\n"
1787                         "%rem       = OpSMod %i32 %inval1 %inval2\n"
1788                         "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
1789                         "             OpStore %outloc %rem\n"
1790                         "             OpReturn\n"
1791                         "             OpFunctionEnd\n";
1792
1793                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts1)));
1794                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts2)));
1795                 spec.outputs.push_back  (BufferSp(new Int32Buffer(outputInts)));
1796                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1797                 spec.failResult                 = params.failResult;
1798                 spec.failMessage                = params.failMessage;
1799
1800                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1801         }
1802
1803         return group.release();
1804 }
1805
1806 tcu::TestCaseGroup* createOpSModComputeGroup64 (tcu::TestContext& testCtx, qpTestResult negFailResult)
1807 {
1808         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsmod64", "Test the OpSMod instruction"));
1809         de::Random                                              rnd                             (deStringHash(group->getName()));
1810         const int                                               numElements             = 200;
1811
1812         const struct CaseParams
1813         {
1814                 const char*             name;
1815                 const char*             failMessage;            // customized status message
1816                 qpTestResult    failResult;                     // override status on failure
1817                 bool                    positive;
1818         } cases[] =
1819         {
1820                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    true },
1821                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  false },        // see below
1822         };
1823         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1824
1825         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1826         {
1827                 const CaseParams&       params          = cases[caseNdx];
1828
1829                 ComputeShaderSpec       spec;
1830                 vector<deInt64>         inputInts1      (numElements, 0);
1831                 vector<deInt64>         inputInts2      (numElements, 0);
1832                 vector<deInt64>         outputInts      (numElements, 0);
1833
1834
1835                 if (params.positive)
1836                 {
1837                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements, filterNonNegative);
1838                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterPositive);
1839                 }
1840                 else
1841                 {
1842                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements);
1843                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterNotZero);
1844                 }
1845
1846                 for (int ndx = 0; ndx < numElements; ++ndx)
1847                 {
1848                         deInt64 rem = inputInts1[ndx] % inputInts2[ndx];
1849                         if (rem == 0)
1850                         {
1851                                 outputInts[ndx] = 0;
1852                         }
1853                         else if ((inputInts1[ndx] >= 0) == (inputInts2[ndx] >= 0))
1854                         {
1855                                 // They have the same sign
1856                                 outputInts[ndx] = rem;
1857                         }
1858                         else
1859                         {
1860                                 // They have opposite sign.  The remainder operation takes the
1861                                 // sign inputInts1[ndx] but OpSMod is supposed to take ths sign
1862                                 // of inputInts2[ndx].  Adding inputInts2[ndx] will ensure that
1863                                 // the result has the correct sign and that it is still
1864                                 // congruent to inputInts1[ndx] modulo inputInts2[ndx]
1865                                 //
1866                                 // See also http://mathforum.org/library/drmath/view/52343.html
1867                                 outputInts[ndx] = rem + inputInts2[ndx];
1868                         }
1869                 }
1870
1871                 spec.assembly =
1872                         "OpCapability Int64\n"
1873
1874                         + string(getComputeAsmShaderPreamble()) +
1875
1876                         "OpName %main           \"main\"\n"
1877                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1878
1879                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1880
1881                         "OpDecorate %buf BufferBlock\n"
1882                         "OpDecorate %indata1 DescriptorSet 0\n"
1883                         "OpDecorate %indata1 Binding 0\n"
1884                         "OpDecorate %indata2 DescriptorSet 0\n"
1885                         "OpDecorate %indata2 Binding 1\n"
1886                         "OpDecorate %outdata DescriptorSet 0\n"
1887                         "OpDecorate %outdata Binding 2\n"
1888                         "OpDecorate %i64arr ArrayStride 8\n"
1889                         "OpMemberDecorate %buf 0 Offset 0\n"
1890
1891                         + string(getComputeAsmCommonTypes())
1892                         + string(getComputeAsmCommonInt64Types()) +
1893
1894                         "%buf        = OpTypeStruct %i64arr\n"
1895                         "%bufptr     = OpTypePointer Uniform %buf\n"
1896                         "%indata1    = OpVariable %bufptr Uniform\n"
1897                         "%indata2    = OpVariable %bufptr Uniform\n"
1898                         "%outdata    = OpVariable %bufptr Uniform\n"
1899
1900                         "%id        = OpVariable %uvec3ptr Input\n"
1901                         "%zero      = OpConstant %i64 0\n"
1902
1903                         "%main      = OpFunction %void None %voidf\n"
1904                         "%label     = OpLabel\n"
1905                         "%idval     = OpLoad %uvec3 %id\n"
1906                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1907                         "%inloc1    = OpAccessChain %i64ptr %indata1 %zero %x\n"
1908                         "%inval1    = OpLoad %i64 %inloc1\n"
1909                         "%inloc2    = OpAccessChain %i64ptr %indata2 %zero %x\n"
1910                         "%inval2    = OpLoad %i64 %inloc2\n"
1911                         "%rem       = OpSMod %i64 %inval1 %inval2\n"
1912                         "%outloc    = OpAccessChain %i64ptr %outdata %zero %x\n"
1913                         "             OpStore %outloc %rem\n"
1914                         "             OpReturn\n"
1915                         "             OpFunctionEnd\n";
1916
1917                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts1)));
1918                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts2)));
1919                 spec.outputs.push_back  (BufferSp(new Int64Buffer(outputInts)));
1920                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1921                 spec.failResult                 = params.failResult;
1922                 spec.failMessage                = params.failMessage;
1923
1924                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec, COMPUTE_TEST_USES_INT64));
1925         }
1926
1927         return group.release();
1928 }
1929
1930 // Copy contents in the input buffer to the output buffer.
1931 tcu::TestCaseGroup* createOpCopyMemoryGroup (tcu::TestContext& testCtx)
1932 {
1933         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opcopymemory", "Test the OpCopyMemory instruction"));
1934         de::Random                                              rnd                             (deStringHash(group->getName()));
1935         const int                                               numElements             = 100;
1936
1937         // 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.
1938         ComputeShaderSpec                               spec1;
1939         vector<Vec4>                                    inputFloats1    (numElements);
1940         vector<Vec4>                                    outputFloats1   (numElements);
1941
1942         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats1[0], numElements * 4);
1943
1944         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
1945         floorAll(inputFloats1);
1946
1947         for (size_t ndx = 0; ndx < numElements; ++ndx)
1948                 outputFloats1[ndx] = inputFloats1[ndx] + Vec4(0.f, 0.5f, 1.5f, 2.5f);
1949
1950         spec1.assembly =
1951                 string(getComputeAsmShaderPreamble()) +
1952
1953                 "OpName %main           \"main\"\n"
1954                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1955
1956                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1957                 "OpDecorate %vec4arr ArrayStride 16\n"
1958
1959                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
1960
1961                 "%vec4       = OpTypeVector %f32 4\n"
1962                 "%vec4ptr_u  = OpTypePointer Uniform %vec4\n"
1963                 "%vec4ptr_f  = OpTypePointer Function %vec4\n"
1964                 "%vec4arr    = OpTypeRuntimeArray %vec4\n"
1965                 "%buf        = OpTypeStruct %vec4arr\n"
1966                 "%bufptr     = OpTypePointer Uniform %buf\n"
1967                 "%indata     = OpVariable %bufptr Uniform\n"
1968                 "%outdata    = OpVariable %bufptr Uniform\n"
1969
1970                 "%id         = OpVariable %uvec3ptr Input\n"
1971                 "%zero       = OpConstant %i32 0\n"
1972                 "%c_f_0      = OpConstant %f32 0.\n"
1973                 "%c_f_0_5    = OpConstant %f32 0.5\n"
1974                 "%c_f_1_5    = OpConstant %f32 1.5\n"
1975                 "%c_f_2_5    = OpConstant %f32 2.5\n"
1976                 "%c_vec4     = OpConstantComposite %vec4 %c_f_0 %c_f_0_5 %c_f_1_5 %c_f_2_5\n"
1977
1978                 "%main       = OpFunction %void None %voidf\n"
1979                 "%label      = OpLabel\n"
1980                 "%v_vec4     = OpVariable %vec4ptr_f Function\n"
1981                 "%idval      = OpLoad %uvec3 %id\n"
1982                 "%x          = OpCompositeExtract %u32 %idval 0\n"
1983                 "%inloc      = OpAccessChain %vec4ptr_u %indata %zero %x\n"
1984                 "%outloc     = OpAccessChain %vec4ptr_u %outdata %zero %x\n"
1985                 "              OpCopyMemory %v_vec4 %inloc\n"
1986                 "%v_vec4_val = OpLoad %vec4 %v_vec4\n"
1987                 "%add        = OpFAdd %vec4 %v_vec4_val %c_vec4\n"
1988                 "              OpStore %outloc %add\n"
1989                 "              OpReturn\n"
1990                 "              OpFunctionEnd\n";
1991
1992         spec1.inputs.push_back(BufferSp(new Vec4Buffer(inputFloats1)));
1993         spec1.outputs.push_back(BufferSp(new Vec4Buffer(outputFloats1)));
1994         spec1.numWorkGroups = IVec3(numElements, 1, 1);
1995
1996         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector", "OpCopyMemory elements of vector type", spec1));
1997
1998         // The following case copies a float[100] variable from the input buffer to the output buffer.
1999         ComputeShaderSpec                               spec2;
2000         vector<float>                                   inputFloats2    (numElements);
2001         vector<float>                                   outputFloats2   (numElements);
2002
2003         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats2[0], numElements);
2004
2005         for (size_t ndx = 0; ndx < numElements; ++ndx)
2006                 outputFloats2[ndx] = inputFloats2[ndx];
2007
2008         spec2.assembly =
2009                 string(getComputeAsmShaderPreamble()) +
2010
2011                 "OpName %main           \"main\"\n"
2012                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2013
2014                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2015                 "OpDecorate %f32arr100 ArrayStride 4\n"
2016
2017                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2018
2019                 "%hundred        = OpConstant %u32 100\n"
2020                 "%f32arr100      = OpTypeArray %f32 %hundred\n"
2021                 "%f32arr100ptr_f = OpTypePointer Function %f32arr100\n"
2022                 "%f32arr100ptr_u = OpTypePointer Uniform %f32arr100\n"
2023                 "%buf            = OpTypeStruct %f32arr100\n"
2024                 "%bufptr         = OpTypePointer Uniform %buf\n"
2025                 "%indata         = OpVariable %bufptr Uniform\n"
2026                 "%outdata        = OpVariable %bufptr Uniform\n"
2027
2028                 "%id             = OpVariable %uvec3ptr Input\n"
2029                 "%zero           = OpConstant %i32 0\n"
2030
2031                 "%main           = OpFunction %void None %voidf\n"
2032                 "%label          = OpLabel\n"
2033                 "%var            = OpVariable %f32arr100ptr_f Function\n"
2034                 "%inarr          = OpAccessChain %f32arr100ptr_u %indata %zero\n"
2035                 "%outarr         = OpAccessChain %f32arr100ptr_u %outdata %zero\n"
2036                 "                  OpCopyMemory %var %inarr\n"
2037                 "                  OpCopyMemory %outarr %var\n"
2038                 "                  OpReturn\n"
2039                 "                  OpFunctionEnd\n";
2040
2041         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
2042         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
2043         spec2.numWorkGroups = IVec3(1, 1, 1);
2044
2045         group->addChild(new SpvAsmComputeShaderCase(testCtx, "array", "OpCopyMemory elements of array type", spec2));
2046
2047         // The following case copies a struct{vec4, vec4, vec4, vec4} variable from the input buffer to the output buffer.
2048         ComputeShaderSpec                               spec3;
2049         vector<float>                                   inputFloats3    (16);
2050         vector<float>                                   outputFloats3   (16);
2051
2052         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats3[0], 16);
2053
2054         for (size_t ndx = 0; ndx < 16; ++ndx)
2055                 outputFloats3[ndx] = inputFloats3[ndx];
2056
2057         spec3.assembly =
2058                 string(getComputeAsmShaderPreamble()) +
2059
2060                 "OpName %main           \"main\"\n"
2061                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2062
2063                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2064                 "OpMemberDecorate %buf 0 Offset 0\n"
2065                 "OpMemberDecorate %buf 1 Offset 16\n"
2066                 "OpMemberDecorate %buf 2 Offset 32\n"
2067                 "OpMemberDecorate %buf 3 Offset 48\n"
2068
2069                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2070
2071                 "%vec4      = OpTypeVector %f32 4\n"
2072                 "%buf       = OpTypeStruct %vec4 %vec4 %vec4 %vec4\n"
2073                 "%bufptr    = OpTypePointer Uniform %buf\n"
2074                 "%indata    = OpVariable %bufptr Uniform\n"
2075                 "%outdata   = OpVariable %bufptr Uniform\n"
2076                 "%vec4stptr = OpTypePointer Function %buf\n"
2077
2078                 "%id        = OpVariable %uvec3ptr Input\n"
2079                 "%zero      = OpConstant %i32 0\n"
2080
2081                 "%main      = OpFunction %void None %voidf\n"
2082                 "%label     = OpLabel\n"
2083                 "%var       = OpVariable %vec4stptr Function\n"
2084                 "             OpCopyMemory %var %indata\n"
2085                 "             OpCopyMemory %outdata %var\n"
2086                 "             OpReturn\n"
2087                 "             OpFunctionEnd\n";
2088
2089         spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
2090         spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
2091         spec3.numWorkGroups = IVec3(1, 1, 1);
2092
2093         group->addChild(new SpvAsmComputeShaderCase(testCtx, "struct", "OpCopyMemory elements of struct type", spec3));
2094
2095         // The following case negates multiple float variables from the input buffer and stores the results to the output buffer.
2096         ComputeShaderSpec                               spec4;
2097         vector<float>                                   inputFloats4    (numElements);
2098         vector<float>                                   outputFloats4   (numElements);
2099
2100         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats4[0], numElements);
2101
2102         for (size_t ndx = 0; ndx < numElements; ++ndx)
2103                 outputFloats4[ndx] = -inputFloats4[ndx];
2104
2105         spec4.assembly =
2106                 string(getComputeAsmShaderPreamble()) +
2107
2108                 "OpName %main           \"main\"\n"
2109                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2110
2111                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2112
2113                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2114
2115                 "%f32ptr_f  = OpTypePointer Function %f32\n"
2116                 "%id        = OpVariable %uvec3ptr Input\n"
2117                 "%zero      = OpConstant %i32 0\n"
2118
2119                 "%main      = OpFunction %void None %voidf\n"
2120                 "%label     = OpLabel\n"
2121                 "%var       = OpVariable %f32ptr_f Function\n"
2122                 "%idval     = OpLoad %uvec3 %id\n"
2123                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2124                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
2125                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
2126                 "             OpCopyMemory %var %inloc\n"
2127                 "%val       = OpLoad %f32 %var\n"
2128                 "%neg       = OpFNegate %f32 %val\n"
2129                 "             OpStore %outloc %neg\n"
2130                 "             OpReturn\n"
2131                 "             OpFunctionEnd\n";
2132
2133         spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
2134         spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
2135         spec4.numWorkGroups = IVec3(numElements, 1, 1);
2136
2137         group->addChild(new SpvAsmComputeShaderCase(testCtx, "float", "OpCopyMemory elements of float type", spec4));
2138
2139         return group.release();
2140 }
2141
2142 tcu::TestCaseGroup* createOpCopyObjectGroup (tcu::TestContext& testCtx)
2143 {
2144         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opcopyobject", "Test the OpCopyObject instruction"));
2145         ComputeShaderSpec                               spec;
2146         de::Random                                              rnd                             (deStringHash(group->getName()));
2147         const int                                               numElements             = 100;
2148         vector<float>                                   inputFloats             (numElements, 0);
2149         vector<float>                                   outputFloats    (numElements, 0);
2150
2151         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
2152
2153         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2154         floorAll(inputFloats);
2155
2156         for (size_t ndx = 0; ndx < numElements; ++ndx)
2157                 outputFloats[ndx] = inputFloats[ndx] + 7.5f;
2158
2159         spec.assembly =
2160                 string(getComputeAsmShaderPreamble()) +
2161
2162                 "OpName %main           \"main\"\n"
2163                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2164
2165                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2166
2167                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2168
2169                 "%fmat     = OpTypeMatrix %fvec3 3\n"
2170                 "%three    = OpConstant %u32 3\n"
2171                 "%farr     = OpTypeArray %f32 %three\n"
2172                 "%fst      = OpTypeStruct %f32 %f32\n"
2173
2174                 + string(getComputeAsmInputOutputBuffer()) +
2175
2176                 "%id            = OpVariable %uvec3ptr Input\n"
2177                 "%zero          = OpConstant %i32 0\n"
2178                 "%c_f           = OpConstant %f32 1.5\n"
2179                 "%c_fvec3       = OpConstantComposite %fvec3 %c_f %c_f %c_f\n"
2180                 "%c_fmat        = OpConstantComposite %fmat %c_fvec3 %c_fvec3 %c_fvec3\n"
2181                 "%c_farr        = OpConstantComposite %farr %c_f %c_f %c_f\n"
2182                 "%c_fst         = OpConstantComposite %fst %c_f %c_f\n"
2183
2184                 "%main          = OpFunction %void None %voidf\n"
2185                 "%label         = OpLabel\n"
2186                 "%c_f_copy      = OpCopyObject %f32   %c_f\n"
2187                 "%c_fvec3_copy  = OpCopyObject %fvec3 %c_fvec3\n"
2188                 "%c_fmat_copy   = OpCopyObject %fmat  %c_fmat\n"
2189                 "%c_farr_copy   = OpCopyObject %farr  %c_farr\n"
2190                 "%c_fst_copy    = OpCopyObject %fst   %c_fst\n"
2191                 "%fvec3_elem    = OpCompositeExtract %f32 %c_fvec3_copy 0\n"
2192                 "%fmat_elem     = OpCompositeExtract %f32 %c_fmat_copy 1 2\n"
2193                 "%farr_elem     = OpCompositeExtract %f32 %c_farr_copy 2\n"
2194                 "%fst_elem      = OpCompositeExtract %f32 %c_fst_copy 1\n"
2195                 // Add up. 1.5 * 5 = 7.5.
2196                 "%add1          = OpFAdd %f32 %c_f_copy %fvec3_elem\n"
2197                 "%add2          = OpFAdd %f32 %add1     %fmat_elem\n"
2198                 "%add3          = OpFAdd %f32 %add2     %farr_elem\n"
2199                 "%add4          = OpFAdd %f32 %add3     %fst_elem\n"
2200
2201                 "%idval         = OpLoad %uvec3 %id\n"
2202                 "%x             = OpCompositeExtract %u32 %idval 0\n"
2203                 "%inloc         = OpAccessChain %f32ptr %indata %zero %x\n"
2204                 "%outloc        = OpAccessChain %f32ptr %outdata %zero %x\n"
2205                 "%inval         = OpLoad %f32 %inloc\n"
2206                 "%add           = OpFAdd %f32 %add4 %inval\n"
2207                 "                 OpStore %outloc %add\n"
2208                 "                 OpReturn\n"
2209                 "                 OpFunctionEnd\n";
2210         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2211         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2212         spec.numWorkGroups = IVec3(numElements, 1, 1);
2213
2214         group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "OpCopyObject on different types", spec));
2215
2216         return group.release();
2217 }
2218 // Assembly code used for testing OpUnreachable is based on GLSL source code:
2219 //
2220 // #version 430
2221 //
2222 // layout(std140, set = 0, binding = 0) readonly buffer Input {
2223 //   float elements[];
2224 // } input_data;
2225 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
2226 //   float elements[];
2227 // } output_data;
2228 //
2229 // void not_called_func() {
2230 //   // place OpUnreachable here
2231 // }
2232 //
2233 // uint modulo4(uint val) {
2234 //   switch (val % uint(4)) {
2235 //     case 0:  return 3;
2236 //     case 1:  return 2;
2237 //     case 2:  return 1;
2238 //     case 3:  return 0;
2239 //     default: return 100; // place OpUnreachable here
2240 //   }
2241 // }
2242 //
2243 // uint const5() {
2244 //   return 5;
2245 //   // place OpUnreachable here
2246 // }
2247 //
2248 // void main() {
2249 //   uint x = gl_GlobalInvocationID.x;
2250 //   if (const5() > modulo4(1000)) {
2251 //     output_data.elements[x] = -input_data.elements[x];
2252 //   } else {
2253 //     // place OpUnreachable here
2254 //     output_data.elements[x] = input_data.elements[x];
2255 //   }
2256 // }
2257
2258 tcu::TestCaseGroup* createOpUnreachableGroup (tcu::TestContext& testCtx)
2259 {
2260         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opunreachable", "Test the OpUnreachable instruction"));
2261         ComputeShaderSpec                               spec;
2262         de::Random                                              rnd                             (deStringHash(group->getName()));
2263         const int                                               numElements             = 100;
2264         vector<float>                                   positiveFloats  (numElements, 0);
2265         vector<float>                                   negativeFloats  (numElements, 0);
2266
2267         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
2268
2269         for (size_t ndx = 0; ndx < numElements; ++ndx)
2270                 negativeFloats[ndx] = -positiveFloats[ndx];
2271
2272         spec.assembly =
2273                 string(getComputeAsmShaderPreamble()) +
2274
2275                 "OpSource GLSL 430\n"
2276                 "OpName %main            \"main\"\n"
2277                 "OpName %func_not_called_func \"not_called_func(\"\n"
2278                 "OpName %func_modulo4         \"modulo4(u1;\"\n"
2279                 "OpName %func_const5          \"const5(\"\n"
2280                 "OpName %id                   \"gl_GlobalInvocationID\"\n"
2281
2282                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2283
2284                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2285
2286                 "%u32ptr    = OpTypePointer Function %u32\n"
2287                 "%uintfuint = OpTypeFunction %u32 %u32ptr\n"
2288                 "%unitf     = OpTypeFunction %u32\n"
2289
2290                 "%id        = OpVariable %uvec3ptr Input\n"
2291                 "%zero      = OpConstant %u32 0\n"
2292                 "%one       = OpConstant %u32 1\n"
2293                 "%two       = OpConstant %u32 2\n"
2294                 "%three     = OpConstant %u32 3\n"
2295                 "%four      = OpConstant %u32 4\n"
2296                 "%five      = OpConstant %u32 5\n"
2297                 "%hundred   = OpConstant %u32 100\n"
2298                 "%thousand  = OpConstant %u32 1000\n"
2299
2300                 + string(getComputeAsmInputOutputBuffer()) +
2301
2302                 // Main()
2303                 "%main   = OpFunction %void None %voidf\n"
2304                 "%main_entry  = OpLabel\n"
2305                 "%v_thousand  = OpVariable %u32ptr Function %thousand\n"
2306                 "%idval       = OpLoad %uvec3 %id\n"
2307                 "%x           = OpCompositeExtract %u32 %idval 0\n"
2308                 "%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
2309                 "%inval       = OpLoad %f32 %inloc\n"
2310                 "%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
2311                 "%ret_const5  = OpFunctionCall %u32 %func_const5\n"
2312                 "%ret_modulo4 = OpFunctionCall %u32 %func_modulo4 %v_thousand\n"
2313                 "%cmp_gt      = OpUGreaterThan %bool %ret_const5 %ret_modulo4\n"
2314                 "               OpSelectionMerge %if_end None\n"
2315                 "               OpBranchConditional %cmp_gt %if_true %if_false\n"
2316                 "%if_true     = OpLabel\n"
2317                 "%negate      = OpFNegate %f32 %inval\n"
2318                 "               OpStore %outloc %negate\n"
2319                 "               OpBranch %if_end\n"
2320                 "%if_false    = OpLabel\n"
2321                 "               OpUnreachable\n" // Unreachable else branch for if statement
2322                 "%if_end      = OpLabel\n"
2323                 "               OpReturn\n"
2324                 "               OpFunctionEnd\n"
2325
2326                 // not_called_function()
2327                 "%func_not_called_func  = OpFunction %void None %voidf\n"
2328                 "%not_called_func_entry = OpLabel\n"
2329                 "                         OpUnreachable\n" // Unreachable entry block in not called static function
2330                 "                         OpFunctionEnd\n"
2331
2332                 // modulo4()
2333                 "%func_modulo4  = OpFunction %u32 None %uintfuint\n"
2334                 "%valptr        = OpFunctionParameter %u32ptr\n"
2335                 "%modulo4_entry = OpLabel\n"
2336                 "%val           = OpLoad %u32 %valptr\n"
2337                 "%modulo        = OpUMod %u32 %val %four\n"
2338                 "                 OpSelectionMerge %switch_merge None\n"
2339                 "                 OpSwitch %modulo %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
2340                 "%case0         = OpLabel\n"
2341                 "                 OpReturnValue %three\n"
2342                 "%case1         = OpLabel\n"
2343                 "                 OpReturnValue %two\n"
2344                 "%case2         = OpLabel\n"
2345                 "                 OpReturnValue %one\n"
2346                 "%case3         = OpLabel\n"
2347                 "                 OpReturnValue %zero\n"
2348                 "%default       = OpLabel\n"
2349                 "                 OpUnreachable\n" // Unreachable default case for switch statement
2350                 "%switch_merge  = OpLabel\n"
2351                 "                 OpUnreachable\n" // Unreachable merge block for switch statement
2352                 "                 OpFunctionEnd\n"
2353
2354                 // const5()
2355                 "%func_const5  = OpFunction %u32 None %unitf\n"
2356                 "%const5_entry = OpLabel\n"
2357                 "                OpReturnValue %five\n"
2358                 "%unreachable  = OpLabel\n"
2359                 "                OpUnreachable\n" // Unreachable block in function
2360                 "                OpFunctionEnd\n";
2361         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
2362         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
2363         spec.numWorkGroups = IVec3(numElements, 1, 1);
2364
2365         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpUnreachable appearing at different places", spec));
2366
2367         return group.release();
2368 }
2369
2370 // Assembly code used for testing decoration group is based on GLSL source code:
2371 //
2372 // #version 430
2373 //
2374 // layout(std140, set = 0, binding = 0) readonly buffer Input0 {
2375 //   float elements[];
2376 // } input_data0;
2377 // layout(std140, set = 0, binding = 1) readonly buffer Input1 {
2378 //   float elements[];
2379 // } input_data1;
2380 // layout(std140, set = 0, binding = 2) readonly buffer Input2 {
2381 //   float elements[];
2382 // } input_data2;
2383 // layout(std140, set = 0, binding = 3) readonly buffer Input3 {
2384 //   float elements[];
2385 // } input_data3;
2386 // layout(std140, set = 0, binding = 4) readonly buffer Input4 {
2387 //   float elements[];
2388 // } input_data4;
2389 // layout(std140, set = 0, binding = 5) writeonly buffer Output {
2390 //   float elements[];
2391 // } output_data;
2392 //
2393 // void main() {
2394 //   uint x = gl_GlobalInvocationID.x;
2395 //   output_data.elements[x] = input_data0.elements[x] + input_data1.elements[x] + input_data2.elements[x] + input_data3.elements[x] + input_data4.elements[x];
2396 // }
2397 tcu::TestCaseGroup* createDecorationGroupGroup (tcu::TestContext& testCtx)
2398 {
2399         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "decoration_group", "Test the OpDecorationGroup & OpGroupDecorate instruction"));
2400         ComputeShaderSpec                               spec;
2401         de::Random                                              rnd                             (deStringHash(group->getName()));
2402         const int                                               numElements             = 100;
2403         vector<float>                                   inputFloats0    (numElements, 0);
2404         vector<float>                                   inputFloats1    (numElements, 0);
2405         vector<float>                                   inputFloats2    (numElements, 0);
2406         vector<float>                                   inputFloats3    (numElements, 0);
2407         vector<float>                                   inputFloats4    (numElements, 0);
2408         vector<float>                                   outputFloats    (numElements, 0);
2409
2410         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats0[0], numElements);
2411         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats1[0], numElements);
2412         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats2[0], numElements);
2413         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats3[0], numElements);
2414         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats4[0], numElements);
2415
2416         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2417         floorAll(inputFloats0);
2418         floorAll(inputFloats1);
2419         floorAll(inputFloats2);
2420         floorAll(inputFloats3);
2421         floorAll(inputFloats4);
2422
2423         for (size_t ndx = 0; ndx < numElements; ++ndx)
2424                 outputFloats[ndx] = inputFloats0[ndx] + inputFloats1[ndx] + inputFloats2[ndx] + inputFloats3[ndx] + inputFloats4[ndx];
2425
2426         spec.assembly =
2427                 string(getComputeAsmShaderPreamble()) +
2428
2429                 "OpSource GLSL 430\n"
2430                 "OpName %main \"main\"\n"
2431                 "OpName %id \"gl_GlobalInvocationID\"\n"
2432
2433                 // Not using group decoration on variable.
2434                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2435                 // Not using group decoration on type.
2436                 "OpDecorate %f32arr ArrayStride 4\n"
2437
2438                 "OpDecorate %groups BufferBlock\n"
2439                 "OpDecorate %groupm Offset 0\n"
2440                 "%groups = OpDecorationGroup\n"
2441                 "%groupm = OpDecorationGroup\n"
2442
2443                 // Group decoration on multiple structs.
2444                 "OpGroupDecorate %groups %outbuf %inbuf0 %inbuf1 %inbuf2 %inbuf3 %inbuf4\n"
2445                 // Group decoration on multiple struct members.
2446                 "OpGroupMemberDecorate %groupm %outbuf 0 %inbuf0 0 %inbuf1 0 %inbuf2 0 %inbuf3 0 %inbuf4 0\n"
2447
2448                 "OpDecorate %group1 DescriptorSet 0\n"
2449                 "OpDecorate %group3 DescriptorSet 0\n"
2450                 "OpDecorate %group3 NonWritable\n"
2451                 "OpDecorate %group3 Restrict\n"
2452                 "%group0 = OpDecorationGroup\n"
2453                 "%group1 = OpDecorationGroup\n"
2454                 "%group3 = OpDecorationGroup\n"
2455
2456                 // Applying the same decoration group multiple times.
2457                 "OpGroupDecorate %group1 %outdata\n"
2458                 "OpGroupDecorate %group1 %outdata\n"
2459                 "OpGroupDecorate %group1 %outdata\n"
2460                 "OpDecorate %outdata DescriptorSet 0\n"
2461                 "OpDecorate %outdata Binding 5\n"
2462                 // Applying decoration group containing nothing.
2463                 "OpGroupDecorate %group0 %indata0\n"
2464                 "OpDecorate %indata0 DescriptorSet 0\n"
2465                 "OpDecorate %indata0 Binding 0\n"
2466                 // Applying decoration group containing one decoration.
2467                 "OpGroupDecorate %group1 %indata1\n"
2468                 "OpDecorate %indata1 Binding 1\n"
2469                 // Applying decoration group containing multiple decorations.
2470                 "OpGroupDecorate %group3 %indata2 %indata3\n"
2471                 "OpDecorate %indata2 Binding 2\n"
2472                 "OpDecorate %indata3 Binding 3\n"
2473                 // Applying multiple decoration groups (with overlapping).
2474                 "OpGroupDecorate %group0 %indata4\n"
2475                 "OpGroupDecorate %group1 %indata4\n"
2476                 "OpGroupDecorate %group3 %indata4\n"
2477                 "OpDecorate %indata4 Binding 4\n"
2478
2479                 + string(getComputeAsmCommonTypes()) +
2480
2481                 "%id   = OpVariable %uvec3ptr Input\n"
2482                 "%zero = OpConstant %i32 0\n"
2483
2484                 "%outbuf    = OpTypeStruct %f32arr\n"
2485                 "%outbufptr = OpTypePointer Uniform %outbuf\n"
2486                 "%outdata   = OpVariable %outbufptr Uniform\n"
2487                 "%inbuf0    = OpTypeStruct %f32arr\n"
2488                 "%inbuf0ptr = OpTypePointer Uniform %inbuf0\n"
2489                 "%indata0   = OpVariable %inbuf0ptr Uniform\n"
2490                 "%inbuf1    = OpTypeStruct %f32arr\n"
2491                 "%inbuf1ptr = OpTypePointer Uniform %inbuf1\n"
2492                 "%indata1   = OpVariable %inbuf1ptr Uniform\n"
2493                 "%inbuf2    = OpTypeStruct %f32arr\n"
2494                 "%inbuf2ptr = OpTypePointer Uniform %inbuf2\n"
2495                 "%indata2   = OpVariable %inbuf2ptr Uniform\n"
2496                 "%inbuf3    = OpTypeStruct %f32arr\n"
2497                 "%inbuf3ptr = OpTypePointer Uniform %inbuf3\n"
2498                 "%indata3   = OpVariable %inbuf3ptr Uniform\n"
2499                 "%inbuf4    = OpTypeStruct %f32arr\n"
2500                 "%inbufptr  = OpTypePointer Uniform %inbuf4\n"
2501                 "%indata4   = OpVariable %inbufptr Uniform\n"
2502
2503                 "%main   = OpFunction %void None %voidf\n"
2504                 "%label  = OpLabel\n"
2505                 "%idval  = OpLoad %uvec3 %id\n"
2506                 "%x      = OpCompositeExtract %u32 %idval 0\n"
2507                 "%inloc0 = OpAccessChain %f32ptr %indata0 %zero %x\n"
2508                 "%inloc1 = OpAccessChain %f32ptr %indata1 %zero %x\n"
2509                 "%inloc2 = OpAccessChain %f32ptr %indata2 %zero %x\n"
2510                 "%inloc3 = OpAccessChain %f32ptr %indata3 %zero %x\n"
2511                 "%inloc4 = OpAccessChain %f32ptr %indata4 %zero %x\n"
2512                 "%outloc = OpAccessChain %f32ptr %outdata %zero %x\n"
2513                 "%inval0 = OpLoad %f32 %inloc0\n"
2514                 "%inval1 = OpLoad %f32 %inloc1\n"
2515                 "%inval2 = OpLoad %f32 %inloc2\n"
2516                 "%inval3 = OpLoad %f32 %inloc3\n"
2517                 "%inval4 = OpLoad %f32 %inloc4\n"
2518                 "%add0   = OpFAdd %f32 %inval0 %inval1\n"
2519                 "%add1   = OpFAdd %f32 %add0 %inval2\n"
2520                 "%add2   = OpFAdd %f32 %add1 %inval3\n"
2521                 "%add    = OpFAdd %f32 %add2 %inval4\n"
2522                 "          OpStore %outloc %add\n"
2523                 "          OpReturn\n"
2524                 "          OpFunctionEnd\n";
2525         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats0)));
2526         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
2527         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
2528         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
2529         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
2530         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2531         spec.numWorkGroups = IVec3(numElements, 1, 1);
2532
2533         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "decoration group cases", spec));
2534
2535         return group.release();
2536 }
2537
2538 struct SpecConstantTwoIntCase
2539 {
2540         const char*             caseName;
2541         const char*             scDefinition0;
2542         const char*             scDefinition1;
2543         const char*             scResultType;
2544         const char*             scOperation;
2545         deInt32                 scActualValue0;
2546         deInt32                 scActualValue1;
2547         const char*             resultOperation;
2548         vector<deInt32> expectedOutput;
2549
2550                                         SpecConstantTwoIntCase (const char* name,
2551                                                                                         const char* definition0,
2552                                                                                         const char* definition1,
2553                                                                                         const char* resultType,
2554                                                                                         const char* operation,
2555                                                                                         deInt32 value0,
2556                                                                                         deInt32 value1,
2557                                                                                         const char* resultOp,
2558                                                                                         const vector<deInt32>& output)
2559                                                 : caseName                      (name)
2560                                                 , scDefinition0         (definition0)
2561                                                 , scDefinition1         (definition1)
2562                                                 , scResultType          (resultType)
2563                                                 , scOperation           (operation)
2564                                                 , scActualValue0        (value0)
2565                                                 , scActualValue1        (value1)
2566                                                 , resultOperation       (resultOp)
2567                                                 , expectedOutput        (output) {}
2568 };
2569
2570 tcu::TestCaseGroup* createSpecConstantGroup (tcu::TestContext& testCtx)
2571 {
2572         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
2573         vector<SpecConstantTwoIntCase>  cases;
2574         de::Random                                              rnd                             (deStringHash(group->getName()));
2575         const int                                               numElements             = 100;
2576         vector<deInt32>                                 inputInts               (numElements, 0);
2577         vector<deInt32>                                 outputInts1             (numElements, 0);
2578         vector<deInt32>                                 outputInts2             (numElements, 0);
2579         vector<deInt32>                                 outputInts3             (numElements, 0);
2580         vector<deInt32>                                 outputInts4             (numElements, 0);
2581         const StringTemplate                    shaderTemplate  (
2582                 "${CAPABILITIES:opt}"
2583                 + string(getComputeAsmShaderPreamble()) +
2584
2585                 "OpName %main           \"main\"\n"
2586                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2587
2588                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2589                 "OpDecorate %sc_0  SpecId 0\n"
2590                 "OpDecorate %sc_1  SpecId 1\n"
2591                 "OpDecorate %i32arr ArrayStride 4\n"
2592
2593                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2594
2595                 "${OPTYPE_DEFINITIONS:opt}"
2596                 "%buf     = OpTypeStruct %i32arr\n"
2597                 "%bufptr  = OpTypePointer Uniform %buf\n"
2598                 "%indata    = OpVariable %bufptr Uniform\n"
2599                 "%outdata   = OpVariable %bufptr Uniform\n"
2600
2601                 "%id        = OpVariable %uvec3ptr Input\n"
2602                 "%zero      = OpConstant %i32 0\n"
2603
2604                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
2605                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
2606                 "%sc_final  = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n"
2607
2608                 "%main      = OpFunction %void None %voidf\n"
2609                 "%label     = OpLabel\n"
2610                 "${TYPE_CONVERT:opt}"
2611                 "%idval     = OpLoad %uvec3 %id\n"
2612                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2613                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
2614                 "%inval     = OpLoad %i32 %inloc\n"
2615                 "%final     = ${GEN_RESULT}\n"
2616                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2617                 "             OpStore %outloc %final\n"
2618                 "             OpReturn\n"
2619                 "             OpFunctionEnd\n");
2620
2621         fillRandomScalars(rnd, -65536, 65536, &inputInts[0], numElements);
2622
2623         for (size_t ndx = 0; ndx < numElements; ++ndx)
2624         {
2625                 outputInts1[ndx] = inputInts[ndx] + 42;
2626                 outputInts2[ndx] = inputInts[ndx];
2627                 outputInts3[ndx] = inputInts[ndx] - 11200;
2628                 outputInts4[ndx] = inputInts[ndx] + 1;
2629         }
2630
2631         const char addScToInput[]               = "OpIAdd %i32 %inval %sc_final";
2632         const char addSc32ToInput[]             = "OpIAdd %i32 %inval %sc_final32";
2633         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_final %inval %zero";
2634         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_final %zero %inval";
2635
2636         cases.push_back(SpecConstantTwoIntCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                     62,             -20,    addScToInput,           outputInts1));
2637         cases.push_back(SpecConstantTwoIntCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                     100,    58,             addScToInput,           outputInts1));
2638         cases.push_back(SpecConstantTwoIntCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                     -2,             -21,    addScToInput,           outputInts1));
2639         cases.push_back(SpecConstantTwoIntCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                     -126,   -3,             addScToInput,           outputInts1));
2640         cases.push_back(SpecConstantTwoIntCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                     126,    3,              addScToInput,           outputInts1));
2641         cases.push_back(SpecConstantTwoIntCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
2642         cases.push_back(SpecConstantTwoIntCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
2643         cases.push_back(SpecConstantTwoIntCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                     342,    50,             addScToInput,           outputInts1));
2644         cases.push_back(SpecConstantTwoIntCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                     42,             63,             addScToInput,           outputInts1));
2645         cases.push_back(SpecConstantTwoIntCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                     34,             8,              addScToInput,           outputInts1));
2646         cases.push_back(SpecConstantTwoIntCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                     18,             56,             addScToInput,           outputInts1));
2647         cases.push_back(SpecConstantTwoIntCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
2648         cases.push_back(SpecConstantTwoIntCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
2649         cases.push_back(SpecConstantTwoIntCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                     21,             1,              addScToInput,           outputInts1));
2650         cases.push_back(SpecConstantTwoIntCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                     -20,    -10,    selectTrueUsingSc,      outputInts2));
2651         cases.push_back(SpecConstantTwoIntCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                     10,             20,             selectTrueUsingSc,      outputInts2));
2652         cases.push_back(SpecConstantTwoIntCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
2653         cases.push_back(SpecConstantTwoIntCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                     10,             5,              selectTrueUsingSc,      outputInts2));
2654         cases.push_back(SpecConstantTwoIntCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                     -10,    -10,    selectTrueUsingSc,      outputInts2));
2655         cases.push_back(SpecConstantTwoIntCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                     50,             100,    selectTrueUsingSc,      outputInts2));
2656         cases.push_back(SpecConstantTwoIntCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
2657         cases.push_back(SpecConstantTwoIntCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                     10,             10,             selectTrueUsingSc,      outputInts2));
2658         cases.push_back(SpecConstantTwoIntCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                     42,             24,             selectFalseUsingSc,     outputInts2));
2659         cases.push_back(SpecConstantTwoIntCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
2660         cases.push_back(SpecConstantTwoIntCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
2661         cases.push_back(SpecConstantTwoIntCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
2662         cases.push_back(SpecConstantTwoIntCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
2663         cases.push_back(SpecConstantTwoIntCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                           -42,    0,              addScToInput,           outputInts1));
2664         cases.push_back(SpecConstantTwoIntCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                           -43,    0,              addScToInput,           outputInts1));
2665         cases.push_back(SpecConstantTwoIntCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                           1,              0,              selectFalseUsingSc,     outputInts2));
2666         cases.push_back(SpecConstantTwoIntCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %zero",       1,              42,             addScToInput,           outputInts1));
2667         cases.push_back(SpecConstantTwoIntCase("sconvert",                              " %i32 0",              " %i32 0",              "%i16",         "SConvert             %sc_0",                           -11200, 0,              addSc32ToInput,         outputInts3));
2668         // -969998336 stored as 32-bit two's complement is the binary representation of -11200 as IEEE-754 Float
2669         cases.push_back(SpecConstantTwoIntCase("fconvert",                              " %f32 0",              " %f32 0",              "%f64",         "FConvert             %sc_0",                           -969998336, 0,  addSc32ToInput,         outputInts3));
2670
2671         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
2672         {
2673                 map<string, string>             specializations;
2674                 ComputeShaderSpec               spec;
2675                 ComputeTestFeatures             features = COMPUTE_TEST_USES_NONE;
2676
2677                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
2678                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
2679                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
2680                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
2681                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
2682
2683                 // Special SPIR-V code for SConvert-case
2684                 if (strcmp(cases[caseNdx].caseName, "sconvert") == 0)
2685                 {
2686                         features                                                                = COMPUTE_TEST_USES_INT16;
2687                         specializations["CAPABILITIES"]                 = "OpCapability Int16\n";                                                       // Adds 16-bit integer capability
2688                         specializations["OPTYPE_DEFINITIONS"]   = "%i16 = OpTypeInt 16 1\n";                                            // Adds 16-bit integer type
2689                         specializations["TYPE_CONVERT"]                 = "%sc_final32 = OpSConvert %i32 %sc_final\n";          // Converts 16-bit integer to 32-bit integer
2690                 }
2691
2692                 // Special SPIR-V code for FConvert-case
2693                 if (strcmp(cases[caseNdx].caseName, "fconvert") == 0)
2694                 {
2695                         features                                                                = COMPUTE_TEST_USES_FLOAT64;
2696                         specializations["CAPABILITIES"]                 = "OpCapability Float64\n";                                                     // Adds 64-bit float capability
2697                         specializations["OPTYPE_DEFINITIONS"]   = "%f64 = OpTypeFloat 64\n";                                            // Adds 64-bit float type
2698                         specializations["TYPE_CONVERT"]                 = "%sc_final32 = OpConvertFToS %i32 %sc_final\n";       // Converts 64-bit float to 32-bit integer
2699                 }
2700
2701                 spec.assembly = shaderTemplate.specialize(specializations);
2702                 spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
2703                 spec.outputs.push_back(BufferSp(new Int32Buffer(cases[caseNdx].expectedOutput)));
2704                 spec.numWorkGroups = IVec3(numElements, 1, 1);
2705                 spec.specConstants.push_back(cases[caseNdx].scActualValue0);
2706                 spec.specConstants.push_back(cases[caseNdx].scActualValue1);
2707
2708                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].caseName, cases[caseNdx].caseName, spec, features));
2709         }
2710
2711         ComputeShaderSpec                               spec;
2712
2713         spec.assembly =
2714                 string(getComputeAsmShaderPreamble()) +
2715
2716                 "OpName %main           \"main\"\n"
2717                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2718
2719                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2720                 "OpDecorate %sc_0  SpecId 0\n"
2721                 "OpDecorate %sc_1  SpecId 1\n"
2722                 "OpDecorate %sc_2  SpecId 2\n"
2723                 "OpDecorate %i32arr ArrayStride 4\n"
2724
2725                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2726
2727                 "%ivec3       = OpTypeVector %i32 3\n"
2728                 "%buf         = OpTypeStruct %i32arr\n"
2729                 "%bufptr      = OpTypePointer Uniform %buf\n"
2730                 "%indata      = OpVariable %bufptr Uniform\n"
2731                 "%outdata     = OpVariable %bufptr Uniform\n"
2732
2733                 "%id          = OpVariable %uvec3ptr Input\n"
2734                 "%zero        = OpConstant %i32 0\n"
2735                 "%ivec3_0     = OpConstantComposite %ivec3 %zero %zero %zero\n"
2736                 "%vec3_undef  = OpUndef %ivec3\n"
2737
2738                 "%sc_0        = OpSpecConstant %i32 0\n"
2739                 "%sc_1        = OpSpecConstant %i32 0\n"
2740                 "%sc_2        = OpSpecConstant %i32 0\n"
2741                 "%sc_vec3_0   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_0        %ivec3_0     0\n"                                                 // (sc_0, 0, 0)
2742                 "%sc_vec3_1   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_1        %ivec3_0     1\n"                                                 // (0, sc_1, 0)
2743                 "%sc_vec3_2   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_2        %ivec3_0     2\n"                                                 // (0, 0, sc_2)
2744                 "%sc_vec3_0_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0   %vec3_undef  0          0xFFFFFFFF 2\n"   // (sc_0, ???,  0)
2745                 "%sc_vec3_1_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_1   %vec3_undef  0xFFFFFFFF 1          0\n"   // (???,  sc_1, 0)
2746                 "%sc_vec3_2_s = OpSpecConstantOp %ivec3 VectorShuffle    %vec3_undef  %sc_vec3_2   5          0xFFFFFFFF 5\n"   // (sc_2, ???,  sc_2)
2747                 "%sc_vec3_01  = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0_s %sc_vec3_1_s 1 0 4\n"                                             // (0,    sc_0, sc_1)
2748                 "%sc_vec3_012 = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_01  %sc_vec3_2_s 5 1 2\n"                                             // (sc_2, sc_0, sc_1)
2749                 "%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              0\n"                                                 // sc_2
2750                 "%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              1\n"                                                 // sc_0
2751                 "%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              2\n"                                                 // sc_1
2752                 "%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"                                                              // (sc_2 - sc_0)
2753                 "%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n"                                                              // (sc_2 - sc_0) * sc_1
2754
2755                 "%main      = OpFunction %void None %voidf\n"
2756                 "%label     = OpLabel\n"
2757                 "%idval     = OpLoad %uvec3 %id\n"
2758                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2759                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
2760                 "%inval     = OpLoad %i32 %inloc\n"
2761                 "%final     = OpIAdd %i32 %inval %sc_final\n"
2762                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2763                 "             OpStore %outloc %final\n"
2764                 "             OpReturn\n"
2765                 "             OpFunctionEnd\n";
2766         spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
2767         spec.outputs.push_back(BufferSp(new Int32Buffer(outputInts3)));
2768         spec.numWorkGroups = IVec3(numElements, 1, 1);
2769         spec.specConstants.push_back(123);
2770         spec.specConstants.push_back(56);
2771         spec.specConstants.push_back(-77);
2772
2773         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector_related", "VectorShuffle, CompositeExtract, & CompositeInsert", spec));
2774
2775         return group.release();
2776 }
2777
2778 void createOpPhiVartypeTests (de::MovePtr<tcu::TestCaseGroup>& group, tcu::TestContext& testCtx)
2779 {
2780         ComputeShaderSpec       specInt;
2781         ComputeShaderSpec       specFloat;
2782         ComputeShaderSpec       specVec3;
2783         ComputeShaderSpec       specMat4;
2784         ComputeShaderSpec       specArray;
2785         ComputeShaderSpec       specStruct;
2786         de::Random                      rnd                             (deStringHash(group->getName()));
2787         const int                       numElements             = 100;
2788         vector<float>           inputFloats             (numElements, 0);
2789         vector<float>           outputFloats    (numElements, 0);
2790
2791         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
2792
2793         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2794         floorAll(inputFloats);
2795
2796         for (size_t ndx = 0; ndx < numElements; ++ndx)
2797         {
2798                 // Just check if the value is positive or not
2799                 outputFloats[ndx] = (inputFloats[ndx] > 0) ? 1.0f : -1.0f;
2800         }
2801
2802         // All of the tests are of the form:
2803         //
2804         // testtype r
2805         //
2806         // if (inputdata > 0)
2807         //   r = 1
2808         // else
2809         //   r = -1
2810         //
2811         // return (float)r
2812
2813         specFloat.assembly =
2814                 string(getComputeAsmShaderPreamble()) +
2815
2816                 "OpSource GLSL 430\n"
2817                 "OpName %main \"main\"\n"
2818                 "OpName %id \"gl_GlobalInvocationID\"\n"
2819
2820                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2821
2822                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2823
2824                 "%id = OpVariable %uvec3ptr Input\n"
2825                 "%zero       = OpConstant %i32 0\n"
2826                 "%float_0    = OpConstant %f32 0.0\n"
2827                 "%float_1    = OpConstant %f32 1.0\n"
2828                 "%float_n1   = OpConstant %f32 -1.0\n"
2829
2830                 "%main     = OpFunction %void None %voidf\n"
2831                 "%entry    = OpLabel\n"
2832                 "%idval    = OpLoad %uvec3 %id\n"
2833                 "%x        = OpCompositeExtract %u32 %idval 0\n"
2834                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
2835                 "%inval    = OpLoad %f32 %inloc\n"
2836
2837                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
2838                 "            OpSelectionMerge %cm None\n"
2839                 "            OpBranchConditional %comp %tb %fb\n"
2840                 "%tb       = OpLabel\n"
2841                 "            OpBranch %cm\n"
2842                 "%fb       = OpLabel\n"
2843                 "            OpBranch %cm\n"
2844                 "%cm       = OpLabel\n"
2845                 "%res      = OpPhi %f32 %float_1 %tb %float_n1 %fb\n"
2846
2847                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
2848                 "            OpStore %outloc %res\n"
2849                 "            OpReturn\n"
2850
2851                 "            OpFunctionEnd\n";
2852         specFloat.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2853         specFloat.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2854         specFloat.numWorkGroups = IVec3(numElements, 1, 1);
2855
2856         specMat4.assembly =
2857                 string(getComputeAsmShaderPreamble()) +
2858
2859                 "OpSource GLSL 430\n"
2860                 "OpName %main \"main\"\n"
2861                 "OpName %id \"gl_GlobalInvocationID\"\n"
2862
2863                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2864
2865                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2866
2867                 "%id = OpVariable %uvec3ptr Input\n"
2868                 "%v4f32      = OpTypeVector %f32 4\n"
2869                 "%mat4v4f32  = OpTypeMatrix %v4f32 4\n"
2870                 "%zero       = OpConstant %i32 0\n"
2871                 "%float_0    = OpConstant %f32 0.0\n"
2872                 "%float_1    = OpConstant %f32 1.0\n"
2873                 "%float_n1   = OpConstant %f32 -1.0\n"
2874                 "%m11        = OpConstantComposite %v4f32 %float_1 %float_0 %float_0 %float_0\n"
2875                 "%m12        = OpConstantComposite %v4f32 %float_0 %float_1 %float_0 %float_0\n"
2876                 "%m13        = OpConstantComposite %v4f32 %float_0 %float_0 %float_1 %float_0\n"
2877                 "%m14        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_1\n"
2878                 "%m1         = OpConstantComposite %mat4v4f32 %m11 %m12 %m13 %m14\n"
2879                 "%m21        = OpConstantComposite %v4f32 %float_n1 %float_0 %float_0 %float_0\n"
2880                 "%m22        = OpConstantComposite %v4f32 %float_0 %float_n1 %float_0 %float_0\n"
2881                 "%m23        = OpConstantComposite %v4f32 %float_0 %float_0 %float_n1 %float_0\n"
2882                 "%m24        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_n1\n"
2883                 "%m2         = OpConstantComposite %mat4v4f32 %m21 %m22 %m23 %m24\n"
2884
2885                 "%main     = OpFunction %void None %voidf\n"
2886                 "%entry    = OpLabel\n"
2887                 "%idval    = OpLoad %uvec3 %id\n"
2888                 "%x        = OpCompositeExtract %u32 %idval 0\n"
2889                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
2890                 "%inval    = OpLoad %f32 %inloc\n"
2891
2892                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
2893                 "            OpSelectionMerge %cm None\n"
2894                 "            OpBranchConditional %comp %tb %fb\n"
2895                 "%tb       = OpLabel\n"
2896                 "            OpBranch %cm\n"
2897                 "%fb       = OpLabel\n"
2898                 "            OpBranch %cm\n"
2899                 "%cm       = OpLabel\n"
2900                 "%mres     = OpPhi %mat4v4f32 %m1 %tb %m2 %fb\n"
2901                 "%res      = OpCompositeExtract %f32 %mres 2 2\n"
2902
2903                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
2904                 "            OpStore %outloc %res\n"
2905                 "            OpReturn\n"
2906
2907                 "            OpFunctionEnd\n";
2908         specMat4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2909         specMat4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2910         specMat4.numWorkGroups = IVec3(numElements, 1, 1);
2911
2912         specVec3.assembly =
2913                 string(getComputeAsmShaderPreamble()) +
2914
2915                 "OpSource GLSL 430\n"
2916                 "OpName %main \"main\"\n"
2917                 "OpName %id \"gl_GlobalInvocationID\"\n"
2918
2919                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2920
2921                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2922
2923                 "%id = OpVariable %uvec3ptr Input\n"
2924                 "%zero       = OpConstant %i32 0\n"
2925                 "%float_0    = OpConstant %f32 0.0\n"
2926                 "%float_1    = OpConstant %f32 1.0\n"
2927                 "%float_n1   = OpConstant %f32 -1.0\n"
2928                 "%v1         = OpConstantComposite %fvec3 %float_1 %float_1 %float_1\n"
2929                 "%v2         = OpConstantComposite %fvec3 %float_n1 %float_n1 %float_n1\n"
2930
2931                 "%main     = OpFunction %void None %voidf\n"
2932                 "%entry    = OpLabel\n"
2933                 "%idval    = OpLoad %uvec3 %id\n"
2934                 "%x        = OpCompositeExtract %u32 %idval 0\n"
2935                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
2936                 "%inval    = OpLoad %f32 %inloc\n"
2937
2938                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
2939                 "            OpSelectionMerge %cm None\n"
2940                 "            OpBranchConditional %comp %tb %fb\n"
2941                 "%tb       = OpLabel\n"
2942                 "            OpBranch %cm\n"
2943                 "%fb       = OpLabel\n"
2944                 "            OpBranch %cm\n"
2945                 "%cm       = OpLabel\n"
2946                 "%vres     = OpPhi %fvec3 %v1 %tb %v2 %fb\n"
2947                 "%res      = OpCompositeExtract %f32 %vres 2\n"
2948
2949                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
2950                 "            OpStore %outloc %res\n"
2951                 "            OpReturn\n"
2952
2953                 "            OpFunctionEnd\n";
2954         specVec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2955         specVec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2956         specVec3.numWorkGroups = IVec3(numElements, 1, 1);
2957
2958         specInt.assembly =
2959                 string(getComputeAsmShaderPreamble()) +
2960
2961                 "OpSource GLSL 430\n"
2962                 "OpName %main \"main\"\n"
2963                 "OpName %id \"gl_GlobalInvocationID\"\n"
2964
2965                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2966
2967                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2968
2969                 "%id = OpVariable %uvec3ptr Input\n"
2970                 "%zero       = OpConstant %i32 0\n"
2971                 "%float_0    = OpConstant %f32 0.0\n"
2972                 "%i1         = OpConstant %i32 1\n"
2973                 "%i2         = OpConstant %i32 -1\n"
2974
2975                 "%main     = OpFunction %void None %voidf\n"
2976                 "%entry    = OpLabel\n"
2977                 "%idval    = OpLoad %uvec3 %id\n"
2978                 "%x        = OpCompositeExtract %u32 %idval 0\n"
2979                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
2980                 "%inval    = OpLoad %f32 %inloc\n"
2981
2982                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
2983                 "            OpSelectionMerge %cm None\n"
2984                 "            OpBranchConditional %comp %tb %fb\n"
2985                 "%tb       = OpLabel\n"
2986                 "            OpBranch %cm\n"
2987                 "%fb       = OpLabel\n"
2988                 "            OpBranch %cm\n"
2989                 "%cm       = OpLabel\n"
2990                 "%ires     = OpPhi %i32 %i1 %tb %i2 %fb\n"
2991                 "%res      = OpConvertSToF %f32 %ires\n"
2992
2993                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
2994                 "            OpStore %outloc %res\n"
2995                 "            OpReturn\n"
2996
2997                 "            OpFunctionEnd\n";
2998         specInt.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2999         specInt.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3000         specInt.numWorkGroups = IVec3(numElements, 1, 1);
3001
3002         specArray.assembly =
3003                 string(getComputeAsmShaderPreamble()) +
3004
3005                 "OpSource GLSL 430\n"
3006                 "OpName %main \"main\"\n"
3007                 "OpName %id \"gl_GlobalInvocationID\"\n"
3008
3009                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3010
3011                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3012
3013                 "%id = OpVariable %uvec3ptr Input\n"
3014                 "%zero       = OpConstant %i32 0\n"
3015                 "%u7         = OpConstant %u32 7\n"
3016                 "%float_0    = OpConstant %f32 0.0\n"
3017                 "%float_1    = OpConstant %f32 1.0\n"
3018                 "%float_n1   = OpConstant %f32 -1.0\n"
3019                 "%f32a7      = OpTypeArray %f32 %u7\n"
3020                 "%a1         = OpConstantComposite %f32a7 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1\n"
3021                 "%a2         = OpConstantComposite %f32a7 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1\n"
3022                 "%main     = OpFunction %void None %voidf\n"
3023                 "%entry    = OpLabel\n"
3024                 "%idval    = OpLoad %uvec3 %id\n"
3025                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3026                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3027                 "%inval    = OpLoad %f32 %inloc\n"
3028
3029                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3030                 "            OpSelectionMerge %cm None\n"
3031                 "            OpBranchConditional %comp %tb %fb\n"
3032                 "%tb       = OpLabel\n"
3033                 "            OpBranch %cm\n"
3034                 "%fb       = OpLabel\n"
3035                 "            OpBranch %cm\n"
3036                 "%cm       = OpLabel\n"
3037                 "%ares     = OpPhi %f32a7 %a1 %tb %a2 %fb\n"
3038                 "%res      = OpCompositeExtract %f32 %ares 5\n"
3039
3040                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3041                 "            OpStore %outloc %res\n"
3042                 "            OpReturn\n"
3043
3044                 "            OpFunctionEnd\n";
3045         specArray.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3046         specArray.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3047         specArray.numWorkGroups = IVec3(numElements, 1, 1);
3048
3049         specStruct.assembly =
3050                 string(getComputeAsmShaderPreamble()) +
3051
3052                 "OpSource GLSL 430\n"
3053                 "OpName %main \"main\"\n"
3054                 "OpName %id \"gl_GlobalInvocationID\"\n"
3055
3056                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3057
3058                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3059
3060                 "%id = OpVariable %uvec3ptr Input\n"
3061                 "%zero       = OpConstant %i32 0\n"
3062                 "%float_0    = OpConstant %f32 0.0\n"
3063                 "%float_1    = OpConstant %f32 1.0\n"
3064                 "%float_n1   = OpConstant %f32 -1.0\n"
3065
3066                 "%v2f32      = OpTypeVector %f32 2\n"
3067                 "%Data2      = OpTypeStruct %f32 %v2f32\n"
3068                 "%Data       = OpTypeStruct %Data2 %f32\n"
3069
3070                 "%in1a       = OpConstantComposite %v2f32 %float_1 %float_1\n"
3071                 "%in1b       = OpConstantComposite %Data2 %float_1 %in1a\n"
3072                 "%s1         = OpConstantComposite %Data %in1b %float_1\n"
3073                 "%in2a       = OpConstantComposite %v2f32 %float_n1 %float_n1\n"
3074                 "%in2b       = OpConstantComposite %Data2 %float_n1 %in2a\n"
3075                 "%s2         = OpConstantComposite %Data %in2b %float_n1\n"
3076
3077                 "%main     = OpFunction %void None %voidf\n"
3078                 "%entry    = OpLabel\n"
3079                 "%idval    = OpLoad %uvec3 %id\n"
3080                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3081                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3082                 "%inval    = OpLoad %f32 %inloc\n"
3083
3084                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3085                 "            OpSelectionMerge %cm None\n"
3086                 "            OpBranchConditional %comp %tb %fb\n"
3087                 "%tb       = OpLabel\n"
3088                 "            OpBranch %cm\n"
3089                 "%fb       = OpLabel\n"
3090                 "            OpBranch %cm\n"
3091                 "%cm       = OpLabel\n"
3092                 "%sres     = OpPhi %Data %s1 %tb %s2 %fb\n"
3093                 "%res      = OpCompositeExtract %f32 %sres 0 0\n"
3094
3095                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3096                 "            OpStore %outloc %res\n"
3097                 "            OpReturn\n"
3098
3099                 "            OpFunctionEnd\n";
3100         specStruct.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3101         specStruct.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3102         specStruct.numWorkGroups = IVec3(numElements, 1, 1);
3103
3104         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_int", "OpPhi with int variables", specInt));
3105         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_float", "OpPhi with float variables", specFloat));
3106         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_vec3", "OpPhi with vec3 variables", specVec3));
3107         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_mat4", "OpPhi with mat4 variables", specMat4));
3108         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_array", "OpPhi with array variables", specArray));
3109         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_struct", "OpPhi with struct variables", specStruct));
3110 }
3111
3112 string generateConstantDefinitions (int count)
3113 {
3114         std::ostringstream      r;
3115         for (int i = 0; i < count; i++)
3116                 r << "%cf" << (i * 10 + 5) << " = OpConstant %f32 " <<(i * 10 + 5) << ".0\n";
3117         r << "\n";
3118         return r.str();
3119 }
3120
3121 string generateSwitchCases (int count)
3122 {
3123         std::ostringstream      r;
3124         for (int i = 0; i < count; i++)
3125                 r << " " << i << " %case" << i;
3126         r << "\n";
3127         return r.str();
3128 }
3129
3130 string generateSwitchTargets (int count)
3131 {
3132         std::ostringstream      r;
3133         for (int i = 0; i < count; i++)
3134                 r << "%case" << i << " = OpLabel\n            OpBranch %phi\n";
3135         r << "\n";
3136         return r.str();
3137 }
3138
3139 string generateOpPhiParams (int count)
3140 {
3141         std::ostringstream      r;
3142         for (int i = 0; i < count; i++)
3143                 r << " %cf" << (i * 10 + 5) << " %case" << i;
3144         r << "\n";
3145         return r.str();
3146 }
3147
3148 string generateIntWidth (int value)
3149 {
3150         std::ostringstream      r;
3151         r << value;
3152         return r.str();
3153 }
3154
3155 // Expand input string by injecting "ABC" between the input
3156 // string characters. The acc/add/treshold parameters are used
3157 // to skip some of the injections to make the result less
3158 // uniform (and a lot shorter).
3159 string expandOpPhiCase5 (const string& s, int &acc, int add, int treshold)
3160 {
3161         std::ostringstream      res;
3162         const char*                     p = s.c_str();
3163
3164         while (*p)
3165         {
3166                 res << *p;
3167                 acc += add;
3168                 if (acc > treshold)
3169                 {
3170                         acc -= treshold;
3171                         res << "ABC";
3172                 }
3173                 p++;
3174         }
3175         return res.str();
3176 }
3177
3178 // Calculate expected result based on the code string
3179 float calcOpPhiCase5 (float val, const string& s)
3180 {
3181         const char*             p               = s.c_str();
3182         float                   x[8];
3183         bool                    b[8];
3184         const float             tv[8]   = { 0.5f, 1.5f, 3.5f, 7.5f, 15.5f, 31.5f, 63.5f, 127.5f };
3185         const float             v               = deFloatAbs(val);
3186         float                   res             = 0;
3187         int                             depth   = -1;
3188         int                             skip    = 0;
3189
3190         for (int i = 7; i >= 0; --i)
3191                 x[i] = std::fmod((float)v, (float)(2 << i));
3192         for (int i = 7; i >= 0; --i)
3193                 b[i] = x[i] > tv[i];
3194
3195         while (*p)
3196         {
3197                 if (*p == 'A')
3198                 {
3199                         depth++;
3200                         if (skip == 0 && b[depth])
3201                         {
3202                                 res++;
3203                         }
3204                         else
3205                                 skip++;
3206                 }
3207                 if (*p == 'B')
3208                 {
3209                         if (skip)
3210                                 skip--;
3211                         if (b[depth] || skip)
3212                                 skip++;
3213                 }
3214                 if (*p == 'C')
3215                 {
3216                         depth--;
3217                         if (skip)
3218                                 skip--;
3219                 }
3220                 p++;
3221         }
3222         return res;
3223 }
3224
3225 // In the code string, the letters represent the following:
3226 //
3227 // A:
3228 //     if (certain bit is set)
3229 //     {
3230 //       result++;
3231 //
3232 // B:
3233 //     } else {
3234 //
3235 // C:
3236 //     }
3237 //
3238 // examples:
3239 // AABCBC leads to if(){r++;if(){r++;}else{}}else{}
3240 // ABABCC leads to if(){r++;}else{if(){r++;}else{}}
3241 // ABCABC leads to if(){r++;}else{}if(){r++;}else{}
3242 //
3243 // Code generation gets a bit complicated due to the else-branches,
3244 // which do not generate new values. Thus, the generator needs to
3245 // keep track of the previous variable change seen by the else
3246 // branch.
3247 string generateOpPhiCase5 (const string& s)
3248 {
3249         std::stack<int>                         idStack;
3250         std::stack<std::string>         value;
3251         std::stack<std::string>         valueLabel;
3252         std::stack<std::string>         mergeLeft;
3253         std::stack<std::string>         mergeRight;
3254         std::ostringstream                      res;
3255         const char*                                     p                       = s.c_str();
3256         int                                                     depth           = -1;
3257         int                                                     currId          = 0;
3258         int                                                     iter            = 0;
3259
3260         idStack.push(-1);
3261         value.push("%f32_0");
3262         valueLabel.push("%f32_0 %entry");
3263
3264         while (*p)
3265         {
3266                 if (*p == 'A')
3267                 {
3268                         depth++;
3269                         currId = iter;
3270                         idStack.push(currId);
3271                         res << "\tOpSelectionMerge %m" << currId << " None\n";
3272                         res << "\tOpBranchConditional %b" << depth << " %t" << currId << " %f" << currId << "\n";
3273                         res << "%t" << currId << " = OpLabel\n";
3274                         res << "%rt" << currId << " = OpFAdd %f32 " << value.top() << " %f32_1\n";
3275                         std::ostringstream tag;
3276                         tag << "%rt" << currId;
3277                         value.push(tag.str());
3278                         tag << " %t" << currId;
3279                         valueLabel.push(tag.str());
3280                 }
3281
3282                 if (*p == 'B')
3283                 {
3284                         mergeLeft.push(valueLabel.top());
3285                         value.pop();
3286                         valueLabel.pop();
3287                         res << "\tOpBranch %m" << currId << "\n";
3288                         res << "%f" << currId << " = OpLabel\n";
3289                         std::ostringstream tag;
3290                         tag << value.top() << " %f" << currId;
3291                         valueLabel.pop();
3292                         valueLabel.push(tag.str());
3293                 }
3294
3295                 if (*p == 'C')
3296                 {
3297                         mergeRight.push(valueLabel.top());
3298                         res << "\tOpBranch %m" << currId << "\n";
3299                         res << "%m" << currId << " = OpLabel\n";
3300                         if (*(p + 1) == 0)
3301                                 res << "%res"; // last result goes to %res
3302                         else
3303                                 res << "%rm" << currId;
3304                         res << " = OpPhi %f32  " << mergeLeft.top() << "  " << mergeRight.top() << "\n";
3305                         std::ostringstream tag;
3306                         tag << "%rm" << currId;
3307                         value.pop();
3308                         value.push(tag.str());
3309                         tag << " %m" << currId;
3310                         valueLabel.pop();
3311                         valueLabel.push(tag.str());
3312                         mergeLeft.pop();
3313                         mergeRight.pop();
3314                         depth--;
3315                         idStack.pop();
3316                         currId = idStack.top();
3317                 }
3318                 p++;
3319                 iter++;
3320         }
3321         return res.str();
3322 }
3323
3324 tcu::TestCaseGroup* createOpPhiGroup (tcu::TestContext& testCtx)
3325 {
3326         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
3327         ComputeShaderSpec                               spec1;
3328         ComputeShaderSpec                               spec2;
3329         ComputeShaderSpec                               spec3;
3330         ComputeShaderSpec                               spec4;
3331         ComputeShaderSpec                               spec5;
3332         de::Random                                              rnd                             (deStringHash(group->getName()));
3333         const int                                               numElements             = 100;
3334         vector<float>                                   inputFloats             (numElements, 0);
3335         vector<float>                                   outputFloats1   (numElements, 0);
3336         vector<float>                                   outputFloats2   (numElements, 0);
3337         vector<float>                                   outputFloats3   (numElements, 0);
3338         vector<float>                                   outputFloats4   (numElements, 0);
3339         vector<float>                                   outputFloats5   (numElements, 0);
3340         std::string                                             codestring              = "ABC";
3341         const int                                               test4Width              = 1024;
3342
3343         // Build case 5 code string. Each iteration makes the hierarchy more complicated.
3344         // 9 iterations with (7, 24) parameters makes the hierarchy 8 deep with about 1500 lines of
3345         // shader code.
3346         for (int i = 0, acc = 0; i < 9; i++)
3347                 codestring = expandOpPhiCase5(codestring, acc, 7, 24);
3348
3349         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
3350
3351         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3352         floorAll(inputFloats);
3353
3354         for (size_t ndx = 0; ndx < numElements; ++ndx)
3355         {
3356                 switch (ndx % 3)
3357                 {
3358                         case 0:         outputFloats1[ndx] = inputFloats[ndx] + 5.5f;   break;
3359                         case 1:         outputFloats1[ndx] = inputFloats[ndx] + 20.5f;  break;
3360                         case 2:         outputFloats1[ndx] = inputFloats[ndx] + 1.75f;  break;
3361                         default:        break;
3362                 }
3363                 outputFloats2[ndx] = inputFloats[ndx] + 6.5f * 3;
3364                 outputFloats3[ndx] = 8.5f - inputFloats[ndx];
3365
3366                 int index4 = (int)deFloor(deAbs((float)ndx * inputFloats[ndx]));
3367                 outputFloats4[ndx] = (float)(index4 % test4Width) * 10.0f + 5.0f;
3368
3369                 outputFloats5[ndx] = calcOpPhiCase5(inputFloats[ndx], codestring);
3370         }
3371
3372         spec1.assembly =
3373                 string(getComputeAsmShaderPreamble()) +
3374
3375                 "OpSource GLSL 430\n"
3376                 "OpName %main \"main\"\n"
3377                 "OpName %id \"gl_GlobalInvocationID\"\n"
3378
3379                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3380
3381                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3382
3383                 "%id = OpVariable %uvec3ptr Input\n"
3384                 "%zero       = OpConstant %i32 0\n"
3385                 "%three      = OpConstant %u32 3\n"
3386                 "%constf5p5  = OpConstant %f32 5.5\n"
3387                 "%constf20p5 = OpConstant %f32 20.5\n"
3388                 "%constf1p75 = OpConstant %f32 1.75\n"
3389                 "%constf8p5  = OpConstant %f32 8.5\n"
3390                 "%constf6p5  = OpConstant %f32 6.5\n"
3391
3392                 "%main     = OpFunction %void None %voidf\n"
3393                 "%entry    = OpLabel\n"
3394                 "%idval    = OpLoad %uvec3 %id\n"
3395                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3396                 "%selector = OpUMod %u32 %x %three\n"
3397                 "            OpSelectionMerge %phi None\n"
3398                 "            OpSwitch %selector %default 0 %case0 1 %case1 2 %case2\n"
3399
3400                 // Case 1 before OpPhi.
3401                 "%case1    = OpLabel\n"
3402                 "            OpBranch %phi\n"
3403
3404                 "%default  = OpLabel\n"
3405                 "            OpUnreachable\n"
3406
3407                 "%phi      = OpLabel\n"
3408                 "%operand  = OpPhi %f32   %constf1p75 %case2   %constf20p5 %case1   %constf5p5 %case0\n" // not in the order of blocks
3409                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3410                 "%inval    = OpLoad %f32 %inloc\n"
3411                 "%add      = OpFAdd %f32 %inval %operand\n"
3412                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3413                 "            OpStore %outloc %add\n"
3414                 "            OpReturn\n"
3415
3416                 // Case 0 after OpPhi.
3417                 "%case0    = OpLabel\n"
3418                 "            OpBranch %phi\n"
3419
3420
3421                 // Case 2 after OpPhi.
3422                 "%case2    = OpLabel\n"
3423                 "            OpBranch %phi\n"
3424
3425                 "            OpFunctionEnd\n";
3426         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3427         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
3428         spec1.numWorkGroups = IVec3(numElements, 1, 1);
3429
3430         group->addChild(new SpvAsmComputeShaderCase(testCtx, "block", "out-of-order and unreachable blocks for OpPhi", spec1));
3431
3432         spec2.assembly =
3433                 string(getComputeAsmShaderPreamble()) +
3434
3435                 "OpName %main \"main\"\n"
3436                 "OpName %id \"gl_GlobalInvocationID\"\n"
3437
3438                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3439
3440                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3441
3442                 "%id         = OpVariable %uvec3ptr Input\n"
3443                 "%zero       = OpConstant %i32 0\n"
3444                 "%one        = OpConstant %i32 1\n"
3445                 "%three      = OpConstant %i32 3\n"
3446                 "%constf6p5  = OpConstant %f32 6.5\n"
3447
3448                 "%main       = OpFunction %void None %voidf\n"
3449                 "%entry      = OpLabel\n"
3450                 "%idval      = OpLoad %uvec3 %id\n"
3451                 "%x          = OpCompositeExtract %u32 %idval 0\n"
3452                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3453                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3454                 "%inval      = OpLoad %f32 %inloc\n"
3455                 "              OpBranch %phi\n"
3456
3457                 "%phi        = OpLabel\n"
3458                 "%step       = OpPhi %i32 %zero  %entry %step_next  %phi\n"
3459                 "%accum      = OpPhi %f32 %inval %entry %accum_next %phi\n"
3460                 "%step_next  = OpIAdd %i32 %step %one\n"
3461                 "%accum_next = OpFAdd %f32 %accum %constf6p5\n"
3462                 "%still_loop = OpSLessThan %bool %step %three\n"
3463                 "              OpLoopMerge %exit %phi None\n"
3464                 "              OpBranchConditional %still_loop %phi %exit\n"
3465
3466                 "%exit       = OpLabel\n"
3467                 "              OpStore %outloc %accum\n"
3468                 "              OpReturn\n"
3469                 "              OpFunctionEnd\n";
3470         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3471         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
3472         spec2.numWorkGroups = IVec3(numElements, 1, 1);
3473
3474         group->addChild(new SpvAsmComputeShaderCase(testCtx, "induction", "The usual way induction variables are handled in LLVM IR", spec2));
3475
3476         spec3.assembly =
3477                 string(getComputeAsmShaderPreamble()) +
3478
3479                 "OpName %main \"main\"\n"
3480                 "OpName %id \"gl_GlobalInvocationID\"\n"
3481
3482                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3483
3484                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3485
3486                 "%f32ptr_f   = OpTypePointer Function %f32\n"
3487                 "%id         = OpVariable %uvec3ptr Input\n"
3488                 "%true       = OpConstantTrue %bool\n"
3489                 "%false      = OpConstantFalse %bool\n"
3490                 "%zero       = OpConstant %i32 0\n"
3491                 "%constf8p5  = OpConstant %f32 8.5\n"
3492
3493                 "%main       = OpFunction %void None %voidf\n"
3494                 "%entry      = OpLabel\n"
3495                 "%b          = OpVariable %f32ptr_f Function %constf8p5\n"
3496                 "%idval      = OpLoad %uvec3 %id\n"
3497                 "%x          = OpCompositeExtract %u32 %idval 0\n"
3498                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3499                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3500                 "%a_init     = OpLoad %f32 %inloc\n"
3501                 "%b_init     = OpLoad %f32 %b\n"
3502                 "              OpBranch %phi\n"
3503
3504                 "%phi        = OpLabel\n"
3505                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
3506                 "%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
3507                 "%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
3508                 "              OpLoopMerge %exit %phi None\n"
3509                 "              OpBranchConditional %still_loop %phi %exit\n"
3510
3511                 "%exit       = OpLabel\n"
3512                 "%sub        = OpFSub %f32 %a_next %b_next\n"
3513                 "              OpStore %outloc %sub\n"
3514                 "              OpReturn\n"
3515                 "              OpFunctionEnd\n";
3516         spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3517         spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
3518         spec3.numWorkGroups = IVec3(numElements, 1, 1);
3519
3520         group->addChild(new SpvAsmComputeShaderCase(testCtx, "swap", "Swap the values of two variables using OpPhi", spec3));
3521
3522         spec4.assembly =
3523                 "OpCapability Shader\n"
3524                 "%ext = OpExtInstImport \"GLSL.std.450\"\n"
3525                 "OpMemoryModel Logical GLSL450\n"
3526                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3527                 "OpExecutionMode %main LocalSize 1 1 1\n"
3528
3529                 "OpSource GLSL 430\n"
3530                 "OpName %main \"main\"\n"
3531                 "OpName %id \"gl_GlobalInvocationID\"\n"
3532
3533                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3534
3535                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3536
3537                 "%id       = OpVariable %uvec3ptr Input\n"
3538                 "%zero     = OpConstant %i32 0\n"
3539                 "%cimod    = OpConstant %u32 " + generateIntWidth(test4Width) + "\n"
3540
3541                 + generateConstantDefinitions(test4Width) +
3542
3543                 "%main     = OpFunction %void None %voidf\n"
3544                 "%entry    = OpLabel\n"
3545                 "%idval    = OpLoad %uvec3 %id\n"
3546                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3547                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3548                 "%inval    = OpLoad %f32 %inloc\n"
3549                 "%xf       = OpConvertUToF %f32 %x\n"
3550                 "%xm       = OpFMul %f32 %xf %inval\n"
3551                 "%xa       = OpExtInst %f32 %ext FAbs %xm\n"
3552                 "%xi       = OpConvertFToU %u32 %xa\n"
3553                 "%selector = OpUMod %u32 %xi %cimod\n"
3554                 "            OpSelectionMerge %phi None\n"
3555                 "            OpSwitch %selector %default "
3556
3557                 + generateSwitchCases(test4Width) +
3558
3559                 "%default  = OpLabel\n"
3560                 "            OpUnreachable\n"
3561
3562                 + generateSwitchTargets(test4Width) +
3563
3564                 "%phi      = OpLabel\n"
3565                 "%result   = OpPhi %f32"
3566
3567                 + generateOpPhiParams(test4Width) +
3568
3569                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3570                 "            OpStore %outloc %result\n"
3571                 "            OpReturn\n"
3572
3573                 "            OpFunctionEnd\n";
3574         spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3575         spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
3576         spec4.numWorkGroups = IVec3(numElements, 1, 1);
3577
3578         group->addChild(new SpvAsmComputeShaderCase(testCtx, "wide", "OpPhi with a lot of parameters", spec4));
3579
3580         spec5.assembly =
3581                 "OpCapability Shader\n"
3582                 "%ext      = OpExtInstImport \"GLSL.std.450\"\n"
3583                 "OpMemoryModel Logical GLSL450\n"
3584                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3585                 "OpExecutionMode %main LocalSize 1 1 1\n"
3586                 "%code     = OpString \"" + codestring + "\"\n"
3587
3588                 "OpSource GLSL 430\n"
3589                 "OpName %main \"main\"\n"
3590                 "OpName %id \"gl_GlobalInvocationID\"\n"
3591
3592                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3593
3594                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3595
3596                 "%id       = OpVariable %uvec3ptr Input\n"
3597                 "%zero     = OpConstant %i32 0\n"
3598                 "%f32_0    = OpConstant %f32 0.0\n"
3599                 "%f32_0_5  = OpConstant %f32 0.5\n"
3600                 "%f32_1    = OpConstant %f32 1.0\n"
3601                 "%f32_1_5  = OpConstant %f32 1.5\n"
3602                 "%f32_2    = OpConstant %f32 2.0\n"
3603                 "%f32_3_5  = OpConstant %f32 3.5\n"
3604                 "%f32_4    = OpConstant %f32 4.0\n"
3605                 "%f32_7_5  = OpConstant %f32 7.5\n"
3606                 "%f32_8    = OpConstant %f32 8.0\n"
3607                 "%f32_15_5 = OpConstant %f32 15.5\n"
3608                 "%f32_16   = OpConstant %f32 16.0\n"
3609                 "%f32_31_5 = OpConstant %f32 31.5\n"
3610                 "%f32_32   = OpConstant %f32 32.0\n"
3611                 "%f32_63_5 = OpConstant %f32 63.5\n"
3612                 "%f32_64   = OpConstant %f32 64.0\n"
3613                 "%f32_127_5 = OpConstant %f32 127.5\n"
3614                 "%f32_128  = OpConstant %f32 128.0\n"
3615                 "%f32_256  = OpConstant %f32 256.0\n"
3616
3617                 "%main     = OpFunction %void None %voidf\n"
3618                 "%entry    = OpLabel\n"
3619                 "%idval    = OpLoad %uvec3 %id\n"
3620                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3621                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3622                 "%inval    = OpLoad %f32 %inloc\n"
3623
3624                 "%xabs     = OpExtInst %f32 %ext FAbs %inval\n"
3625                 "%x8       = OpFMod %f32 %xabs %f32_256\n"
3626                 "%x7       = OpFMod %f32 %xabs %f32_128\n"
3627                 "%x6       = OpFMod %f32 %xabs %f32_64\n"
3628                 "%x5       = OpFMod %f32 %xabs %f32_32\n"
3629                 "%x4       = OpFMod %f32 %xabs %f32_16\n"
3630                 "%x3       = OpFMod %f32 %xabs %f32_8\n"
3631                 "%x2       = OpFMod %f32 %xabs %f32_4\n"
3632                 "%x1       = OpFMod %f32 %xabs %f32_2\n"
3633
3634                 "%b7       = OpFOrdGreaterThanEqual %bool %x8 %f32_127_5\n"
3635                 "%b6       = OpFOrdGreaterThanEqual %bool %x7 %f32_63_5\n"
3636                 "%b5       = OpFOrdGreaterThanEqual %bool %x6 %f32_31_5\n"
3637                 "%b4       = OpFOrdGreaterThanEqual %bool %x5 %f32_15_5\n"
3638                 "%b3       = OpFOrdGreaterThanEqual %bool %x4 %f32_7_5\n"
3639                 "%b2       = OpFOrdGreaterThanEqual %bool %x3 %f32_3_5\n"
3640                 "%b1       = OpFOrdGreaterThanEqual %bool %x2 %f32_1_5\n"
3641                 "%b0       = OpFOrdGreaterThanEqual %bool %x1 %f32_0_5\n"
3642
3643                 + generateOpPhiCase5(codestring) +
3644
3645                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3646                 "            OpStore %outloc %res\n"
3647                 "            OpReturn\n"
3648
3649                 "            OpFunctionEnd\n";
3650         spec5.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3651         spec5.outputs.push_back(BufferSp(new Float32Buffer(outputFloats5)));
3652         spec5.numWorkGroups = IVec3(numElements, 1, 1);
3653
3654         group->addChild(new SpvAsmComputeShaderCase(testCtx, "nested", "Stress OpPhi with a lot of nesting", spec5));
3655
3656         createOpPhiVartypeTests(group, testCtx);
3657
3658         return group.release();
3659 }
3660
3661 // Assembly code used for testing block order is based on GLSL source code:
3662 //
3663 // #version 430
3664 //
3665 // layout(std140, set = 0, binding = 0) readonly buffer Input {
3666 //   float elements[];
3667 // } input_data;
3668 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
3669 //   float elements[];
3670 // } output_data;
3671 //
3672 // void main() {
3673 //   uint x = gl_GlobalInvocationID.x;
3674 //   output_data.elements[x] = input_data.elements[x];
3675 //   if (x > uint(50)) {
3676 //     switch (x % uint(3)) {
3677 //       case 0: output_data.elements[x] += 1.5f; break;
3678 //       case 1: output_data.elements[x] += 42.f; break;
3679 //       case 2: output_data.elements[x] -= 27.f; break;
3680 //       default: break;
3681 //     }
3682 //   } else {
3683 //     output_data.elements[x] = -input_data.elements[x];
3684 //   }
3685 // }
3686 tcu::TestCaseGroup* createBlockOrderGroup (tcu::TestContext& testCtx)
3687 {
3688         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "block_order", "Test block orders"));
3689         ComputeShaderSpec                               spec;
3690         de::Random                                              rnd                             (deStringHash(group->getName()));
3691         const int                                               numElements             = 100;
3692         vector<float>                                   inputFloats             (numElements, 0);
3693         vector<float>                                   outputFloats    (numElements, 0);
3694
3695         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
3696
3697         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3698         floorAll(inputFloats);
3699
3700         for (size_t ndx = 0; ndx <= 50; ++ndx)
3701                 outputFloats[ndx] = -inputFloats[ndx];
3702
3703         for (size_t ndx = 51; ndx < numElements; ++ndx)
3704         {
3705                 switch (ndx % 3)
3706                 {
3707                         case 0:         outputFloats[ndx] = inputFloats[ndx] + 1.5f; break;
3708                         case 1:         outputFloats[ndx] = inputFloats[ndx] + 42.f; break;
3709                         case 2:         outputFloats[ndx] = inputFloats[ndx] - 27.f; break;
3710                         default:        break;
3711                 }
3712         }
3713
3714         spec.assembly =
3715                 string(getComputeAsmShaderPreamble()) +
3716
3717                 "OpSource GLSL 430\n"
3718                 "OpName %main \"main\"\n"
3719                 "OpName %id \"gl_GlobalInvocationID\"\n"
3720
3721                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3722
3723                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
3724
3725                 "%u32ptr       = OpTypePointer Function %u32\n"
3726                 "%u32ptr_input = OpTypePointer Input %u32\n"
3727
3728                 + string(getComputeAsmInputOutputBuffer()) +
3729
3730                 "%id        = OpVariable %uvec3ptr Input\n"
3731                 "%zero      = OpConstant %i32 0\n"
3732                 "%const3    = OpConstant %u32 3\n"
3733                 "%const50   = OpConstant %u32 50\n"
3734                 "%constf1p5 = OpConstant %f32 1.5\n"
3735                 "%constf27  = OpConstant %f32 27.0\n"
3736                 "%constf42  = OpConstant %f32 42.0\n"
3737
3738                 "%main = OpFunction %void None %voidf\n"
3739
3740                 // entry block.
3741                 "%entry    = OpLabel\n"
3742
3743                 // Create a temporary variable to hold the value of gl_GlobalInvocationID.x.
3744                 "%xvar     = OpVariable %u32ptr Function\n"
3745                 "%xptr     = OpAccessChain %u32ptr_input %id %zero\n"
3746                 "%x        = OpLoad %u32 %xptr\n"
3747                 "            OpStore %xvar %x\n"
3748
3749                 "%cmp      = OpUGreaterThan %bool %x %const50\n"
3750                 "            OpSelectionMerge %if_merge None\n"
3751                 "            OpBranchConditional %cmp %if_true %if_false\n"
3752
3753                 // False branch for if-statement: placed in the middle of switch cases and before true branch.
3754                 "%if_false = OpLabel\n"
3755                 "%x_f      = OpLoad %u32 %xvar\n"
3756                 "%inloc_f  = OpAccessChain %f32ptr %indata %zero %x_f\n"
3757                 "%inval_f  = OpLoad %f32 %inloc_f\n"
3758                 "%negate   = OpFNegate %f32 %inval_f\n"
3759                 "%outloc_f = OpAccessChain %f32ptr %outdata %zero %x_f\n"
3760                 "            OpStore %outloc_f %negate\n"
3761                 "            OpBranch %if_merge\n"
3762
3763                 // Merge block for if-statement: placed in the middle of true and false branch.
3764                 "%if_merge = OpLabel\n"
3765                 "            OpReturn\n"
3766
3767                 // True branch for if-statement: placed in the middle of swtich cases and after the false branch.
3768                 "%if_true  = OpLabel\n"
3769                 "%xval_t   = OpLoad %u32 %xvar\n"
3770                 "%mod      = OpUMod %u32 %xval_t %const3\n"
3771                 "            OpSelectionMerge %switch_merge None\n"
3772                 "            OpSwitch %mod %default 0 %case0 1 %case1 2 %case2\n"
3773
3774                 // Merge block for switch-statement: placed before the case
3775                 // bodies.  But it must follow OpSwitch which dominates it.
3776                 "%switch_merge = OpLabel\n"
3777                 "                OpBranch %if_merge\n"
3778
3779                 // Case 1 for switch-statement: placed before case 0.
3780                 // It must follow the OpSwitch that dominates it.
3781                 "%case1    = OpLabel\n"
3782                 "%x_1      = OpLoad %u32 %xvar\n"
3783                 "%inloc_1  = OpAccessChain %f32ptr %indata %zero %x_1\n"
3784                 "%inval_1  = OpLoad %f32 %inloc_1\n"
3785                 "%addf42   = OpFAdd %f32 %inval_1 %constf42\n"
3786                 "%outloc_1 = OpAccessChain %f32ptr %outdata %zero %x_1\n"
3787                 "            OpStore %outloc_1 %addf42\n"
3788                 "            OpBranch %switch_merge\n"
3789
3790                 // Case 2 for switch-statement.
3791                 "%case2    = OpLabel\n"
3792                 "%x_2      = OpLoad %u32 %xvar\n"
3793                 "%inloc_2  = OpAccessChain %f32ptr %indata %zero %x_2\n"
3794                 "%inval_2  = OpLoad %f32 %inloc_2\n"
3795                 "%subf27   = OpFSub %f32 %inval_2 %constf27\n"
3796                 "%outloc_2 = OpAccessChain %f32ptr %outdata %zero %x_2\n"
3797                 "            OpStore %outloc_2 %subf27\n"
3798                 "            OpBranch %switch_merge\n"
3799
3800                 // Default case for switch-statement: placed in the middle of normal cases.
3801                 "%default = OpLabel\n"
3802                 "           OpBranch %switch_merge\n"
3803
3804                 // Case 0 for switch-statement: out of order.
3805                 "%case0    = OpLabel\n"
3806                 "%x_0      = OpLoad %u32 %xvar\n"
3807                 "%inloc_0  = OpAccessChain %f32ptr %indata %zero %x_0\n"
3808                 "%inval_0  = OpLoad %f32 %inloc_0\n"
3809                 "%addf1p5  = OpFAdd %f32 %inval_0 %constf1p5\n"
3810                 "%outloc_0 = OpAccessChain %f32ptr %outdata %zero %x_0\n"
3811                 "            OpStore %outloc_0 %addf1p5\n"
3812                 "            OpBranch %switch_merge\n"
3813
3814                 "            OpFunctionEnd\n";
3815         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3816         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3817         spec.numWorkGroups = IVec3(numElements, 1, 1);
3818
3819         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "various out-of-order blocks", spec));
3820
3821         return group.release();
3822 }
3823
3824 tcu::TestCaseGroup* createMultipleShaderGroup (tcu::TestContext& testCtx)
3825 {
3826         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "multiple_shaders", "Test multiple shaders in the same module"));
3827         ComputeShaderSpec                               spec1;
3828         ComputeShaderSpec                               spec2;
3829         de::Random                                              rnd                             (deStringHash(group->getName()));
3830         const int                                               numElements             = 100;
3831         vector<float>                                   inputFloats             (numElements, 0);
3832         vector<float>                                   outputFloats1   (numElements, 0);
3833         vector<float>                                   outputFloats2   (numElements, 0);
3834         fillRandomScalars(rnd, -500.f, 500.f, &inputFloats[0], numElements);
3835
3836         for (size_t ndx = 0; ndx < numElements; ++ndx)
3837         {
3838                 outputFloats1[ndx] = inputFloats[ndx] + inputFloats[ndx];
3839                 outputFloats2[ndx] = -inputFloats[ndx];
3840         }
3841
3842         const string assembly(
3843                 "OpCapability Shader\n"
3844                 "OpCapability ClipDistance\n"
3845                 "OpMemoryModel Logical GLSL450\n"
3846                 "OpEntryPoint GLCompute %comp_main1 \"entrypoint1\" %id\n"
3847                 "OpEntryPoint GLCompute %comp_main2 \"entrypoint2\" %id\n"
3848                 // A module cannot have two OpEntryPoint instructions with the same Execution Model and the same Name string.
3849                 "OpEntryPoint Vertex    %vert_main  \"entrypoint2\" %vert_builtins %vertexIndex %instanceIndex\n"
3850                 "OpExecutionMode %comp_main1 LocalSize 1 1 1\n"
3851                 "OpExecutionMode %comp_main2 LocalSize 1 1 1\n"
3852
3853                 "OpName %comp_main1              \"entrypoint1\"\n"
3854                 "OpName %comp_main2              \"entrypoint2\"\n"
3855                 "OpName %vert_main               \"entrypoint2\"\n"
3856                 "OpName %id                      \"gl_GlobalInvocationID\"\n"
3857                 "OpName %vert_builtin_st         \"gl_PerVertex\"\n"
3858                 "OpName %vertexIndex             \"gl_VertexIndex\"\n"
3859                 "OpName %instanceIndex           \"gl_InstanceIndex\"\n"
3860                 "OpMemberName %vert_builtin_st 0 \"gl_Position\"\n"
3861                 "OpMemberName %vert_builtin_st 1 \"gl_PointSize\"\n"
3862                 "OpMemberName %vert_builtin_st 2 \"gl_ClipDistance\"\n"
3863
3864                 "OpDecorate %id                      BuiltIn GlobalInvocationId\n"
3865                 "OpDecorate %vertexIndex             BuiltIn VertexIndex\n"
3866                 "OpDecorate %instanceIndex           BuiltIn InstanceIndex\n"
3867                 "OpDecorate %vert_builtin_st         Block\n"
3868                 "OpMemberDecorate %vert_builtin_st 0 BuiltIn Position\n"
3869                 "OpMemberDecorate %vert_builtin_st 1 BuiltIn PointSize\n"
3870                 "OpMemberDecorate %vert_builtin_st 2 BuiltIn ClipDistance\n"
3871
3872                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3873
3874                 "%zero       = OpConstant %i32 0\n"
3875                 "%one        = OpConstant %u32 1\n"
3876                 "%c_f32_1    = OpConstant %f32 1\n"
3877
3878                 "%i32inputptr         = OpTypePointer Input %i32\n"
3879                 "%vec4                = OpTypeVector %f32 4\n"
3880                 "%vec4ptr             = OpTypePointer Output %vec4\n"
3881                 "%f32arr1             = OpTypeArray %f32 %one\n"
3882                 "%vert_builtin_st     = OpTypeStruct %vec4 %f32 %f32arr1\n"
3883                 "%vert_builtin_st_ptr = OpTypePointer Output %vert_builtin_st\n"
3884                 "%vert_builtins       = OpVariable %vert_builtin_st_ptr Output\n"
3885
3886                 "%id         = OpVariable %uvec3ptr Input\n"
3887                 "%vertexIndex = OpVariable %i32inputptr Input\n"
3888                 "%instanceIndex = OpVariable %i32inputptr Input\n"
3889                 "%c_vec4_1   = OpConstantComposite %vec4 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
3890
3891                 // gl_Position = vec4(1.);
3892                 "%vert_main  = OpFunction %void None %voidf\n"
3893                 "%vert_entry = OpLabel\n"
3894                 "%position   = OpAccessChain %vec4ptr %vert_builtins %zero\n"
3895                 "              OpStore %position %c_vec4_1\n"
3896                 "              OpReturn\n"
3897                 "              OpFunctionEnd\n"
3898
3899                 // Double inputs.
3900                 "%comp_main1  = OpFunction %void None %voidf\n"
3901                 "%comp1_entry = OpLabel\n"
3902                 "%idval1      = OpLoad %uvec3 %id\n"
3903                 "%x1          = OpCompositeExtract %u32 %idval1 0\n"
3904                 "%inloc1      = OpAccessChain %f32ptr %indata %zero %x1\n"
3905                 "%inval1      = OpLoad %f32 %inloc1\n"
3906                 "%add         = OpFAdd %f32 %inval1 %inval1\n"
3907                 "%outloc1     = OpAccessChain %f32ptr %outdata %zero %x1\n"
3908                 "               OpStore %outloc1 %add\n"
3909                 "               OpReturn\n"
3910                 "               OpFunctionEnd\n"
3911
3912                 // Negate inputs.
3913                 "%comp_main2  = OpFunction %void None %voidf\n"
3914                 "%comp2_entry = OpLabel\n"
3915                 "%idval2      = OpLoad %uvec3 %id\n"
3916                 "%x2          = OpCompositeExtract %u32 %idval2 0\n"
3917                 "%inloc2      = OpAccessChain %f32ptr %indata %zero %x2\n"
3918                 "%inval2      = OpLoad %f32 %inloc2\n"
3919                 "%neg         = OpFNegate %f32 %inval2\n"
3920                 "%outloc2     = OpAccessChain %f32ptr %outdata %zero %x2\n"
3921                 "               OpStore %outloc2 %neg\n"
3922                 "               OpReturn\n"
3923                 "               OpFunctionEnd\n");
3924
3925         spec1.assembly = assembly;
3926         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3927         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
3928         spec1.numWorkGroups = IVec3(numElements, 1, 1);
3929         spec1.entryPoint = "entrypoint1";
3930
3931         spec2.assembly = assembly;
3932         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3933         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
3934         spec2.numWorkGroups = IVec3(numElements, 1, 1);
3935         spec2.entryPoint = "entrypoint2";
3936
3937         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader1", "multiple shaders in the same module", spec1));
3938         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader2", "multiple shaders in the same module", spec2));
3939
3940         return group.release();
3941 }
3942
3943 inline std::string makeLongUTF8String (size_t num4ByteChars)
3944 {
3945         // An example of a longest valid UTF-8 character.  Be explicit about the
3946         // character type because Microsoft compilers can otherwise interpret the
3947         // character string as being over wide (16-bit) characters. Ideally, we
3948         // would just use a C++11 UTF-8 string literal, but we want to support older
3949         // Microsoft compilers.
3950         const std::basic_string<char> earthAfrica("\xF0\x9F\x8C\x8D");
3951         std::string longString;
3952         longString.reserve(num4ByteChars * 4);
3953         for (size_t count = 0; count < num4ByteChars; count++)
3954         {
3955                 longString += earthAfrica;
3956         }
3957         return longString;
3958 }
3959
3960 tcu::TestCaseGroup* createOpSourceGroup (tcu::TestContext& testCtx)
3961 {
3962         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsource", "Tests the OpSource & OpSourceContinued instruction"));
3963         vector<CaseParameter>                   cases;
3964         de::Random                                              rnd                             (deStringHash(group->getName()));
3965         const int                                               numElements             = 100;
3966         vector<float>                                   positiveFloats  (numElements, 0);
3967         vector<float>                                   negativeFloats  (numElements, 0);
3968         const StringTemplate                    shaderTemplate  (
3969                 "OpCapability Shader\n"
3970                 "OpMemoryModel Logical GLSL450\n"
3971
3972                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3973                 "OpExecutionMode %main LocalSize 1 1 1\n"
3974
3975                 "${SOURCE}\n"
3976
3977                 "OpName %main           \"main\"\n"
3978                 "OpName %id             \"gl_GlobalInvocationID\"\n"
3979
3980                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3981
3982                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3983
3984                 "%id        = OpVariable %uvec3ptr Input\n"
3985                 "%zero      = OpConstant %i32 0\n"
3986
3987                 "%main      = OpFunction %void None %voidf\n"
3988                 "%label     = OpLabel\n"
3989                 "%idval     = OpLoad %uvec3 %id\n"
3990                 "%x         = OpCompositeExtract %u32 %idval 0\n"
3991                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
3992                 "%inval     = OpLoad %f32 %inloc\n"
3993                 "%neg       = OpFNegate %f32 %inval\n"
3994                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
3995                 "             OpStore %outloc %neg\n"
3996                 "             OpReturn\n"
3997                 "             OpFunctionEnd\n");
3998
3999         cases.push_back(CaseParameter("unknown_source",                                                 "OpSource Unknown 0"));
4000         cases.push_back(CaseParameter("wrong_source",                                                   "OpSource OpenCL_C 210"));
4001         cases.push_back(CaseParameter("normal_filename",                                                "%fname = OpString \"filename\"\n"
4002                                                                                                                                                         "OpSource GLSL 430 %fname"));
4003         cases.push_back(CaseParameter("empty_filename",                                                 "%fname = OpString \"\"\n"
4004                                                                                                                                                         "OpSource GLSL 430 %fname"));
4005         cases.push_back(CaseParameter("normal_source_code",                                             "%fname = OpString \"filename\"\n"
4006                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\""));
4007         cases.push_back(CaseParameter("empty_source_code",                                              "%fname = OpString \"filename\"\n"
4008                                                                                                                                                         "OpSource GLSL 430 %fname \"\""));
4009         cases.push_back(CaseParameter("long_source_code",                                               "%fname = OpString \"filename\"\n"
4010                                                                                                                                                         "OpSource GLSL 430 %fname \"" + makeLongUTF8String(65530) + "ccc\"")); // word count: 65535
4011         cases.push_back(CaseParameter("utf8_source_code",                                               "%fname = OpString \"filename\"\n"
4012                                                                                                                                                         "OpSource GLSL 430 %fname \"\xE2\x98\x82\xE2\x98\x85\"")); // umbrella & black star symbol
4013         cases.push_back(CaseParameter("normal_sourcecontinued",                                 "%fname = OpString \"filename\"\n"
4014                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvo\"\n"
4015                                                                                                                                                         "OpSourceContinued \"id main() {}\""));
4016         cases.push_back(CaseParameter("empty_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
4017                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4018                                                                                                                                                         "OpSourceContinued \"\""));
4019         cases.push_back(CaseParameter("long_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
4020                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4021                                                                                                                                                         "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\"")); // word count: 65535
4022         cases.push_back(CaseParameter("utf8_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
4023                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4024                                                                                                                                                         "OpSourceContinued \"\xE2\x98\x8E\xE2\x9A\x91\"")); // white telephone & black flag symbol
4025         cases.push_back(CaseParameter("multi_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
4026                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\n\"\n"
4027                                                                                                                                                         "OpSourceContinued \"void\"\n"
4028                                                                                                                                                         "OpSourceContinued \"main()\"\n"
4029                                                                                                                                                         "OpSourceContinued \"{}\""));
4030         cases.push_back(CaseParameter("empty_source_before_sourcecontinued",    "%fname = OpString \"filename\"\n"
4031                                                                                                                                                         "OpSource GLSL 430 %fname \"\"\n"
4032                                                                                                                                                         "OpSourceContinued \"#version 430\nvoid main() {}\""));
4033
4034         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4035
4036         for (size_t ndx = 0; ndx < numElements; ++ndx)
4037                 negativeFloats[ndx] = -positiveFloats[ndx];
4038
4039         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4040         {
4041                 map<string, string>             specializations;
4042                 ComputeShaderSpec               spec;
4043
4044                 specializations["SOURCE"] = cases[caseNdx].param;
4045                 spec.assembly = shaderTemplate.specialize(specializations);
4046                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4047                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4048                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4049
4050                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4051         }
4052
4053         return group.release();
4054 }
4055
4056 tcu::TestCaseGroup* createOpSourceExtensionGroup (tcu::TestContext& testCtx)
4057 {
4058         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsourceextension", "Tests the OpSource instruction"));
4059         vector<CaseParameter>                   cases;
4060         de::Random                                              rnd                             (deStringHash(group->getName()));
4061         const int                                               numElements             = 100;
4062         vector<float>                                   inputFloats             (numElements, 0);
4063         vector<float>                                   outputFloats    (numElements, 0);
4064         const StringTemplate                    shaderTemplate  (
4065                 string(getComputeAsmShaderPreamble()) +
4066
4067                 "OpSourceExtension \"${EXTENSION}\"\n"
4068
4069                 "OpName %main           \"main\"\n"
4070                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4071
4072                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4073
4074                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4075
4076                 "%id        = OpVariable %uvec3ptr Input\n"
4077                 "%zero      = OpConstant %i32 0\n"
4078
4079                 "%main      = OpFunction %void None %voidf\n"
4080                 "%label     = OpLabel\n"
4081                 "%idval     = OpLoad %uvec3 %id\n"
4082                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4083                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4084                 "%inval     = OpLoad %f32 %inloc\n"
4085                 "%neg       = OpFNegate %f32 %inval\n"
4086                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4087                 "             OpStore %outloc %neg\n"
4088                 "             OpReturn\n"
4089                 "             OpFunctionEnd\n");
4090
4091         cases.push_back(CaseParameter("empty_extension",        ""));
4092         cases.push_back(CaseParameter("real_extension",         "GL_ARB_texture_rectangle"));
4093         cases.push_back(CaseParameter("fake_extension",         "GL_ARB_im_the_ultimate_extension"));
4094         cases.push_back(CaseParameter("utf8_extension",         "GL_ARB_\xE2\x98\x82\xE2\x98\x85"));
4095         cases.push_back(CaseParameter("long_extension",         makeLongUTF8String(65533) + "ccc")); // word count: 65535
4096
4097         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
4098
4099         for (size_t ndx = 0; ndx < numElements; ++ndx)
4100                 outputFloats[ndx] = -inputFloats[ndx];
4101
4102         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4103         {
4104                 map<string, string>             specializations;
4105                 ComputeShaderSpec               spec;
4106
4107                 specializations["EXTENSION"] = cases[caseNdx].param;
4108                 spec.assembly = shaderTemplate.specialize(specializations);
4109                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4110                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
4111                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4112
4113                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4114         }
4115
4116         return group.release();
4117 }
4118
4119 // Checks that a compute shader can generate a constant null value of various types, without exercising a computation on it.
4120 tcu::TestCaseGroup* createOpConstantNullGroup (tcu::TestContext& testCtx)
4121 {
4122         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnull", "Tests the OpConstantNull instruction"));
4123         vector<CaseParameter>                   cases;
4124         de::Random                                              rnd                             (deStringHash(group->getName()));
4125         const int                                               numElements             = 100;
4126         vector<float>                                   positiveFloats  (numElements, 0);
4127         vector<float>                                   negativeFloats  (numElements, 0);
4128         const StringTemplate                    shaderTemplate  (
4129                 string(getComputeAsmShaderPreamble()) +
4130
4131                 "OpSource GLSL 430\n"
4132                 "OpName %main           \"main\"\n"
4133                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4134
4135                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4136
4137                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4138                 "%uvec2     = OpTypeVector %u32 2\n"
4139                 "%bvec3     = OpTypeVector %bool 3\n"
4140                 "%fvec4     = OpTypeVector %f32 4\n"
4141                 "%fmat33    = OpTypeMatrix %fvec3 3\n"
4142                 "%const100  = OpConstant %u32 100\n"
4143                 "%uarr100   = OpTypeArray %i32 %const100\n"
4144                 "%struct    = OpTypeStruct %f32 %i32 %u32\n"
4145                 "%pointer   = OpTypePointer Function %i32\n"
4146                 + string(getComputeAsmInputOutputBuffer()) +
4147
4148                 "%null      = OpConstantNull ${TYPE}\n"
4149
4150                 "%id        = OpVariable %uvec3ptr Input\n"
4151                 "%zero      = OpConstant %i32 0\n"
4152
4153                 "%main      = OpFunction %void None %voidf\n"
4154                 "%label     = OpLabel\n"
4155                 "%idval     = OpLoad %uvec3 %id\n"
4156                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4157                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4158                 "%inval     = OpLoad %f32 %inloc\n"
4159                 "%neg       = OpFNegate %f32 %inval\n"
4160                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4161                 "             OpStore %outloc %neg\n"
4162                 "             OpReturn\n"
4163                 "             OpFunctionEnd\n");
4164
4165         cases.push_back(CaseParameter("bool",                   "%bool"));
4166         cases.push_back(CaseParameter("sint32",                 "%i32"));
4167         cases.push_back(CaseParameter("uint32",                 "%u32"));
4168         cases.push_back(CaseParameter("float32",                "%f32"));
4169         cases.push_back(CaseParameter("vec4float32",    "%fvec4"));
4170         cases.push_back(CaseParameter("vec3bool",               "%bvec3"));
4171         cases.push_back(CaseParameter("vec2uint32",             "%uvec2"));
4172         cases.push_back(CaseParameter("matrix",                 "%fmat33"));
4173         cases.push_back(CaseParameter("array",                  "%uarr100"));
4174         cases.push_back(CaseParameter("struct",                 "%struct"));
4175         cases.push_back(CaseParameter("pointer",                "%pointer"));
4176
4177         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4178
4179         for (size_t ndx = 0; ndx < numElements; ++ndx)
4180                 negativeFloats[ndx] = -positiveFloats[ndx];
4181
4182         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4183         {
4184                 map<string, string>             specializations;
4185                 ComputeShaderSpec               spec;
4186
4187                 specializations["TYPE"] = cases[caseNdx].param;
4188                 spec.assembly = shaderTemplate.specialize(specializations);
4189                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4190                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4191                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4192
4193                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4194         }
4195
4196         return group.release();
4197 }
4198
4199 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
4200 tcu::TestCaseGroup* createOpConstantCompositeGroup (tcu::TestContext& testCtx)
4201 {
4202         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "Tests the OpConstantComposite instruction"));
4203         vector<CaseParameter>                   cases;
4204         de::Random                                              rnd                             (deStringHash(group->getName()));
4205         const int                                               numElements             = 100;
4206         vector<float>                                   positiveFloats  (numElements, 0);
4207         vector<float>                                   negativeFloats  (numElements, 0);
4208         const StringTemplate                    shaderTemplate  (
4209                 string(getComputeAsmShaderPreamble()) +
4210
4211                 "OpSource GLSL 430\n"
4212                 "OpName %main           \"main\"\n"
4213                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4214
4215                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4216
4217                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4218
4219                 "%id        = OpVariable %uvec3ptr Input\n"
4220                 "%zero      = OpConstant %i32 0\n"
4221
4222                 "${CONSTANT}\n"
4223
4224                 "%main      = OpFunction %void None %voidf\n"
4225                 "%label     = OpLabel\n"
4226                 "%idval     = OpLoad %uvec3 %id\n"
4227                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4228                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4229                 "%inval     = OpLoad %f32 %inloc\n"
4230                 "%neg       = OpFNegate %f32 %inval\n"
4231                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4232                 "             OpStore %outloc %neg\n"
4233                 "             OpReturn\n"
4234                 "             OpFunctionEnd\n");
4235
4236         cases.push_back(CaseParameter("vector",                 "%five = OpConstant %u32 5\n"
4237                                                                                                         "%const = OpConstantComposite %uvec3 %five %zero %five"));
4238         cases.push_back(CaseParameter("matrix",                 "%m3fvec3 = OpTypeMatrix %fvec3 3\n"
4239                                                                                                         "%ten = OpConstant %f32 10.\n"
4240                                                                                                         "%fzero = OpConstant %f32 0.\n"
4241                                                                                                         "%vec = OpConstantComposite %fvec3 %ten %fzero %ten\n"
4242                                                                                                         "%mat = OpConstantComposite %m3fvec3 %vec %vec %vec"));
4243         cases.push_back(CaseParameter("struct",                 "%m2vec3 = OpTypeMatrix %fvec3 2\n"
4244                                                                                                         "%struct = OpTypeStruct %i32 %f32 %fvec3 %m2vec3\n"
4245                                                                                                         "%fzero = OpConstant %f32 0.\n"
4246                                                                                                         "%one = OpConstant %f32 1.\n"
4247                                                                                                         "%point5 = OpConstant %f32 0.5\n"
4248                                                                                                         "%vec = OpConstantComposite %fvec3 %one %one %fzero\n"
4249                                                                                                         "%mat = OpConstantComposite %m2vec3 %vec %vec\n"
4250                                                                                                         "%const = OpConstantComposite %struct %zero %point5 %vec %mat"));
4251         cases.push_back(CaseParameter("nested_struct",  "%st1 = OpTypeStruct %u32 %f32\n"
4252                                                                                                         "%st2 = OpTypeStruct %i32 %i32\n"
4253                                                                                                         "%struct = OpTypeStruct %st1 %st2\n"
4254                                                                                                         "%point5 = OpConstant %f32 0.5\n"
4255                                                                                                         "%one = OpConstant %u32 1\n"
4256                                                                                                         "%ten = OpConstant %i32 10\n"
4257                                                                                                         "%st1val = OpConstantComposite %st1 %one %point5\n"
4258                                                                                                         "%st2val = OpConstantComposite %st2 %ten %ten\n"
4259                                                                                                         "%const = OpConstantComposite %struct %st1val %st2val"));
4260
4261         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4262
4263         for (size_t ndx = 0; ndx < numElements; ++ndx)
4264                 negativeFloats[ndx] = -positiveFloats[ndx];
4265
4266         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4267         {
4268                 map<string, string>             specializations;
4269                 ComputeShaderSpec               spec;
4270
4271                 specializations["CONSTANT"] = cases[caseNdx].param;
4272                 spec.assembly = shaderTemplate.specialize(specializations);
4273                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4274                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4275                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4276
4277                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4278         }
4279
4280         return group.release();
4281 }
4282
4283 // Creates a floating point number with the given exponent, and significand
4284 // bits set. It can only create normalized numbers. Only the least significant
4285 // 24 bits of the significand will be examined. The final bit of the
4286 // significand will also be ignored. This allows alignment to be written
4287 // similarly to C99 hex-floats.
4288 // For example if you wanted to write 0x1.7f34p-12 you would call
4289 // constructNormalizedFloat(-12, 0x7f3400)
4290 float constructNormalizedFloat (deInt32 exponent, deUint32 significand)
4291 {
4292         float f = 1.0f;
4293
4294         for (deInt32 idx = 0; idx < 23; ++idx)
4295         {
4296                 f += ((significand & 0x800000) == 0) ? 0.f : std::ldexp(1.0f, -(idx + 1));
4297                 significand <<= 1;
4298         }
4299
4300         return std::ldexp(f, exponent);
4301 }
4302
4303 // Compare instruction for the OpQuantizeF16 compute exact case.
4304 // Returns true if the output is what is expected from the test case.
4305 bool compareOpQuantizeF16ComputeExactCase (const std::vector<BufferSp>&, const vector<AllocationSp>& outputAllocs, const std::vector<BufferSp>& expectedOutputs, TestLog&)
4306 {
4307         if (outputAllocs.size() != 1)
4308                 return false;
4309
4310         // Only size is needed because we cannot compare Nans.
4311         size_t byteSize = expectedOutputs[0]->getByteSize();
4312
4313         const float*    outputAsFloat   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
4314
4315         if (byteSize != 4*sizeof(float)) {
4316                 return false;
4317         }
4318
4319         if (*outputAsFloat != constructNormalizedFloat(8, 0x304000) &&
4320                 *outputAsFloat != constructNormalizedFloat(8, 0x300000)) {
4321                 return false;
4322         }
4323         outputAsFloat++;
4324
4325         if (*outputAsFloat != -constructNormalizedFloat(-7, 0x600000) &&
4326                 *outputAsFloat != -constructNormalizedFloat(-7, 0x604000)) {
4327                 return false;
4328         }
4329         outputAsFloat++;
4330
4331         if (*outputAsFloat != constructNormalizedFloat(2, 0x01C000) &&
4332                 *outputAsFloat != constructNormalizedFloat(2, 0x020000)) {
4333                 return false;
4334         }
4335         outputAsFloat++;
4336
4337         if (*outputAsFloat != constructNormalizedFloat(1, 0xFFC000) &&
4338                 *outputAsFloat != constructNormalizedFloat(2, 0x000000)) {
4339                 return false;
4340         }
4341
4342         return true;
4343 }
4344
4345 // Checks that every output from a test-case is a float NaN.
4346 bool compareNan (const std::vector<BufferSp>&, const vector<AllocationSp>& outputAllocs, const std::vector<BufferSp>& expectedOutputs, TestLog&)
4347 {
4348         if (outputAllocs.size() != 1)
4349                 return false;
4350
4351         // Only size is needed because we cannot compare Nans.
4352         size_t byteSize = expectedOutputs[0]->getByteSize();
4353
4354         const float* const      output_as_float = static_cast<const float* const>(outputAllocs[0]->getHostPtr());
4355
4356         for (size_t idx = 0; idx < byteSize / sizeof(float); ++idx)
4357         {
4358                 if (!deFloatIsNaN(output_as_float[idx]))
4359                 {
4360                         return false;
4361                 }
4362         }
4363
4364         return true;
4365 }
4366
4367 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
4368 tcu::TestCaseGroup* createOpQuantizeToF16Group (tcu::TestContext& testCtx)
4369 {
4370         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opquantize", "Tests the OpQuantizeToF16 instruction"));
4371
4372         const std::string shader (
4373                 string(getComputeAsmShaderPreamble()) +
4374
4375                 "OpSource GLSL 430\n"
4376                 "OpName %main           \"main\"\n"
4377                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4378
4379                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4380
4381                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4382
4383                 "%id        = OpVariable %uvec3ptr Input\n"
4384                 "%zero      = OpConstant %i32 0\n"
4385
4386                 "%main      = OpFunction %void None %voidf\n"
4387                 "%label     = OpLabel\n"
4388                 "%idval     = OpLoad %uvec3 %id\n"
4389                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4390                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4391                 "%inval     = OpLoad %f32 %inloc\n"
4392                 "%quant     = OpQuantizeToF16 %f32 %inval\n"
4393                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4394                 "             OpStore %outloc %quant\n"
4395                 "             OpReturn\n"
4396                 "             OpFunctionEnd\n");
4397
4398         {
4399                 ComputeShaderSpec       spec;
4400                 const deUint32          numElements             = 100;
4401                 vector<float>           infinities;
4402                 vector<float>           results;
4403
4404                 infinities.reserve(numElements);
4405                 results.reserve(numElements);
4406
4407                 for (size_t idx = 0; idx < numElements; ++idx)
4408                 {
4409                         switch(idx % 4)
4410                         {
4411                                 case 0:
4412                                         infinities.push_back(std::numeric_limits<float>::infinity());
4413                                         results.push_back(std::numeric_limits<float>::infinity());
4414                                         break;
4415                                 case 1:
4416                                         infinities.push_back(-std::numeric_limits<float>::infinity());
4417                                         results.push_back(-std::numeric_limits<float>::infinity());
4418                                         break;
4419                                 case 2:
4420                                         infinities.push_back(std::ldexp(1.0f, 16));
4421                                         results.push_back(std::numeric_limits<float>::infinity());
4422                                         break;
4423                                 case 3:
4424                                         infinities.push_back(std::ldexp(-1.0f, 32));
4425                                         results.push_back(-std::numeric_limits<float>::infinity());
4426                                         break;
4427                         }
4428                 }
4429
4430                 spec.assembly = shader;
4431                 spec.inputs.push_back(BufferSp(new Float32Buffer(infinities)));
4432                 spec.outputs.push_back(BufferSp(new Float32Buffer(results)));
4433                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4434
4435                 group->addChild(new SpvAsmComputeShaderCase(
4436                         testCtx, "infinities", "Check that infinities propagated and created", spec));
4437         }
4438
4439         {
4440                 ComputeShaderSpec       spec;
4441                 vector<float>           nans;
4442                 const deUint32          numElements             = 100;
4443
4444                 nans.reserve(numElements);
4445
4446                 for (size_t idx = 0; idx < numElements; ++idx)
4447                 {
4448                         if (idx % 2 == 0)
4449                         {
4450                                 nans.push_back(std::numeric_limits<float>::quiet_NaN());
4451                         }
4452                         else
4453                         {
4454                                 nans.push_back(-std::numeric_limits<float>::quiet_NaN());
4455                         }
4456                 }
4457
4458                 spec.assembly = shader;
4459                 spec.inputs.push_back(BufferSp(new Float32Buffer(nans)));
4460                 spec.outputs.push_back(BufferSp(new Float32Buffer(nans)));
4461                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4462                 spec.verifyIO = &compareNan;
4463
4464                 group->addChild(new SpvAsmComputeShaderCase(
4465                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
4466         }
4467
4468         {
4469                 ComputeShaderSpec       spec;
4470                 vector<float>           small;
4471                 vector<float>           zeros;
4472                 const deUint32          numElements             = 100;
4473
4474                 small.reserve(numElements);
4475                 zeros.reserve(numElements);
4476
4477                 for (size_t idx = 0; idx < numElements; ++idx)
4478                 {
4479                         switch(idx % 6)
4480                         {
4481                                 case 0:
4482                                         small.push_back(0.f);
4483                                         zeros.push_back(0.f);
4484                                         break;
4485                                 case 1:
4486                                         small.push_back(-0.f);
4487                                         zeros.push_back(-0.f);
4488                                         break;
4489                                 case 2:
4490                                         small.push_back(std::ldexp(1.0f, -16));
4491                                         zeros.push_back(0.f);
4492                                         break;
4493                                 case 3:
4494                                         small.push_back(std::ldexp(-1.0f, -32));
4495                                         zeros.push_back(-0.f);
4496                                         break;
4497                                 case 4:
4498                                         small.push_back(std::ldexp(1.0f, -127));
4499                                         zeros.push_back(0.f);
4500                                         break;
4501                                 case 5:
4502                                         small.push_back(-std::ldexp(1.0f, -128));
4503                                         zeros.push_back(-0.f);
4504                                         break;
4505                         }
4506                 }
4507
4508                 spec.assembly = shader;
4509                 spec.inputs.push_back(BufferSp(new Float32Buffer(small)));
4510                 spec.outputs.push_back(BufferSp(new Float32Buffer(zeros)));
4511                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4512
4513                 group->addChild(new SpvAsmComputeShaderCase(
4514                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
4515         }
4516
4517         {
4518                 ComputeShaderSpec       spec;
4519                 vector<float>           exact;
4520                 const deUint32          numElements             = 200;
4521
4522                 exact.reserve(numElements);
4523
4524                 for (size_t idx = 0; idx < numElements; ++idx)
4525                         exact.push_back(static_cast<float>(static_cast<int>(idx) - 100));
4526
4527                 spec.assembly = shader;
4528                 spec.inputs.push_back(BufferSp(new Float32Buffer(exact)));
4529                 spec.outputs.push_back(BufferSp(new Float32Buffer(exact)));
4530                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4531
4532                 group->addChild(new SpvAsmComputeShaderCase(
4533                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
4534         }
4535
4536         {
4537                 ComputeShaderSpec       spec;
4538                 vector<float>           inputs;
4539                 const deUint32          numElements             = 4;
4540
4541                 inputs.push_back(constructNormalizedFloat(8,    0x300300));
4542                 inputs.push_back(-constructNormalizedFloat(-7,  0x600800));
4543                 inputs.push_back(constructNormalizedFloat(2,    0x01E000));
4544                 inputs.push_back(constructNormalizedFloat(1,    0xFFE000));
4545
4546                 spec.assembly = shader;
4547                 spec.verifyIO = &compareOpQuantizeF16ComputeExactCase;
4548                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4549                 spec.outputs.push_back(BufferSp(new Float32Buffer(inputs)));
4550                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4551
4552                 group->addChild(new SpvAsmComputeShaderCase(
4553                         testCtx, "rounded", "Check that are rounded when needed", spec));
4554         }
4555
4556         return group.release();
4557 }
4558
4559 tcu::TestCaseGroup* createSpecConstantOpQuantizeToF16Group (tcu::TestContext& testCtx)
4560 {
4561         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opspecconstantop_opquantize", "Tests the OpQuantizeToF16 opcode for the OpSpecConstantOp instruction"));
4562
4563         const std::string shader (
4564                 string(getComputeAsmShaderPreamble()) +
4565
4566                 "OpName %main           \"main\"\n"
4567                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4568
4569                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4570
4571                 "OpDecorate %sc_0  SpecId 0\n"
4572                 "OpDecorate %sc_1  SpecId 1\n"
4573                 "OpDecorate %sc_2  SpecId 2\n"
4574                 "OpDecorate %sc_3  SpecId 3\n"
4575                 "OpDecorate %sc_4  SpecId 4\n"
4576                 "OpDecorate %sc_5  SpecId 5\n"
4577
4578                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4579
4580                 "%id        = OpVariable %uvec3ptr Input\n"
4581                 "%zero      = OpConstant %i32 0\n"
4582                 "%c_u32_6   = OpConstant %u32 6\n"
4583
4584                 "%sc_0      = OpSpecConstant %f32 0.\n"
4585                 "%sc_1      = OpSpecConstant %f32 0.\n"
4586                 "%sc_2      = OpSpecConstant %f32 0.\n"
4587                 "%sc_3      = OpSpecConstant %f32 0.\n"
4588                 "%sc_4      = OpSpecConstant %f32 0.\n"
4589                 "%sc_5      = OpSpecConstant %f32 0.\n"
4590
4591                 "%sc_0_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_0\n"
4592                 "%sc_1_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_1\n"
4593                 "%sc_2_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_2\n"
4594                 "%sc_3_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_3\n"
4595                 "%sc_4_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_4\n"
4596                 "%sc_5_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_5\n"
4597
4598                 "%main      = OpFunction %void None %voidf\n"
4599                 "%label     = OpLabel\n"
4600                 "%idval     = OpLoad %uvec3 %id\n"
4601                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4602                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4603                 "%selector  = OpUMod %u32 %x %c_u32_6\n"
4604                 "            OpSelectionMerge %exit None\n"
4605                 "            OpSwitch %selector %exit 0 %case0 1 %case1 2 %case2 3 %case3 4 %case4 5 %case5\n"
4606
4607                 "%case0     = OpLabel\n"
4608                 "             OpStore %outloc %sc_0_quant\n"
4609                 "             OpBranch %exit\n"
4610
4611                 "%case1     = OpLabel\n"
4612                 "             OpStore %outloc %sc_1_quant\n"
4613                 "             OpBranch %exit\n"
4614
4615                 "%case2     = OpLabel\n"
4616                 "             OpStore %outloc %sc_2_quant\n"
4617                 "             OpBranch %exit\n"
4618
4619                 "%case3     = OpLabel\n"
4620                 "             OpStore %outloc %sc_3_quant\n"
4621                 "             OpBranch %exit\n"
4622
4623                 "%case4     = OpLabel\n"
4624                 "             OpStore %outloc %sc_4_quant\n"
4625                 "             OpBranch %exit\n"
4626
4627                 "%case5     = OpLabel\n"
4628                 "             OpStore %outloc %sc_5_quant\n"
4629                 "             OpBranch %exit\n"
4630
4631                 "%exit      = OpLabel\n"
4632                 "             OpReturn\n"
4633
4634                 "             OpFunctionEnd\n");
4635
4636         {
4637                 ComputeShaderSpec       spec;
4638                 const deUint8           numCases        = 4;
4639                 vector<float>           inputs          (numCases, 0.f);
4640                 vector<float>           outputs;
4641
4642                 spec.assembly           = shader;
4643                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4644
4645                 spec.specConstants.push_back(bitwiseCast<deUint32>(std::numeric_limits<float>::infinity()));
4646                 spec.specConstants.push_back(bitwiseCast<deUint32>(-std::numeric_limits<float>::infinity()));
4647                 spec.specConstants.push_back(bitwiseCast<deUint32>(std::ldexp(1.0f, 16)));
4648                 spec.specConstants.push_back(bitwiseCast<deUint32>(std::ldexp(-1.0f, 32)));
4649
4650                 outputs.push_back(std::numeric_limits<float>::infinity());
4651                 outputs.push_back(-std::numeric_limits<float>::infinity());
4652                 outputs.push_back(std::numeric_limits<float>::infinity());
4653                 outputs.push_back(-std::numeric_limits<float>::infinity());
4654
4655                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4656                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4657
4658                 group->addChild(new SpvAsmComputeShaderCase(
4659                         testCtx, "infinities", "Check that infinities propagated and created", spec));
4660         }
4661
4662         {
4663                 ComputeShaderSpec       spec;
4664                 const deUint8           numCases        = 2;
4665                 vector<float>           inputs          (numCases, 0.f);
4666                 vector<float>           outputs;
4667
4668                 spec.assembly           = shader;
4669                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4670                 spec.verifyIO           = &compareNan;
4671
4672                 outputs.push_back(std::numeric_limits<float>::quiet_NaN());
4673                 outputs.push_back(-std::numeric_limits<float>::quiet_NaN());
4674
4675                 for (deUint8 idx = 0; idx < numCases; ++idx)
4676                         spec.specConstants.push_back(bitwiseCast<deUint32>(outputs[idx]));
4677
4678                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4679                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4680
4681                 group->addChild(new SpvAsmComputeShaderCase(
4682                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
4683         }
4684
4685         {
4686                 ComputeShaderSpec       spec;
4687                 const deUint8           numCases        = 6;
4688                 vector<float>           inputs          (numCases, 0.f);
4689                 vector<float>           outputs;
4690
4691                 spec.assembly           = shader;
4692                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4693
4694                 spec.specConstants.push_back(bitwiseCast<deUint32>(0.f));
4695                 spec.specConstants.push_back(bitwiseCast<deUint32>(-0.f));
4696                 spec.specConstants.push_back(bitwiseCast<deUint32>(std::ldexp(1.0f, -16)));
4697                 spec.specConstants.push_back(bitwiseCast<deUint32>(std::ldexp(-1.0f, -32)));
4698                 spec.specConstants.push_back(bitwiseCast<deUint32>(std::ldexp(1.0f, -127)));
4699                 spec.specConstants.push_back(bitwiseCast<deUint32>(-std::ldexp(1.0f, -128)));
4700
4701                 outputs.push_back(0.f);
4702                 outputs.push_back(-0.f);
4703                 outputs.push_back(0.f);
4704                 outputs.push_back(-0.f);
4705                 outputs.push_back(0.f);
4706                 outputs.push_back(-0.f);
4707
4708                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4709                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4710
4711                 group->addChild(new SpvAsmComputeShaderCase(
4712                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
4713         }
4714
4715         {
4716                 ComputeShaderSpec       spec;
4717                 const deUint8           numCases        = 6;
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                 for (deUint8 idx = 0; idx < 6; ++idx)
4725                 {
4726                         const float f = static_cast<float>(idx * 10 - 30) / 4.f;
4727                         spec.specConstants.push_back(bitwiseCast<deUint32>(f));
4728                         outputs.push_back(f);
4729                 }
4730
4731                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4732                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4733
4734                 group->addChild(new SpvAsmComputeShaderCase(
4735                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
4736         }
4737
4738         {
4739                 ComputeShaderSpec       spec;
4740                 const deUint8           numCases        = 4;
4741                 vector<float>           inputs          (numCases, 0.f);
4742                 vector<float>           outputs;
4743
4744                 spec.assembly           = shader;
4745                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4746                 spec.verifyIO           = &compareOpQuantizeF16ComputeExactCase;
4747
4748                 outputs.push_back(constructNormalizedFloat(8, 0x300300));
4749                 outputs.push_back(-constructNormalizedFloat(-7, 0x600800));
4750                 outputs.push_back(constructNormalizedFloat(2, 0x01E000));
4751                 outputs.push_back(constructNormalizedFloat(1, 0xFFE000));
4752
4753                 for (deUint8 idx = 0; idx < numCases; ++idx)
4754                         spec.specConstants.push_back(bitwiseCast<deUint32>(outputs[idx]));
4755
4756                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4757                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4758
4759                 group->addChild(new SpvAsmComputeShaderCase(
4760                         testCtx, "rounded", "Check that are rounded when needed", spec));
4761         }
4762
4763         return group.release();
4764 }
4765
4766 // Checks that constant null/composite values can be used in computation.
4767 tcu::TestCaseGroup* createOpConstantUsageGroup (tcu::TestContext& testCtx)
4768 {
4769         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnullcomposite", "Spotcheck the OpConstantNull & OpConstantComposite instruction"));
4770         ComputeShaderSpec                               spec;
4771         de::Random                                              rnd                             (deStringHash(group->getName()));
4772         const int                                               numElements             = 100;
4773         vector<float>                                   positiveFloats  (numElements, 0);
4774         vector<float>                                   negativeFloats  (numElements, 0);
4775
4776         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4777
4778         for (size_t ndx = 0; ndx < numElements; ++ndx)
4779                 negativeFloats[ndx] = -positiveFloats[ndx];
4780
4781         spec.assembly =
4782                 "OpCapability Shader\n"
4783                 "%std450 = OpExtInstImport \"GLSL.std.450\"\n"
4784                 "OpMemoryModel Logical GLSL450\n"
4785                 "OpEntryPoint GLCompute %main \"main\" %id\n"
4786                 "OpExecutionMode %main LocalSize 1 1 1\n"
4787
4788                 "OpSource GLSL 430\n"
4789                 "OpName %main           \"main\"\n"
4790                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4791
4792                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4793
4794                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4795
4796                 "%fmat      = OpTypeMatrix %fvec3 3\n"
4797                 "%ten       = OpConstant %u32 10\n"
4798                 "%f32arr10  = OpTypeArray %f32 %ten\n"
4799                 "%fst       = OpTypeStruct %f32 %f32\n"
4800
4801                 + string(getComputeAsmInputOutputBuffer()) +
4802
4803                 "%id        = OpVariable %uvec3ptr Input\n"
4804                 "%zero      = OpConstant %i32 0\n"
4805
4806                 // Create a bunch of null values
4807                 "%unull     = OpConstantNull %u32\n"
4808                 "%fnull     = OpConstantNull %f32\n"
4809                 "%vnull     = OpConstantNull %fvec3\n"
4810                 "%mnull     = OpConstantNull %fmat\n"
4811                 "%anull     = OpConstantNull %f32arr10\n"
4812                 "%snull     = OpConstantComposite %fst %fnull %fnull\n"
4813
4814                 "%main      = OpFunction %void None %voidf\n"
4815                 "%label     = OpLabel\n"
4816                 "%idval     = OpLoad %uvec3 %id\n"
4817                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4818                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4819                 "%inval     = OpLoad %f32 %inloc\n"
4820                 "%neg       = OpFNegate %f32 %inval\n"
4821
4822                 // Get the abs() of (a certain element of) those null values
4823                 "%unull_cov = OpConvertUToF %f32 %unull\n"
4824                 "%unull_abs = OpExtInst %f32 %std450 FAbs %unull_cov\n"
4825                 "%fnull_abs = OpExtInst %f32 %std450 FAbs %fnull\n"
4826                 "%vnull_0   = OpCompositeExtract %f32 %vnull 0\n"
4827                 "%vnull_abs = OpExtInst %f32 %std450 FAbs %vnull_0\n"
4828                 "%mnull_12  = OpCompositeExtract %f32 %mnull 1 2\n"
4829                 "%mnull_abs = OpExtInst %f32 %std450 FAbs %mnull_12\n"
4830                 "%anull_3   = OpCompositeExtract %f32 %anull 3\n"
4831                 "%anull_abs = OpExtInst %f32 %std450 FAbs %anull_3\n"
4832                 "%snull_1   = OpCompositeExtract %f32 %snull 1\n"
4833                 "%snull_abs = OpExtInst %f32 %std450 FAbs %snull_1\n"
4834
4835                 // Add them all
4836                 "%add1      = OpFAdd %f32 %neg  %unull_abs\n"
4837                 "%add2      = OpFAdd %f32 %add1 %fnull_abs\n"
4838                 "%add3      = OpFAdd %f32 %add2 %vnull_abs\n"
4839                 "%add4      = OpFAdd %f32 %add3 %mnull_abs\n"
4840                 "%add5      = OpFAdd %f32 %add4 %anull_abs\n"
4841                 "%final     = OpFAdd %f32 %add5 %snull_abs\n"
4842
4843                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4844                 "             OpStore %outloc %final\n" // write to output
4845                 "             OpReturn\n"
4846                 "             OpFunctionEnd\n";
4847         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4848         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4849         spec.numWorkGroups = IVec3(numElements, 1, 1);
4850
4851         group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "Check that values constructed via OpConstantNull & OpConstantComposite can be used", spec));
4852
4853         return group.release();
4854 }
4855
4856 // Assembly code used for testing loop control is based on GLSL source code:
4857 // #version 430
4858 //
4859 // layout(std140, set = 0, binding = 0) readonly buffer Input {
4860 //   float elements[];
4861 // } input_data;
4862 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
4863 //   float elements[];
4864 // } output_data;
4865 //
4866 // void main() {
4867 //   uint x = gl_GlobalInvocationID.x;
4868 //   output_data.elements[x] = input_data.elements[x];
4869 //   for (uint i = 0; i < 4; ++i)
4870 //     output_data.elements[x] += 1.f;
4871 // }
4872 tcu::TestCaseGroup* createLoopControlGroup (tcu::TestContext& testCtx)
4873 {
4874         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "loop_control", "Tests loop control cases"));
4875         vector<CaseParameter>                   cases;
4876         de::Random                                              rnd                             (deStringHash(group->getName()));
4877         const int                                               numElements             = 100;
4878         vector<float>                                   inputFloats             (numElements, 0);
4879         vector<float>                                   outputFloats    (numElements, 0);
4880         const StringTemplate                    shaderTemplate  (
4881                 string(getComputeAsmShaderPreamble()) +
4882
4883                 "OpSource GLSL 430\n"
4884                 "OpName %main \"main\"\n"
4885                 "OpName %id \"gl_GlobalInvocationID\"\n"
4886
4887                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4888
4889                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4890
4891                 "%u32ptr      = OpTypePointer Function %u32\n"
4892
4893                 "%id          = OpVariable %uvec3ptr Input\n"
4894                 "%zero        = OpConstant %i32 0\n"
4895                 "%uzero       = OpConstant %u32 0\n"
4896                 "%one         = OpConstant %i32 1\n"
4897                 "%constf1     = OpConstant %f32 1.0\n"
4898                 "%four        = OpConstant %u32 4\n"
4899
4900                 "%main        = OpFunction %void None %voidf\n"
4901                 "%entry       = OpLabel\n"
4902                 "%i           = OpVariable %u32ptr Function\n"
4903                 "               OpStore %i %uzero\n"
4904
4905                 "%idval       = OpLoad %uvec3 %id\n"
4906                 "%x           = OpCompositeExtract %u32 %idval 0\n"
4907                 "%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
4908                 "%inval       = OpLoad %f32 %inloc\n"
4909                 "%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
4910                 "               OpStore %outloc %inval\n"
4911                 "               OpBranch %loop_entry\n"
4912
4913                 "%loop_entry  = OpLabel\n"
4914                 "%i_val       = OpLoad %u32 %i\n"
4915                 "%cmp_lt      = OpULessThan %bool %i_val %four\n"
4916                 "               OpLoopMerge %loop_merge %loop_body ${CONTROL}\n"
4917                 "               OpBranchConditional %cmp_lt %loop_body %loop_merge\n"
4918                 "%loop_body   = OpLabel\n"
4919                 "%outval      = OpLoad %f32 %outloc\n"
4920                 "%addf1       = OpFAdd %f32 %outval %constf1\n"
4921                 "               OpStore %outloc %addf1\n"
4922                 "%new_i       = OpIAdd %u32 %i_val %one\n"
4923                 "               OpStore %i %new_i\n"
4924                 "               OpBranch %loop_entry\n"
4925                 "%loop_merge  = OpLabel\n"
4926                 "               OpReturn\n"
4927                 "               OpFunctionEnd\n");
4928
4929         cases.push_back(CaseParameter("none",                           "None"));
4930         cases.push_back(CaseParameter("unroll",                         "Unroll"));
4931         cases.push_back(CaseParameter("dont_unroll",            "DontUnroll"));
4932         cases.push_back(CaseParameter("unroll_dont_unroll",     "Unroll|DontUnroll"));
4933
4934         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
4935
4936         for (size_t ndx = 0; ndx < numElements; ++ndx)
4937                 outputFloats[ndx] = inputFloats[ndx] + 4.f;
4938
4939         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4940         {
4941                 map<string, string>             specializations;
4942                 ComputeShaderSpec               spec;
4943
4944                 specializations["CONTROL"] = cases[caseNdx].param;
4945                 spec.assembly = shaderTemplate.specialize(specializations);
4946                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4947                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
4948                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4949
4950                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4951         }
4952
4953         group->addChild(new SpvAsmLoopControlDependencyLengthCase(testCtx, "dependency_length", "dependency_length"));
4954         group->addChild(new SpvAsmLoopControlDependencyInfiniteCase(testCtx, "dependency_infinite", "dependency_infinite"));
4955
4956         return group.release();
4957 }
4958
4959 // Assembly code used for testing selection control is based on GLSL source code:
4960 // #version 430
4961 //
4962 // layout(std140, set = 0, binding = 0) readonly buffer Input {
4963 //   float elements[];
4964 // } input_data;
4965 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
4966 //   float elements[];
4967 // } output_data;
4968 //
4969 // void main() {
4970 //   uint x = gl_GlobalInvocationID.x;
4971 //   float val = input_data.elements[x];
4972 //   if (val > 10.f)
4973 //     output_data.elements[x] = val + 1.f;
4974 //   else
4975 //     output_data.elements[x] = val - 1.f;
4976 // }
4977 tcu::TestCaseGroup* createSelectionControlGroup (tcu::TestContext& testCtx)
4978 {
4979         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "selection_control", "Tests selection control cases"));
4980         vector<CaseParameter>                   cases;
4981         de::Random                                              rnd                             (deStringHash(group->getName()));
4982         const int                                               numElements             = 100;
4983         vector<float>                                   inputFloats             (numElements, 0);
4984         vector<float>                                   outputFloats    (numElements, 0);
4985         const StringTemplate                    shaderTemplate  (
4986                 string(getComputeAsmShaderPreamble()) +
4987
4988                 "OpSource GLSL 430\n"
4989                 "OpName %main \"main\"\n"
4990                 "OpName %id \"gl_GlobalInvocationID\"\n"
4991
4992                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4993
4994                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4995
4996                 "%id       = OpVariable %uvec3ptr Input\n"
4997                 "%zero     = OpConstant %i32 0\n"
4998                 "%constf1  = OpConstant %f32 1.0\n"
4999                 "%constf10 = OpConstant %f32 10.0\n"
5000
5001                 "%main     = OpFunction %void None %voidf\n"
5002                 "%entry    = OpLabel\n"
5003                 "%idval    = OpLoad %uvec3 %id\n"
5004                 "%x        = OpCompositeExtract %u32 %idval 0\n"
5005                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
5006                 "%inval    = OpLoad %f32 %inloc\n"
5007                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
5008                 "%cmp_gt   = OpFOrdGreaterThan %bool %inval %constf10\n"
5009
5010                 "            OpSelectionMerge %if_end ${CONTROL}\n"
5011                 "            OpBranchConditional %cmp_gt %if_true %if_false\n"
5012                 "%if_true  = OpLabel\n"
5013                 "%addf1    = OpFAdd %f32 %inval %constf1\n"
5014                 "            OpStore %outloc %addf1\n"
5015                 "            OpBranch %if_end\n"
5016                 "%if_false = OpLabel\n"
5017                 "%subf1    = OpFSub %f32 %inval %constf1\n"
5018                 "            OpStore %outloc %subf1\n"
5019                 "            OpBranch %if_end\n"
5020                 "%if_end   = OpLabel\n"
5021                 "            OpReturn\n"
5022                 "            OpFunctionEnd\n");
5023
5024         cases.push_back(CaseParameter("none",                                   "None"));
5025         cases.push_back(CaseParameter("flatten",                                "Flatten"));
5026         cases.push_back(CaseParameter("dont_flatten",                   "DontFlatten"));
5027         cases.push_back(CaseParameter("flatten_dont_flatten",   "DontFlatten|Flatten"));
5028
5029         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5030
5031         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
5032         floorAll(inputFloats);
5033
5034         for (size_t ndx = 0; ndx < numElements; ++ndx)
5035                 outputFloats[ndx] = inputFloats[ndx] + (inputFloats[ndx] > 10.f ? 1.f : -1.f);
5036
5037         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5038         {
5039                 map<string, string>             specializations;
5040                 ComputeShaderSpec               spec;
5041
5042                 specializations["CONTROL"] = cases[caseNdx].param;
5043                 spec.assembly = shaderTemplate.specialize(specializations);
5044                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5045                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5046                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5047
5048                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5049         }
5050
5051         return group.release();
5052 }
5053
5054 // Assembly code used for testing function control is based on GLSL source code:
5055 //
5056 // #version 430
5057 //
5058 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5059 //   float elements[];
5060 // } input_data;
5061 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5062 //   float elements[];
5063 // } output_data;
5064 //
5065 // float const10() { return 10.f; }
5066 //
5067 // void main() {
5068 //   uint x = gl_GlobalInvocationID.x;
5069 //   output_data.elements[x] = input_data.elements[x] + const10();
5070 // }
5071 tcu::TestCaseGroup* createFunctionControlGroup (tcu::TestContext& testCtx)
5072 {
5073         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "function_control", "Tests function control cases"));
5074         vector<CaseParameter>                   cases;
5075         de::Random                                              rnd                             (deStringHash(group->getName()));
5076         const int                                               numElements             = 100;
5077         vector<float>                                   inputFloats             (numElements, 0);
5078         vector<float>                                   outputFloats    (numElements, 0);
5079         const StringTemplate                    shaderTemplate  (
5080                 string(getComputeAsmShaderPreamble()) +
5081
5082                 "OpSource GLSL 430\n"
5083                 "OpName %main \"main\"\n"
5084                 "OpName %func_const10 \"const10(\"\n"
5085                 "OpName %id \"gl_GlobalInvocationID\"\n"
5086
5087                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5088
5089                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5090
5091                 "%f32f = OpTypeFunction %f32\n"
5092                 "%id = OpVariable %uvec3ptr Input\n"
5093                 "%zero = OpConstant %i32 0\n"
5094                 "%constf10 = OpConstant %f32 10.0\n"
5095
5096                 "%main         = OpFunction %void None %voidf\n"
5097                 "%entry        = OpLabel\n"
5098                 "%idval        = OpLoad %uvec3 %id\n"
5099                 "%x            = OpCompositeExtract %u32 %idval 0\n"
5100                 "%inloc        = OpAccessChain %f32ptr %indata %zero %x\n"
5101                 "%inval        = OpLoad %f32 %inloc\n"
5102                 "%ret_10       = OpFunctionCall %f32 %func_const10\n"
5103                 "%fadd         = OpFAdd %f32 %inval %ret_10\n"
5104                 "%outloc       = OpAccessChain %f32ptr %outdata %zero %x\n"
5105                 "                OpStore %outloc %fadd\n"
5106                 "                OpReturn\n"
5107                 "                OpFunctionEnd\n"
5108
5109                 "%func_const10 = OpFunction %f32 ${CONTROL} %f32f\n"
5110                 "%label        = OpLabel\n"
5111                 "                OpReturnValue %constf10\n"
5112                 "                OpFunctionEnd\n");
5113
5114         cases.push_back(CaseParameter("none",                                           "None"));
5115         cases.push_back(CaseParameter("inline",                                         "Inline"));
5116         cases.push_back(CaseParameter("dont_inline",                            "DontInline"));
5117         cases.push_back(CaseParameter("pure",                                           "Pure"));
5118         cases.push_back(CaseParameter("const",                                          "Const"));
5119         cases.push_back(CaseParameter("inline_pure",                            "Inline|Pure"));
5120         cases.push_back(CaseParameter("const_dont_inline",                      "Const|DontInline"));
5121         cases.push_back(CaseParameter("inline_dont_inline",                     "Inline|DontInline"));
5122         cases.push_back(CaseParameter("pure_inline_dont_inline",        "Pure|Inline|DontInline"));
5123
5124         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5125
5126         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
5127         floorAll(inputFloats);
5128
5129         for (size_t ndx = 0; ndx < numElements; ++ndx)
5130                 outputFloats[ndx] = inputFloats[ndx] + 10.f;
5131
5132         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5133         {
5134                 map<string, string>             specializations;
5135                 ComputeShaderSpec               spec;
5136
5137                 specializations["CONTROL"] = cases[caseNdx].param;
5138                 spec.assembly = shaderTemplate.specialize(specializations);
5139                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5140                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5141                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5142
5143                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5144         }
5145
5146         return group.release();
5147 }
5148
5149 tcu::TestCaseGroup* createMemoryAccessGroup (tcu::TestContext& testCtx)
5150 {
5151         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "memory_access", "Tests memory access cases"));
5152         vector<CaseParameter>                   cases;
5153         de::Random                                              rnd                             (deStringHash(group->getName()));
5154         const int                                               numElements             = 100;
5155         vector<float>                                   inputFloats             (numElements, 0);
5156         vector<float>                                   outputFloats    (numElements, 0);
5157         const StringTemplate                    shaderTemplate  (
5158                 string(getComputeAsmShaderPreamble()) +
5159
5160                 "OpSource GLSL 430\n"
5161                 "OpName %main           \"main\"\n"
5162                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5163
5164                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5165
5166                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5167
5168                 "%f32ptr_f  = OpTypePointer Function %f32\n"
5169
5170                 "%id        = OpVariable %uvec3ptr Input\n"
5171                 "%zero      = OpConstant %i32 0\n"
5172                 "%four      = OpConstant %i32 4\n"
5173
5174                 "%main      = OpFunction %void None %voidf\n"
5175                 "%label     = OpLabel\n"
5176                 "%copy      = OpVariable %f32ptr_f Function\n"
5177                 "%idval     = OpLoad %uvec3 %id ${ACCESS}\n"
5178                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5179                 "%inloc     = OpAccessChain %f32ptr %indata  %zero %x\n"
5180                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5181                 "             OpCopyMemory %copy %inloc ${ACCESS}\n"
5182                 "%val1      = OpLoad %f32 %copy\n"
5183                 "%val2      = OpLoad %f32 %inloc\n"
5184                 "%add       = OpFAdd %f32 %val1 %val2\n"
5185                 "             OpStore %outloc %add ${ACCESS}\n"
5186                 "             OpReturn\n"
5187                 "             OpFunctionEnd\n");
5188
5189         cases.push_back(CaseParameter("null",                                   ""));
5190         cases.push_back(CaseParameter("none",                                   "None"));
5191         cases.push_back(CaseParameter("volatile",                               "Volatile"));
5192         cases.push_back(CaseParameter("aligned",                                "Aligned 4"));
5193         cases.push_back(CaseParameter("nontemporal",                    "Nontemporal"));
5194         cases.push_back(CaseParameter("aligned_nontemporal",    "Aligned|Nontemporal 4"));
5195         cases.push_back(CaseParameter("aligned_volatile",               "Volatile|Aligned 4"));
5196
5197         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5198
5199         for (size_t ndx = 0; ndx < numElements; ++ndx)
5200                 outputFloats[ndx] = inputFloats[ndx] + inputFloats[ndx];
5201
5202         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5203         {
5204                 map<string, string>             specializations;
5205                 ComputeShaderSpec               spec;
5206
5207                 specializations["ACCESS"] = cases[caseNdx].param;
5208                 spec.assembly = shaderTemplate.specialize(specializations);
5209                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5210                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5211                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5212
5213                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5214         }
5215
5216         return group.release();
5217 }
5218
5219 // Checks that we can get undefined values for various types, without exercising a computation with it.
5220 tcu::TestCaseGroup* createOpUndefGroup (tcu::TestContext& testCtx)
5221 {
5222         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opundef", "Tests the OpUndef instruction"));
5223         vector<CaseParameter>                   cases;
5224         de::Random                                              rnd                             (deStringHash(group->getName()));
5225         const int                                               numElements             = 100;
5226         vector<float>                                   positiveFloats  (numElements, 0);
5227         vector<float>                                   negativeFloats  (numElements, 0);
5228         const StringTemplate                    shaderTemplate  (
5229                 string(getComputeAsmShaderPreamble()) +
5230
5231                 "OpSource GLSL 430\n"
5232                 "OpName %main           \"main\"\n"
5233                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5234
5235                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5236
5237                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
5238                 "%uvec2     = OpTypeVector %u32 2\n"
5239                 "%fvec4     = OpTypeVector %f32 4\n"
5240                 "%fmat33    = OpTypeMatrix %fvec3 3\n"
5241                 "%image     = OpTypeImage %f32 2D 0 0 0 1 Unknown\n"
5242                 "%sampler   = OpTypeSampler\n"
5243                 "%simage    = OpTypeSampledImage %image\n"
5244                 "%const100  = OpConstant %u32 100\n"
5245                 "%uarr100   = OpTypeArray %i32 %const100\n"
5246                 "%struct    = OpTypeStruct %f32 %i32 %u32\n"
5247                 "%pointer   = OpTypePointer Function %i32\n"
5248                 + string(getComputeAsmInputOutputBuffer()) +
5249
5250                 "%id        = OpVariable %uvec3ptr Input\n"
5251                 "%zero      = OpConstant %i32 0\n"
5252
5253                 "%main      = OpFunction %void None %voidf\n"
5254                 "%label     = OpLabel\n"
5255
5256                 "%undef     = OpUndef ${TYPE}\n"
5257
5258                 "%idval     = OpLoad %uvec3 %id\n"
5259                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5260
5261                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5262                 "%inval     = OpLoad %f32 %inloc\n"
5263                 "%neg       = OpFNegate %f32 %inval\n"
5264                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5265                 "             OpStore %outloc %neg\n"
5266                 "             OpReturn\n"
5267                 "             OpFunctionEnd\n");
5268
5269         cases.push_back(CaseParameter("bool",                   "%bool"));
5270         cases.push_back(CaseParameter("sint32",                 "%i32"));
5271         cases.push_back(CaseParameter("uint32",                 "%u32"));
5272         cases.push_back(CaseParameter("float32",                "%f32"));
5273         cases.push_back(CaseParameter("vec4float32",    "%fvec4"));
5274         cases.push_back(CaseParameter("vec2uint32",             "%uvec2"));
5275         cases.push_back(CaseParameter("matrix",                 "%fmat33"));
5276         cases.push_back(CaseParameter("image",                  "%image"));
5277         cases.push_back(CaseParameter("sampler",                "%sampler"));
5278         cases.push_back(CaseParameter("sampledimage",   "%simage"));
5279         cases.push_back(CaseParameter("array",                  "%uarr100"));
5280         cases.push_back(CaseParameter("runtimearray",   "%f32arr"));
5281         cases.push_back(CaseParameter("struct",                 "%struct"));
5282         cases.push_back(CaseParameter("pointer",                "%pointer"));
5283
5284         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
5285
5286         for (size_t ndx = 0; ndx < numElements; ++ndx)
5287                 negativeFloats[ndx] = -positiveFloats[ndx];
5288
5289         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5290         {
5291                 map<string, string>             specializations;
5292                 ComputeShaderSpec               spec;
5293
5294                 specializations["TYPE"] = cases[caseNdx].param;
5295                 spec.assembly = shaderTemplate.specialize(specializations);
5296                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
5297                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
5298                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5299
5300                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5301         }
5302
5303                 return group.release();
5304 }
5305 } // anonymous
5306
5307 tcu::TestCaseGroup* createOpSourceTests (tcu::TestContext& testCtx)
5308 {
5309         struct NameCodePair { string name, code; };
5310         RGBA                                                    defaultColors[4];
5311         de::MovePtr<tcu::TestCaseGroup> opSourceTests                   (new tcu::TestCaseGroup(testCtx, "opsource", "OpSource instruction"));
5312         const std::string                               opsourceGLSLWithFile    = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile ";
5313         map<string, string>                             fragments                               = passthruFragments();
5314         const NameCodePair                              tests[]                                 =
5315         {
5316                 {"unknown", "OpSource Unknown 321"},
5317                 {"essl", "OpSource ESSL 310"},
5318                 {"glsl", "OpSource GLSL 450"},
5319                 {"opencl_cpp", "OpSource OpenCL_CPP 120"},
5320                 {"opencl_c", "OpSource OpenCL_C 120"},
5321                 {"multiple", "OpSource GLSL 450\nOpSource GLSL 450"},
5322                 {"file", opsourceGLSLWithFile},
5323                 {"source", opsourceGLSLWithFile + "\"void main(){}\""},
5324                 // Longest possible source string: SPIR-V limits instructions to 65535
5325                 // words, of which the first 4 are opsourceGLSLWithFile; the rest will
5326                 // contain 65530 UTF8 characters (one word each) plus one last word
5327                 // containing 3 ASCII characters and \0.
5328                 {"longsource", opsourceGLSLWithFile + '"' + makeLongUTF8String(65530) + "ccc" + '"'}
5329         };
5330
5331         getDefaultColors(defaultColors);
5332         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
5333         {
5334                 fragments["debug"] = tests[testNdx].code;
5335                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
5336         }
5337
5338         return opSourceTests.release();
5339 }
5340
5341 tcu::TestCaseGroup* createOpSourceContinuedTests (tcu::TestContext& testCtx)
5342 {
5343         struct NameCodePair { string name, code; };
5344         RGBA                                                            defaultColors[4];
5345         de::MovePtr<tcu::TestCaseGroup>         opSourceTests           (new tcu::TestCaseGroup(testCtx, "opsourcecontinued", "OpSourceContinued instruction"));
5346         map<string, string>                                     fragments                       = passthruFragments();
5347         const std::string                                       opsource                        = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile \"void main(){}\"\n";
5348         const NameCodePair                                      tests[]                         =
5349         {
5350                 {"empty", opsource + "OpSourceContinued \"\""},
5351                 {"short", opsource + "OpSourceContinued \"abcde\""},
5352                 {"multiple", opsource + "OpSourceContinued \"abcde\"\nOpSourceContinued \"fghij\""},
5353                 // Longest possible source string: SPIR-V limits instructions to 65535
5354                 // words, of which the first one is OpSourceContinued/length; the rest
5355                 // will contain 65533 UTF8 characters (one word each) plus one last word
5356                 // containing 3 ASCII characters and \0.
5357                 {"long", opsource + "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\""}
5358         };
5359
5360         getDefaultColors(defaultColors);
5361         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
5362         {
5363                 fragments["debug"] = tests[testNdx].code;
5364                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
5365         }
5366
5367         return opSourceTests.release();
5368 }
5369 tcu::TestCaseGroup* createOpNoLineTests(tcu::TestContext& testCtx)
5370 {
5371         RGBA                                                             defaultColors[4];
5372         de::MovePtr<tcu::TestCaseGroup>          opLineTests             (new tcu::TestCaseGroup(testCtx, "opnoline", "OpNoLine instruction"));
5373         map<string, string>                                      fragments;
5374         getDefaultColors(defaultColors);
5375         fragments["debug"]                      =
5376                 "%name = OpString \"name\"\n";
5377
5378         fragments["pre_main"]   =
5379                 "OpNoLine\n"
5380                 "OpNoLine\n"
5381                 "OpLine %name 1 1\n"
5382                 "OpNoLine\n"
5383                 "OpLine %name 1 1\n"
5384                 "OpLine %name 1 1\n"
5385                 "%second_function = OpFunction %v4f32 None %v4f32_function\n"
5386                 "OpNoLine\n"
5387                 "OpLine %name 1 1\n"
5388                 "OpNoLine\n"
5389                 "OpLine %name 1 1\n"
5390                 "OpLine %name 1 1\n"
5391                 "%second_param1 = OpFunctionParameter %v4f32\n"
5392                 "OpNoLine\n"
5393                 "OpNoLine\n"
5394                 "%label_secondfunction = OpLabel\n"
5395                 "OpNoLine\n"
5396                 "OpReturnValue %second_param1\n"
5397                 "OpFunctionEnd\n"
5398                 "OpNoLine\n"
5399                 "OpNoLine\n";
5400
5401         fragments["testfun"]            =
5402                 // A %test_code function that returns its argument unchanged.
5403                 "OpNoLine\n"
5404                 "OpNoLine\n"
5405                 "OpLine %name 1 1\n"
5406                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
5407                 "OpNoLine\n"
5408                 "%param1 = OpFunctionParameter %v4f32\n"
5409                 "OpNoLine\n"
5410                 "OpNoLine\n"
5411                 "%label_testfun = OpLabel\n"
5412                 "OpNoLine\n"
5413                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
5414                 "OpReturnValue %val1\n"
5415                 "OpFunctionEnd\n"
5416                 "OpLine %name 1 1\n"
5417                 "OpNoLine\n";
5418
5419         createTestsForAllStages("opnoline", defaultColors, defaultColors, fragments, opLineTests.get());
5420
5421         return opLineTests.release();
5422 }
5423
5424 tcu::TestCaseGroup* createOpModuleProcessedTests(tcu::TestContext& testCtx)
5425 {
5426         RGBA                                                            defaultColors[4];
5427         de::MovePtr<tcu::TestCaseGroup>         opModuleProcessedTests                  (new tcu::TestCaseGroup(testCtx, "opmoduleprocessed", "OpModuleProcessed instruction"));
5428         map<string, string>                                     fragments;
5429         std::vector<std::string>                        noExtensions;
5430         GraphicsResources                                       resources;
5431
5432         getDefaultColors(defaultColors);
5433         resources.verifyBinary = veryfiBinaryShader;
5434         resources.spirvVersion = SPIRV_VERSION_1_3;
5435
5436         fragments["moduleprocessed"]                                                    =
5437                 "OpModuleProcessed \"VULKAN CTS\"\n"
5438                 "OpModuleProcessed \"Negative values\"\n"
5439                 "OpModuleProcessed \"Date: 2017/09/21\"\n";
5440
5441         fragments["pre_main"]   =
5442                 "%second_function = OpFunction %v4f32 None %v4f32_function\n"
5443                 "%second_param1 = OpFunctionParameter %v4f32\n"
5444                 "%label_secondfunction = OpLabel\n"
5445                 "OpReturnValue %second_param1\n"
5446                 "OpFunctionEnd\n";
5447
5448         fragments["testfun"]            =
5449                 // A %test_code function that returns its argument unchanged.
5450                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
5451                 "%param1 = OpFunctionParameter %v4f32\n"
5452                 "%label_testfun = OpLabel\n"
5453                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
5454                 "OpReturnValue %val1\n"
5455                 "OpFunctionEnd\n";
5456
5457         createTestsForAllStages ("opmoduleprocessed", defaultColors, defaultColors, fragments, resources, noExtensions, opModuleProcessedTests.get());
5458
5459         return opModuleProcessedTests.release();
5460 }
5461
5462
5463 tcu::TestCaseGroup* createOpLineTests(tcu::TestContext& testCtx)
5464 {
5465         RGBA                                                                                                    defaultColors[4];
5466         de::MovePtr<tcu::TestCaseGroup>                                                 opLineTests                     (new tcu::TestCaseGroup(testCtx, "opline", "OpLine instruction"));
5467         map<string, string>                                                                             fragments;
5468         std::vector<std::pair<std::string, std::string> >               problemStrings;
5469
5470         problemStrings.push_back(std::make_pair<std::string, std::string>("empty_name", ""));
5471         problemStrings.push_back(std::make_pair<std::string, std::string>("short_name", "short_name"));
5472         problemStrings.push_back(std::make_pair<std::string, std::string>("long_name", makeLongUTF8String(65530) + "ccc"));
5473         getDefaultColors(defaultColors);
5474
5475         fragments["debug"]                      =
5476                 "%other_name = OpString \"other_name\"\n";
5477
5478         fragments["pre_main"]   =
5479                 "OpLine %file_name 32 0\n"
5480                 "OpLine %file_name 32 32\n"
5481                 "OpLine %file_name 32 40\n"
5482                 "OpLine %other_name 32 40\n"
5483                 "OpLine %other_name 0 100\n"
5484                 "OpLine %other_name 0 4294967295\n"
5485                 "OpLine %other_name 4294967295 0\n"
5486                 "OpLine %other_name 32 40\n"
5487                 "OpLine %file_name 0 0\n"
5488                 "%second_function = OpFunction %v4f32 None %v4f32_function\n"
5489                 "OpLine %file_name 1 0\n"
5490                 "%second_param1 = OpFunctionParameter %v4f32\n"
5491                 "OpLine %file_name 1 3\n"
5492                 "OpLine %file_name 1 2\n"
5493                 "%label_secondfunction = OpLabel\n"
5494                 "OpLine %file_name 0 2\n"
5495                 "OpReturnValue %second_param1\n"
5496                 "OpFunctionEnd\n"
5497                 "OpLine %file_name 0 2\n"
5498                 "OpLine %file_name 0 2\n";
5499
5500         fragments["testfun"]            =
5501                 // A %test_code function that returns its argument unchanged.
5502                 "OpLine %file_name 1 0\n"
5503                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
5504                 "OpLine %file_name 16 330\n"
5505                 "%param1 = OpFunctionParameter %v4f32\n"
5506                 "OpLine %file_name 14 442\n"
5507                 "%label_testfun = OpLabel\n"
5508                 "OpLine %file_name 11 1024\n"
5509                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
5510                 "OpLine %file_name 2 97\n"
5511                 "OpReturnValue %val1\n"
5512                 "OpFunctionEnd\n"
5513                 "OpLine %file_name 5 32\n";
5514
5515         for (size_t i = 0; i < problemStrings.size(); ++i)
5516         {
5517                 map<string, string> testFragments = fragments;
5518                 testFragments["debug"] += "%file_name = OpString \"" + problemStrings[i].second + "\"\n";
5519                 createTestsForAllStages(string("opline") + "_" + problemStrings[i].first, defaultColors, defaultColors, testFragments, opLineTests.get());
5520         }
5521
5522         return opLineTests.release();
5523 }
5524
5525 tcu::TestCaseGroup* createOpConstantNullTests(tcu::TestContext& testCtx)
5526 {
5527         de::MovePtr<tcu::TestCaseGroup> opConstantNullTests             (new tcu::TestCaseGroup(testCtx, "opconstantnull", "OpConstantNull instruction"));
5528         RGBA                                                    colors[4];
5529
5530
5531         const char                                              functionStart[] =
5532                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
5533                 "%param1 = OpFunctionParameter %v4f32\n"
5534                 "%lbl    = OpLabel\n";
5535
5536         const char                                              functionEnd[]   =
5537                 "OpReturnValue %transformed_param\n"
5538                 "OpFunctionEnd\n";
5539
5540         struct NameConstantsCode
5541         {
5542                 string name;
5543                 string constants;
5544                 string code;
5545         };
5546
5547         NameConstantsCode tests[] =
5548         {
5549                 {
5550                         "vec4",
5551                         "%cnull = OpConstantNull %v4f32\n",
5552                         "%transformed_param = OpFAdd %v4f32 %param1 %cnull\n"
5553                 },
5554                 {
5555                         "float",
5556                         "%cnull = OpConstantNull %f32\n",
5557                         "%vp = OpVariable %fp_v4f32 Function\n"
5558                         "%v  = OpLoad %v4f32 %vp\n"
5559                         "%v0 = OpVectorInsertDynamic %v4f32 %v %cnull %c_i32_0\n"
5560                         "%v1 = OpVectorInsertDynamic %v4f32 %v0 %cnull %c_i32_1\n"
5561                         "%v2 = OpVectorInsertDynamic %v4f32 %v1 %cnull %c_i32_2\n"
5562                         "%v3 = OpVectorInsertDynamic %v4f32 %v2 %cnull %c_i32_3\n"
5563                         "%transformed_param = OpFAdd %v4f32 %param1 %v3\n"
5564                 },
5565                 {
5566                         "bool",
5567                         "%cnull             = OpConstantNull %bool\n",
5568                         "%v                 = OpVariable %fp_v4f32 Function\n"
5569                         "                     OpStore %v %param1\n"
5570                         "                     OpSelectionMerge %false_label None\n"
5571                         "                     OpBranchConditional %cnull %true_label %false_label\n"
5572                         "%true_label        = OpLabel\n"
5573                         "                     OpStore %v %c_v4f32_0_5_0_5_0_5_0_5\n"
5574                         "                     OpBranch %false_label\n"
5575                         "%false_label       = OpLabel\n"
5576                         "%transformed_param = OpLoad %v4f32 %v\n"
5577                 },
5578                 {
5579                         "i32",
5580                         "%cnull             = OpConstantNull %i32\n",
5581                         "%v                 = OpVariable %fp_v4f32 Function %c_v4f32_0_5_0_5_0_5_0_5\n"
5582                         "%b                 = OpIEqual %bool %cnull %c_i32_0\n"
5583                         "                     OpSelectionMerge %false_label None\n"
5584                         "                     OpBranchConditional %b %true_label %false_label\n"
5585                         "%true_label        = OpLabel\n"
5586                         "                     OpStore %v %param1\n"
5587                         "                     OpBranch %false_label\n"
5588                         "%false_label       = OpLabel\n"
5589                         "%transformed_param = OpLoad %v4f32 %v\n"
5590                 },
5591                 {
5592                         "struct",
5593                         "%stype             = OpTypeStruct %f32 %v4f32\n"
5594                         "%fp_stype          = OpTypePointer Function %stype\n"
5595                         "%cnull             = OpConstantNull %stype\n",
5596                         "%v                 = OpVariable %fp_stype Function %cnull\n"
5597                         "%f                 = OpAccessChain %fp_v4f32 %v %c_i32_1\n"
5598                         "%f_val             = OpLoad %v4f32 %f\n"
5599                         "%transformed_param = OpFAdd %v4f32 %param1 %f_val\n"
5600                 },
5601                 {
5602                         "array",
5603                         "%a4_v4f32          = OpTypeArray %v4f32 %c_u32_4\n"
5604                         "%fp_a4_v4f32       = OpTypePointer Function %a4_v4f32\n"
5605                         "%cnull             = OpConstantNull %a4_v4f32\n",
5606                         "%v                 = OpVariable %fp_a4_v4f32 Function %cnull\n"
5607                         "%f                 = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
5608                         "%f1                = OpAccessChain %fp_v4f32 %v %c_u32_1\n"
5609                         "%f2                = OpAccessChain %fp_v4f32 %v %c_u32_2\n"
5610                         "%f3                = OpAccessChain %fp_v4f32 %v %c_u32_3\n"
5611                         "%f_val             = OpLoad %v4f32 %f\n"
5612                         "%f1_val            = OpLoad %v4f32 %f1\n"
5613                         "%f2_val            = OpLoad %v4f32 %f2\n"
5614                         "%f3_val            = OpLoad %v4f32 %f3\n"
5615                         "%t0                = OpFAdd %v4f32 %param1 %f_val\n"
5616                         "%t1                = OpFAdd %v4f32 %t0 %f1_val\n"
5617                         "%t2                = OpFAdd %v4f32 %t1 %f2_val\n"
5618                         "%transformed_param = OpFAdd %v4f32 %t2 %f3_val\n"
5619                 },
5620                 {
5621                         "matrix",
5622                         "%mat4x4_f32        = OpTypeMatrix %v4f32 4\n"
5623                         "%cnull             = OpConstantNull %mat4x4_f32\n",
5624                         // Our null matrix * any vector should result in a zero vector.
5625                         "%v                 = OpVectorTimesMatrix %v4f32 %param1 %cnull\n"
5626                         "%transformed_param = OpFAdd %v4f32 %param1 %v\n"
5627                 }
5628         };
5629
5630         getHalfColorsFullAlpha(colors);
5631
5632         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
5633         {
5634                 map<string, string> fragments;
5635                 fragments["pre_main"] = tests[testNdx].constants;
5636                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
5637                 createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, opConstantNullTests.get());
5638         }
5639         return opConstantNullTests.release();
5640 }
5641 tcu::TestCaseGroup* createOpConstantCompositeTests(tcu::TestContext& testCtx)
5642 {
5643         de::MovePtr<tcu::TestCaseGroup> opConstantCompositeTests                (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "OpConstantComposite instruction"));
5644         RGBA                                                    inputColors[4];
5645         RGBA                                                    outputColors[4];
5646
5647
5648         const char                                              functionStart[]  =
5649                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
5650                 "%param1 = OpFunctionParameter %v4f32\n"
5651                 "%lbl    = OpLabel\n";
5652
5653         const char                                              functionEnd[]           =
5654                 "OpReturnValue %transformed_param\n"
5655                 "OpFunctionEnd\n";
5656
5657         struct NameConstantsCode
5658         {
5659                 string name;
5660                 string constants;
5661                 string code;
5662         };
5663
5664         NameConstantsCode tests[] =
5665         {
5666                 {
5667                         "vec4",
5668
5669                         "%cval              = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0\n",
5670                         "%transformed_param = OpFAdd %v4f32 %param1 %cval\n"
5671                 },
5672                 {
5673                         "struct",
5674
5675                         "%stype             = OpTypeStruct %v4f32 %f32\n"
5676                         "%fp_stype          = OpTypePointer Function %stype\n"
5677                         "%f32_n_1           = OpConstant %f32 -1.0\n"
5678                         "%f32_1_5           = OpConstant %f32 !0x3fc00000\n" // +1.5
5679                         "%cvec              = OpConstantComposite %v4f32 %f32_1_5 %f32_1_5 %f32_1_5 %c_f32_1\n"
5680                         "%cval              = OpConstantComposite %stype %cvec %f32_n_1\n",
5681
5682                         "%v                 = OpVariable %fp_stype Function %cval\n"
5683                         "%vec_ptr           = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
5684                         "%f32_ptr           = OpAccessChain %fp_f32 %v %c_u32_1\n"
5685                         "%vec_val           = OpLoad %v4f32 %vec_ptr\n"
5686                         "%f32_val           = OpLoad %f32 %f32_ptr\n"
5687                         "%tmp1              = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_1 %f32_val\n" // vec4(-1)
5688                         "%tmp2              = OpFAdd %v4f32 %tmp1 %param1\n" // param1 + vec4(-1)
5689                         "%transformed_param = OpFAdd %v4f32 %tmp2 %vec_val\n" // param1 + vec4(-1) + vec4(1.5, 1.5, 1.5, 1.0)
5690                 },
5691                 {
5692                         // [1|0|0|0.5] [x] = x + 0.5
5693                         // [0|1|0|0.5] [y] = y + 0.5
5694                         // [0|0|1|0.5] [z] = z + 0.5
5695                         // [0|0|0|1  ] [1] = 1
5696                         "matrix",
5697
5698                         "%mat4x4_f32          = OpTypeMatrix %v4f32 4\n"
5699                     "%v4f32_1_0_0_0       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_0 %c_f32_0 %c_f32_0\n"
5700                     "%v4f32_0_1_0_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_1 %c_f32_0 %c_f32_0\n"
5701                     "%v4f32_0_0_1_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_1 %c_f32_0\n"
5702                     "%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"
5703                         "%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",
5704
5705                         "%transformed_param   = OpMatrixTimesVector %v4f32 %cval %param1\n"
5706                 },
5707                 {
5708                         "array",
5709
5710                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
5711                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
5712                         "%f32_n_1             = OpConstant %f32 -1.0\n"
5713                         "%f32_1_5             = OpConstant %f32 !0x3fc00000\n" // +1.5
5714                         "%carr                = OpConstantComposite %a4f32 %c_f32_0 %f32_n_1 %f32_1_5 %c_f32_0\n",
5715
5716                         "%v                   = OpVariable %fp_a4f32 Function %carr\n"
5717                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_0\n"
5718                         "%f1                  = OpAccessChain %fp_f32 %v %c_u32_1\n"
5719                         "%f2                  = OpAccessChain %fp_f32 %v %c_u32_2\n"
5720                         "%f3                  = OpAccessChain %fp_f32 %v %c_u32_3\n"
5721                         "%f_val               = OpLoad %f32 %f\n"
5722                         "%f1_val              = OpLoad %f32 %f1\n"
5723                         "%f2_val              = OpLoad %f32 %f2\n"
5724                         "%f3_val              = OpLoad %f32 %f3\n"
5725                         "%ftot1               = OpFAdd %f32 %f_val %f1_val\n"
5726                         "%ftot2               = OpFAdd %f32 %ftot1 %f2_val\n"
5727                         "%ftot3               = OpFAdd %f32 %ftot2 %f3_val\n"  // 0 - 1 + 1.5 + 0
5728                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %ftot3\n"
5729                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
5730                 },
5731                 {
5732                         //
5733                         // [
5734                         //   {
5735                         //      0.0,
5736                         //      [ 1.0, 1.0, 1.0, 1.0]
5737                         //   },
5738                         //   {
5739                         //      1.0,
5740                         //      [ 0.0, 0.5, 0.0, 0.0]
5741                         //   }, //     ^^^
5742                         //   {
5743                         //      0.0,
5744                         //      [ 1.0, 1.0, 1.0, 1.0]
5745                         //   }
5746                         // ]
5747                         "array_of_struct_of_array",
5748
5749                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
5750                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
5751                         "%stype               = OpTypeStruct %f32 %a4f32\n"
5752                         "%a3stype             = OpTypeArray %stype %c_u32_3\n"
5753                         "%fp_a3stype          = OpTypePointer Function %a3stype\n"
5754                         "%ca4f32_0            = OpConstantComposite %a4f32 %c_f32_0 %c_f32_0_5 %c_f32_0 %c_f32_0\n"
5755                         "%ca4f32_1            = OpConstantComposite %a4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
5756                         "%cstype1             = OpConstantComposite %stype %c_f32_0 %ca4f32_1\n"
5757                         "%cstype2             = OpConstantComposite %stype %c_f32_1 %ca4f32_0\n"
5758                         "%carr                = OpConstantComposite %a3stype %cstype1 %cstype2 %cstype1",
5759
5760                         "%v                   = OpVariable %fp_a3stype Function %carr\n"
5761                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_1 %c_u32_1 %c_u32_1\n"
5762                         "%f_l                 = OpLoad %f32 %f\n"
5763                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %f_l\n"
5764                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
5765                 }
5766         };
5767
5768         getHalfColorsFullAlpha(inputColors);
5769         outputColors[0] = RGBA(255, 255, 255, 255);
5770         outputColors[1] = RGBA(255, 127, 127, 255);
5771         outputColors[2] = RGBA(127, 255, 127, 255);
5772         outputColors[3] = RGBA(127, 127, 255, 255);
5773
5774         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
5775         {
5776                 map<string, string> fragments;
5777                 fragments["pre_main"] = tests[testNdx].constants;
5778                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
5779                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, opConstantCompositeTests.get());
5780         }
5781         return opConstantCompositeTests.release();
5782 }
5783
5784 tcu::TestCaseGroup* createSelectionBlockOrderTests(tcu::TestContext& testCtx)
5785 {
5786         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "selection_block_order", "Out-of-order blocks for selection"));
5787         RGBA                                                    inputColors[4];
5788         RGBA                                                    outputColors[4];
5789         map<string, string>                             fragments;
5790
5791         // vec4 test_code(vec4 param) {
5792         //   vec4 result = param;
5793         //   for (int i = 0; i < 4; ++i) {
5794         //     if (i == 0) result[i] = 0.;
5795         //     else        result[i] = 1. - result[i];
5796         //   }
5797         //   return result;
5798         // }
5799         const char                                              function[]                      =
5800                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
5801                 "%param1    = OpFunctionParameter %v4f32\n"
5802                 "%lbl       = OpLabel\n"
5803                 "%iptr      = OpVariable %fp_i32 Function\n"
5804                 "%result    = OpVariable %fp_v4f32 Function\n"
5805                 "             OpStore %iptr %c_i32_0\n"
5806                 "             OpStore %result %param1\n"
5807                 "             OpBranch %loop\n"
5808
5809                 // Loop entry block.
5810                 "%loop      = OpLabel\n"
5811                 "%ival      = OpLoad %i32 %iptr\n"
5812                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
5813                 "             OpLoopMerge %exit %if_entry None\n"
5814                 "             OpBranchConditional %lt_4 %if_entry %exit\n"
5815
5816                 // Merge block for loop.
5817                 "%exit      = OpLabel\n"
5818                 "%ret       = OpLoad %v4f32 %result\n"
5819                 "             OpReturnValue %ret\n"
5820
5821                 // If-statement entry block.
5822                 "%if_entry  = OpLabel\n"
5823                 "%loc       = OpAccessChain %fp_f32 %result %ival\n"
5824                 "%eq_0      = OpIEqual %bool %ival %c_i32_0\n"
5825                 "             OpSelectionMerge %if_exit None\n"
5826                 "             OpBranchConditional %eq_0 %if_true %if_false\n"
5827
5828                 // False branch for if-statement.
5829                 "%if_false  = OpLabel\n"
5830                 "%val       = OpLoad %f32 %loc\n"
5831                 "%sub       = OpFSub %f32 %c_f32_1 %val\n"
5832                 "             OpStore %loc %sub\n"
5833                 "             OpBranch %if_exit\n"
5834
5835                 // Merge block for if-statement.
5836                 "%if_exit   = OpLabel\n"
5837                 "%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
5838                 "             OpStore %iptr %ival_next\n"
5839                 "             OpBranch %loop\n"
5840
5841                 // True branch for if-statement.
5842                 "%if_true   = OpLabel\n"
5843                 "             OpStore %loc %c_f32_0\n"
5844                 "             OpBranch %if_exit\n"
5845
5846                 "             OpFunctionEnd\n";
5847
5848         fragments["testfun"]    = function;
5849
5850         inputColors[0]                  = RGBA(127, 127, 127, 0);
5851         inputColors[1]                  = RGBA(127, 0,   0,   0);
5852         inputColors[2]                  = RGBA(0,   127, 0,   0);
5853         inputColors[3]                  = RGBA(0,   0,   127, 0);
5854
5855         outputColors[0]                 = RGBA(0, 128, 128, 255);
5856         outputColors[1]                 = RGBA(0, 255, 255, 255);
5857         outputColors[2]                 = RGBA(0, 128, 255, 255);
5858         outputColors[3]                 = RGBA(0, 255, 128, 255);
5859
5860         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
5861
5862         return group.release();
5863 }
5864
5865 tcu::TestCaseGroup* createSwitchBlockOrderTests(tcu::TestContext& testCtx)
5866 {
5867         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "switch_block_order", "Out-of-order blocks for switch"));
5868         RGBA                                                    inputColors[4];
5869         RGBA                                                    outputColors[4];
5870         map<string, string>                             fragments;
5871
5872         const char                                              typesAndConstants[]     =
5873                 "%c_f32_p2  = OpConstant %f32 0.2\n"
5874                 "%c_f32_p4  = OpConstant %f32 0.4\n"
5875                 "%c_f32_p6  = OpConstant %f32 0.6\n"
5876                 "%c_f32_p8  = OpConstant %f32 0.8\n";
5877
5878         // vec4 test_code(vec4 param) {
5879         //   vec4 result = param;
5880         //   for (int i = 0; i < 4; ++i) {
5881         //     switch (i) {
5882         //       case 0: result[i] += .2; break;
5883         //       case 1: result[i] += .6; break;
5884         //       case 2: result[i] += .4; break;
5885         //       case 3: result[i] += .8; break;
5886         //       default: break; // unreachable
5887         //     }
5888         //   }
5889         //   return result;
5890         // }
5891         const char                                              function[]                      =
5892                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
5893                 "%param1    = OpFunctionParameter %v4f32\n"
5894                 "%lbl       = OpLabel\n"
5895                 "%iptr      = OpVariable %fp_i32 Function\n"
5896                 "%result    = OpVariable %fp_v4f32 Function\n"
5897                 "             OpStore %iptr %c_i32_0\n"
5898                 "             OpStore %result %param1\n"
5899                 "             OpBranch %loop\n"
5900
5901                 // Loop entry block.
5902                 "%loop      = OpLabel\n"
5903                 "%ival      = OpLoad %i32 %iptr\n"
5904                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
5905                 "             OpLoopMerge %exit %switch_exit None\n"
5906                 "             OpBranchConditional %lt_4 %switch_entry %exit\n"
5907
5908                 // Merge block for loop.
5909                 "%exit      = OpLabel\n"
5910                 "%ret       = OpLoad %v4f32 %result\n"
5911                 "             OpReturnValue %ret\n"
5912
5913                 // Switch-statement entry block.
5914                 "%switch_entry   = OpLabel\n"
5915                 "%loc            = OpAccessChain %fp_f32 %result %ival\n"
5916                 "%val            = OpLoad %f32 %loc\n"
5917                 "                  OpSelectionMerge %switch_exit None\n"
5918                 "                  OpSwitch %ival %switch_default 0 %case0 1 %case1 2 %case2 3 %case3\n"
5919
5920                 "%case2          = OpLabel\n"
5921                 "%addp4          = OpFAdd %f32 %val %c_f32_p4\n"
5922                 "                  OpStore %loc %addp4\n"
5923                 "                  OpBranch %switch_exit\n"
5924
5925                 "%switch_default = OpLabel\n"
5926                 "                  OpUnreachable\n"
5927
5928                 "%case3          = OpLabel\n"
5929                 "%addp8          = OpFAdd %f32 %val %c_f32_p8\n"
5930                 "                  OpStore %loc %addp8\n"
5931                 "                  OpBranch %switch_exit\n"
5932
5933                 "%case0          = OpLabel\n"
5934                 "%addp2          = OpFAdd %f32 %val %c_f32_p2\n"
5935                 "                  OpStore %loc %addp2\n"
5936                 "                  OpBranch %switch_exit\n"
5937
5938                 // Merge block for switch-statement.
5939                 "%switch_exit    = OpLabel\n"
5940                 "%ival_next      = OpIAdd %i32 %ival %c_i32_1\n"
5941                 "                  OpStore %iptr %ival_next\n"
5942                 "                  OpBranch %loop\n"
5943
5944                 "%case1          = OpLabel\n"
5945                 "%addp6          = OpFAdd %f32 %val %c_f32_p6\n"
5946                 "                  OpStore %loc %addp6\n"
5947                 "                  OpBranch %switch_exit\n"
5948
5949                 "                  OpFunctionEnd\n";
5950
5951         fragments["pre_main"]   = typesAndConstants;
5952         fragments["testfun"]    = function;
5953
5954         inputColors[0]                  = RGBA(127, 27,  127, 51);
5955         inputColors[1]                  = RGBA(127, 0,   0,   51);
5956         inputColors[2]                  = RGBA(0,   27,  0,   51);
5957         inputColors[3]                  = RGBA(0,   0,   127, 51);
5958
5959         outputColors[0]                 = RGBA(178, 180, 229, 255);
5960         outputColors[1]                 = RGBA(178, 153, 102, 255);
5961         outputColors[2]                 = RGBA(51,  180, 102, 255);
5962         outputColors[3]                 = RGBA(51,  153, 229, 255);
5963
5964         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
5965
5966         return group.release();
5967 }
5968
5969 tcu::TestCaseGroup* createDecorationGroupTests(tcu::TestContext& testCtx)
5970 {
5971         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "decoration_group", "Decoration group tests"));
5972         RGBA                                                    inputColors[4];
5973         RGBA                                                    outputColors[4];
5974         map<string, string>                             fragments;
5975
5976         const char                                              decorations[]           =
5977                 "OpDecorate %array_group         ArrayStride 4\n"
5978                 "OpDecorate %struct_member_group Offset 0\n"
5979                 "%array_group         = OpDecorationGroup\n"
5980                 "%struct_member_group = OpDecorationGroup\n"
5981
5982                 "OpDecorate %group1 RelaxedPrecision\n"
5983                 "OpDecorate %group3 RelaxedPrecision\n"
5984                 "OpDecorate %group3 Invariant\n"
5985                 "OpDecorate %group3 Restrict\n"
5986                 "%group0 = OpDecorationGroup\n"
5987                 "%group1 = OpDecorationGroup\n"
5988                 "%group3 = OpDecorationGroup\n";
5989
5990         const char                                              typesAndConstants[]     =
5991                 "%a3f32     = OpTypeArray %f32 %c_u32_3\n"
5992                 "%struct1   = OpTypeStruct %a3f32\n"
5993                 "%struct2   = OpTypeStruct %a3f32\n"
5994                 "%fp_struct1 = OpTypePointer Function %struct1\n"
5995                 "%fp_struct2 = OpTypePointer Function %struct2\n"
5996                 "%c_f32_2    = OpConstant %f32 2.\n"
5997                 "%c_f32_n2   = OpConstant %f32 -2.\n"
5998
5999                 "%c_a3f32_1 = OpConstantComposite %a3f32 %c_f32_1 %c_f32_2 %c_f32_1\n"
6000                 "%c_a3f32_2 = OpConstantComposite %a3f32 %c_f32_n1 %c_f32_n2 %c_f32_n1\n"
6001                 "%c_struct1 = OpConstantComposite %struct1 %c_a3f32_1\n"
6002                 "%c_struct2 = OpConstantComposite %struct2 %c_a3f32_2\n";
6003
6004         const char                                              function[]                      =
6005                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6006                 "%param     = OpFunctionParameter %v4f32\n"
6007                 "%entry     = OpLabel\n"
6008                 "%result    = OpVariable %fp_v4f32 Function\n"
6009                 "%v_struct1 = OpVariable %fp_struct1 Function\n"
6010                 "%v_struct2 = OpVariable %fp_struct2 Function\n"
6011                 "             OpStore %result %param\n"
6012                 "             OpStore %v_struct1 %c_struct1\n"
6013                 "             OpStore %v_struct2 %c_struct2\n"
6014                 "%ptr1      = OpAccessChain %fp_f32 %v_struct1 %c_i32_0 %c_i32_2\n"
6015                 "%val1      = OpLoad %f32 %ptr1\n"
6016                 "%ptr2      = OpAccessChain %fp_f32 %v_struct2 %c_i32_0 %c_i32_2\n"
6017                 "%val2      = OpLoad %f32 %ptr2\n"
6018                 "%addvalues = OpFAdd %f32 %val1 %val2\n"
6019                 "%ptr       = OpAccessChain %fp_f32 %result %c_i32_1\n"
6020                 "%val       = OpLoad %f32 %ptr\n"
6021                 "%addresult = OpFAdd %f32 %addvalues %val\n"
6022                 "             OpStore %ptr %addresult\n"
6023                 "%ret       = OpLoad %v4f32 %result\n"
6024                 "             OpReturnValue %ret\n"
6025                 "             OpFunctionEnd\n";
6026
6027         struct CaseNameDecoration
6028         {
6029                 string name;
6030                 string decoration;
6031         };
6032
6033         CaseNameDecoration tests[] =
6034         {
6035                 {
6036                         "same_decoration_group_on_multiple_types",
6037                         "OpGroupMemberDecorate %struct_member_group %struct1 0 %struct2 0\n"
6038                 },
6039                 {
6040                         "empty_decoration_group",
6041                         "OpGroupDecorate %group0      %a3f32\n"
6042                         "OpGroupDecorate %group0      %result\n"
6043                 },
6044                 {
6045                         "one_element_decoration_group",
6046                         "OpGroupDecorate %array_group %a3f32\n"
6047                 },
6048                 {
6049                         "multiple_elements_decoration_group",
6050                         "OpGroupDecorate %group3      %v_struct1\n"
6051                 },
6052                 {
6053                         "multiple_decoration_groups_on_same_variable",
6054                         "OpGroupDecorate %group0      %v_struct2\n"
6055                         "OpGroupDecorate %group1      %v_struct2\n"
6056                         "OpGroupDecorate %group3      %v_struct2\n"
6057                 },
6058                 {
6059                         "same_decoration_group_multiple_times",
6060                         "OpGroupDecorate %group1      %addvalues\n"
6061                         "OpGroupDecorate %group1      %addvalues\n"
6062                         "OpGroupDecorate %group1      %addvalues\n"
6063                 },
6064
6065         };
6066
6067         getHalfColorsFullAlpha(inputColors);
6068         getHalfColorsFullAlpha(outputColors);
6069
6070         for (size_t idx = 0; idx < (sizeof(tests) / sizeof(tests[0])); ++idx)
6071         {
6072                 fragments["decoration"] = decorations + tests[idx].decoration;
6073                 fragments["pre_main"]   = typesAndConstants;
6074                 fragments["testfun"]    = function;
6075
6076                 createTestsForAllStages(tests[idx].name, inputColors, outputColors, fragments, group.get());
6077         }
6078
6079         return group.release();
6080 }
6081
6082 struct SpecConstantTwoIntGraphicsCase
6083 {
6084         const char*             caseName;
6085         const char*             scDefinition0;
6086         const char*             scDefinition1;
6087         const char*             scResultType;
6088         const char*             scOperation;
6089         deInt32                 scActualValue0;
6090         deInt32                 scActualValue1;
6091         const char*             resultOperation;
6092         RGBA                    expectedColors[4];
6093
6094                                         SpecConstantTwoIntGraphicsCase (const char* name,
6095                                                                                         const char* definition0,
6096                                                                                         const char* definition1,
6097                                                                                         const char* resultType,
6098                                                                                         const char* operation,
6099                                                                                         deInt32         value0,
6100                                                                                         deInt32         value1,
6101                                                                                         const char* resultOp,
6102                                                                                         const RGBA      (&output)[4])
6103                                                 : caseName                      (name)
6104                                                 , scDefinition0         (definition0)
6105                                                 , scDefinition1         (definition1)
6106                                                 , scResultType          (resultType)
6107                                                 , scOperation           (operation)
6108                                                 , scActualValue0        (value0)
6109                                                 , scActualValue1        (value1)
6110                                                 , resultOperation       (resultOp)
6111         {
6112                 expectedColors[0] = output[0];
6113                 expectedColors[1] = output[1];
6114                 expectedColors[2] = output[2];
6115                 expectedColors[3] = output[3];
6116         }
6117 };
6118
6119 tcu::TestCaseGroup* createSpecConstantTests (tcu::TestContext& testCtx)
6120 {
6121         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
6122         vector<SpecConstantTwoIntGraphicsCase>  cases;
6123         RGBA                                                    inputColors[4];
6124         RGBA                                                    outputColors0[4];
6125         RGBA                                                    outputColors1[4];
6126         RGBA                                                    outputColors2[4];
6127
6128         const char      decorations1[]                  =
6129                 "OpDecorate %sc_0  SpecId 0\n"
6130                 "OpDecorate %sc_1  SpecId 1\n";
6131
6132         const char      typesAndConstants1[]    =
6133                 "${OPTYPE_DEFINITIONS:opt}"
6134                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
6135                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
6136                 "%sc_op     = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n";
6137
6138         const char      function1[]                             =
6139                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6140                 "%param     = OpFunctionParameter %v4f32\n"
6141                 "%label     = OpLabel\n"
6142                 "${TYPE_CONVERT:opt}"
6143                 "%result    = OpVariable %fp_v4f32 Function\n"
6144                 "             OpStore %result %param\n"
6145                 "%gen       = ${GEN_RESULT}\n"
6146                 "%index     = OpIAdd %i32 %gen %c_i32_1\n"
6147                 "%loc       = OpAccessChain %fp_f32 %result %index\n"
6148                 "%val       = OpLoad %f32 %loc\n"
6149                 "%add       = OpFAdd %f32 %val %c_f32_0_5\n"
6150                 "             OpStore %loc %add\n"
6151                 "%ret       = OpLoad %v4f32 %result\n"
6152                 "             OpReturnValue %ret\n"
6153                 "             OpFunctionEnd\n";
6154
6155         inputColors[0] = RGBA(127, 127, 127, 255);
6156         inputColors[1] = RGBA(127, 0,   0,   255);
6157         inputColors[2] = RGBA(0,   127, 0,   255);
6158         inputColors[3] = RGBA(0,   0,   127, 255);
6159
6160         // Derived from inputColors[x] by adding 128 to inputColors[x][0].
6161         outputColors0[0] = RGBA(255, 127, 127, 255);
6162         outputColors0[1] = RGBA(255, 0,   0,   255);
6163         outputColors0[2] = RGBA(128, 127, 0,   255);
6164         outputColors0[3] = RGBA(128, 0,   127, 255);
6165
6166         // Derived from inputColors[x] by adding 128 to inputColors[x][1].
6167         outputColors1[0] = RGBA(127, 255, 127, 255);
6168         outputColors1[1] = RGBA(127, 128, 0,   255);
6169         outputColors1[2] = RGBA(0,   255, 0,   255);
6170         outputColors1[3] = RGBA(0,   128, 127, 255);
6171
6172         // Derived from inputColors[x] by adding 128 to inputColors[x][2].
6173         outputColors2[0] = RGBA(127, 127, 255, 255);
6174         outputColors2[1] = RGBA(127, 0,   128, 255);
6175         outputColors2[2] = RGBA(0,   127, 128, 255);
6176         outputColors2[3] = RGBA(0,   0,   255, 255);
6177
6178         const char addZeroToSc[]                = "OpIAdd %i32 %c_i32_0 %sc_op";
6179         const char addZeroToSc32[]              = "OpIAdd %i32 %c_i32_0 %sc_op32";
6180         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_op %c_i32_1 %c_i32_0";
6181         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_op %c_i32_0 %c_i32_1";
6182
6183         cases.push_back(SpecConstantTwoIntGraphicsCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                             19,             -20,    addZeroToSc,            outputColors0));
6184         cases.push_back(SpecConstantTwoIntGraphicsCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                             19,             20,             addZeroToSc,            outputColors0));
6185         cases.push_back(SpecConstantTwoIntGraphicsCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                             -1,             -1,             addZeroToSc,            outputColors2));
6186         cases.push_back(SpecConstantTwoIntGraphicsCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                             -126,   126,    addZeroToSc,            outputColors0));
6187         cases.push_back(SpecConstantTwoIntGraphicsCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                             126,    126,    addZeroToSc,            outputColors2));
6188         cases.push_back(SpecConstantTwoIntGraphicsCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
6189         cases.push_back(SpecConstantTwoIntGraphicsCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
6190         cases.push_back(SpecConstantTwoIntGraphicsCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                             1001,   500,    addZeroToSc,            outputColors2));
6191         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                             0x33,   0x0d,   addZeroToSc,            outputColors2));
6192         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                             0,              1,              addZeroToSc,            outputColors2));
6193         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                             0x2e,   0x2f,   addZeroToSc,            outputColors2));
6194         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                             2,              1,              addZeroToSc,            outputColors2));
6195         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                             -4,             2,              addZeroToSc,            outputColors0));
6196         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                             1,              0,              addZeroToSc,            outputColors2));
6197         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                             -20,    -10,    selectTrueUsingSc,      outputColors2));
6198         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                             10,             20,             selectTrueUsingSc,      outputColors2));
6199         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
6200         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                             10,             5,              selectTrueUsingSc,      outputColors2));
6201         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                             -10,    -10,    selectTrueUsingSc,      outputColors2));
6202         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                             50,             100,    selectTrueUsingSc,      outputColors2));
6203         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
6204         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                             10,             10,             selectTrueUsingSc,      outputColors2));
6205         cases.push_back(SpecConstantTwoIntGraphicsCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                             42,             24,             selectFalseUsingSc,     outputColors2));
6206         cases.push_back(SpecConstantTwoIntGraphicsCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
6207         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
6208         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
6209         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
6210         cases.push_back(SpecConstantTwoIntGraphicsCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                                   -1,             0,              addZeroToSc,            outputColors2));
6211         cases.push_back(SpecConstantTwoIntGraphicsCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                                   -2,             0,              addZeroToSc,            outputColors2));
6212         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                                   1,              0,              selectFalseUsingSc,     outputColors2));
6213         cases.push_back(SpecConstantTwoIntGraphicsCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %c_i32_0",    1,              1,              addZeroToSc,            outputColors2));
6214         cases.push_back(SpecConstantTwoIntGraphicsCase("sconvert",                              " %i32 0",              " %i32 0",              "%i16",         "SConvert             %sc_0",                                   -1,             0,              addZeroToSc32,          outputColors0));
6215         // -1082130432 stored as 32-bit two's complement is the binary representation of -1 as IEEE-754 Float
6216         cases.push_back(SpecConstantTwoIntGraphicsCase("fconvert",                              " %f32 0",              " %f32 0",              "%f64",         "FConvert             %sc_0",                                   -1082130432, 0, addZeroToSc32,          outputColors0));
6217         // \todo[2015-12-1 antiagainst] OpQuantizeToF16
6218
6219         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
6220         {
6221                 map<string, string>                     specializations;
6222                 map<string, string>                     fragments;
6223                 vector<deInt32>                         specConstants;
6224                 vector<string>                          features;
6225                 PushConstants                           noPushConstants;
6226                 GraphicsResources                       noResources;
6227                 GraphicsInterfaces                      noInterfaces;
6228                 std::vector<std::string>        noExtensions;
6229
6230                 // Special SPIR-V code for SConvert-case
6231                 if (strcmp(cases[caseNdx].caseName, "sconvert") == 0)
6232                 {
6233                         features.push_back("shaderInt16");
6234                         fragments["capability"]                                 = "OpCapability Int16\n";                                       // Adds 16-bit integer capability
6235                         specializations["OPTYPE_DEFINITIONS"]   = "%i16 = OpTypeInt 16 1\n";                            // Adds 16-bit integer type
6236                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpSConvert %i32 %sc_op\n";        // Converts 16-bit integer to 32-bit integer
6237                 }
6238
6239                 // Special SPIR-V code for FConvert-case
6240                 if (strcmp(cases[caseNdx].caseName, "fconvert") == 0)
6241                 {
6242                         features.push_back("shaderFloat64");
6243                         fragments["capability"]                                 = "OpCapability Float64\n";                                     // Adds 64-bit float capability
6244                         specializations["OPTYPE_DEFINITIONS"]   = "%f64 = OpTypeFloat 64\n";                            // Adds 64-bit float type
6245                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpConvertFToS %i32 %sc_op\n";     // Converts 64-bit float to 32-bit integer
6246                 }
6247
6248                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
6249                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
6250                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
6251                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
6252                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
6253
6254                 fragments["decoration"]                         = tcu::StringTemplate(decorations1).specialize(specializations);
6255                 fragments["pre_main"]                           = tcu::StringTemplate(typesAndConstants1).specialize(specializations);
6256                 fragments["testfun"]                            = tcu::StringTemplate(function1).specialize(specializations);
6257
6258                 specConstants.push_back(cases[caseNdx].scActualValue0);
6259                 specConstants.push_back(cases[caseNdx].scActualValue1);
6260
6261                 createTestsForAllStages(
6262                         cases[caseNdx].caseName, inputColors, cases[caseNdx].expectedColors, fragments, specConstants,
6263                         noPushConstants, noResources, noInterfaces, noExtensions, features, VulkanFeatures(), group.get());
6264         }
6265
6266         const char      decorations2[]                  =
6267                 "OpDecorate %sc_0  SpecId 0\n"
6268                 "OpDecorate %sc_1  SpecId 1\n"
6269                 "OpDecorate %sc_2  SpecId 2\n";
6270
6271         const char      typesAndConstants2[]    =
6272                 "%vec3_0      = OpConstantComposite %v3i32 %c_i32_0 %c_i32_0 %c_i32_0\n"
6273                 "%vec3_undef  = OpUndef %v3i32\n"
6274
6275                 "%sc_0        = OpSpecConstant %i32 0\n"
6276                 "%sc_1        = OpSpecConstant %i32 0\n"
6277                 "%sc_2        = OpSpecConstant %i32 0\n"
6278                 "%sc_vec3_0   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_0        %vec3_0      0\n"                                                 // (sc_0, 0,    0)
6279                 "%sc_vec3_1   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_1        %vec3_0      1\n"                                                 // (0,    sc_1, 0)
6280                 "%sc_vec3_2   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_2        %vec3_0      2\n"                                                 // (0,    0,    sc_2)
6281                 "%sc_vec3_0_s = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_0   %vec3_undef  0          0xFFFFFFFF 2\n"   // (sc_0, ???,  0)
6282                 "%sc_vec3_1_s = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_1   %vec3_undef  0xFFFFFFFF 1          0\n"   // (???,  sc_1, 0)
6283                 "%sc_vec3_2_s = OpSpecConstantOp %v3i32 VectorShuffle    %vec3_undef  %sc_vec3_2   5          0xFFFFFFFF 5\n"   // (sc_2, ???,  sc_2)
6284                 "%sc_vec3_01  = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_0_s %sc_vec3_1_s 1 0 4\n"                                             // (0,    sc_0, sc_1)
6285                 "%sc_vec3_012 = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_01  %sc_vec3_2_s 5 1 2\n"                                             // (sc_2, sc_0, sc_1)
6286                 "%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              0\n"                                                 // sc_2
6287                 "%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              1\n"                                                 // sc_0
6288                 "%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              2\n"                                                 // sc_1
6289                 "%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"                                                              // (sc_2 - sc_0)
6290                 "%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n";                                                             // (sc_2 - sc_0) * sc_1
6291
6292         const char      function2[]                             =
6293                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6294                 "%param     = OpFunctionParameter %v4f32\n"
6295                 "%label     = OpLabel\n"
6296                 "%result    = OpVariable %fp_v4f32 Function\n"
6297                 "             OpStore %result %param\n"
6298                 "%loc       = OpAccessChain %fp_f32 %result %sc_final\n"
6299                 "%val       = OpLoad %f32 %loc\n"
6300                 "%add       = OpFAdd %f32 %val %c_f32_0_5\n"
6301                 "             OpStore %loc %add\n"
6302                 "%ret       = OpLoad %v4f32 %result\n"
6303                 "             OpReturnValue %ret\n"
6304                 "             OpFunctionEnd\n";
6305
6306         map<string, string>     fragments;
6307         vector<deInt32>         specConstants;
6308
6309         fragments["decoration"] = decorations2;
6310         fragments["pre_main"]   = typesAndConstants2;
6311         fragments["testfun"]    = function2;
6312
6313         specConstants.push_back(56789);
6314         specConstants.push_back(-2);
6315         specConstants.push_back(56788);
6316
6317         createTestsForAllStages("vector_related", inputColors, outputColors2, fragments, specConstants, group.get());
6318
6319         return group.release();
6320 }
6321
6322 tcu::TestCaseGroup* createOpPhiTests(tcu::TestContext& testCtx)
6323 {
6324         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
6325         RGBA                                                    inputColors[4];
6326         RGBA                                                    outputColors1[4];
6327         RGBA                                                    outputColors2[4];
6328         RGBA                                                    outputColors3[4];
6329         map<string, string>                             fragments1;
6330         map<string, string>                             fragments2;
6331         map<string, string>                             fragments3;
6332
6333         const char      typesAndConstants1[]    =
6334                 "%c_f32_p2  = OpConstant %f32 0.2\n"
6335                 "%c_f32_p4  = OpConstant %f32 0.4\n"
6336                 "%c_f32_p5  = OpConstant %f32 0.5\n"
6337                 "%c_f32_p8  = OpConstant %f32 0.8\n";
6338
6339         // vec4 test_code(vec4 param) {
6340         //   vec4 result = param;
6341         //   for (int i = 0; i < 4; ++i) {
6342         //     float operand;
6343         //     switch (i) {
6344         //       case 0: operand = .2; break;
6345         //       case 1: operand = .5; break;
6346         //       case 2: operand = .4; break;
6347         //       case 3: operand = .0; break;
6348         //       default: break; // unreachable
6349         //     }
6350         //     result[i] += operand;
6351         //   }
6352         //   return result;
6353         // }
6354         const char      function1[]                             =
6355                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6356                 "%param1    = OpFunctionParameter %v4f32\n"
6357                 "%lbl       = OpLabel\n"
6358                 "%iptr      = OpVariable %fp_i32 Function\n"
6359                 "%result    = OpVariable %fp_v4f32 Function\n"
6360                 "             OpStore %iptr %c_i32_0\n"
6361                 "             OpStore %result %param1\n"
6362                 "             OpBranch %loop\n"
6363
6364                 "%loop      = OpLabel\n"
6365                 "%ival      = OpLoad %i32 %iptr\n"
6366                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6367                 "             OpLoopMerge %exit %phi None\n"
6368                 "             OpBranchConditional %lt_4 %entry %exit\n"
6369
6370                 "%entry     = OpLabel\n"
6371                 "%loc       = OpAccessChain %fp_f32 %result %ival\n"
6372                 "%val       = OpLoad %f32 %loc\n"
6373                 "             OpSelectionMerge %phi None\n"
6374                 "             OpSwitch %ival %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
6375
6376                 "%case0     = OpLabel\n"
6377                 "             OpBranch %phi\n"
6378                 "%case1     = OpLabel\n"
6379                 "             OpBranch %phi\n"
6380                 "%case2     = OpLabel\n"
6381                 "             OpBranch %phi\n"
6382                 "%case3     = OpLabel\n"
6383                 "             OpBranch %phi\n"
6384
6385                 "%default   = OpLabel\n"
6386                 "             OpUnreachable\n"
6387
6388                 "%phi       = OpLabel\n"
6389                 "%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
6390                 "%add       = OpFAdd %f32 %val %operand\n"
6391                 "             OpStore %loc %add\n"
6392                 "%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
6393                 "             OpStore %iptr %ival_next\n"
6394                 "             OpBranch %loop\n"
6395
6396                 "%exit      = OpLabel\n"
6397                 "%ret       = OpLoad %v4f32 %result\n"
6398                 "             OpReturnValue %ret\n"
6399
6400                 "             OpFunctionEnd\n";
6401
6402         fragments1["pre_main"]  = typesAndConstants1;
6403         fragments1["testfun"]   = function1;
6404
6405         getHalfColorsFullAlpha(inputColors);
6406
6407         outputColors1[0]                = RGBA(178, 255, 229, 255);
6408         outputColors1[1]                = RGBA(178, 127, 102, 255);
6409         outputColors1[2]                = RGBA(51,  255, 102, 255);
6410         outputColors1[3]                = RGBA(51,  127, 229, 255);
6411
6412         createTestsForAllStages("out_of_order", inputColors, outputColors1, fragments1, group.get());
6413
6414         const char      typesAndConstants2[]    =
6415                 "%c_f32_p2  = OpConstant %f32 0.2\n";
6416
6417         // Add .4 to the second element of the given parameter.
6418         const char      function2[]                             =
6419                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6420                 "%param     = OpFunctionParameter %v4f32\n"
6421                 "%entry     = OpLabel\n"
6422                 "%result    = OpVariable %fp_v4f32 Function\n"
6423                 "             OpStore %result %param\n"
6424                 "%loc       = OpAccessChain %fp_f32 %result %c_i32_1\n"
6425                 "%val       = OpLoad %f32 %loc\n"
6426                 "             OpBranch %phi\n"
6427
6428                 "%phi        = OpLabel\n"
6429                 "%step       = OpPhi %i32 %c_i32_0  %entry %step_next  %phi\n"
6430                 "%accum      = OpPhi %f32 %val      %entry %accum_next %phi\n"
6431                 "%step_next  = OpIAdd %i32 %step  %c_i32_1\n"
6432                 "%accum_next = OpFAdd %f32 %accum %c_f32_p2\n"
6433                 "%still_loop = OpSLessThan %bool %step %c_i32_2\n"
6434                 "              OpLoopMerge %exit %phi None\n"
6435                 "              OpBranchConditional %still_loop %phi %exit\n"
6436
6437                 "%exit       = OpLabel\n"
6438                 "              OpStore %loc %accum\n"
6439                 "%ret        = OpLoad %v4f32 %result\n"
6440                 "              OpReturnValue %ret\n"
6441
6442                 "              OpFunctionEnd\n";
6443
6444         fragments2["pre_main"]  = typesAndConstants2;
6445         fragments2["testfun"]   = function2;
6446
6447         outputColors2[0]                        = RGBA(127, 229, 127, 255);
6448         outputColors2[1]                        = RGBA(127, 102, 0,   255);
6449         outputColors2[2]                        = RGBA(0,   229, 0,   255);
6450         outputColors2[3]                        = RGBA(0,   102, 127, 255);
6451
6452         createTestsForAllStages("induction", inputColors, outputColors2, fragments2, group.get());
6453
6454         const char      typesAndConstants3[]    =
6455                 "%true      = OpConstantTrue %bool\n"
6456                 "%false     = OpConstantFalse %bool\n"
6457                 "%c_f32_p2  = OpConstant %f32 0.2\n";
6458
6459         // Swap the second and the third element of the given parameter.
6460         const char      function3[]                             =
6461                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6462                 "%param     = OpFunctionParameter %v4f32\n"
6463                 "%entry     = OpLabel\n"
6464                 "%result    = OpVariable %fp_v4f32 Function\n"
6465                 "             OpStore %result %param\n"
6466                 "%a_loc     = OpAccessChain %fp_f32 %result %c_i32_1\n"
6467                 "%a_init    = OpLoad %f32 %a_loc\n"
6468                 "%b_loc     = OpAccessChain %fp_f32 %result %c_i32_2\n"
6469                 "%b_init    = OpLoad %f32 %b_loc\n"
6470                 "             OpBranch %phi\n"
6471
6472                 "%phi        = OpLabel\n"
6473                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
6474                 "%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
6475                 "%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
6476                 "              OpLoopMerge %exit %phi None\n"
6477                 "              OpBranchConditional %still_loop %phi %exit\n"
6478
6479                 "%exit       = OpLabel\n"
6480                 "              OpStore %a_loc %a_next\n"
6481                 "              OpStore %b_loc %b_next\n"
6482                 "%ret        = OpLoad %v4f32 %result\n"
6483                 "              OpReturnValue %ret\n"
6484
6485                 "              OpFunctionEnd\n";
6486
6487         fragments3["pre_main"]  = typesAndConstants3;
6488         fragments3["testfun"]   = function3;
6489
6490         outputColors3[0]                        = RGBA(127, 127, 127, 255);
6491         outputColors3[1]                        = RGBA(127, 0,   0,   255);
6492         outputColors3[2]                        = RGBA(0,   0,   127, 255);
6493         outputColors3[3]                        = RGBA(0,   127, 0,   255);
6494
6495         createTestsForAllStages("swap", inputColors, outputColors3, fragments3, group.get());
6496
6497         return group.release();
6498 }
6499
6500 tcu::TestCaseGroup* createNoContractionTests(tcu::TestContext& testCtx)
6501 {
6502         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
6503         RGBA                                                    inputColors[4];
6504         RGBA                                                    outputColors[4];
6505
6506         // With NoContraction, (1 + 2^-23) * (1 - 2^-23) - 1 should be conducted as a multiplication and an addition separately.
6507         // For the multiplication, the result is 1 - 2^-46, which is out of the precision range for 32-bit float. (32-bit float
6508         // only have 23-bit fraction.) So it will be rounded to 1. Or 0x1.fffffc. Then the final result is 0 or -0x1p-24.
6509         // On the contrary, the result will be 2^-46, which is a normalized number perfectly representable as 32-bit float.
6510         const char                                              constantsAndTypes[]      =
6511                 "%c_vec4_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_0 %c_f32_1\n"
6512                 "%c_vec4_1       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
6513                 "%c_f32_1pl2_23  = OpConstant %f32 0x1.000002p+0\n" // 1 + 2^-23
6514                 "%c_f32_1mi2_23  = OpConstant %f32 0x1.fffffcp-1\n" // 1 - 2^-23
6515                 "%c_f32_n1pn24   = OpConstant %f32 -0x1p-24\n";
6516
6517         const char                                              function[]       =
6518                 "%test_code      = OpFunction %v4f32 None %v4f32_function\n"
6519                 "%param          = OpFunctionParameter %v4f32\n"
6520                 "%label          = OpLabel\n"
6521                 "%var1           = OpVariable %fp_f32 Function %c_f32_1pl2_23\n"
6522                 "%var2           = OpVariable %fp_f32 Function\n"
6523                 "%red            = OpCompositeExtract %f32 %param 0\n"
6524                 "%plus_red       = OpFAdd %f32 %c_f32_1mi2_23 %red\n"
6525                 "                  OpStore %var2 %plus_red\n"
6526                 "%val1           = OpLoad %f32 %var1\n"
6527                 "%val2           = OpLoad %f32 %var2\n"
6528                 "%mul            = OpFMul %f32 %val1 %val2\n"
6529                 "%add            = OpFAdd %f32 %mul %c_f32_n1\n"
6530                 "%is0            = OpFOrdEqual %bool %add %c_f32_0\n"
6531                 "%isn1n24         = OpFOrdEqual %bool %add %c_f32_n1pn24\n"
6532                 "%success        = OpLogicalOr %bool %is0 %isn1n24\n"
6533                 "%v4success      = OpCompositeConstruct %v4bool %success %success %success %success\n"
6534                 "%ret            = OpSelect %v4f32 %v4success %c_vec4_0 %c_vec4_1\n"
6535                 "                  OpReturnValue %ret\n"
6536                 "                  OpFunctionEnd\n";
6537
6538         struct CaseNameDecoration
6539         {
6540                 string name;
6541                 string decoration;
6542         };
6543
6544
6545         CaseNameDecoration tests[] = {
6546                 {"multiplication",      "OpDecorate %mul NoContraction"},
6547                 {"addition",            "OpDecorate %add NoContraction"},
6548                 {"both",                        "OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"},
6549         };
6550
6551         getHalfColorsFullAlpha(inputColors);
6552
6553         for (deUint8 idx = 0; idx < 4; ++idx)
6554         {
6555                 inputColors[idx].setRed(0);
6556                 outputColors[idx] = RGBA(0, 0, 0, 255);
6557         }
6558
6559         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(CaseNameDecoration); ++testNdx)
6560         {
6561                 map<string, string> fragments;
6562
6563                 fragments["decoration"] = tests[testNdx].decoration;
6564                 fragments["pre_main"] = constantsAndTypes;
6565                 fragments["testfun"] = function;
6566
6567                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, group.get());
6568         }
6569
6570         return group.release();
6571 }
6572
6573 tcu::TestCaseGroup* createMemoryAccessTests(tcu::TestContext& testCtx)
6574 {
6575         de::MovePtr<tcu::TestCaseGroup> memoryAccessTests (new tcu::TestCaseGroup(testCtx, "opmemoryaccess", "Memory Semantics"));
6576         RGBA                                                    colors[4];
6577
6578         const char                                              constantsAndTypes[]      =
6579                 "%c_a2f32_1         = OpConstantComposite %a2f32 %c_f32_1 %c_f32_1\n"
6580                 "%fp_a2f32          = OpTypePointer Function %a2f32\n"
6581                 "%stype             = OpTypeStruct  %v4f32 %a2f32 %f32\n"
6582                 "%fp_stype          = OpTypePointer Function %stype\n";
6583
6584         const char                                              function[]       =
6585                 "%test_code         = OpFunction %v4f32 None %v4f32_function\n"
6586                 "%param1            = OpFunctionParameter %v4f32\n"
6587                 "%lbl               = OpLabel\n"
6588                 "%v1                = OpVariable %fp_v4f32 Function\n"
6589                 "%v2                = OpVariable %fp_a2f32 Function\n"
6590                 "%v3                = OpVariable %fp_f32 Function\n"
6591                 "%v                 = OpVariable %fp_stype Function\n"
6592                 "%vv                = OpVariable %fp_stype Function\n"
6593                 "%vvv               = OpVariable %fp_f32 Function\n"
6594
6595                 "                     OpStore %v1 %c_v4f32_1_1_1_1\n"
6596                 "                     OpStore %v2 %c_a2f32_1\n"
6597                 "                     OpStore %v3 %c_f32_1\n"
6598
6599                 "%p_v4f32          = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
6600                 "%p_a2f32          = OpAccessChain %fp_a2f32 %v %c_u32_1\n"
6601                 "%p_f32            = OpAccessChain %fp_f32 %v %c_u32_2\n"
6602                 "%v1_v             = OpLoad %v4f32 %v1 ${access_type}\n"
6603                 "%v2_v             = OpLoad %a2f32 %v2 ${access_type}\n"
6604                 "%v3_v             = OpLoad %f32 %v3 ${access_type}\n"
6605
6606                 "                    OpStore %p_v4f32 %v1_v ${access_type}\n"
6607                 "                    OpStore %p_a2f32 %v2_v ${access_type}\n"
6608                 "                    OpStore %p_f32 %v3_v ${access_type}\n"
6609
6610                 "                    OpCopyMemory %vv %v ${access_type}\n"
6611                 "                    OpCopyMemory %vvv %p_f32 ${access_type}\n"
6612
6613                 "%p_f32_2          = OpAccessChain %fp_f32 %vv %c_u32_2\n"
6614                 "%v_f32_2          = OpLoad %f32 %p_f32_2\n"
6615                 "%v_f32_3          = OpLoad %f32 %vvv\n"
6616
6617                 "%ret1             = OpVectorTimesScalar %v4f32 %param1 %v_f32_2\n"
6618                 "%ret2             = OpVectorTimesScalar %v4f32 %ret1 %v_f32_3\n"
6619                 "                    OpReturnValue %ret2\n"
6620                 "                    OpFunctionEnd\n";
6621
6622         struct NameMemoryAccess
6623         {
6624                 string name;
6625                 string accessType;
6626         };
6627
6628
6629         NameMemoryAccess tests[] =
6630         {
6631                 { "none", "" },
6632                 { "volatile", "Volatile" },
6633                 { "aligned",  "Aligned 1" },
6634                 { "volatile_aligned",  "Volatile|Aligned 1" },
6635                 { "nontemporal_aligned",  "Nontemporal|Aligned 1" },
6636                 { "volatile_nontemporal",  "Volatile|Nontemporal" },
6637                 { "volatile_nontermporal_aligned",  "Volatile|Nontemporal|Aligned 1" },
6638         };
6639
6640         getHalfColorsFullAlpha(colors);
6641
6642         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameMemoryAccess); ++testNdx)
6643         {
6644                 map<string, string> fragments;
6645                 map<string, string> memoryAccess;
6646                 memoryAccess["access_type"] = tests[testNdx].accessType;
6647
6648                 fragments["pre_main"] = constantsAndTypes;
6649                 fragments["testfun"] = tcu::StringTemplate(function).specialize(memoryAccess);
6650                 createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, memoryAccessTests.get());
6651         }
6652         return memoryAccessTests.release();
6653 }
6654 tcu::TestCaseGroup* createOpUndefTests(tcu::TestContext& testCtx)
6655 {
6656         de::MovePtr<tcu::TestCaseGroup>         opUndefTests             (new tcu::TestCaseGroup(testCtx, "opundef", "Test OpUndef"));
6657         RGBA                                                            defaultColors[4];
6658         map<string, string>                                     fragments;
6659         getDefaultColors(defaultColors);
6660
6661         // First, simple cases that don't do anything with the OpUndef result.
6662         struct NameCodePair { string name, decl, type; };
6663         const NameCodePair tests[] =
6664         {
6665                 {"bool", "", "%bool"},
6666                 {"vec2uint32", "", "%v2u32"},
6667                 {"image", "%type = OpTypeImage %f32 2D 0 0 0 1 Unknown", "%type"},
6668                 {"sampler", "%type = OpTypeSampler", "%type"},
6669                 {"sampledimage", "%img = OpTypeImage %f32 2D 0 0 0 1 Unknown\n" "%type = OpTypeSampledImage %img", "%type"},
6670                 {"pointer", "", "%fp_i32"},
6671                 {"runtimearray", "%type = OpTypeRuntimeArray %f32", "%type"},
6672                 {"array", "%c_u32_100 = OpConstant %u32 100\n" "%type = OpTypeArray %i32 %c_u32_100", "%type"},
6673                 {"struct", "%type = OpTypeStruct %f32 %i32 %u32", "%type"}};
6674         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
6675         {
6676                 fragments["undef_type"] = tests[testNdx].type;
6677                 fragments["testfun"] = StringTemplate(
6678                         "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6679                         "%param1 = OpFunctionParameter %v4f32\n"
6680                         "%label_testfun = OpLabel\n"
6681                         "%undef = OpUndef ${undef_type}\n"
6682                         "OpReturnValue %param1\n"
6683                         "OpFunctionEnd\n").specialize(fragments);
6684                 fragments["pre_main"] = tests[testNdx].decl;
6685                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opUndefTests.get());
6686         }
6687         fragments.clear();
6688
6689         fragments["testfun"] =
6690                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6691                 "%param1 = OpFunctionParameter %v4f32\n"
6692                 "%label_testfun = OpLabel\n"
6693                 "%undef = OpUndef %f32\n"
6694                 "%zero = OpFMul %f32 %undef %c_f32_0\n"
6695                 "%is_nan = OpIsNan %bool %zero\n" //OpUndef may result in NaN which may turn %zero into Nan.
6696                 "%actually_zero = OpSelect %f32 %is_nan %c_f32_0 %zero\n"
6697                 "%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
6698                 "%b = OpFAdd %f32 %a %actually_zero\n"
6699                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %b %c_i32_0\n"
6700                 "OpReturnValue %ret\n"
6701                 "OpFunctionEnd\n";
6702
6703         createTestsForAllStages("float32", defaultColors, defaultColors, fragments, opUndefTests.get());
6704
6705         fragments["testfun"] =
6706                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6707                 "%param1 = OpFunctionParameter %v4f32\n"
6708                 "%label_testfun = OpLabel\n"
6709                 "%undef = OpUndef %i32\n"
6710                 "%zero = OpIMul %i32 %undef %c_i32_0\n"
6711                 "%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
6712                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
6713                 "OpReturnValue %ret\n"
6714                 "OpFunctionEnd\n";
6715
6716         createTestsForAllStages("sint32", defaultColors, defaultColors, fragments, opUndefTests.get());
6717
6718         fragments["testfun"] =
6719                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6720                 "%param1 = OpFunctionParameter %v4f32\n"
6721                 "%label_testfun = OpLabel\n"
6722                 "%undef = OpUndef %u32\n"
6723                 "%zero = OpIMul %u32 %undef %c_i32_0\n"
6724                 "%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
6725                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
6726                 "OpReturnValue %ret\n"
6727                 "OpFunctionEnd\n";
6728
6729         createTestsForAllStages("uint32", defaultColors, defaultColors, fragments, opUndefTests.get());
6730
6731         fragments["testfun"] =
6732                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6733                 "%param1 = OpFunctionParameter %v4f32\n"
6734                 "%label_testfun = OpLabel\n"
6735                 "%undef = OpUndef %v4f32\n"
6736                 "%vzero = OpVectorTimesScalar %v4f32 %undef %c_f32_0\n"
6737                 "%zero_0 = OpVectorExtractDynamic %f32 %vzero %c_i32_0\n"
6738                 "%zero_1 = OpVectorExtractDynamic %f32 %vzero %c_i32_1\n"
6739                 "%zero_2 = OpVectorExtractDynamic %f32 %vzero %c_i32_2\n"
6740                 "%zero_3 = OpVectorExtractDynamic %f32 %vzero %c_i32_3\n"
6741                 "%is_nan_0 = OpIsNan %bool %zero_0\n"
6742                 "%is_nan_1 = OpIsNan %bool %zero_1\n"
6743                 "%is_nan_2 = OpIsNan %bool %zero_2\n"
6744                 "%is_nan_3 = OpIsNan %bool %zero_3\n"
6745                 "%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
6746                 "%actually_zero_1 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_1\n"
6747                 "%actually_zero_2 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_2\n"
6748                 "%actually_zero_3 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_3\n"
6749                 "%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
6750                 "%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
6751                 "%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
6752                 "%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
6753                 "%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
6754                 "%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
6755                 "%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
6756                 "%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
6757                 "%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
6758                 "%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
6759                 "%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
6760                 "%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
6761                 "OpReturnValue %ret\n"
6762                 "OpFunctionEnd\n";
6763
6764         createTestsForAllStages("vec4float32", defaultColors, defaultColors, fragments, opUndefTests.get());
6765
6766         fragments["pre_main"] =
6767                 "%m2x2f32 = OpTypeMatrix %v2f32 2\n";
6768         fragments["testfun"] =
6769                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6770                 "%param1 = OpFunctionParameter %v4f32\n"
6771                 "%label_testfun = OpLabel\n"
6772                 "%undef = OpUndef %m2x2f32\n"
6773                 "%mzero = OpMatrixTimesScalar %m2x2f32 %undef %c_f32_0\n"
6774                 "%zero_0 = OpCompositeExtract %f32 %mzero 0 0\n"
6775                 "%zero_1 = OpCompositeExtract %f32 %mzero 0 1\n"
6776                 "%zero_2 = OpCompositeExtract %f32 %mzero 1 0\n"
6777                 "%zero_3 = OpCompositeExtract %f32 %mzero 1 1\n"
6778                 "%is_nan_0 = OpIsNan %bool %zero_0\n"
6779                 "%is_nan_1 = OpIsNan %bool %zero_1\n"
6780                 "%is_nan_2 = OpIsNan %bool %zero_2\n"
6781                 "%is_nan_3 = OpIsNan %bool %zero_3\n"
6782                 "%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
6783                 "%actually_zero_1 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_1\n"
6784                 "%actually_zero_2 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_2\n"
6785                 "%actually_zero_3 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_3\n"
6786                 "%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
6787                 "%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
6788                 "%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
6789                 "%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
6790                 "%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
6791                 "%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
6792                 "%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
6793                 "%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
6794                 "%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
6795                 "%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
6796                 "%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
6797                 "%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
6798                 "OpReturnValue %ret\n"
6799                 "OpFunctionEnd\n";
6800
6801         createTestsForAllStages("matrix", defaultColors, defaultColors, fragments, opUndefTests.get());
6802
6803         return opUndefTests.release();
6804 }
6805
6806 void createOpQuantizeSingleOptionTests(tcu::TestCaseGroup* testCtx)
6807 {
6808         const RGBA              inputColors[4]          =
6809         {
6810                 RGBA(0,         0,              0,              255),
6811                 RGBA(0,         0,              255,    255),
6812                 RGBA(0,         255,    0,              255),
6813                 RGBA(0,         255,    255,    255)
6814         };
6815
6816         const RGBA              expectedColors[4]       =
6817         {
6818                 RGBA(255,        0,              0,              255),
6819                 RGBA(255,        0,              0,              255),
6820                 RGBA(255,        0,              0,              255),
6821                 RGBA(255,        0,              0,              255)
6822         };
6823
6824         const struct SingleFP16Possibility
6825         {
6826                 const char* name;
6827                 const char* constant;  // Value to assign to %test_constant.
6828                 float           valueAsFloat;
6829                 const char* condition; // Must assign to %cond an expression that evaluates to true after %c = OpQuantizeToF16(%test_constant + 0).
6830         }                               tests[]                         =
6831         {
6832                 {
6833                         "negative",
6834                         "-0x1.3p1\n",
6835                         -constructNormalizedFloat(1, 0x300000),
6836                         "%cond = OpFOrdEqual %bool %c %test_constant\n"
6837                 }, // -19
6838                 {
6839                         "positive",
6840                         "0x1.0p7\n",
6841                         constructNormalizedFloat(7, 0x000000),
6842                         "%cond = OpFOrdEqual %bool %c %test_constant\n"
6843                 },  // +128
6844                 // SPIR-V requires that OpQuantizeToF16 flushes
6845                 // any numbers that would end up denormalized in F16 to zero.
6846                 {
6847                         "denorm",
6848                         "0x0.0006p-126\n",
6849                         std::ldexp(1.5f, -140),
6850                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
6851                 },  // denorm
6852                 {
6853                         "negative_denorm",
6854                         "-0x0.0006p-126\n",
6855                         -std::ldexp(1.5f, -140),
6856                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
6857                 }, // -denorm
6858                 {
6859                         "too_small",
6860                         "0x1.0p-16\n",
6861                         std::ldexp(1.0f, -16),
6862                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
6863                 },     // too small positive
6864                 {
6865                         "negative_too_small",
6866                         "-0x1.0p-32\n",
6867                         -std::ldexp(1.0f, -32),
6868                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
6869                 },      // too small negative
6870                 {
6871                         "negative_inf",
6872                         "-0x1.0p128\n",
6873                         -std::ldexp(1.0f, 128),
6874
6875                         "%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
6876                         "%inf = OpIsInf %bool %c\n"
6877                         "%cond = OpLogicalAnd %bool %gz %inf\n"
6878                 },     // -inf to -inf
6879                 {
6880                         "inf",
6881                         "0x1.0p128\n",
6882                         std::ldexp(1.0f, 128),
6883
6884                         "%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
6885                         "%inf = OpIsInf %bool %c\n"
6886                         "%cond = OpLogicalAnd %bool %gz %inf\n"
6887                 },     // +inf to +inf
6888                 {
6889                         "round_to_negative_inf",
6890                         "-0x1.0p32\n",
6891                         -std::ldexp(1.0f, 32),
6892
6893                         "%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
6894                         "%inf = OpIsInf %bool %c\n"
6895                         "%cond = OpLogicalAnd %bool %gz %inf\n"
6896                 },     // round to -inf
6897                 {
6898                         "round_to_inf",
6899                         "0x1.0p16\n",
6900                         std::ldexp(1.0f, 16),
6901
6902                         "%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
6903                         "%inf = OpIsInf %bool %c\n"
6904                         "%cond = OpLogicalAnd %bool %gz %inf\n"
6905                 },     // round to +inf
6906                 {
6907                         "nan",
6908                         "0x1.1p128\n",
6909                         std::numeric_limits<float>::quiet_NaN(),
6910
6911                         // Test for any NaN value, as NaNs are not preserved
6912                         "%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
6913                         "%cond = OpIsNan %bool %direct_quant\n"
6914                 }, // nan
6915                 {
6916                         "negative_nan",
6917                         "-0x1.0001p128\n",
6918                         std::numeric_limits<float>::quiet_NaN(),
6919
6920                         // Test for any NaN value, as NaNs are not preserved
6921                         "%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
6922                         "%cond = OpIsNan %bool %direct_quant\n"
6923                 } // -nan
6924         };
6925         const char*             constants                       =
6926                 "%test_constant = OpConstant %f32 ";  // The value will be test.constant.
6927
6928         StringTemplate  function                        (
6929                 "%test_code     = OpFunction %v4f32 None %v4f32_function\n"
6930                 "%param1        = OpFunctionParameter %v4f32\n"
6931                 "%label_testfun = OpLabel\n"
6932                 "%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
6933                 "%b             = OpFAdd %f32 %test_constant %a\n"
6934                 "%c             = OpQuantizeToF16 %f32 %b\n"
6935                 "${condition}\n"
6936                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
6937                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
6938                 "                 OpReturnValue %retval\n"
6939                 "OpFunctionEnd\n"
6940         );
6941
6942         const char*             specDecorations         = "OpDecorate %test_constant SpecId 0\n";
6943         const char*             specConstants           =
6944                         "%test_constant = OpSpecConstant %f32 0.\n"
6945                         "%c             = OpSpecConstantOp %f32 QuantizeToF16 %test_constant\n";
6946
6947         StringTemplate  specConstantFunction(
6948                 "%test_code     = OpFunction %v4f32 None %v4f32_function\n"
6949                 "%param1        = OpFunctionParameter %v4f32\n"
6950                 "%label_testfun = OpLabel\n"
6951                 "${condition}\n"
6952                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
6953                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
6954                 "                 OpReturnValue %retval\n"
6955                 "OpFunctionEnd\n"
6956         );
6957
6958         for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
6959         {
6960                 map<string, string>                                                             codeSpecialization;
6961                 map<string, string>                                                             fragments;
6962                 codeSpecialization["condition"]                                 = tests[idx].condition;
6963                 fragments["testfun"]                                                    = function.specialize(codeSpecialization);
6964                 fragments["pre_main"]                                                   = string(constants) + tests[idx].constant + "\n";
6965                 createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
6966         }
6967
6968         for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
6969         {
6970                 map<string, string>                                                             codeSpecialization;
6971                 map<string, string>                                                             fragments;
6972                 vector<deInt32>                                                                 passConstants;
6973                 deInt32                                                                                 specConstant;
6974
6975                 codeSpecialization["condition"]                                 = tests[idx].condition;
6976                 fragments["testfun"]                                                    = specConstantFunction.specialize(codeSpecialization);
6977                 fragments["decoration"]                                                 = specDecorations;
6978                 fragments["pre_main"]                                                   = specConstants;
6979
6980                 memcpy(&specConstant, &tests[idx].valueAsFloat, sizeof(float));
6981                 passConstants.push_back(specConstant);
6982
6983                 createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
6984         }
6985 }
6986
6987 void createOpQuantizeTwoPossibilityTests(tcu::TestCaseGroup* testCtx)
6988 {
6989         RGBA inputColors[4] =  {
6990                 RGBA(0,         0,              0,              255),
6991                 RGBA(0,         0,              255,    255),
6992                 RGBA(0,         255,    0,              255),
6993                 RGBA(0,         255,    255,    255)
6994         };
6995
6996         RGBA expectedColors[4] =
6997         {
6998                 RGBA(255,        0,              0,              255),
6999                 RGBA(255,        0,              0,              255),
7000                 RGBA(255,        0,              0,              255),
7001                 RGBA(255,        0,              0,              255)
7002         };
7003
7004         struct DualFP16Possibility
7005         {
7006                 const char* name;
7007                 const char* input;
7008                 float           inputAsFloat;
7009                 const char* possibleOutput1;
7010                 const char* possibleOutput2;
7011         } tests[] = {
7012                 {
7013                         "positive_round_up_or_round_down",
7014                         "0x1.3003p8",
7015                         constructNormalizedFloat(8, 0x300300),
7016                         "0x1.304p8",
7017                         "0x1.3p8"
7018                 },
7019                 {
7020                         "negative_round_up_or_round_down",
7021                         "-0x1.6008p-7",
7022                         -constructNormalizedFloat(-7, 0x600800),
7023                         "-0x1.6p-7",
7024                         "-0x1.604p-7"
7025                 },
7026                 {
7027                         "carry_bit",
7028                         "0x1.01ep2",
7029                         constructNormalizedFloat(2, 0x01e000),
7030                         "0x1.01cp2",
7031                         "0x1.02p2"
7032                 },
7033                 {
7034                         "carry_to_exponent",
7035                         "0x1.ffep1",
7036                         constructNormalizedFloat(1, 0xffe000),
7037                         "0x1.ffcp1",
7038                         "0x1.0p2"
7039                 },
7040         };
7041         StringTemplate constants (
7042                 "%input_const = OpConstant %f32 ${input}\n"
7043                 "%possible_solution1 = OpConstant %f32 ${output1}\n"
7044                 "%possible_solution2 = OpConstant %f32 ${output2}\n"
7045                 );
7046
7047         StringTemplate specConstants (
7048                 "%input_const = OpSpecConstant %f32 0.\n"
7049                 "%possible_solution1 = OpConstant %f32 ${output1}\n"
7050                 "%possible_solution2 = OpConstant %f32 ${output2}\n"
7051         );
7052
7053         const char* specDecorations = "OpDecorate %input_const  SpecId 0\n";
7054
7055         const char* function  =
7056                 "%test_code     = OpFunction %v4f32 None %v4f32_function\n"
7057                 "%param1        = OpFunctionParameter %v4f32\n"
7058                 "%label_testfun = OpLabel\n"
7059                 "%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7060                 // For the purposes of this test we assume that 0.f will always get
7061                 // faithfully passed through the pipeline stages.
7062                 "%b             = OpFAdd %f32 %input_const %a\n"
7063                 "%c             = OpQuantizeToF16 %f32 %b\n"
7064                 "%eq_1          = OpFOrdEqual %bool %c %possible_solution1\n"
7065                 "%eq_2          = OpFOrdEqual %bool %c %possible_solution2\n"
7066                 "%cond          = OpLogicalOr %bool %eq_1 %eq_2\n"
7067                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
7068                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1"
7069                 "                 OpReturnValue %retval\n"
7070                 "OpFunctionEnd\n";
7071
7072         for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
7073                 map<string, string>                                                                     fragments;
7074                 map<string, string>                                                                     constantSpecialization;
7075
7076                 constantSpecialization["input"]                                         = tests[idx].input;
7077                 constantSpecialization["output1"]                                       = tests[idx].possibleOutput1;
7078                 constantSpecialization["output2"]                                       = tests[idx].possibleOutput2;
7079                 fragments["testfun"]                                                            = function;
7080                 fragments["pre_main"]                                                           = constants.specialize(constantSpecialization);
7081                 createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
7082         }
7083
7084         for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
7085                 map<string, string>                                                                     fragments;
7086                 map<string, string>                                                                     constantSpecialization;
7087                 vector<deInt32>                                                                         passConstants;
7088                 deInt32                                                                                         specConstant;
7089
7090                 constantSpecialization["output1"]                                       = tests[idx].possibleOutput1;
7091                 constantSpecialization["output2"]                                       = tests[idx].possibleOutput2;
7092                 fragments["testfun"]                                                            = function;
7093                 fragments["decoration"]                                                         = specDecorations;
7094                 fragments["pre_main"]                                                           = specConstants.specialize(constantSpecialization);
7095
7096                 memcpy(&specConstant, &tests[idx].inputAsFloat, sizeof(float));
7097                 passConstants.push_back(specConstant);
7098
7099                 createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
7100         }
7101 }
7102
7103 tcu::TestCaseGroup* createOpQuantizeTests(tcu::TestContext& testCtx)
7104 {
7105         de::MovePtr<tcu::TestCaseGroup> opQuantizeTests (new tcu::TestCaseGroup(testCtx, "opquantize", "Test OpQuantizeToF16"));
7106         createOpQuantizeSingleOptionTests(opQuantizeTests.get());
7107         createOpQuantizeTwoPossibilityTests(opQuantizeTests.get());
7108         return opQuantizeTests.release();
7109 }
7110
7111 struct ShaderPermutation
7112 {
7113         deUint8 vertexPermutation;
7114         deUint8 geometryPermutation;
7115         deUint8 tesscPermutation;
7116         deUint8 tessePermutation;
7117         deUint8 fragmentPermutation;
7118 };
7119
7120 ShaderPermutation getShaderPermutation(deUint8 inputValue)
7121 {
7122         ShaderPermutation       permutation =
7123         {
7124                 static_cast<deUint8>(inputValue & 0x10? 1u: 0u),
7125                 static_cast<deUint8>(inputValue & 0x08? 1u: 0u),
7126                 static_cast<deUint8>(inputValue & 0x04? 1u: 0u),
7127                 static_cast<deUint8>(inputValue & 0x02? 1u: 0u),
7128                 static_cast<deUint8>(inputValue & 0x01? 1u: 0u)
7129         };
7130         return permutation;
7131 }
7132
7133 tcu::TestCaseGroup* createModuleTests(tcu::TestContext& testCtx)
7134 {
7135         RGBA                                                            defaultColors[4];
7136         RGBA                                                            invertedColors[4];
7137         de::MovePtr<tcu::TestCaseGroup>         moduleTests                     (new tcu::TestCaseGroup(testCtx, "module", "Multiple entry points into shaders"));
7138
7139         const ShaderElement                                     combinedPipeline[]      =
7140         {
7141                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
7142                 ShaderElement("module", "main", VK_SHADER_STAGE_GEOMETRY_BIT),
7143                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
7144                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
7145                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
7146         };
7147
7148         getDefaultColors(defaultColors);
7149         getInvertedDefaultColors(invertedColors);
7150         addFunctionCaseWithPrograms<InstanceContext>(
7151                         moduleTests.get(), "same_module", "", createCombinedModule, runAndVerifyDefaultPipeline,
7152                         createInstanceContext(combinedPipeline, map<string, string>()));
7153
7154         const char* numbers[] =
7155         {
7156                 "1", "2"
7157         };
7158
7159         for (deInt8 idx = 0; idx < 32; ++idx)
7160         {
7161                 ShaderPermutation                       permutation             = getShaderPermutation(idx);
7162                 string                                          name                    = string("vert") + numbers[permutation.vertexPermutation] + "_geom" + numbers[permutation.geometryPermutation] + "_tessc" + numbers[permutation.tesscPermutation] + "_tesse" + numbers[permutation.tessePermutation] + "_frag" + numbers[permutation.fragmentPermutation];
7163                 const ShaderElement                     pipeline[]              =
7164                 {
7165                         ShaderElement("vert",   string("vert") +        numbers[permutation.vertexPermutation],         VK_SHADER_STAGE_VERTEX_BIT),
7166                         ShaderElement("geom",   string("geom") +        numbers[permutation.geometryPermutation],       VK_SHADER_STAGE_GEOMETRY_BIT),
7167                         ShaderElement("tessc",  string("tessc") +       numbers[permutation.tesscPermutation],          VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
7168                         ShaderElement("tesse",  string("tesse") +       numbers[permutation.tessePermutation],          VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
7169                         ShaderElement("frag",   string("frag") +        numbers[permutation.fragmentPermutation],       VK_SHADER_STAGE_FRAGMENT_BIT)
7170                 };
7171
7172                 // If there are an even number of swaps, then it should be no-op.
7173                 // If there are an odd number, the color should be flipped.
7174                 if ((permutation.vertexPermutation + permutation.geometryPermutation + permutation.tesscPermutation + permutation.tessePermutation + permutation.fragmentPermutation) % 2 == 0)
7175                 {
7176                         addFunctionCaseWithPrograms<InstanceContext>(
7177                                         moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline,
7178                                         createInstanceContext(pipeline, defaultColors, defaultColors, map<string, string>()));
7179                 }
7180                 else
7181                 {
7182                         addFunctionCaseWithPrograms<InstanceContext>(
7183                                         moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline,
7184                                         createInstanceContext(pipeline, defaultColors, invertedColors, map<string, string>()));
7185                 }
7186         }
7187         return moduleTests.release();
7188 }
7189
7190 tcu::TestCaseGroup* createLoopTests(tcu::TestContext& testCtx)
7191 {
7192         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "loop", "Looping control flow"));
7193         RGBA defaultColors[4];
7194         getDefaultColors(defaultColors);
7195         map<string, string> fragments;
7196         fragments["pre_main"] =
7197                 "%c_f32_5 = OpConstant %f32 5.\n";
7198
7199         // A loop with a single block. The Continue Target is the loop block
7200         // itself. In SPIR-V terms, the "loop construct" contains no blocks at all
7201         // -- the "continue construct" forms the entire loop.
7202         fragments["testfun"] =
7203                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7204                 "%param1 = OpFunctionParameter %v4f32\n"
7205
7206                 "%entry = OpLabel\n"
7207                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7208                 "OpBranch %loop\n"
7209
7210                 ";adds and subtracts 1.0 to %val in alternate iterations\n"
7211                 "%loop = OpLabel\n"
7212                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
7213                 "%delta = OpPhi %f32 %c_f32_1 %entry %minus_delta %loop\n"
7214                 "%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
7215                 "%val = OpFAdd %f32 %val1 %delta\n"
7216                 "%minus_delta = OpFSub %f32 %c_f32_0 %delta\n"
7217                 "%count__ = OpISub %i32 %count %c_i32_1\n"
7218                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
7219                 "OpLoopMerge %exit %loop None\n"
7220                 "OpBranchConditional %again %loop %exit\n"
7221
7222                 "%exit = OpLabel\n"
7223                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
7224                 "OpReturnValue %result\n"
7225
7226                 "OpFunctionEnd\n";
7227
7228         createTestsForAllStages("single_block", defaultColors, defaultColors, fragments, testGroup.get());
7229
7230         // Body comprised of multiple basic blocks.
7231         const StringTemplate multiBlock(
7232                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7233                 "%param1 = OpFunctionParameter %v4f32\n"
7234
7235                 "%entry = OpLabel\n"
7236                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7237                 "OpBranch %loop\n"
7238
7239                 ";adds and subtracts 1.0 to %val in alternate iterations\n"
7240                 "%loop = OpLabel\n"
7241                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %gather\n"
7242                 "%delta = OpPhi %f32 %c_f32_1 %entry %delta_next %gather\n"
7243                 "%val1 = OpPhi %f32 %val0 %entry %val %gather\n"
7244                 // There are several possibilities for the Continue Target below.  Each
7245                 // will be specialized into a separate test case.
7246                 "OpLoopMerge %exit ${continue_target} None\n"
7247                 "OpBranch %if\n"
7248
7249                 "%if = OpLabel\n"
7250                 ";delta_next = (delta > 0) ? -1 : 1;\n"
7251                 "%gt0 = OpFOrdGreaterThan %bool %delta %c_f32_0\n"
7252                 "OpSelectionMerge %gather DontFlatten\n"
7253                 "OpBranchConditional %gt0 %even %odd ;tells us if %count is even or odd\n"
7254
7255                 "%odd = OpLabel\n"
7256                 "OpBranch %gather\n"
7257
7258                 "%even = OpLabel\n"
7259                 "OpBranch %gather\n"
7260
7261                 "%gather = OpLabel\n"
7262                 "%delta_next = OpPhi %f32 %c_f32_n1 %even %c_f32_1 %odd\n"
7263                 "%val = OpFAdd %f32 %val1 %delta\n"
7264                 "%count__ = OpISub %i32 %count %c_i32_1\n"
7265                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
7266                 "OpBranchConditional %again %loop %exit\n"
7267
7268                 "%exit = OpLabel\n"
7269                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
7270                 "OpReturnValue %result\n"
7271
7272                 "OpFunctionEnd\n");
7273
7274         map<string, string> continue_target;
7275
7276         // The Continue Target is the loop block itself.
7277         continue_target["continue_target"] = "%loop";
7278         fragments["testfun"] = multiBlock.specialize(continue_target);
7279         createTestsForAllStages("multi_block_continue_construct", defaultColors, defaultColors, fragments, testGroup.get());
7280
7281         // The Continue Target is at the end of the loop.
7282         continue_target["continue_target"] = "%gather";
7283         fragments["testfun"] = multiBlock.specialize(continue_target);
7284         createTestsForAllStages("multi_block_loop_construct", defaultColors, defaultColors, fragments, testGroup.get());
7285
7286         // A loop with continue statement.
7287         fragments["testfun"] =
7288                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7289                 "%param1 = OpFunctionParameter %v4f32\n"
7290
7291                 "%entry = OpLabel\n"
7292                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7293                 "OpBranch %loop\n"
7294
7295                 ";adds 4, 3, and 1 to %val0 (skips 2)\n"
7296                 "%loop = OpLabel\n"
7297                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
7298                 "%val1 = OpPhi %f32 %val0 %entry %val %continue\n"
7299                 "OpLoopMerge %exit %continue None\n"
7300                 "OpBranch %if\n"
7301
7302                 "%if = OpLabel\n"
7303                 ";skip if %count==2\n"
7304                 "%eq2 = OpIEqual %bool %count %c_i32_2\n"
7305                 "OpSelectionMerge %continue DontFlatten\n"
7306                 "OpBranchConditional %eq2 %continue %body\n"
7307
7308                 "%body = OpLabel\n"
7309                 "%fcount = OpConvertSToF %f32 %count\n"
7310                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
7311                 "OpBranch %continue\n"
7312
7313                 "%continue = OpLabel\n"
7314                 "%val = OpPhi %f32 %val2 %body %val1 %if\n"
7315                 "%count__ = OpISub %i32 %count %c_i32_1\n"
7316                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
7317                 "OpBranchConditional %again %loop %exit\n"
7318
7319                 "%exit = OpLabel\n"
7320                 "%same = OpFSub %f32 %val %c_f32_8\n"
7321                 "%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
7322                 "OpReturnValue %result\n"
7323                 "OpFunctionEnd\n";
7324         createTestsForAllStages("continue", defaultColors, defaultColors, fragments, testGroup.get());
7325
7326         // A loop with break.
7327         fragments["testfun"] =
7328                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7329                 "%param1 = OpFunctionParameter %v4f32\n"
7330
7331                 "%entry = OpLabel\n"
7332                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
7333                 "%dot = OpDot %f32 %param1 %param1\n"
7334                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
7335                 "%zero = OpConvertFToU %u32 %div\n"
7336                 "%two = OpIAdd %i32 %zero %c_i32_2\n"
7337                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7338                 "OpBranch %loop\n"
7339
7340                 ";adds 4 and 3 to %val0 (exits early)\n"
7341                 "%loop = OpLabel\n"
7342                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
7343                 "%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
7344                 "OpLoopMerge %exit %continue None\n"
7345                 "OpBranch %if\n"
7346
7347                 "%if = OpLabel\n"
7348                 ";end loop if %count==%two\n"
7349                 "%above2 = OpSGreaterThan %bool %count %two\n"
7350                 "OpSelectionMerge %continue DontFlatten\n"
7351                 "OpBranchConditional %above2 %body %exit\n"
7352
7353                 "%body = OpLabel\n"
7354                 "%fcount = OpConvertSToF %f32 %count\n"
7355                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
7356                 "OpBranch %continue\n"
7357
7358                 "%continue = OpLabel\n"
7359                 "%count__ = OpISub %i32 %count %c_i32_1\n"
7360                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
7361                 "OpBranchConditional %again %loop %exit\n"
7362
7363                 "%exit = OpLabel\n"
7364                 "%val_post = OpPhi %f32 %val2 %continue %val1 %if\n"
7365                 "%same = OpFSub %f32 %val_post %c_f32_7\n"
7366                 "%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
7367                 "OpReturnValue %result\n"
7368                 "OpFunctionEnd\n";
7369         createTestsForAllStages("break", defaultColors, defaultColors, fragments, testGroup.get());
7370
7371         // A loop with return.
7372         fragments["testfun"] =
7373                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7374                 "%param1 = OpFunctionParameter %v4f32\n"
7375
7376                 "%entry = OpLabel\n"
7377                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
7378                 "%dot = OpDot %f32 %param1 %param1\n"
7379                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
7380                 "%zero = OpConvertFToU %u32 %div\n"
7381                 "%two = OpIAdd %i32 %zero %c_i32_2\n"
7382                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7383                 "OpBranch %loop\n"
7384
7385                 ";returns early without modifying %param1\n"
7386                 "%loop = OpLabel\n"
7387                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
7388                 "%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
7389                 "OpLoopMerge %exit %continue None\n"
7390                 "OpBranch %if\n"
7391
7392                 "%if = OpLabel\n"
7393                 ";return if %count==%two\n"
7394                 "%above2 = OpSGreaterThan %bool %count %two\n"
7395                 "OpSelectionMerge %continue DontFlatten\n"
7396                 "OpBranchConditional %above2 %body %early_exit\n"
7397
7398                 "%early_exit = OpLabel\n"
7399                 "OpReturnValue %param1\n"
7400
7401                 "%body = OpLabel\n"
7402                 "%fcount = OpConvertSToF %f32 %count\n"
7403                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
7404                 "OpBranch %continue\n"
7405
7406                 "%continue = OpLabel\n"
7407                 "%count__ = OpISub %i32 %count %c_i32_1\n"
7408                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
7409                 "OpBranchConditional %again %loop %exit\n"
7410
7411                 "%exit = OpLabel\n"
7412                 ";should never get here, so return an incorrect result\n"
7413                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val2 %c_i32_0\n"
7414                 "OpReturnValue %result\n"
7415                 "OpFunctionEnd\n";
7416         createTestsForAllStages("return", defaultColors, defaultColors, fragments, testGroup.get());
7417
7418         // Continue inside a switch block to break to enclosing loop's merge block.
7419         // Matches roughly the following GLSL code:
7420         // for (; keep_going; keep_going = false)
7421         // {
7422         //     switch (int(param1.x))
7423         //     {
7424         //         case 0: continue;
7425         //         case 1: continue;
7426         //         default: continue;
7427         //     }
7428         //     dead code: modify return value to invalid result.
7429         // }
7430         fragments["pre_main"] =
7431                 "%fp_bool = OpTypePointer Function %bool\n"
7432                 "%true = OpConstantTrue %bool\n"
7433                 "%false = OpConstantFalse %bool\n";
7434
7435         fragments["testfun"] =
7436                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7437                 "%param1 = OpFunctionParameter %v4f32\n"
7438
7439                 "%entry = OpLabel\n"
7440                 "%keep_going = OpVariable %fp_bool Function\n"
7441                 "%val_ptr = OpVariable %fp_f32 Function\n"
7442                 "%param1_x = OpCompositeExtract %f32 %param1 0\n"
7443                 "OpStore %keep_going %true\n"
7444                 "OpBranch %forloop_begin\n"
7445
7446                 "%forloop_begin = OpLabel\n"
7447                 "OpLoopMerge %forloop_merge %forloop_continue None\n"
7448                 "OpBranch %forloop\n"
7449
7450                 "%forloop = OpLabel\n"
7451                 "%for_condition = OpLoad %bool %keep_going\n"
7452                 "OpBranchConditional %for_condition %forloop_body %forloop_merge\n"
7453
7454                 "%forloop_body = OpLabel\n"
7455                 "OpStore %val_ptr %param1_x\n"
7456                 "%param1_x_int = OpConvertFToS %i32 %param1_x\n"
7457
7458                 "OpSelectionMerge %switch_merge None\n"
7459                 "OpSwitch %param1_x_int %default 0 %case_0 1 %case_1\n"
7460                 "%case_0 = OpLabel\n"
7461                 "OpBranch %forloop_continue\n"
7462                 "%case_1 = OpLabel\n"
7463                 "OpBranch %forloop_continue\n"
7464                 "%default = OpLabel\n"
7465                 "OpBranch %forloop_continue\n"
7466                 "%switch_merge = OpLabel\n"
7467                 ";should never get here, so change the return value to invalid result\n"
7468                 "OpStore %val_ptr %c_f32_1\n"
7469                 "OpBranch %forloop_continue\n"
7470
7471                 "%forloop_continue = OpLabel\n"
7472                 "OpStore %keep_going %false\n"
7473                 "OpBranch %forloop_begin\n"
7474                 "%forloop_merge = OpLabel\n"
7475
7476                 "%val = OpLoad %f32 %val_ptr\n"
7477                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
7478                 "OpReturnValue %result\n"
7479                 "OpFunctionEnd\n";
7480         createTestsForAllStages("switch_continue", defaultColors, defaultColors, fragments, testGroup.get());
7481
7482         return testGroup.release();
7483 }
7484
7485 // A collection of tests putting OpControlBarrier in places GLSL forbids but SPIR-V allows.
7486 tcu::TestCaseGroup* createBarrierTests(tcu::TestContext& testCtx)
7487 {
7488         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "barrier", "OpControlBarrier"));
7489         map<string, string> fragments;
7490
7491         // A barrier inside a function body.
7492         fragments["pre_main"] =
7493                 "%Workgroup = OpConstant %i32 2\n"
7494                 "%SequentiallyConsistent = OpConstant %i32 0x10\n";
7495         fragments["testfun"] =
7496                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7497                 "%param1 = OpFunctionParameter %v4f32\n"
7498                 "%label_testfun = OpLabel\n"
7499                 "OpControlBarrier %Workgroup %Workgroup %SequentiallyConsistent\n"
7500                 "OpReturnValue %param1\n"
7501                 "OpFunctionEnd\n";
7502         addTessCtrlTest(testGroup.get(), "in_function", fragments);
7503
7504         // Common setup code for the following tests.
7505         fragments["pre_main"] =
7506                 "%Workgroup = OpConstant %i32 2\n"
7507                 "%SequentiallyConsistent = OpConstant %i32 0x10\n"
7508                 "%c_f32_5 = OpConstant %f32 5.\n";
7509         const string setupPercentZero =  // Begins %test_code function with code that sets %zero to 0u but cannot be optimized away.
7510                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7511                 "%param1 = OpFunctionParameter %v4f32\n"
7512                 "%entry = OpLabel\n"
7513                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
7514                 "%dot = OpDot %f32 %param1 %param1\n"
7515                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
7516                 "%zero = OpConvertFToU %u32 %div\n";
7517
7518         // Barriers inside OpSwitch branches.
7519         fragments["testfun"] =
7520                 setupPercentZero +
7521                 "OpSelectionMerge %switch_exit None\n"
7522                 "OpSwitch %zero %switch_default 0 %case0 1 %case1 ;should always go to %case0\n"
7523
7524                 "%case1 = OpLabel\n"
7525                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
7526                 "OpControlBarrier %Workgroup %Workgroup %SequentiallyConsistent\n"
7527                 "%wrong_branch_alert1 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
7528                 "OpBranch %switch_exit\n"
7529
7530                 "%switch_default = OpLabel\n"
7531                 "%wrong_branch_alert2 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
7532                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
7533                 "OpControlBarrier %Workgroup %Workgroup %SequentiallyConsistent\n"
7534                 "OpBranch %switch_exit\n"
7535
7536                 "%case0 = OpLabel\n"
7537                 "OpControlBarrier %Workgroup %Workgroup %SequentiallyConsistent\n"
7538                 "OpBranch %switch_exit\n"
7539
7540                 "%switch_exit = OpLabel\n"
7541                 "%ret = OpPhi %v4f32 %param1 %case0 %wrong_branch_alert1 %case1 %wrong_branch_alert2 %switch_default\n"
7542                 "OpReturnValue %ret\n"
7543                 "OpFunctionEnd\n";
7544         addTessCtrlTest(testGroup.get(), "in_switch", fragments);
7545
7546         // Barriers inside if-then-else.
7547         fragments["testfun"] =
7548                 setupPercentZero +
7549                 "%eq0 = OpIEqual %bool %zero %c_u32_0\n"
7550                 "OpSelectionMerge %exit DontFlatten\n"
7551                 "OpBranchConditional %eq0 %then %else\n"
7552
7553                 "%else = OpLabel\n"
7554                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
7555                 "OpControlBarrier %Workgroup %Workgroup %SequentiallyConsistent\n"
7556                 "%wrong_branch_alert = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
7557                 "OpBranch %exit\n"
7558
7559                 "%then = OpLabel\n"
7560                 "OpControlBarrier %Workgroup %Workgroup %SequentiallyConsistent\n"
7561                 "OpBranch %exit\n"
7562
7563                 "%exit = OpLabel\n"
7564                 "%ret = OpPhi %v4f32 %param1 %then %wrong_branch_alert %else\n"
7565                 "OpReturnValue %ret\n"
7566                 "OpFunctionEnd\n";
7567         addTessCtrlTest(testGroup.get(), "in_if", fragments);
7568
7569         // A barrier after control-flow reconvergence, tempting the compiler to attempt something like this:
7570         // http://lists.llvm.org/pipermail/llvm-dev/2009-October/026317.html.
7571         fragments["testfun"] =
7572                 setupPercentZero +
7573                 "%thread_id = OpLoad %i32 %BP_gl_InvocationID\n"
7574                 "%thread0 = OpIEqual %bool %thread_id %c_i32_0\n"
7575                 "OpSelectionMerge %exit DontFlatten\n"
7576                 "OpBranchConditional %thread0 %then %else\n"
7577
7578                 "%else = OpLabel\n"
7579                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7580                 "OpBranch %exit\n"
7581
7582                 "%then = OpLabel\n"
7583                 "%val1 = OpVectorExtractDynamic %f32 %param1 %zero\n"
7584                 "OpBranch %exit\n"
7585
7586                 "%exit = OpLabel\n"
7587                 "%val = OpPhi %f32 %val0 %else %val1 %then\n"
7588                 "OpControlBarrier %Workgroup %Workgroup %SequentiallyConsistent\n"
7589                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %val %zero\n"
7590                 "OpReturnValue %ret\n"
7591                 "OpFunctionEnd\n";
7592         addTessCtrlTest(testGroup.get(), "after_divergent_if", fragments);
7593
7594         // A barrier inside a loop.
7595         fragments["pre_main"] =
7596                 "%Workgroup = OpConstant %i32 2\n"
7597                 "%SequentiallyConsistent = OpConstant %i32 0x10\n"
7598                 "%c_f32_10 = OpConstant %f32 10.\n";
7599         fragments["testfun"] =
7600                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7601                 "%param1 = OpFunctionParameter %v4f32\n"
7602                 "%entry = OpLabel\n"
7603                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7604                 "OpBranch %loop\n"
7605
7606                 ";adds 4, 3, 2, and 1 to %val0\n"
7607                 "%loop = OpLabel\n"
7608                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
7609                 "%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
7610                 "OpControlBarrier %Workgroup %Workgroup %SequentiallyConsistent\n"
7611                 "%fcount = OpConvertSToF %f32 %count\n"
7612                 "%val = OpFAdd %f32 %val1 %fcount\n"
7613                 "%count__ = OpISub %i32 %count %c_i32_1\n"
7614                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
7615                 "OpLoopMerge %exit %loop None\n"
7616                 "OpBranchConditional %again %loop %exit\n"
7617
7618                 "%exit = OpLabel\n"
7619                 "%same = OpFSub %f32 %val %c_f32_10\n"
7620                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
7621                 "OpReturnValue %ret\n"
7622                 "OpFunctionEnd\n";
7623         addTessCtrlTest(testGroup.get(), "in_loop", fragments);
7624
7625         return testGroup.release();
7626 }
7627
7628 // Test for the OpFRem instruction.
7629 tcu::TestCaseGroup* createFRemTests(tcu::TestContext& testCtx)
7630 {
7631         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "frem", "OpFRem"));
7632         map<string, string>                                     fragments;
7633         RGBA                                                            inputColors[4];
7634         RGBA                                                            outputColors[4];
7635
7636         fragments["pre_main"]                            =
7637                 "%c_f32_3 = OpConstant %f32 3.0\n"
7638                 "%c_f32_n3 = OpConstant %f32 -3.0\n"
7639                 "%c_f32_4 = OpConstant %f32 4.0\n"
7640                 "%c_f32_p75 = OpConstant %f32 0.75\n"
7641                 "%c_v4f32_p75_p75_p75_p75 = OpConstantComposite %v4f32 %c_f32_p75 %c_f32_p75 %c_f32_p75 %c_f32_p75 \n"
7642                 "%c_v4f32_4_4_4_4 = OpConstantComposite %v4f32 %c_f32_4 %c_f32_4 %c_f32_4 %c_f32_4\n"
7643                 "%c_v4f32_3_n3_3_n3 = OpConstantComposite %v4f32 %c_f32_3 %c_f32_n3 %c_f32_3 %c_f32_n3\n";
7644
7645         // The test does the following.
7646         // vec4 result = (param1 * 8.0) - 4.0;
7647         // return (frem(result.x,3) + 0.75, frem(result.y, -3) + 0.75, 0, 1)
7648         fragments["testfun"]                             =
7649                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7650                 "%param1 = OpFunctionParameter %v4f32\n"
7651                 "%label_testfun = OpLabel\n"
7652                 "%v_times_8 = OpVectorTimesScalar %v4f32 %param1 %c_f32_8\n"
7653                 "%minus_4 = OpFSub %v4f32 %v_times_8 %c_v4f32_4_4_4_4\n"
7654                 "%frem = OpFRem %v4f32 %minus_4 %c_v4f32_3_n3_3_n3\n"
7655                 "%added = OpFAdd %v4f32 %frem %c_v4f32_p75_p75_p75_p75\n"
7656                 "%xyz_1 = OpVectorInsertDynamic %v4f32 %added %c_f32_1 %c_i32_3\n"
7657                 "%xy_0_1 = OpVectorInsertDynamic %v4f32 %xyz_1 %c_f32_0 %c_i32_2\n"
7658                 "OpReturnValue %xy_0_1\n"
7659                 "OpFunctionEnd\n";
7660
7661
7662         inputColors[0]          = RGBA(16,      16,             0, 255);
7663         inputColors[1]          = RGBA(232, 232,        0, 255);
7664         inputColors[2]          = RGBA(232, 16,         0, 255);
7665         inputColors[3]          = RGBA(16,      232,    0, 255);
7666
7667         outputColors[0]         = RGBA(64,      64,             0, 255);
7668         outputColors[1]         = RGBA(255, 255,        0, 255);
7669         outputColors[2]         = RGBA(255, 64,         0, 255);
7670         outputColors[3]         = RGBA(64,      255,    0, 255);
7671
7672         createTestsForAllStages("frem", inputColors, outputColors, fragments, testGroup.get());
7673         return testGroup.release();
7674 }
7675
7676 // Test for the OpSRem instruction.
7677 tcu::TestCaseGroup* createOpSRemGraphicsTests(tcu::TestContext& testCtx, qpTestResult negFailResult)
7678 {
7679         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "srem", "OpSRem"));
7680         map<string, string>                                     fragments;
7681
7682         fragments["pre_main"]                            =
7683                 "%c_f32_255 = OpConstant %f32 255.0\n"
7684                 "%c_i32_128 = OpConstant %i32 128\n"
7685                 "%c_i32_255 = OpConstant %i32 255\n"
7686                 "%c_v4f32_255 = OpConstantComposite %v4f32 %c_f32_255 %c_f32_255 %c_f32_255 %c_f32_255 \n"
7687                 "%c_v4f32_0_5 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 \n"
7688                 "%c_v4i32_128 = OpConstantComposite %v4i32 %c_i32_128 %c_i32_128 %c_i32_128 %c_i32_128 \n";
7689
7690         // The test does the following.
7691         // ivec4 ints = int(param1 * 255.0 + 0.5) - 128;
7692         // ivec4 result = ivec4(srem(ints.x, ints.y), srem(ints.y, ints.z), srem(ints.z, ints.x), 255);
7693         // return float(result + 128) / 255.0;
7694         fragments["testfun"]                             =
7695                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7696                 "%param1 = OpFunctionParameter %v4f32\n"
7697                 "%label_testfun = OpLabel\n"
7698                 "%div255 = OpFMul %v4f32 %param1 %c_v4f32_255\n"
7699                 "%add0_5 = OpFAdd %v4f32 %div255 %c_v4f32_0_5\n"
7700                 "%uints_in = OpConvertFToS %v4i32 %add0_5\n"
7701                 "%ints_in = OpISub %v4i32 %uints_in %c_v4i32_128\n"
7702                 "%x_in = OpCompositeExtract %i32 %ints_in 0\n"
7703                 "%y_in = OpCompositeExtract %i32 %ints_in 1\n"
7704                 "%z_in = OpCompositeExtract %i32 %ints_in 2\n"
7705                 "%x_out = OpSRem %i32 %x_in %y_in\n"
7706                 "%y_out = OpSRem %i32 %y_in %z_in\n"
7707                 "%z_out = OpSRem %i32 %z_in %x_in\n"
7708                 "%ints_out = OpCompositeConstruct %v4i32 %x_out %y_out %z_out %c_i32_255\n"
7709                 "%ints_offset = OpIAdd %v4i32 %ints_out %c_v4i32_128\n"
7710                 "%f_ints_offset = OpConvertSToF %v4f32 %ints_offset\n"
7711                 "%float_out = OpFDiv %v4f32 %f_ints_offset %c_v4f32_255\n"
7712                 "OpReturnValue %float_out\n"
7713                 "OpFunctionEnd\n";
7714
7715         const struct CaseParams
7716         {
7717                 const char*             name;
7718                 const char*             failMessageTemplate;    // customized status message
7719                 qpTestResult    failResult;                             // override status on failure
7720                 int                             operands[4][3];                 // four (x, y, z) vectors of operands
7721                 int                             results[4][3];                  // four (x, y, z) vectors of results
7722         } cases[] =
7723         {
7724                 {
7725                         "positive",
7726                         "${reason}",
7727                         QP_TEST_RESULT_FAIL,
7728                         { { 5, 12, 17 }, { 5, 5, 7 }, { 75, 8, 81 }, { 25, 60, 100 } },                 // operands
7729                         { { 5, 12,  2 }, { 0, 5, 2 }, {  3, 8,  6 }, { 25, 60,   0 } },                 // results
7730                 },
7731                 {
7732                         "all",
7733                         "Inconsistent results, but within specification: ${reason}",
7734                         negFailResult,                                                                                                                  // negative operands, not required by the spec
7735                         { { 5, 12, -17 }, { -5, -5, 7 }, { 75, 8, -81 }, { 25, -60, 100 } },    // operands
7736                         { { 5, 12,  -2 }, {  0, -5, 2 }, {  3, 8,  -6 }, { 25, -60,   0 } },    // results
7737                 },
7738         };
7739         // If either operand is negative the result is undefined. Some implementations may still return correct values.
7740
7741         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
7742         {
7743                 const CaseParams&       params                  = cases[caseNdx];
7744                 RGBA                            inputColors[4];
7745                 RGBA                            outputColors[4];
7746
7747                 for (int i = 0; i < 4; ++i)
7748                 {
7749                         inputColors [i] = RGBA(params.operands[i][0] + 128, params.operands[i][1] + 128, params.operands[i][2] + 128, 255);
7750                         outputColors[i] = RGBA(params.results [i][0] + 128, params.results [i][1] + 128, params.results [i][2] + 128, 255);
7751                 }
7752
7753                 createTestsForAllStages(params.name, inputColors, outputColors, fragments, testGroup.get(), params.failResult, params.failMessageTemplate);
7754         }
7755
7756         return testGroup.release();
7757 }
7758
7759 // Test for the OpSMod instruction.
7760 tcu::TestCaseGroup* createOpSModGraphicsTests(tcu::TestContext& testCtx, qpTestResult negFailResult)
7761 {
7762         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "smod", "OpSMod"));
7763         map<string, string>                                     fragments;
7764
7765         fragments["pre_main"]                            =
7766                 "%c_f32_255 = OpConstant %f32 255.0\n"
7767                 "%c_i32_128 = OpConstant %i32 128\n"
7768                 "%c_i32_255 = OpConstant %i32 255\n"
7769                 "%c_v4f32_255 = OpConstantComposite %v4f32 %c_f32_255 %c_f32_255 %c_f32_255 %c_f32_255 \n"
7770                 "%c_v4f32_0_5 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 \n"
7771                 "%c_v4i32_128 = OpConstantComposite %v4i32 %c_i32_128 %c_i32_128 %c_i32_128 %c_i32_128 \n";
7772
7773         // The test does the following.
7774         // ivec4 ints = int(param1 * 255.0 + 0.5) - 128;
7775         // ivec4 result = ivec4(smod(ints.x, ints.y), smod(ints.y, ints.z), smod(ints.z, ints.x), 255);
7776         // return float(result + 128) / 255.0;
7777         fragments["testfun"]                             =
7778                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7779                 "%param1 = OpFunctionParameter %v4f32\n"
7780                 "%label_testfun = OpLabel\n"
7781                 "%div255 = OpFMul %v4f32 %param1 %c_v4f32_255\n"
7782                 "%add0_5 = OpFAdd %v4f32 %div255 %c_v4f32_0_5\n"
7783                 "%uints_in = OpConvertFToS %v4i32 %add0_5\n"
7784                 "%ints_in = OpISub %v4i32 %uints_in %c_v4i32_128\n"
7785                 "%x_in = OpCompositeExtract %i32 %ints_in 0\n"
7786                 "%y_in = OpCompositeExtract %i32 %ints_in 1\n"
7787                 "%z_in = OpCompositeExtract %i32 %ints_in 2\n"
7788                 "%x_out = OpSMod %i32 %x_in %y_in\n"
7789                 "%y_out = OpSMod %i32 %y_in %z_in\n"
7790                 "%z_out = OpSMod %i32 %z_in %x_in\n"
7791                 "%ints_out = OpCompositeConstruct %v4i32 %x_out %y_out %z_out %c_i32_255\n"
7792                 "%ints_offset = OpIAdd %v4i32 %ints_out %c_v4i32_128\n"
7793                 "%f_ints_offset = OpConvertSToF %v4f32 %ints_offset\n"
7794                 "%float_out = OpFDiv %v4f32 %f_ints_offset %c_v4f32_255\n"
7795                 "OpReturnValue %float_out\n"
7796                 "OpFunctionEnd\n";
7797
7798         const struct CaseParams
7799         {
7800                 const char*             name;
7801                 const char*             failMessageTemplate;    // customized status message
7802                 qpTestResult    failResult;                             // override status on failure
7803                 int                             operands[4][3];                 // four (x, y, z) vectors of operands
7804                 int                             results[4][3];                  // four (x, y, z) vectors of results
7805         } cases[] =
7806         {
7807                 {
7808                         "positive",
7809                         "${reason}",
7810                         QP_TEST_RESULT_FAIL,
7811                         { { 5, 12, 17 }, { 5, 5, 7 }, { 75, 8, 81 }, { 25, 60, 100 } },                         // operands
7812                         { { 5, 12,  2 }, { 0, 5, 2 }, {  3, 8,  6 }, { 25, 60,   0 } },                         // results
7813                 },
7814                 {
7815                         "all",
7816                         "Inconsistent results, but within specification: ${reason}",
7817                         negFailResult,                                                                                                                          // negative operands, not required by the spec
7818                         { { 5, 12, -17 }, { -5, -5,  7 }, { 75,   8, -81 }, {  25, -60, 100 } },        // operands
7819                         { { 5, -5,   3 }, {  0,  2, -3 }, {  3, -73,  69 }, { -35,  40,   0 } },        // results
7820                 },
7821         };
7822         // If either operand is negative the result is undefined. Some implementations may still return correct values.
7823
7824         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
7825         {
7826                 const CaseParams&       params                  = cases[caseNdx];
7827                 RGBA                            inputColors[4];
7828                 RGBA                            outputColors[4];
7829
7830                 for (int i = 0; i < 4; ++i)
7831                 {
7832                         inputColors [i] = RGBA(params.operands[i][0] + 128, params.operands[i][1] + 128, params.operands[i][2] + 128, 255);
7833                         outputColors[i] = RGBA(params.results [i][0] + 128, params.results [i][1] + 128, params.results [i][2] + 128, 255);
7834                 }
7835
7836                 createTestsForAllStages(params.name, inputColors, outputColors, fragments, testGroup.get(), params.failResult, params.failMessageTemplate);
7837         }
7838         return testGroup.release();
7839 }
7840
7841
7842 enum IntegerType
7843 {
7844         INTEGER_TYPE_SIGNED_16,
7845         INTEGER_TYPE_SIGNED_32,
7846         INTEGER_TYPE_SIGNED_64,
7847
7848         INTEGER_TYPE_UNSIGNED_16,
7849         INTEGER_TYPE_UNSIGNED_32,
7850         INTEGER_TYPE_UNSIGNED_64,
7851 };
7852
7853 const string getBitWidthStr (IntegerType type)
7854 {
7855         switch (type)
7856         {
7857                 case INTEGER_TYPE_SIGNED_16:
7858                 case INTEGER_TYPE_UNSIGNED_16:  return "16";
7859
7860                 case INTEGER_TYPE_SIGNED_32:
7861                 case INTEGER_TYPE_UNSIGNED_32:  return "32";
7862
7863                 case INTEGER_TYPE_SIGNED_64:
7864                 case INTEGER_TYPE_UNSIGNED_64:  return "64";
7865
7866                 default:                                                DE_ASSERT(false);
7867                                                                                 return "";
7868         }
7869 }
7870
7871 const string getByteWidthStr (IntegerType type)
7872 {
7873         switch (type)
7874         {
7875                 case INTEGER_TYPE_SIGNED_16:
7876                 case INTEGER_TYPE_UNSIGNED_16:  return "2";
7877
7878                 case INTEGER_TYPE_SIGNED_32:
7879                 case INTEGER_TYPE_UNSIGNED_32:  return "4";
7880
7881                 case INTEGER_TYPE_SIGNED_64:
7882                 case INTEGER_TYPE_UNSIGNED_64:  return "8";
7883
7884                 default:                                                DE_ASSERT(false);
7885                                                                                 return "";
7886         }
7887 }
7888
7889 bool isSigned (IntegerType type)
7890 {
7891         return (type <= INTEGER_TYPE_SIGNED_64);
7892 }
7893
7894 const string getTypeName (IntegerType type)
7895 {
7896         string prefix = isSigned(type) ? "" : "u";
7897         return prefix + "int" + getBitWidthStr(type);
7898 }
7899
7900 const string getTestName (IntegerType from, IntegerType to)
7901 {
7902         return getTypeName(from) + "_to_" + getTypeName(to);
7903 }
7904
7905 const string getAsmTypeDeclaration (IntegerType type)
7906 {
7907         string sign = isSigned(type) ? " 1" : " 0";
7908         return "OpTypeInt " + getBitWidthStr(type) + sign;
7909 }
7910
7911 const string getAsmTypeName (IntegerType type)
7912 {
7913         const string prefix = isSigned(type) ? "%i" : "%u";
7914         return prefix + getBitWidthStr(type);
7915 }
7916
7917 template<typename T>
7918 BufferSp getSpecializedBuffer (deInt64 number)
7919 {
7920         return BufferSp(new Buffer<T>(vector<T>(1, (T)number)));
7921 }
7922
7923 BufferSp getBuffer (IntegerType type, deInt64 number)
7924 {
7925         switch (type)
7926         {
7927                 case INTEGER_TYPE_SIGNED_16:    return getSpecializedBuffer<deInt16>(number);
7928                 case INTEGER_TYPE_SIGNED_32:    return getSpecializedBuffer<deInt32>(number);
7929                 case INTEGER_TYPE_SIGNED_64:    return getSpecializedBuffer<deInt64>(number);
7930
7931                 case INTEGER_TYPE_UNSIGNED_16:  return getSpecializedBuffer<deUint16>(number);
7932                 case INTEGER_TYPE_UNSIGNED_32:  return getSpecializedBuffer<deUint32>(number);
7933                 case INTEGER_TYPE_UNSIGNED_64:  return getSpecializedBuffer<deUint64>(number);
7934
7935                 default:                                                DE_ASSERT(false);
7936                                                                                 return BufferSp(new Buffer<deInt32>(vector<deInt32>(1, 0)));
7937         }
7938 }
7939
7940 bool usesInt16 (IntegerType from, IntegerType to)
7941 {
7942         return (from == INTEGER_TYPE_SIGNED_16 || from == INTEGER_TYPE_UNSIGNED_16
7943                         || to == INTEGER_TYPE_SIGNED_16 || to == INTEGER_TYPE_UNSIGNED_16);
7944 }
7945
7946 bool usesInt64 (IntegerType from, IntegerType to)
7947 {
7948         return (from == INTEGER_TYPE_SIGNED_64 || from == INTEGER_TYPE_UNSIGNED_64
7949                         || to == INTEGER_TYPE_SIGNED_64 || to == INTEGER_TYPE_UNSIGNED_64);
7950 }
7951
7952 ComputeTestFeatures getConversionUsedFeatures (IntegerType from, IntegerType to)
7953 {
7954         if (usesInt16(from, to))
7955         {
7956                 if (usesInt64(from, to))
7957                 {
7958                         return COMPUTE_TEST_USES_INT16_INT64;
7959                 }
7960                 else
7961                 {
7962                         return COMPUTE_TEST_USES_INT16;
7963                 }
7964         }
7965         else
7966         {
7967                 return COMPUTE_TEST_USES_INT64;
7968         }
7969 }
7970
7971 struct ConvertCase
7972 {
7973         ConvertCase (IntegerType from, IntegerType to, deInt64 number)
7974         : m_fromType            (from)
7975         , m_toType                      (to)
7976         , m_features            (getConversionUsedFeatures(from, to))
7977         , m_name                        (getTestName(from, to))
7978         , m_inputBuffer         (getBuffer(from, number))
7979         , m_outputBuffer        (getBuffer(to, number))
7980         {
7981                 m_asmTypes["inputType"]         = getAsmTypeName(from);
7982                 m_asmTypes["outputType"]        = getAsmTypeName(to);
7983
7984                 if (m_features == COMPUTE_TEST_USES_INT16)
7985                 {
7986                         m_asmTypes["int_capabilities"]    = "OpCapability Int16\n"
7987                                                                                                 "OpCapability StorageUniformBufferBlock16\n";
7988                         m_asmTypes["int_additional_decl"] = "%i16        = OpTypeInt 16 1\n"
7989                                                                                                 "%u16        = OpTypeInt 16 0\n";
7990                         m_asmTypes["int_extensions"]      = "OpExtension \"SPV_KHR_16bit_storage\"\n";
7991                 }
7992                 else if (m_features == COMPUTE_TEST_USES_INT64)
7993                 {
7994                         m_asmTypes["int_capabilities"]    = "OpCapability Int64\n";
7995                         m_asmTypes["int_additional_decl"] = "%i64        = OpTypeInt 64 1\n"
7996                                                                                                 "%u64        = OpTypeInt 64 0\n";
7997                         m_asmTypes["int_extensions"]      = "";
7998                 }
7999                 else if (m_features == COMPUTE_TEST_USES_INT16_INT64)
8000                 {
8001                         m_asmTypes["int_capabilities"]    = "OpCapability Int16\n"
8002                                                                                                 "OpCapability StorageUniformBufferBlock16\n"
8003                                                                                                 "OpCapability Int64\n";
8004                         m_asmTypes["int_additional_decl"] = "%i16        = OpTypeInt 16 1\n"
8005                                                                                                 "%u16        = OpTypeInt 16 0\n"
8006                                                                                                 "%i64        = OpTypeInt 64 1\n"
8007                                                                                                 "%u64        = OpTypeInt 64 0\n";
8008                         m_asmTypes["int_extensions"]      = "OpExtension \"SPV_KHR_16bit_storage\"\n";
8009                 }
8010                 else
8011                 {
8012                         DE_ASSERT(false);
8013                 }
8014         }
8015
8016         IntegerType                             m_fromType;
8017         IntegerType                             m_toType;
8018         ComputeTestFeatures             m_features;
8019         string                                  m_name;
8020         map<string, string>             m_asmTypes;
8021         BufferSp                                m_inputBuffer;
8022         BufferSp                                m_outputBuffer;
8023 };
8024
8025 const string getConvertCaseShaderStr (const string& instruction, const ConvertCase& convertCase)
8026 {
8027         map<string, string> params = convertCase.m_asmTypes;
8028
8029         params["instruction"] = instruction;
8030
8031         params["inDecorator"] = getByteWidthStr(convertCase.m_fromType);
8032         params["outDecorator"] = getByteWidthStr(convertCase.m_toType);
8033
8034         const StringTemplate shader (
8035                 "OpCapability Shader\n"
8036                 "${int_capabilities}"
8037                 "${int_extensions}"
8038                 "OpMemoryModel Logical GLSL450\n"
8039                 "OpEntryPoint GLCompute %main \"main\" %id\n"
8040                 "OpExecutionMode %main LocalSize 1 1 1\n"
8041                 "OpSource GLSL 430\n"
8042                 "OpName %main           \"main\"\n"
8043                 "OpName %id             \"gl_GlobalInvocationID\"\n"
8044                 // Decorators
8045                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
8046                 "OpDecorate %indata DescriptorSet 0\n"
8047                 "OpDecorate %indata Binding 0\n"
8048                 "OpDecorate %outdata DescriptorSet 0\n"
8049                 "OpDecorate %outdata Binding 1\n"
8050                 "OpDecorate %in_arr ArrayStride ${inDecorator}\n"
8051                 "OpDecorate %out_arr ArrayStride ${outDecorator}\n"
8052                 "OpDecorate %in_buf BufferBlock\n"
8053                 "OpDecorate %out_buf BufferBlock\n"
8054                 "OpMemberDecorate %in_buf 0 Offset 0\n"
8055                 "OpMemberDecorate %out_buf 0 Offset 0\n"
8056                 // Base types
8057                 "%void       = OpTypeVoid\n"
8058                 "%voidf      = OpTypeFunction %void\n"
8059                 "%u32        = OpTypeInt 32 0\n"
8060                 "%i32        = OpTypeInt 32 1\n"
8061                 "${int_additional_decl}"
8062                 "%uvec3      = OpTypeVector %u32 3\n"
8063                 "%uvec3ptr   = OpTypePointer Input %uvec3\n"
8064                 // Derived types
8065                 "%in_ptr     = OpTypePointer Uniform ${inputType}\n"
8066                 "%out_ptr    = OpTypePointer Uniform ${outputType}\n"
8067                 "%in_arr     = OpTypeRuntimeArray ${inputType}\n"
8068                 "%out_arr    = OpTypeRuntimeArray ${outputType}\n"
8069                 "%in_buf     = OpTypeStruct %in_arr\n"
8070                 "%out_buf    = OpTypeStruct %out_arr\n"
8071                 "%in_bufptr  = OpTypePointer Uniform %in_buf\n"
8072                 "%out_bufptr = OpTypePointer Uniform %out_buf\n"
8073                 "%indata     = OpVariable %in_bufptr Uniform\n"
8074                 "%outdata    = OpVariable %out_bufptr Uniform\n"
8075                 "%inputptr   = OpTypePointer Input ${inputType}\n"
8076                 "%id         = OpVariable %uvec3ptr Input\n"
8077                 // Constants
8078                 "%zero       = OpConstant %i32 0\n"
8079                 // Main function
8080                 "%main       = OpFunction %void None %voidf\n"
8081                 "%label      = OpLabel\n"
8082                 "%idval      = OpLoad %uvec3 %id\n"
8083                 "%x          = OpCompositeExtract %u32 %idval 0\n"
8084                 "%inloc      = OpAccessChain %in_ptr %indata %zero %x\n"
8085                 "%outloc     = OpAccessChain %out_ptr %outdata %zero %x\n"
8086                 "%inval      = OpLoad ${inputType} %inloc\n"
8087                 "%conv       = ${instruction} ${outputType} %inval\n"
8088                 "              OpStore %outloc %conv\n"
8089                 "              OpReturn\n"
8090                 "              OpFunctionEnd\n"
8091         );
8092
8093         return shader.specialize(params);
8094 }
8095
8096 void createSConvertCases (vector<ConvertCase>& testCases)
8097 {
8098         // Convert int to int
8099         testCases.push_back(ConvertCase(INTEGER_TYPE_SIGNED_16, INTEGER_TYPE_SIGNED_32,         14669));
8100         testCases.push_back(ConvertCase(INTEGER_TYPE_SIGNED_16, INTEGER_TYPE_SIGNED_64,         3341));
8101
8102         testCases.push_back(ConvertCase(INTEGER_TYPE_SIGNED_32, INTEGER_TYPE_SIGNED_64,         973610259));
8103
8104         // Convert int to unsigned int
8105         testCases.push_back(ConvertCase(INTEGER_TYPE_SIGNED_16, INTEGER_TYPE_UNSIGNED_32,       9288));
8106         testCases.push_back(ConvertCase(INTEGER_TYPE_SIGNED_16, INTEGER_TYPE_UNSIGNED_64,       15460));
8107
8108         testCases.push_back(ConvertCase(INTEGER_TYPE_SIGNED_32, INTEGER_TYPE_UNSIGNED_64,       346213461));
8109 }
8110
8111 //  Test for the OpSConvert instruction.
8112 tcu::TestCaseGroup* createSConvertTests (tcu::TestContext& testCtx)
8113 {
8114         const string instruction                                ("OpSConvert");
8115         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "sconvert", "OpSConvert"));
8116         vector<ConvertCase>                             testCases;
8117         createSConvertCases(testCases);
8118
8119         for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
8120         {
8121                 ComputeShaderSpec       spec;
8122
8123                 spec.assembly = getConvertCaseShaderStr(instruction, *test);
8124                 spec.inputs.push_back(test->m_inputBuffer);
8125                 spec.outputs.push_back(test->m_outputBuffer);
8126                 spec.numWorkGroups = IVec3(1, 1, 1);
8127
8128                 if (test->m_features == COMPUTE_TEST_USES_INT16 || test->m_features == COMPUTE_TEST_USES_INT16_INT64)
8129                 {
8130                         spec.extensions.push_back("VK_KHR_16bit_storage");
8131                         spec.requestedVulkanFeatures.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
8132                 }
8133
8134                 group->addChild(new SpvAsmComputeShaderCase(testCtx, test->m_name.c_str(), "Convert integers with OpSConvert.", spec, test->m_features));
8135         }
8136
8137         return group.release();
8138 }
8139
8140 void createUConvertCases (vector<ConvertCase>& testCases)
8141 {
8142         // Convert unsigned int to unsigned int
8143         testCases.push_back(ConvertCase(INTEGER_TYPE_UNSIGNED_16,       INTEGER_TYPE_UNSIGNED_32,       60653));
8144         testCases.push_back(ConvertCase(INTEGER_TYPE_UNSIGNED_16,       INTEGER_TYPE_UNSIGNED_64,       17991));
8145
8146         testCases.push_back(ConvertCase(INTEGER_TYPE_UNSIGNED_32,       INTEGER_TYPE_UNSIGNED_64,       904256275));
8147 }
8148
8149 //  Test for the OpUConvert instruction.
8150 tcu::TestCaseGroup* createUConvertTests (tcu::TestContext& testCtx)
8151 {
8152         const string instruction                                ("OpUConvert");
8153         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "uconvert", "OpUConvert"));
8154         vector<ConvertCase>                             testCases;
8155         createUConvertCases(testCases);
8156
8157         for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
8158         {
8159                 ComputeShaderSpec       spec;
8160
8161                 spec.assembly = getConvertCaseShaderStr(instruction, *test);
8162                 spec.inputs.push_back(test->m_inputBuffer);
8163                 spec.outputs.push_back(test->m_outputBuffer);
8164                 spec.numWorkGroups = IVec3(1, 1, 1);
8165
8166                 if (test->m_features == COMPUTE_TEST_USES_INT16 || test->m_features == COMPUTE_TEST_USES_INT16_INT64)
8167                 {
8168                         spec.extensions.push_back("VK_KHR_16bit_storage");
8169                         spec.requestedVulkanFeatures.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
8170                 }
8171
8172                 group->addChild(new SpvAsmComputeShaderCase(testCtx, test->m_name.c_str(), "Convert integers with OpUConvert.", spec, test->m_features));
8173         }
8174         return group.release();
8175 }
8176
8177 const string getNumberTypeName (const NumberType type)
8178 {
8179         if (type == NUMBERTYPE_INT32)
8180         {
8181                 return "int";
8182         }
8183         else if (type == NUMBERTYPE_UINT32)
8184         {
8185                 return "uint";
8186         }
8187         else if (type == NUMBERTYPE_FLOAT32)
8188         {
8189                 return "float";
8190         }
8191         else
8192         {
8193                 DE_ASSERT(false);
8194                 return "";
8195         }
8196 }
8197
8198 deInt32 getInt(de::Random& rnd)
8199 {
8200         return rnd.getInt(std::numeric_limits<int>::min(), std::numeric_limits<int>::max());
8201 }
8202
8203 const string repeatString (const string& str, int times)
8204 {
8205         string filler;
8206         for (int i = 0; i < times; ++i)
8207         {
8208                 filler += str;
8209         }
8210         return filler;
8211 }
8212
8213 const string getRandomConstantString (const NumberType type, de::Random& rnd)
8214 {
8215         if (type == NUMBERTYPE_INT32)
8216         {
8217                 return numberToString<deInt32>(getInt(rnd));
8218         }
8219         else if (type == NUMBERTYPE_UINT32)
8220         {
8221                 return numberToString<deUint32>(rnd.getUint32());
8222         }
8223         else if (type == NUMBERTYPE_FLOAT32)
8224         {
8225                 return numberToString<float>(rnd.getFloat());
8226         }
8227         else
8228         {
8229                 DE_ASSERT(false);
8230                 return "";
8231         }
8232 }
8233
8234 void createVectorCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
8235 {
8236         map<string, string> params;
8237
8238         // Vec2 to Vec4
8239         for (int width = 2; width <= 4; ++width)
8240         {
8241                 const string randomConst = numberToString(getInt(rnd));
8242                 const string widthStr = numberToString(width);
8243                 const string composite_type = "${customType}vec" + widthStr;
8244                 const int index = rnd.getInt(0, width-1);
8245
8246                 params["type"]                  = "vec";
8247                 params["name"]                  = params["type"] + "_" + widthStr;
8248                 params["compositeDecl"]         = composite_type + " = OpTypeVector ${customType} " + widthStr +"\n";
8249                 params["compositeType"]         = composite_type;
8250                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
8251                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct " + composite_type + repeatString(" %filler", width) + "\n";
8252                 params["indexes"]               = numberToString(index);
8253                 testCases.push_back(params);
8254         }
8255 }
8256
8257 void createArrayCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
8258 {
8259         const int limit = 10;
8260         map<string, string> params;
8261
8262         for (int width = 2; width <= limit; ++width)
8263         {
8264                 string randomConst = numberToString(getInt(rnd));
8265                 string widthStr = numberToString(width);
8266                 int index = rnd.getInt(0, width-1);
8267
8268                 params["type"]                  = "array";
8269                 params["name"]                  = params["type"] + "_" + widthStr;
8270                 params["compositeDecl"]         = string("%arraywidth = OpConstant %u32 " + widthStr + "\n")
8271                                                                                         +        "%composite = OpTypeArray ${customType} %arraywidth\n";
8272                 params["compositeType"]         = "%composite";
8273                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
8274                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
8275                 params["indexes"]               = numberToString(index);
8276                 testCases.push_back(params);
8277         }
8278 }
8279
8280 void createStructCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
8281 {
8282         const int limit = 10;
8283         map<string, string> params;
8284
8285         for (int width = 2; width <= limit; ++width)
8286         {
8287                 string randomConst = numberToString(getInt(rnd));
8288                 int index = rnd.getInt(0, width-1);
8289
8290                 params["type"]                  = "struct";
8291                 params["name"]                  = params["type"] + "_" + numberToString(width);
8292                 params["compositeDecl"]         = "%composite = OpTypeStruct" + repeatString(" ${customType}", width) + "\n";
8293                 params["compositeType"]         = "%composite";
8294                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
8295                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
8296                 params["indexes"]               = numberToString(index);
8297                 testCases.push_back(params);
8298         }
8299 }
8300
8301 void createMatrixCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
8302 {
8303         map<string, string> params;
8304
8305         // Vec2 to Vec4
8306         for (int width = 2; width <= 4; ++width)
8307         {
8308                 string widthStr = numberToString(width);
8309
8310                 for (int column = 2 ; column <= 4; ++column)
8311                 {
8312                         int index_0 = rnd.getInt(0, column-1);
8313                         int index_1 = rnd.getInt(0, width-1);
8314                         string columnStr = numberToString(column);
8315
8316                         params["type"]          = "matrix";
8317                         params["name"]          = params["type"] + "_" + widthStr + "x" + columnStr;
8318                         params["compositeDecl"] = string("%vectype   = OpTypeVector ${customType} " + widthStr + "\n")
8319                                                                                                 +        "%composite = OpTypeMatrix %vectype " + columnStr + "\n";
8320                         params["compositeType"] = "%composite";
8321
8322                         params["filler"]        = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n"
8323                                                                                                 +        "%fillerVec = OpConstantComposite %vectype" + repeatString(" %filler", width) + "\n";
8324
8325                         params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %fillerVec", column) + "\n";
8326                         params["indexes"]       = numberToString(index_0) + " " + numberToString(index_1);
8327                         testCases.push_back(params);
8328                 }
8329         }
8330 }
8331
8332 void createCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
8333 {
8334         createVectorCompositeCases(testCases, rnd, type);
8335         createArrayCompositeCases(testCases, rnd, type);
8336         createStructCompositeCases(testCases, rnd, type);
8337         // Matrix only supports float types
8338         if (type == NUMBERTYPE_FLOAT32)
8339         {
8340                 createMatrixCompositeCases(testCases, rnd, type);
8341         }
8342 }
8343
8344 const string getAssemblyTypeDeclaration (const NumberType type)
8345 {
8346         switch (type)
8347         {
8348                 case NUMBERTYPE_INT32:          return "OpTypeInt 32 1";
8349                 case NUMBERTYPE_UINT32:         return "OpTypeInt 32 0";
8350                 case NUMBERTYPE_FLOAT32:        return "OpTypeFloat 32";
8351                 default:                        DE_ASSERT(false); return "";
8352         }
8353 }
8354
8355 const string getAssemblyTypeName (const NumberType type)
8356 {
8357         switch (type)
8358         {
8359                 case NUMBERTYPE_INT32:          return "%i32";
8360                 case NUMBERTYPE_UINT32:         return "%u32";
8361                 case NUMBERTYPE_FLOAT32:        return "%f32";
8362                 default:                        DE_ASSERT(false); return "";
8363         }
8364 }
8365
8366 const string specializeCompositeInsertShaderTemplate (const NumberType type, const map<string, string>& params)
8367 {
8368         map<string, string>     parameters(params);
8369
8370         const string customType = getAssemblyTypeName(type);
8371         map<string, string> substCustomType;
8372         substCustomType["customType"] = customType;
8373         parameters["compositeDecl"] = StringTemplate(parameters.at("compositeDecl")).specialize(substCustomType);
8374         parameters["compositeType"] = StringTemplate(parameters.at("compositeType")).specialize(substCustomType);
8375         parameters["compositeConstruct"] = StringTemplate(parameters.at("compositeConstruct")).specialize(substCustomType);
8376         parameters["filler"] = StringTemplate(parameters.at("filler")).specialize(substCustomType);
8377         parameters["customType"] = customType;
8378         parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
8379
8380         if (parameters.at("compositeType") != "%u32vec3")
8381         {
8382                 parameters["u32vec3Decl"] = "%u32vec3   = OpTypeVector %u32 3\n";
8383         }
8384
8385         return StringTemplate(
8386                 "OpCapability Shader\n"
8387                 "OpCapability Matrix\n"
8388                 "OpMemoryModel Logical GLSL450\n"
8389                 "OpEntryPoint GLCompute %main \"main\" %id\n"
8390                 "OpExecutionMode %main LocalSize 1 1 1\n"
8391
8392                 "OpSource GLSL 430\n"
8393                 "OpName %main           \"main\"\n"
8394                 "OpName %id             \"gl_GlobalInvocationID\"\n"
8395
8396                 // Decorators
8397                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
8398                 "OpDecorate %buf BufferBlock\n"
8399                 "OpDecorate %indata DescriptorSet 0\n"
8400                 "OpDecorate %indata Binding 0\n"
8401                 "OpDecorate %outdata DescriptorSet 0\n"
8402                 "OpDecorate %outdata Binding 1\n"
8403                 "OpDecorate %customarr ArrayStride 4\n"
8404                 "${compositeDecorator}"
8405                 "OpMemberDecorate %buf 0 Offset 0\n"
8406
8407                 // General types
8408                 "%void      = OpTypeVoid\n"
8409                 "%voidf     = OpTypeFunction %void\n"
8410                 "%u32       = OpTypeInt 32 0\n"
8411                 "%i32       = OpTypeInt 32 1\n"
8412                 "%f32       = OpTypeFloat 32\n"
8413
8414                 // Composite declaration
8415                 "${compositeDecl}"
8416
8417                 // Constants
8418                 "${filler}"
8419
8420                 "${u32vec3Decl:opt}"
8421                 "%uvec3ptr  = OpTypePointer Input %u32vec3\n"
8422
8423                 // Inherited from custom
8424                 "%customptr = OpTypePointer Uniform ${customType}\n"
8425                 "%customarr = OpTypeRuntimeArray ${customType}\n"
8426                 "%buf       = OpTypeStruct %customarr\n"
8427                 "%bufptr    = OpTypePointer Uniform %buf\n"
8428
8429                 "%indata    = OpVariable %bufptr Uniform\n"
8430                 "%outdata   = OpVariable %bufptr Uniform\n"
8431
8432                 "%id        = OpVariable %uvec3ptr Input\n"
8433                 "%zero      = OpConstant %i32 0\n"
8434
8435                 "%main      = OpFunction %void None %voidf\n"
8436                 "%label     = OpLabel\n"
8437                 "%idval     = OpLoad %u32vec3 %id\n"
8438                 "%x         = OpCompositeExtract %u32 %idval 0\n"
8439
8440                 "%inloc     = OpAccessChain %customptr %indata %zero %x\n"
8441                 "%outloc    = OpAccessChain %customptr %outdata %zero %x\n"
8442                 // Read the input value
8443                 "%inval     = OpLoad ${customType} %inloc\n"
8444                 // Create the composite and fill it
8445                 "${compositeConstruct}"
8446                 // Insert the input value to a place
8447                 "%instance2 = OpCompositeInsert ${compositeType} %inval %instance ${indexes}\n"
8448                 // Read back the value from the position
8449                 "%out_val   = OpCompositeExtract ${customType} %instance2 ${indexes}\n"
8450                 // Store it in the output position
8451                 "             OpStore %outloc %out_val\n"
8452                 "             OpReturn\n"
8453                 "             OpFunctionEnd\n"
8454         ).specialize(parameters);
8455 }
8456
8457 template<typename T>
8458 BufferSp createCompositeBuffer(T number)
8459 {
8460         return BufferSp(new Buffer<T>(vector<T>(1, number)));
8461 }
8462
8463 tcu::TestCaseGroup* createOpCompositeInsertGroup (tcu::TestContext& testCtx)
8464 {
8465         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "opcompositeinsert", "Test the OpCompositeInsert instruction"));
8466         de::Random                                              rnd             (deStringHash(group->getName()));
8467
8468         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
8469         {
8470                 NumberType                                              numberType              = NumberType(type);
8471                 const string                                    typeName                = getNumberTypeName(numberType);
8472                 const string                                    description             = "Test the OpCompositeInsert instruction with " + typeName + "s";
8473                 de::MovePtr<tcu::TestCaseGroup> subGroup                (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
8474                 vector<map<string, string> >    testCases;
8475
8476                 createCompositeCases(testCases, rnd, numberType);
8477
8478                 for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
8479                 {
8480                         ComputeShaderSpec       spec;
8481
8482                         spec.assembly = specializeCompositeInsertShaderTemplate(numberType, *test);
8483
8484                         switch (numberType)
8485                         {
8486                                 case NUMBERTYPE_INT32:
8487                                 {
8488                                         deInt32 number = getInt(rnd);
8489                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
8490                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
8491                                         break;
8492                                 }
8493                                 case NUMBERTYPE_UINT32:
8494                                 {
8495                                         deUint32 number = rnd.getUint32();
8496                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
8497                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
8498                                         break;
8499                                 }
8500                                 case NUMBERTYPE_FLOAT32:
8501                                 {
8502                                         float number = rnd.getFloat();
8503                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
8504                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
8505                                         break;
8506                                 }
8507                                 default:
8508                                         DE_ASSERT(false);
8509                         }
8510
8511                         spec.numWorkGroups = IVec3(1, 1, 1);
8512                         subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpCompositeInsert test", spec));
8513                 }
8514                 group->addChild(subGroup.release());
8515         }
8516         return group.release();
8517 }
8518
8519 struct AssemblyStructInfo
8520 {
8521         AssemblyStructInfo (const deUint32 comp, const deUint32 idx)
8522         : components    (comp)
8523         , index                 (idx)
8524         {}
8525
8526         deUint32 components;
8527         deUint32 index;
8528 };
8529
8530 const string specializeInBoundsShaderTemplate (const NumberType type, const AssemblyStructInfo& structInfo, const map<string, string>& params)
8531 {
8532         // Create the full index string
8533         string                          fullIndex       = numberToString(structInfo.index) + " " + params.at("indexes");
8534         // Convert it to list of indexes
8535         vector<string>          indexes         = de::splitString(fullIndex, ' ');
8536
8537         map<string, string>     parameters      (params);
8538         parameters["structType"]        = repeatString(" ${compositeType}", structInfo.components);
8539         parameters["structConstruct"]   = repeatString(" %instance", structInfo.components);
8540         parameters["insertIndexes"]     = fullIndex;
8541
8542         // In matrix cases the last two index is the CompositeExtract indexes
8543         const deUint32 extractIndexes = (parameters["type"] == "matrix") ? 2 : 1;
8544
8545         // Construct the extractIndex
8546         for (vector<string>::const_iterator index = indexes.end() - extractIndexes; index != indexes.end(); ++index)
8547         {
8548                 parameters["extractIndexes"] += " " + *index;
8549         }
8550
8551         // Remove the last 1 or 2 element depends on matrix case or not
8552         indexes.erase(indexes.end() - extractIndexes, indexes.end());
8553
8554         deUint32 id = 0;
8555         // Generate AccessChain index expressions (except for the last one, because we use ptr to the composite)
8556         for (vector<string>::const_iterator index = indexes.begin(); index != indexes.end(); ++index)
8557         {
8558                 string indexId = "%index_" + numberToString(id++);
8559                 parameters["accessChainConstDeclaration"] += indexId + "   = OpConstant %u32 " + *index + "\n";
8560                 parameters["accessChainIndexes"] += " " + indexId;
8561         }
8562
8563         parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
8564
8565         const string customType = getAssemblyTypeName(type);
8566         map<string, string> substCustomType;
8567         substCustomType["customType"] = customType;
8568         parameters["compositeDecl"] = StringTemplate(parameters.at("compositeDecl")).specialize(substCustomType);
8569         parameters["compositeType"] = StringTemplate(parameters.at("compositeType")).specialize(substCustomType);
8570         parameters["compositeConstruct"] = StringTemplate(parameters.at("compositeConstruct")).specialize(substCustomType);
8571         parameters["filler"] = StringTemplate(parameters.at("filler")).specialize(substCustomType);
8572         parameters["customType"] = customType;
8573
8574         const string compositeType = parameters.at("compositeType");
8575         map<string, string> substCompositeType;
8576         substCompositeType["compositeType"] = compositeType;
8577         parameters["structType"] = StringTemplate(parameters.at("structType")).specialize(substCompositeType);
8578         if (compositeType != "%u32vec3")
8579         {
8580                 parameters["u32vec3Decl"] = "%u32vec3   = OpTypeVector %u32 3\n";
8581         }
8582
8583         return StringTemplate(
8584                 "OpCapability Shader\n"
8585                 "OpCapability Matrix\n"
8586                 "OpMemoryModel Logical GLSL450\n"
8587                 "OpEntryPoint GLCompute %main \"main\" %id\n"
8588                 "OpExecutionMode %main LocalSize 1 1 1\n"
8589
8590                 "OpSource GLSL 430\n"
8591                 "OpName %main           \"main\"\n"
8592                 "OpName %id             \"gl_GlobalInvocationID\"\n"
8593                 // Decorators
8594                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
8595                 "OpDecorate %buf BufferBlock\n"
8596                 "OpDecorate %indata DescriptorSet 0\n"
8597                 "OpDecorate %indata Binding 0\n"
8598                 "OpDecorate %outdata DescriptorSet 0\n"
8599                 "OpDecorate %outdata Binding 1\n"
8600                 "OpDecorate %customarr ArrayStride 4\n"
8601                 "${compositeDecorator}"
8602                 "OpMemberDecorate %buf 0 Offset 0\n"
8603                 // General types
8604                 "%void      = OpTypeVoid\n"
8605                 "%voidf     = OpTypeFunction %void\n"
8606                 "%i32       = OpTypeInt 32 1\n"
8607                 "%u32       = OpTypeInt 32 0\n"
8608                 "%f32       = OpTypeFloat 32\n"
8609                 // Custom types
8610                 "${compositeDecl}"
8611                 // %u32vec3 if not already declared in ${compositeDecl}
8612                 "${u32vec3Decl:opt}"
8613                 "%uvec3ptr  = OpTypePointer Input %u32vec3\n"
8614                 // Inherited from composite
8615                 "%composite_p = OpTypePointer Function ${compositeType}\n"
8616                 "%struct_t  = OpTypeStruct${structType}\n"
8617                 "%struct_p  = OpTypePointer Function %struct_t\n"
8618                 // Constants
8619                 "${filler}"
8620                 "${accessChainConstDeclaration}"
8621                 // Inherited from custom
8622                 "%customptr = OpTypePointer Uniform ${customType}\n"
8623                 "%customarr = OpTypeRuntimeArray ${customType}\n"
8624                 "%buf       = OpTypeStruct %customarr\n"
8625                 "%bufptr    = OpTypePointer Uniform %buf\n"
8626                 "%indata    = OpVariable %bufptr Uniform\n"
8627                 "%outdata   = OpVariable %bufptr Uniform\n"
8628
8629                 "%id        = OpVariable %uvec3ptr Input\n"
8630                 "%zero      = OpConstant %u32 0\n"
8631                 "%main      = OpFunction %void None %voidf\n"
8632                 "%label     = OpLabel\n"
8633                 "%struct_v  = OpVariable %struct_p Function\n"
8634                 "%idval     = OpLoad %u32vec3 %id\n"
8635                 "%x         = OpCompositeExtract %u32 %idval 0\n"
8636                 // Create the input/output type
8637                 "%inloc     = OpInBoundsAccessChain %customptr %indata %zero %x\n"
8638                 "%outloc    = OpInBoundsAccessChain %customptr %outdata %zero %x\n"
8639                 // Read the input value
8640                 "%inval     = OpLoad ${customType} %inloc\n"
8641                 // Create the composite and fill it
8642                 "${compositeConstruct}"
8643                 // Create the struct and fill it with the composite
8644                 "%struct    = OpCompositeConstruct %struct_t${structConstruct}\n"
8645                 // Insert the value
8646                 "%comp_obj  = OpCompositeInsert %struct_t %inval %struct ${insertIndexes}\n"
8647                 // Store the object
8648                 "             OpStore %struct_v %comp_obj\n"
8649                 // Get deepest possible composite pointer
8650                 "%inner_ptr = OpInBoundsAccessChain %composite_p %struct_v${accessChainIndexes}\n"
8651                 "%read_obj  = OpLoad ${compositeType} %inner_ptr\n"
8652                 // Read back the stored value
8653                 "%read_val  = OpCompositeExtract ${customType} %read_obj${extractIndexes}\n"
8654                 "             OpStore %outloc %read_val\n"
8655                 "             OpReturn\n"
8656                 "             OpFunctionEnd\n"
8657         ).specialize(parameters);
8658 }
8659
8660 tcu::TestCaseGroup* createOpInBoundsAccessChainGroup (tcu::TestContext& testCtx)
8661 {
8662         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opinboundsaccesschain", "Test the OpInBoundsAccessChain instruction"));
8663         de::Random                                              rnd                             (deStringHash(group->getName()));
8664
8665         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
8666         {
8667                 NumberType                                              numberType      = NumberType(type);
8668                 const string                                    typeName        = getNumberTypeName(numberType);
8669                 const string                                    description     = "Test the OpInBoundsAccessChain instruction with " + typeName + "s";
8670                 de::MovePtr<tcu::TestCaseGroup> subGroup        (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
8671
8672                 vector<map<string, string> >    testCases;
8673                 createCompositeCases(testCases, rnd, numberType);
8674
8675                 for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
8676                 {
8677                         ComputeShaderSpec       spec;
8678
8679                         // Number of components inside of a struct
8680                         deUint32 structComponents = rnd.getInt(2, 8);
8681                         // Component index value
8682                         deUint32 structIndex = rnd.getInt(0, structComponents - 1);
8683                         AssemblyStructInfo structInfo(structComponents, structIndex);
8684
8685                         spec.assembly = specializeInBoundsShaderTemplate(numberType, structInfo, *test);
8686
8687                         switch (numberType)
8688                         {
8689                                 case NUMBERTYPE_INT32:
8690                                 {
8691                                         deInt32 number = getInt(rnd);
8692                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
8693                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
8694                                         break;
8695                                 }
8696                                 case NUMBERTYPE_UINT32:
8697                                 {
8698                                         deUint32 number = rnd.getUint32();
8699                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
8700                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
8701                                         break;
8702                                 }
8703                                 case NUMBERTYPE_FLOAT32:
8704                                 {
8705                                         float number = rnd.getFloat();
8706                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
8707                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
8708                                         break;
8709                                 }
8710                                 default:
8711                                         DE_ASSERT(false);
8712                         }
8713                         spec.numWorkGroups = IVec3(1, 1, 1);
8714                         subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpInBoundsAccessChain test", spec));
8715                 }
8716                 group->addChild(subGroup.release());
8717         }
8718         return group.release();
8719 }
8720
8721 // If the params missing, uninitialized case
8722 const string specializeDefaultOutputShaderTemplate (const NumberType type, const map<string, string>& params = map<string, string>())
8723 {
8724         map<string, string> parameters(params);
8725
8726         parameters["customType"]        = getAssemblyTypeName(type);
8727
8728         // Declare the const value, and use it in the initializer
8729         if (params.find("constValue") != params.end())
8730         {
8731                 parameters["variableInitializer"]       = " %const";
8732         }
8733         // Uninitialized case
8734         else
8735         {
8736                 parameters["commentDecl"]       = ";";
8737         }
8738
8739         return StringTemplate(
8740                 "OpCapability Shader\n"
8741                 "OpMemoryModel Logical GLSL450\n"
8742                 "OpEntryPoint GLCompute %main \"main\" %id\n"
8743                 "OpExecutionMode %main LocalSize 1 1 1\n"
8744                 "OpSource GLSL 430\n"
8745                 "OpName %main           \"main\"\n"
8746                 "OpName %id             \"gl_GlobalInvocationID\"\n"
8747                 // Decorators
8748                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
8749                 "OpDecorate %indata DescriptorSet 0\n"
8750                 "OpDecorate %indata Binding 0\n"
8751                 "OpDecorate %outdata DescriptorSet 0\n"
8752                 "OpDecorate %outdata Binding 1\n"
8753                 "OpDecorate %in_arr ArrayStride 4\n"
8754                 "OpDecorate %in_buf BufferBlock\n"
8755                 "OpMemberDecorate %in_buf 0 Offset 0\n"
8756                 // Base types
8757                 "%void       = OpTypeVoid\n"
8758                 "%voidf      = OpTypeFunction %void\n"
8759                 "%u32        = OpTypeInt 32 0\n"
8760                 "%i32        = OpTypeInt 32 1\n"
8761                 "%f32        = OpTypeFloat 32\n"
8762                 "%uvec3      = OpTypeVector %u32 3\n"
8763                 "%uvec3ptr   = OpTypePointer Input %uvec3\n"
8764                 "${commentDecl:opt}%const      = OpConstant ${customType} ${constValue:opt}\n"
8765                 // Derived types
8766                 "%in_ptr     = OpTypePointer Uniform ${customType}\n"
8767                 "%in_arr     = OpTypeRuntimeArray ${customType}\n"
8768                 "%in_buf     = OpTypeStruct %in_arr\n"
8769                 "%in_bufptr  = OpTypePointer Uniform %in_buf\n"
8770                 "%indata     = OpVariable %in_bufptr Uniform\n"
8771                 "%outdata    = OpVariable %in_bufptr Uniform\n"
8772                 "%id         = OpVariable %uvec3ptr Input\n"
8773                 "%var_ptr    = OpTypePointer Function ${customType}\n"
8774                 // Constants
8775                 "%zero       = OpConstant %i32 0\n"
8776                 // Main function
8777                 "%main       = OpFunction %void None %voidf\n"
8778                 "%label      = OpLabel\n"
8779                 "%out_var    = OpVariable %var_ptr Function${variableInitializer:opt}\n"
8780                 "%idval      = OpLoad %uvec3 %id\n"
8781                 "%x          = OpCompositeExtract %u32 %idval 0\n"
8782                 "%inloc      = OpAccessChain %in_ptr %indata %zero %x\n"
8783                 "%outloc     = OpAccessChain %in_ptr %outdata %zero %x\n"
8784
8785                 "%outval     = OpLoad ${customType} %out_var\n"
8786                 "              OpStore %outloc %outval\n"
8787                 "              OpReturn\n"
8788                 "              OpFunctionEnd\n"
8789         ).specialize(parameters);
8790 }
8791
8792 bool compareFloats (const std::vector<BufferSp>&, const vector<AllocationSp>& outputAllocs, const std::vector<BufferSp>& expectedOutputs, TestLog& log)
8793 {
8794         DE_ASSERT(outputAllocs.size() != 0);
8795         DE_ASSERT(outputAllocs.size() == expectedOutputs.size());
8796
8797         // Use custom epsilon because of the float->string conversion
8798         const float     epsilon = 0.00001f;
8799
8800         for (size_t outputNdx = 0; outputNdx < outputAllocs.size(); ++outputNdx)
8801         {
8802                 vector<deUint8> expectedBytes;
8803                 float                   expected;
8804                 float                   actual;
8805
8806                 expectedOutputs[outputNdx]->getBytes(expectedBytes);
8807                 memcpy(&expected, &expectedBytes.front(), expectedBytes.size());
8808                 memcpy(&actual, outputAllocs[outputNdx]->getHostPtr(), expectedBytes.size());
8809
8810                 // Test with epsilon
8811                 if (fabs(expected - actual) > epsilon)
8812                 {
8813                         log << TestLog::Message << "Error: The actual and expected values not matching."
8814                                 << " Expected: " << expected << " Actual: " << actual << " Epsilon: " << epsilon << TestLog::EndMessage;
8815                         return false;
8816                 }
8817         }
8818         return true;
8819 }
8820
8821 // Checks if the driver crash with uninitialized cases
8822 bool passthruVerify (const std::vector<BufferSp>&, const vector<AllocationSp>& outputAllocs, const std::vector<BufferSp>& expectedOutputs, TestLog&)
8823 {
8824         DE_ASSERT(outputAllocs.size() != 0);
8825         DE_ASSERT(outputAllocs.size() == expectedOutputs.size());
8826
8827         // Copy and discard the result.
8828         for (size_t outputNdx = 0; outputNdx < outputAllocs.size(); ++outputNdx)
8829         {
8830                 vector<deUint8> expectedBytes;
8831                 expectedOutputs[outputNdx]->getBytes(expectedBytes);
8832
8833                 const size_t    width                   = expectedBytes.size();
8834                 vector<char>    data                    (width);
8835
8836                 memcpy(&data[0], outputAllocs[outputNdx]->getHostPtr(), width);
8837         }
8838         return true;
8839 }
8840
8841 tcu::TestCaseGroup* createShaderDefaultOutputGroup (tcu::TestContext& testCtx)
8842 {
8843         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "shader_default_output", "Test shader default output."));
8844         de::Random                                              rnd             (deStringHash(group->getName()));
8845
8846         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
8847         {
8848                 NumberType                                              numberType      = NumberType(type);
8849                 const string                                    typeName        = getNumberTypeName(numberType);
8850                 const string                                    description     = "Test the OpVariable initializer with " + typeName + ".";
8851                 de::MovePtr<tcu::TestCaseGroup> subGroup        (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
8852
8853                 // 2 similar subcases (initialized and uninitialized)
8854                 for (int subCase = 0; subCase < 2; ++subCase)
8855                 {
8856                         ComputeShaderSpec spec;
8857                         spec.numWorkGroups = IVec3(1, 1, 1);
8858
8859                         map<string, string>                             params;
8860
8861                         switch (numberType)
8862                         {
8863                                 case NUMBERTYPE_INT32:
8864                                 {
8865                                         deInt32 number = getInt(rnd);
8866                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
8867                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
8868                                         params["constValue"] = numberToString(number);
8869                                         break;
8870                                 }
8871                                 case NUMBERTYPE_UINT32:
8872                                 {
8873                                         deUint32 number = rnd.getUint32();
8874                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
8875                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
8876                                         params["constValue"] = numberToString(number);
8877                                         break;
8878                                 }
8879                                 case NUMBERTYPE_FLOAT32:
8880                                 {
8881                                         float number = rnd.getFloat();
8882                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
8883                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
8884                                         spec.verifyIO = &compareFloats;
8885                                         params["constValue"] = numberToString(number);
8886                                         break;
8887                                 }
8888                                 default:
8889                                         DE_ASSERT(false);
8890                         }
8891
8892                         // Initialized subcase
8893                         if (!subCase)
8894                         {
8895                                 spec.assembly = specializeDefaultOutputShaderTemplate(numberType, params);
8896                                 subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "initialized", "OpVariable initializer tests.", spec));
8897                         }
8898                         // Uninitialized subcase
8899                         else
8900                         {
8901                                 spec.assembly = specializeDefaultOutputShaderTemplate(numberType);
8902                                 spec.verifyIO = &passthruVerify;
8903                                 subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "uninitialized", "OpVariable initializer tests.", spec));
8904                         }
8905                 }
8906                 group->addChild(subGroup.release());
8907         }
8908         return group.release();
8909 }
8910
8911 tcu::TestCaseGroup* createOpNopTests (tcu::TestContext& testCtx)
8912 {
8913         de::MovePtr<tcu::TestCaseGroup> testGroup (new tcu::TestCaseGroup(testCtx, "opnop", "Test OpNop"));
8914         RGBA                                                    defaultColors[4];
8915         map<string, string>                             opNopFragments;
8916
8917         getDefaultColors(defaultColors);
8918
8919         opNopFragments["testfun"]               =
8920                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
8921                 "%param1 = OpFunctionParameter %v4f32\n"
8922                 "%label_testfun = OpLabel\n"
8923                 "OpNop\n"
8924                 "OpNop\n"
8925                 "OpNop\n"
8926                 "OpNop\n"
8927                 "OpNop\n"
8928                 "OpNop\n"
8929                 "OpNop\n"
8930                 "OpNop\n"
8931                 "%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8932                 "%b = OpFAdd %f32 %a %a\n"
8933                 "OpNop\n"
8934                 "%c = OpFSub %f32 %b %a\n"
8935                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
8936                 "OpNop\n"
8937                 "OpNop\n"
8938                 "OpReturnValue %ret\n"
8939                 "OpFunctionEnd\n";
8940
8941         createTestsForAllStages("opnop", defaultColors, defaultColors, opNopFragments, testGroup.get());
8942
8943         return testGroup.release();
8944 }
8945
8946 tcu::TestCaseGroup* createInstructionTests (tcu::TestContext& testCtx)
8947 {
8948         const bool testComputePipeline = true;
8949
8950         de::MovePtr<tcu::TestCaseGroup> instructionTests        (new tcu::TestCaseGroup(testCtx, "instruction", "Instructions with special opcodes/operands"));
8951         de::MovePtr<tcu::TestCaseGroup> computeTests            (new tcu::TestCaseGroup(testCtx, "compute", "Compute Instructions with special opcodes/operands"));
8952         de::MovePtr<tcu::TestCaseGroup> graphicsTests           (new tcu::TestCaseGroup(testCtx, "graphics", "Graphics Instructions with special opcodes/operands"));
8953
8954         computeTests->addChild(createSpivVersionCheckTests(testCtx, testComputePipeline));
8955         computeTests->addChild(createLocalSizeGroup(testCtx));
8956         computeTests->addChild(createOpNopGroup(testCtx));
8957         computeTests->addChild(createOpFUnordGroup(testCtx));
8958         computeTests->addChild(createOpAtomicGroup(testCtx, false));
8959         computeTests->addChild(createOpAtomicGroup(testCtx, true)); // Using new StorageBuffer decoration
8960         computeTests->addChild(createOpLineGroup(testCtx));
8961         computeTests->addChild(createOpModuleProcessedGroup(testCtx));
8962         computeTests->addChild(createOpNoLineGroup(testCtx));
8963         computeTests->addChild(createOpConstantNullGroup(testCtx));
8964         computeTests->addChild(createOpConstantCompositeGroup(testCtx));
8965         computeTests->addChild(createOpConstantUsageGroup(testCtx));
8966         computeTests->addChild(createSpecConstantGroup(testCtx));
8967         computeTests->addChild(createOpSourceGroup(testCtx));
8968         computeTests->addChild(createOpSourceExtensionGroup(testCtx));
8969         computeTests->addChild(createDecorationGroupGroup(testCtx));
8970         computeTests->addChild(createOpPhiGroup(testCtx));
8971         computeTests->addChild(createLoopControlGroup(testCtx));
8972         computeTests->addChild(createFunctionControlGroup(testCtx));
8973         computeTests->addChild(createSelectionControlGroup(testCtx));
8974         computeTests->addChild(createBlockOrderGroup(testCtx));
8975         computeTests->addChild(createMultipleShaderGroup(testCtx));
8976         computeTests->addChild(createMemoryAccessGroup(testCtx));
8977         computeTests->addChild(createOpCopyMemoryGroup(testCtx));
8978         computeTests->addChild(createOpCopyObjectGroup(testCtx));
8979         computeTests->addChild(createNoContractionGroup(testCtx));
8980         computeTests->addChild(createOpUndefGroup(testCtx));
8981         computeTests->addChild(createOpUnreachableGroup(testCtx));
8982         computeTests ->addChild(createOpQuantizeToF16Group(testCtx));
8983         computeTests ->addChild(createOpFRemGroup(testCtx));
8984         computeTests->addChild(createOpSRemComputeGroup(testCtx, QP_TEST_RESULT_PASS));
8985         computeTests->addChild(createOpSRemComputeGroup64(testCtx, QP_TEST_RESULT_PASS));
8986         computeTests->addChild(createOpSModComputeGroup(testCtx, QP_TEST_RESULT_PASS));
8987         computeTests->addChild(createOpSModComputeGroup64(testCtx, QP_TEST_RESULT_PASS));
8988         computeTests->addChild(createSConvertTests(testCtx));
8989         computeTests->addChild(createUConvertTests(testCtx));
8990         computeTests->addChild(createOpCompositeInsertGroup(testCtx));
8991         computeTests->addChild(createOpInBoundsAccessChainGroup(testCtx));
8992         computeTests->addChild(createShaderDefaultOutputGroup(testCtx));
8993         computeTests->addChild(createOpNMinGroup(testCtx));
8994         computeTests->addChild(createOpNMaxGroup(testCtx));
8995         computeTests->addChild(createOpNClampGroup(testCtx));
8996         {
8997                 de::MovePtr<tcu::TestCaseGroup> computeAndroidTests     (new tcu::TestCaseGroup(testCtx, "android", "Android CTS Tests"));
8998
8999                 computeAndroidTests->addChild(createOpSRemComputeGroup(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
9000                 computeAndroidTests->addChild(createOpSModComputeGroup(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
9001
9002                 computeTests->addChild(computeAndroidTests.release());
9003         }
9004
9005         computeTests->addChild(create8BitStorageComputeGroup(testCtx));
9006         computeTests->addChild(create16BitStorageComputeGroup(testCtx));
9007         computeTests->addChild(createUboMatrixPaddingComputeGroup(testCtx));
9008         computeTests->addChild(createConditionalBranchComputeGroup(testCtx));
9009         computeTests->addChild(createIndexingComputeGroup(testCtx));
9010         computeTests->addChild(createVariablePointersComputeGroup(testCtx));
9011         computeTests->addChild(createImageSamplerComputeGroup(testCtx));
9012         graphicsTests->addChild(createSpivVersionCheckTests(testCtx, !testComputePipeline));
9013         graphicsTests->addChild(createOpNopTests(testCtx));
9014         graphicsTests->addChild(createOpSourceTests(testCtx));
9015         graphicsTests->addChild(createOpSourceContinuedTests(testCtx));
9016         graphicsTests->addChild(createOpModuleProcessedTests(testCtx));
9017         graphicsTests->addChild(createOpLineTests(testCtx));
9018         graphicsTests->addChild(createOpNoLineTests(testCtx));
9019         graphicsTests->addChild(createOpConstantNullTests(testCtx));
9020         graphicsTests->addChild(createOpConstantCompositeTests(testCtx));
9021         graphicsTests->addChild(createMemoryAccessTests(testCtx));
9022         graphicsTests->addChild(createOpUndefTests(testCtx));
9023         graphicsTests->addChild(createSelectionBlockOrderTests(testCtx));
9024         graphicsTests->addChild(createModuleTests(testCtx));
9025         graphicsTests->addChild(createSwitchBlockOrderTests(testCtx));
9026         graphicsTests->addChild(createOpPhiTests(testCtx));
9027         graphicsTests->addChild(createNoContractionTests(testCtx));
9028         graphicsTests->addChild(createOpQuantizeTests(testCtx));
9029         graphicsTests->addChild(createLoopTests(testCtx));
9030         graphicsTests->addChild(createSpecConstantTests(testCtx));
9031         graphicsTests->addChild(createSpecConstantOpQuantizeToF16Group(testCtx));
9032         graphicsTests->addChild(createBarrierTests(testCtx));
9033         graphicsTests->addChild(createDecorationGroupTests(testCtx));
9034         graphicsTests->addChild(createFRemTests(testCtx));
9035         graphicsTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
9036         graphicsTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
9037
9038         {
9039                 de::MovePtr<tcu::TestCaseGroup> graphicsAndroidTests    (new tcu::TestCaseGroup(testCtx, "android", "Android CTS Tests"));
9040
9041                 graphicsAndroidTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
9042                 graphicsAndroidTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
9043
9044                 graphicsTests->addChild(graphicsAndroidTests.release());
9045         }
9046
9047         graphicsTests->addChild(create8BitStorageGraphicsGroup(testCtx));
9048         graphicsTests->addChild(create16BitStorageGraphicsGroup(testCtx));
9049         graphicsTests->addChild(createUboMatrixPaddingGraphicsGroup(testCtx));
9050         graphicsTests->addChild(createConditionalBranchGraphicsGroup(testCtx));
9051         graphicsTests->addChild(createIndexingGraphicsGroup(testCtx));
9052         graphicsTests->addChild(createVariablePointersGraphicsGroup(testCtx));
9053         graphicsTests->addChild(createImageSamplerGraphicsGroup(testCtx));
9054
9055         instructionTests->addChild(computeTests.release());
9056         instructionTests->addChild(graphicsTests.release());
9057
9058         return instructionTests.release();
9059 }
9060
9061 } // SpirVAssembly
9062 } // vkt