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 "vktSpvAsm16bitStorageTests.hpp"
53 #include "vktSpvAsmUboMatrixPaddingTests.hpp"
54 #include "vktSpvAsmConditionalBranchTests.hpp"
55 #include "vktSpvAsmIndexingTests.hpp"
56 #include "vktSpvAsmImageSamplerTests.hpp"
57 #include "vktSpvAsmComputeShaderCase.hpp"
58 #include "vktSpvAsmComputeShaderTestUtil.hpp"
59 #include "vktSpvAsmGraphicsShaderTestUtil.hpp"
60 #include "vktSpvAsmVariablePointersTests.hpp"
61 #include "vktSpvAsmSpirvVersionTests.hpp"
62 #include "vktTestCaseUtil.hpp"
63 #include "vktSpvAsmLoopDepLenTests.hpp"
64 #include "vktSpvAsmLoopDepInfTests.hpp"
65
66 #include <cmath>
67 #include <limits>
68 #include <map>
69 #include <string>
70 #include <sstream>
71 #include <utility>
72 #include <stack>
73
74 namespace vkt
75 {
76 namespace SpirVAssembly
77 {
78
79 namespace
80 {
81
82 using namespace vk;
83 using std::map;
84 using std::string;
85 using std::vector;
86 using tcu::IVec3;
87 using tcu::IVec4;
88 using tcu::RGBA;
89 using tcu::TestLog;
90 using tcu::TestStatus;
91 using tcu::Vec4;
92 using de::UniquePtr;
93 using tcu::StringTemplate;
94 using tcu::Vec4;
95
96 template<typename T>
97 static void fillRandomScalars (de::Random& rnd, T minValue, T maxValue, void* dst, int numValues, int offset = 0)
98 {
99         T* const typedPtr = (T*)dst;
100         for (int ndx = 0; ndx < numValues; ndx++)
101                 typedPtr[offset + ndx] = randomScalar<T>(rnd, minValue, maxValue);
102 }
103
104 // Filter is a function that returns true if a value should pass, false otherwise.
105 template<typename T, typename FilterT>
106 static void fillRandomScalars (de::Random& rnd, T minValue, T maxValue, void* dst, int numValues, FilterT filter, int offset = 0)
107 {
108         T* const typedPtr = (T*)dst;
109         T value;
110         for (int ndx = 0; ndx < numValues; ndx++)
111         {
112                 do
113                         value = randomScalar<T>(rnd, minValue, maxValue);
114                 while (!filter(value));
115
116                 typedPtr[offset + ndx] = value;
117         }
118 }
119
120 // Gets a 64-bit integer with a more logarithmic distribution
121 deInt64 randomInt64LogDistributed (de::Random& rnd)
122 {
123         deInt64 val = rnd.getUint64();
124         val &= (1ull << rnd.getInt(1, 63)) - 1;
125         if (rnd.getBool())
126                 val = -val;
127         return val;
128 }
129
130 static void fillRandomInt64sLogDistributed (de::Random& rnd, vector<deInt64>& dst, int numValues)
131 {
132         for (int ndx = 0; ndx < numValues; ndx++)
133                 dst[ndx] = randomInt64LogDistributed(rnd);
134 }
135
136 template<typename FilterT>
137 static void fillRandomInt64sLogDistributed (de::Random& rnd, vector<deInt64>& dst, int numValues, FilterT filter)
138 {
139         for (int ndx = 0; ndx < numValues; ndx++)
140         {
141                 deInt64 value;
142                 do {
143                         value = randomInt64LogDistributed(rnd);
144                 } while (!filter(value));
145                 dst[ndx] = value;
146         }
147 }
148
149 inline bool filterNonNegative (const deInt64 value)
150 {
151         return value >= 0;
152 }
153
154 inline bool filterPositive (const deInt64 value)
155 {
156         return value > 0;
157 }
158
159 inline bool filterNotZero (const deInt64 value)
160 {
161         return value != 0;
162 }
163
164 static void floorAll (vector<float>& values)
165 {
166         for (size_t i = 0; i < values.size(); i++)
167                 values[i] = deFloatFloor(values[i]);
168 }
169
170 static void floorAll (vector<Vec4>& values)
171 {
172         for (size_t i = 0; i < values.size(); i++)
173                 values[i] = floor(values[i]);
174 }
175
176 struct CaseParameter
177 {
178         const char*             name;
179         string                  param;
180
181         CaseParameter   (const char* case_, const string& param_) : name(case_), param(param_) {}
182 };
183
184 // Assembly code used for testing LocalSize, OpNop, OpConstant{Null|Composite}, Op[No]Line, OpSource[Continued], OpSourceExtension, OpUndef is based on GLSL source code:
185 //
186 // #version 430
187 //
188 // layout(std140, set = 0, binding = 0) readonly buffer Input {
189 //   float elements[];
190 // } input_data;
191 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
192 //   float elements[];
193 // } output_data;
194 //
195 // layout (local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
196 //
197 // void main() {
198 //   uint x = gl_GlobalInvocationID.x;
199 //   output_data.elements[x] = -input_data.elements[x];
200 // }
201
202 static string getAsmForLocalSizeTest(bool useLiteralLocalSize, bool useSpecConstantWorkgroupSize, IVec3 workGroupSize, deUint32 ndx)
203 {
204         std::ostringstream out;
205         out << getComputeAsmShaderPreambleWithoutLocalSize();
206
207         if (useLiteralLocalSize)
208         {
209                 out << "OpExecutionMode %main LocalSize "
210                         << workGroupSize.x() << " " << workGroupSize.y() << " " << workGroupSize.z() << "\n";
211         }
212
213         out << "OpSource GLSL 430\n"
214                 "OpName %main           \"main\"\n"
215                 "OpName %id             \"gl_GlobalInvocationID\"\n"
216                 "OpDecorate %id BuiltIn GlobalInvocationId\n";
217
218         if (useSpecConstantWorkgroupSize)
219         {
220                 out << "OpDecorate %spec_0 SpecId 100\n"
221                         << "OpDecorate %spec_1 SpecId 101\n"
222                         << "OpDecorate %spec_2 SpecId 102\n"
223                         << "OpDecorate %gl_WorkGroupSize BuiltIn WorkgroupSize\n";
224         }
225
226         out << getComputeAsmInputOutputBufferTraits()
227                 << getComputeAsmCommonTypes()
228                 << getComputeAsmInputOutputBuffer()
229                 << "%id        = OpVariable %uvec3ptr Input\n"
230                 << "%zero      = OpConstant %i32 0 \n";
231
232         if (useSpecConstantWorkgroupSize)
233         {
234                 out     << "%spec_0   = OpSpecConstant %u32 "<< workGroupSize.x() << "\n"
235                         << "%spec_1   = OpSpecConstant %u32 "<< workGroupSize.y() << "\n"
236                         << "%spec_2   = OpSpecConstant %u32 "<< workGroupSize.z() << "\n"
237                         << "%gl_WorkGroupSize = OpSpecConstantComposite %uvec3 %spec_0 %spec_1 %spec_2\n";
238         }
239
240         out << "%main      = OpFunction %void None %voidf\n"
241                 << "%label     = OpLabel\n"
242                 << "%idval     = OpLoad %uvec3 %id\n"
243                 << "%ndx         = OpCompositeExtract %u32 %idval " << ndx << "\n"
244
245                         "%inloc     = OpAccessChain %f32ptr %indata %zero %ndx\n"
246                         "%inval     = OpLoad %f32 %inloc\n"
247                         "%neg       = OpFNegate %f32 %inval\n"
248                         "%outloc    = OpAccessChain %f32ptr %outdata %zero %ndx\n"
249                         "             OpStore %outloc %neg\n"
250                         "             OpReturn\n"
251                         "             OpFunctionEnd\n";
252         return out.str();
253 }
254
255 tcu::TestCaseGroup* createLocalSizeGroup (tcu::TestContext& testCtx)
256 {
257         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "localsize", ""));
258         ComputeShaderSpec                               spec;
259         de::Random                                              rnd                             (deStringHash(group->getName()));
260         const deUint32                                  numElements             = 64u;
261         vector<float>                                   positiveFloats  (numElements, 0);
262         vector<float>                                   negativeFloats  (numElements, 0);
263
264         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
265
266         for (size_t ndx = 0; ndx < numElements; ++ndx)
267                 negativeFloats[ndx] = -positiveFloats[ndx];
268
269         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
270         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
271
272         spec.numWorkGroups = IVec3(numElements, 1, 1);
273
274         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, 1, 1), 0u);
275         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize", "", spec));
276
277         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, 1, 1), 0u);
278         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize", "", spec));
279
280         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, 1, 1), 0u);
281         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize", "", spec));
282
283         spec.numWorkGroups = IVec3(1, 1, 1);
284
285         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(numElements, 1, 1), 0u);
286         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_x", "", spec));
287
288         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(numElements, 1, 1), 0u);
289         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_x", "", spec));
290
291         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(numElements, 1, 1), 0u);
292         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_x", "", spec));
293
294         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, numElements, 1), 1u);
295         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_y", "", spec));
296
297         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, numElements, 1), 1u);
298         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_y", "", spec));
299
300         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, numElements, 1), 1u);
301         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_y", "", spec));
302
303         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, 1, numElements), 2u);
304         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_z", "", spec));
305
306         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, 1, numElements), 2u);
307         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_z", "", spec));
308
309         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, 1, numElements), 2u);
310         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_z", "", spec));
311
312         return group.release();
313 }
314
315 tcu::TestCaseGroup* createOpNopGroup (tcu::TestContext& testCtx)
316 {
317         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnop", "Test the OpNop instruction"));
318         ComputeShaderSpec                               spec;
319         de::Random                                              rnd                             (deStringHash(group->getName()));
320         const int                                               numElements             = 100;
321         vector<float>                                   positiveFloats  (numElements, 0);
322         vector<float>                                   negativeFloats  (numElements, 0);
323
324         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
325
326         for (size_t ndx = 0; ndx < numElements; ++ndx)
327                 negativeFloats[ndx] = -positiveFloats[ndx];
328
329         spec.assembly =
330                 string(getComputeAsmShaderPreamble()) +
331
332                 "OpSource GLSL 430\n"
333                 "OpName %main           \"main\"\n"
334                 "OpName %id             \"gl_GlobalInvocationID\"\n"
335
336                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
337
338                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes())
339
340                 + string(getComputeAsmInputOutputBuffer()) +
341
342                 "%id        = OpVariable %uvec3ptr Input\n"
343                 "%zero      = OpConstant %i32 0\n"
344
345                 "%main      = OpFunction %void None %voidf\n"
346                 "%label     = OpLabel\n"
347                 "%idval     = OpLoad %uvec3 %id\n"
348                 "%x         = OpCompositeExtract %u32 %idval 0\n"
349
350                 "             OpNop\n" // Inside a function body
351
352                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
353                 "%inval     = OpLoad %f32 %inloc\n"
354                 "%neg       = OpFNegate %f32 %inval\n"
355                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
356                 "             OpStore %outloc %neg\n"
357                 "             OpReturn\n"
358                 "             OpFunctionEnd\n";
359         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
360         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
361         spec.numWorkGroups = IVec3(numElements, 1, 1);
362
363         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpNop appearing at different places", spec));
364
365         return group.release();
366 }
367
368 bool compareFUnord (const std::vector<BufferSp>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<BufferSp>& expectedOutputs, TestLog& log)
369 {
370         if (outputAllocs.size() != 1)
371                 return false;
372
373         vector<deUint8> input1Bytes;
374         vector<deUint8> input2Bytes;
375         vector<deUint8> expectedBytes;
376
377         inputs[0]->getBytes(input1Bytes);
378         inputs[1]->getBytes(input2Bytes);
379         expectedOutputs[0]->getBytes(expectedBytes);
380
381         const deInt32* const    expectedOutputAsInt             = reinterpret_cast<const deInt32* const>(&expectedBytes.front());
382         const deInt32* const    outputAsInt                             = static_cast<const deInt32* const>(outputAllocs[0]->getHostPtr());
383         const float* const              input1AsFloat                   = reinterpret_cast<const float* const>(&input1Bytes.front());
384         const float* const              input2AsFloat                   = reinterpret_cast<const float* const>(&input2Bytes.front());
385         bool returnValue                                                                = true;
386
387         for (size_t idx = 0; idx < expectedBytes.size() / sizeof(deInt32); ++idx)
388         {
389                 if (outputAsInt[idx] != expectedOutputAsInt[idx])
390                 {
391                         log << TestLog::Message << "ERROR: Sub-case failed. inputs: " << input1AsFloat[idx] << "," << input2AsFloat[idx] << " output: " << outputAsInt[idx]<< " expected output: " << expectedOutputAsInt[idx] << TestLog::EndMessage;
392                         returnValue = false;
393                 }
394         }
395         return returnValue;
396 }
397
398 typedef VkBool32 (*compareFuncType) (float, float);
399
400 struct OpFUnordCase
401 {
402         const char*             name;
403         const char*             opCode;
404         compareFuncType compareFunc;
405
406                                         OpFUnordCase                    (const char* _name, const char* _opCode, compareFuncType _compareFunc)
407                                                 : name                          (_name)
408                                                 , opCode                        (_opCode)
409                                                 , compareFunc           (_compareFunc) {}
410 };
411
412 #define ADD_OPFUNORD_CASE(NAME, OPCODE, OPERATOR) \
413 do { \
414     struct compare_##NAME { static VkBool32 compare(float x, float y) { return (x OPERATOR y) ? VK_TRUE : VK_FALSE; } }; \
415     cases.push_back(OpFUnordCase(#NAME, OPCODE, compare_##NAME::compare)); \
416 } while (deGetFalse())
417
418 tcu::TestCaseGroup* createOpFUnordGroup (tcu::TestContext& testCtx)
419 {
420         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opfunord", "Test the OpFUnord* opcodes"));
421         de::Random                                              rnd                             (deStringHash(group->getName()));
422         const int                                               numElements             = 100;
423         vector<OpFUnordCase>                    cases;
424
425         const StringTemplate                    shaderTemplate  (
426
427                 string(getComputeAsmShaderPreamble()) +
428
429                 "OpSource GLSL 430\n"
430                 "OpName %main           \"main\"\n"
431                 "OpName %id             \"gl_GlobalInvocationID\"\n"
432
433                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
434
435                 "OpDecorate %buf BufferBlock\n"
436                 "OpDecorate %buf2 BufferBlock\n"
437                 "OpDecorate %indata1 DescriptorSet 0\n"
438                 "OpDecorate %indata1 Binding 0\n"
439                 "OpDecorate %indata2 DescriptorSet 0\n"
440                 "OpDecorate %indata2 Binding 1\n"
441                 "OpDecorate %outdata DescriptorSet 0\n"
442                 "OpDecorate %outdata Binding 2\n"
443                 "OpDecorate %f32arr ArrayStride 4\n"
444                 "OpDecorate %i32arr ArrayStride 4\n"
445                 "OpMemberDecorate %buf 0 Offset 0\n"
446                 "OpMemberDecorate %buf2 0 Offset 0\n"
447
448                 + string(getComputeAsmCommonTypes()) +
449
450                 "%buf        = OpTypeStruct %f32arr\n"
451                 "%bufptr     = OpTypePointer Uniform %buf\n"
452                 "%indata1    = OpVariable %bufptr Uniform\n"
453                 "%indata2    = OpVariable %bufptr Uniform\n"
454
455                 "%buf2       = OpTypeStruct %i32arr\n"
456                 "%buf2ptr    = OpTypePointer Uniform %buf2\n"
457                 "%outdata    = OpVariable %buf2ptr Uniform\n"
458
459                 "%id        = OpVariable %uvec3ptr Input\n"
460                 "%zero      = OpConstant %i32 0\n"
461                 "%consti1   = OpConstant %i32 1\n"
462                 "%constf1   = OpConstant %f32 1.0\n"
463
464                 "%main      = OpFunction %void None %voidf\n"
465                 "%label     = OpLabel\n"
466                 "%idval     = OpLoad %uvec3 %id\n"
467                 "%x         = OpCompositeExtract %u32 %idval 0\n"
468
469                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
470                 "%inval1    = OpLoad %f32 %inloc1\n"
471                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
472                 "%inval2    = OpLoad %f32 %inloc2\n"
473                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
474
475                 "%result    = ${OPCODE} %bool %inval1 %inval2\n"
476                 "%int_res   = OpSelect %i32 %result %consti1 %zero\n"
477                 "             OpStore %outloc %int_res\n"
478
479                 "             OpReturn\n"
480                 "             OpFunctionEnd\n");
481
482         ADD_OPFUNORD_CASE(equal, "OpFUnordEqual", ==);
483         ADD_OPFUNORD_CASE(less, "OpFUnordLessThan", <);
484         ADD_OPFUNORD_CASE(lessequal, "OpFUnordLessThanEqual", <=);
485         ADD_OPFUNORD_CASE(greater, "OpFUnordGreaterThan", >);
486         ADD_OPFUNORD_CASE(greaterequal, "OpFUnordGreaterThanEqual", >=);
487         ADD_OPFUNORD_CASE(notequal, "OpFUnordNotEqual", !=);
488
489         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
490         {
491                 map<string, string>                     specializations;
492                 ComputeShaderSpec                       spec;
493                 const float                                     NaN                             = std::numeric_limits<float>::quiet_NaN();
494                 vector<float>                           inputFloats1    (numElements, 0);
495                 vector<float>                           inputFloats2    (numElements, 0);
496                 vector<deInt32>                         expectedInts    (numElements, 0);
497
498                 specializations["OPCODE"]       = cases[caseNdx].opCode;
499                 spec.assembly                           = shaderTemplate.specialize(specializations);
500
501                 fillRandomScalars(rnd, 1.f, 100.f, &inputFloats1[0], numElements);
502                 for (size_t ndx = 0; ndx < numElements; ++ndx)
503                 {
504                         switch (ndx % 6)
505                         {
506                                 case 0:         inputFloats2[ndx] = inputFloats1[ndx] + 1.0f; break;
507                                 case 1:         inputFloats2[ndx] = inputFloats1[ndx] - 1.0f; break;
508                                 case 2:         inputFloats2[ndx] = inputFloats1[ndx]; break;
509                                 case 3:         inputFloats2[ndx] = NaN; break;
510                                 case 4:         inputFloats2[ndx] = inputFloats1[ndx];  inputFloats1[ndx] = NaN; break;
511                                 case 5:         inputFloats2[ndx] = NaN;                                inputFloats1[ndx] = NaN; break;
512                         }
513                         expectedInts[ndx] = tcu::Float32(inputFloats1[ndx]).isNaN() || tcu::Float32(inputFloats2[ndx]).isNaN() || cases[caseNdx].compareFunc(inputFloats1[ndx], inputFloats2[ndx]);
514                 }
515
516                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
517                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
518                 spec.outputs.push_back(BufferSp(new Int32Buffer(expectedInts)));
519                 spec.numWorkGroups = IVec3(numElements, 1, 1);
520                 spec.verifyIO = &compareFUnord;
521                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
522         }
523
524         return group.release();
525 }
526
527 struct OpAtomicCase
528 {
529         const char*             name;
530         const char*             assembly;
531         OpAtomicType    opAtomic;
532         deInt32                 numOutputElements;
533
534                                         OpAtomicCase                    (const char* _name, const char* _assembly, OpAtomicType _opAtomic, deInt32 _numOutputElements)
535                                                 : name                          (_name)
536                                                 , assembly                      (_assembly)
537                                                 , opAtomic                      (_opAtomic)
538                                                 , numOutputElements     (_numOutputElements) {}
539 };
540
541 tcu::TestCaseGroup* createOpAtomicGroup (tcu::TestContext& testCtx, bool useStorageBuffer)
542 {
543         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx,
544                                                                                                                                                                 useStorageBuffer ? "opatomic_storage_buffer" : "opatomic",
545                                                                                                                                                                 "Test the OpAtomic* opcodes"));
546         const int                                               numElements                     = 65535;
547         vector<OpAtomicCase>                    cases;
548
549         const StringTemplate                    shaderTemplate  (
550
551                 string("OpCapability Shader\n") +
552                 (useStorageBuffer ? "OpExtension \"SPV_KHR_storage_buffer_storage_class\"\n" : "") +
553                 "OpMemoryModel Logical GLSL450\n"
554                 "OpEntryPoint GLCompute %main \"main\" %id\n"
555                 "OpExecutionMode %main LocalSize 1 1 1\n" +
556
557                 "OpSource GLSL 430\n"
558                 "OpName %main           \"main\"\n"
559                 "OpName %id             \"gl_GlobalInvocationID\"\n"
560
561                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
562
563                 "OpDecorate %buf ${BLOCK_DECORATION}\n"
564                 "OpDecorate %indata DescriptorSet 0\n"
565                 "OpDecorate %indata Binding 0\n"
566                 "OpDecorate %i32arr ArrayStride 4\n"
567                 "OpMemberDecorate %buf 0 Offset 0\n"
568
569                 "OpDecorate %sumbuf ${BLOCK_DECORATION}\n"
570                 "OpDecorate %sum DescriptorSet 0\n"
571                 "OpDecorate %sum Binding 1\n"
572                 "OpMemberDecorate %sumbuf 0 Coherent\n"
573                 "OpMemberDecorate %sumbuf 0 Offset 0\n"
574
575                 + getComputeAsmCommonTypes("${BLOCK_POINTER_TYPE}") +
576
577                 "%buf       = OpTypeStruct %i32arr\n"
578                 "%bufptr    = OpTypePointer ${BLOCK_POINTER_TYPE} %buf\n"
579                 "%indata    = OpVariable %bufptr ${BLOCK_POINTER_TYPE}\n"
580
581                 "%sumbuf    = OpTypeStruct %i32arr\n"
582                 "%sumbufptr = OpTypePointer ${BLOCK_POINTER_TYPE} %sumbuf\n"
583                 "%sum       = OpVariable %sumbufptr ${BLOCK_POINTER_TYPE}\n"
584
585                 "%id        = OpVariable %uvec3ptr Input\n"
586                 "%minusone  = OpConstant %i32 -1\n"
587                 "%zero      = OpConstant %i32 0\n"
588                 "%one       = OpConstant %u32 1\n"
589                 "%two       = OpConstant %i32 2\n"
590
591                 "%main      = OpFunction %void None %voidf\n"
592                 "%label     = OpLabel\n"
593                 "%idval     = OpLoad %uvec3 %id\n"
594                 "%x         = OpCompositeExtract %u32 %idval 0\n"
595
596                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
597                 "%inval     = OpLoad %i32 %inloc\n"
598
599                 "%outloc    = OpAccessChain %i32ptr %sum %zero ${INDEX}\n"
600                 "${INSTRUCTION}"
601
602                 "             OpReturn\n"
603                 "             OpFunctionEnd\n");
604
605         #define ADD_OPATOMIC_CASE(NAME, ASSEMBLY, OPATOMIC, NUM_OUTPUT_ELEMENTS) \
606         do { \
607                 DE_STATIC_ASSERT((NUM_OUTPUT_ELEMENTS) == 1 || (NUM_OUTPUT_ELEMENTS) == numElements); \
608                 cases.push_back(OpAtomicCase(#NAME, ASSEMBLY, OPATOMIC, NUM_OUTPUT_ELEMENTS)); \
609         } while (deGetFalse())
610         #define ADD_OPATOMIC_CASE_1(NAME, ASSEMBLY, OPATOMIC) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, OPATOMIC, 1)
611         #define ADD_OPATOMIC_CASE_N(NAME, ASSEMBLY, OPATOMIC) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, OPATOMIC, numElements)
612
613         ADD_OPATOMIC_CASE_1(iadd,       "%unused    = OpAtomicIAdd %i32 %outloc %one %zero %inval\n", OPATOMIC_IADD );
614         ADD_OPATOMIC_CASE_1(isub,       "%unused    = OpAtomicISub %i32 %outloc %one %zero %inval\n", OPATOMIC_ISUB );
615         ADD_OPATOMIC_CASE_1(iinc,       "%unused    = OpAtomicIIncrement %i32 %outloc %one %zero\n",  OPATOMIC_IINC );
616         ADD_OPATOMIC_CASE_1(idec,       "%unused    = OpAtomicIDecrement %i32 %outloc %one %zero\n",  OPATOMIC_IDEC );
617         ADD_OPATOMIC_CASE_N(load,       "%inval2    = OpAtomicLoad %i32 %inloc %zero %zero\n"
618                                                                 "             OpStore %outloc %inval2\n",  OPATOMIC_LOAD );
619         ADD_OPATOMIC_CASE_N(store,      "             OpAtomicStore %outloc %zero %zero %inval\n",  OPATOMIC_STORE );
620         ADD_OPATOMIC_CASE_N(compex, "%even      = OpSMod %i32 %inval %two\n"
621                                                                 "             OpStore %outloc %even\n"
622                                                                 "%unused    = OpAtomicCompareExchange %i32 %outloc %one %zero %zero %minusone %zero\n",  OPATOMIC_COMPEX );
623
624         #undef ADD_OPATOMIC_CASE
625         #undef ADD_OPATOMIC_CASE_1
626         #undef ADD_OPATOMIC_CASE_N
627
628         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
629         {
630                 map<string, string>                     specializations;
631                 ComputeShaderSpec                       spec;
632                 vector<deInt32>                         inputInts               (numElements, 0);
633                 vector<deInt32>                         expected                (cases[caseNdx].numOutputElements, -1);
634
635                 specializations["INDEX"]                                = (cases[caseNdx].numOutputElements == 1) ? "%zero" : "%x";
636                 specializations["INSTRUCTION"]                  = cases[caseNdx].assembly;
637                 specializations["BLOCK_DECORATION"]             = useStorageBuffer ? "Block" : "BufferBlock";
638                 specializations["BLOCK_POINTER_TYPE"]   = useStorageBuffer ? "StorageBuffer" : "Uniform";
639                 spec.assembly                                                   = shaderTemplate.specialize(specializations);
640
641                 if (useStorageBuffer)
642                         spec.extensions.push_back("VK_KHR_storage_buffer_storage_class");
643
644                 spec.inputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_INPUT)));
645                 spec.outputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_EXPECTED)));
646                 spec.numWorkGroups = IVec3(numElements, 1, 1);
647                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
648         }
649
650         return group.release();
651 }
652
653 tcu::TestCaseGroup* createOpLineGroup (tcu::TestContext& testCtx)
654 {
655         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opline", "Test the OpLine instruction"));
656         ComputeShaderSpec                               spec;
657         de::Random                                              rnd                             (deStringHash(group->getName()));
658         const int                                               numElements             = 100;
659         vector<float>                                   positiveFloats  (numElements, 0);
660         vector<float>                                   negativeFloats  (numElements, 0);
661
662         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
663
664         for (size_t ndx = 0; ndx < numElements; ++ndx)
665                 negativeFloats[ndx] = -positiveFloats[ndx];
666
667         spec.assembly =
668                 string(getComputeAsmShaderPreamble()) +
669
670                 "%fname1 = OpString \"negateInputs.comp\"\n"
671                 "%fname2 = OpString \"negateInputs\"\n"
672
673                 "OpSource GLSL 430\n"
674                 "OpName %main           \"main\"\n"
675                 "OpName %id             \"gl_GlobalInvocationID\"\n"
676
677                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
678
679                 + string(getComputeAsmInputOutputBufferTraits()) +
680
681                 "OpLine %fname1 0 0\n" // At the earliest possible position
682
683                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
684
685                 "OpLine %fname1 0 1\n" // Multiple OpLines in sequence
686                 "OpLine %fname2 1 0\n" // Different filenames
687                 "OpLine %fname1 1000 100000\n"
688
689                 "%id        = OpVariable %uvec3ptr Input\n"
690                 "%zero      = OpConstant %i32 0\n"
691
692                 "OpLine %fname1 1 1\n" // Before a function
693
694                 "%main      = OpFunction %void None %voidf\n"
695                 "%label     = OpLabel\n"
696
697                 "OpLine %fname1 1 1\n" // In a function
698
699                 "%idval     = OpLoad %uvec3 %id\n"
700                 "%x         = OpCompositeExtract %u32 %idval 0\n"
701                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
702                 "%inval     = OpLoad %f32 %inloc\n"
703                 "%neg       = OpFNegate %f32 %inval\n"
704                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
705                 "             OpStore %outloc %neg\n"
706                 "             OpReturn\n"
707                 "             OpFunctionEnd\n";
708         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
709         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
710         spec.numWorkGroups = IVec3(numElements, 1, 1);
711
712         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpLine appearing at different places", spec));
713
714         return group.release();
715 }
716
717 bool veryfiBinaryShader (const ProgramBinary& binary)
718 {
719         const size_t    paternCount                     = 3u;
720         bool paternsCheck[paternCount]          =
721         {
722                 false, false, false
723         };
724         const string patersns[paternCount]      =
725         {
726                 "VULKAN CTS",
727                 "Negative values",
728                 "Date: 2017/09/21"
729         };
730         size_t                  paternNdx               = 0u;
731
732         for (size_t ndx = 0u; ndx < binary.getSize(); ++ndx)
733         {
734                 if (false == paternsCheck[paternNdx] &&
735                         patersns[paternNdx][0] == static_cast<char>(binary.getBinary()[ndx]) &&
736                         deMemoryEqual((const char*)&binary.getBinary()[ndx], &patersns[paternNdx][0], patersns[paternNdx].length()))
737                 {
738                         paternsCheck[paternNdx]= true;
739                         paternNdx++;
740                         if (paternNdx == paternCount)
741                                 break;
742                 }
743         }
744
745         for (size_t ndx = 0u; ndx < paternCount; ++ndx)
746         {
747                 if (!paternsCheck[ndx])
748                         return false;
749         }
750
751         return true;
752 }
753
754 tcu::TestCaseGroup* createOpModuleProcessedGroup (tcu::TestContext& testCtx)
755 {
756         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opmoduleprocessed", "Test the OpModuleProcessed instruction"));
757         ComputeShaderSpec                               spec;
758         de::Random                                              rnd                             (deStringHash(group->getName()));
759         const int                                               numElements             = 10;
760         vector<float>                                   positiveFloats  (numElements, 0);
761         vector<float>                                   negativeFloats  (numElements, 0);
762
763         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
764
765         for (size_t ndx = 0; ndx < numElements; ++ndx)
766                 negativeFloats[ndx] = -positiveFloats[ndx];
767
768         spec.assembly =
769                 string(getComputeAsmShaderPreamble()) +
770                 "%fname = OpString \"negateInputs.comp\"\n"
771
772                 "OpSource GLSL 430\n"
773                 "OpName %main           \"main\"\n"
774                 "OpName %id             \"gl_GlobalInvocationID\"\n"
775                 "OpModuleProcessed \"VULKAN CTS\"\n"                                    //OpModuleProcessed;
776                 "OpModuleProcessed \"Negative values\"\n"
777                 "OpModuleProcessed \"Date: 2017/09/21\"\n"
778                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
779
780                 + string(getComputeAsmInputOutputBufferTraits())
781
782                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
783
784                 "OpLine %fname 0 1\n"
785
786                 "OpLine %fname 1000 1\n"
787
788                 "%id        = OpVariable %uvec3ptr Input\n"
789                 "%zero      = OpConstant %i32 0\n"
790                 "%main      = OpFunction %void None %voidf\n"
791
792                 "%label     = OpLabel\n"
793                 "%idval     = OpLoad %uvec3 %id\n"
794                 "%x         = OpCompositeExtract %u32 %idval 0\n"
795
796                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
797                 "%inval     = OpLoad %f32 %inloc\n"
798                 "%neg       = OpFNegate %f32 %inval\n"
799                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
800                 "             OpStore %outloc %neg\n"
801                 "             OpReturn\n"
802                 "             OpFunctionEnd\n";
803         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
804         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
805         spec.numWorkGroups = IVec3(numElements, 1, 1);
806         spec.verifyBinary = veryfiBinaryShader;
807         spec.spirvVersion = SPIRV_VERSION_1_3;
808
809         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpModuleProcessed Tests", spec));
810
811         return group.release();
812 }
813
814 tcu::TestCaseGroup* createOpNoLineGroup (tcu::TestContext& testCtx)
815 {
816         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnoline", "Test the OpNoLine instruction"));
817         ComputeShaderSpec                               spec;
818         de::Random                                              rnd                             (deStringHash(group->getName()));
819         const int                                               numElements             = 100;
820         vector<float>                                   positiveFloats  (numElements, 0);
821         vector<float>                                   negativeFloats  (numElements, 0);
822
823         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
824
825         for (size_t ndx = 0; ndx < numElements; ++ndx)
826                 negativeFloats[ndx] = -positiveFloats[ndx];
827
828         spec.assembly =
829                 string(getComputeAsmShaderPreamble()) +
830
831                 "%fname = OpString \"negateInputs.comp\"\n"
832
833                 "OpSource GLSL 430\n"
834                 "OpName %main           \"main\"\n"
835                 "OpName %id             \"gl_GlobalInvocationID\"\n"
836
837                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
838
839                 + string(getComputeAsmInputOutputBufferTraits()) +
840
841                 "OpNoLine\n" // At the earliest possible position, without preceding OpLine
842
843                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
844
845                 "OpLine %fname 0 1\n"
846                 "OpNoLine\n" // Immediately following a preceding OpLine
847
848                 "OpLine %fname 1000 1\n"
849
850                 "%id        = OpVariable %uvec3ptr Input\n"
851                 "%zero      = OpConstant %i32 0\n"
852
853                 "OpNoLine\n" // Contents after the previous OpLine
854
855                 "%main      = OpFunction %void None %voidf\n"
856                 "%label     = OpLabel\n"
857                 "%idval     = OpLoad %uvec3 %id\n"
858                 "%x         = OpCompositeExtract %u32 %idval 0\n"
859
860                 "OpNoLine\n" // Multiple OpNoLine
861                 "OpNoLine\n"
862                 "OpNoLine\n"
863
864                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
865                 "%inval     = OpLoad %f32 %inloc\n"
866                 "%neg       = OpFNegate %f32 %inval\n"
867                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
868                 "             OpStore %outloc %neg\n"
869                 "             OpReturn\n"
870                 "             OpFunctionEnd\n";
871         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
872         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
873         spec.numWorkGroups = IVec3(numElements, 1, 1);
874
875         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpNoLine appearing at different places", spec));
876
877         return group.release();
878 }
879
880 // Compare instruction for the contraction compute case.
881 // Returns true if the output is what is expected from the test case.
882 bool compareNoContractCase(const std::vector<BufferSp>&, const vector<AllocationSp>& outputAllocs, const std::vector<BufferSp>& expectedOutputs, TestLog&)
883 {
884         if (outputAllocs.size() != 1)
885                 return false;
886
887         // Only size is needed because we are not comparing the exact values.
888         size_t byteSize = expectedOutputs[0]->getByteSize();
889
890         const float*    outputAsFloat   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
891
892         for(size_t i = 0; i < byteSize / sizeof(float); ++i) {
893                 if (outputAsFloat[i] != 0.f &&
894                         outputAsFloat[i] != -ldexp(1, -24)) {
895                         return false;
896                 }
897         }
898
899         return true;
900 }
901
902 tcu::TestCaseGroup* createNoContractionGroup (tcu::TestContext& testCtx)
903 {
904         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
905         vector<CaseParameter>                   cases;
906         const int                                               numElements             = 100;
907         vector<float>                                   inputFloats1    (numElements, 0);
908         vector<float>                                   inputFloats2    (numElements, 0);
909         vector<float>                                   outputFloats    (numElements, 0);
910         const StringTemplate                    shaderTemplate  (
911                 string(getComputeAsmShaderPreamble()) +
912
913                 "OpName %main           \"main\"\n"
914                 "OpName %id             \"gl_GlobalInvocationID\"\n"
915
916                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
917
918                 "${DECORATION}\n"
919
920                 "OpDecorate %buf BufferBlock\n"
921                 "OpDecorate %indata1 DescriptorSet 0\n"
922                 "OpDecorate %indata1 Binding 0\n"
923                 "OpDecorate %indata2 DescriptorSet 0\n"
924                 "OpDecorate %indata2 Binding 1\n"
925                 "OpDecorate %outdata DescriptorSet 0\n"
926                 "OpDecorate %outdata Binding 2\n"
927                 "OpDecorate %f32arr ArrayStride 4\n"
928                 "OpMemberDecorate %buf 0 Offset 0\n"
929
930                 + string(getComputeAsmCommonTypes()) +
931
932                 "%buf        = OpTypeStruct %f32arr\n"
933                 "%bufptr     = OpTypePointer Uniform %buf\n"
934                 "%indata1    = OpVariable %bufptr Uniform\n"
935                 "%indata2    = OpVariable %bufptr Uniform\n"
936                 "%outdata    = OpVariable %bufptr Uniform\n"
937
938                 "%id         = OpVariable %uvec3ptr Input\n"
939                 "%zero       = OpConstant %i32 0\n"
940                 "%c_f_m1     = OpConstant %f32 -1.\n"
941
942                 "%main       = OpFunction %void None %voidf\n"
943                 "%label      = OpLabel\n"
944                 "%idval      = OpLoad %uvec3 %id\n"
945                 "%x          = OpCompositeExtract %u32 %idval 0\n"
946                 "%inloc1     = OpAccessChain %f32ptr %indata1 %zero %x\n"
947                 "%inval1     = OpLoad %f32 %inloc1\n"
948                 "%inloc2     = OpAccessChain %f32ptr %indata2 %zero %x\n"
949                 "%inval2     = OpLoad %f32 %inloc2\n"
950                 "%mul        = OpFMul %f32 %inval1 %inval2\n"
951                 "%add        = OpFAdd %f32 %mul %c_f_m1\n"
952                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
953                 "              OpStore %outloc %add\n"
954                 "              OpReturn\n"
955                 "              OpFunctionEnd\n");
956
957         cases.push_back(CaseParameter("multiplication", "OpDecorate %mul NoContraction"));
958         cases.push_back(CaseParameter("addition",               "OpDecorate %add NoContraction"));
959         cases.push_back(CaseParameter("both",                   "OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"));
960
961         for (size_t ndx = 0; ndx < numElements; ++ndx)
962         {
963                 inputFloats1[ndx]       = 1.f + std::ldexp(1.f, -23); // 1 + 2^-23.
964                 inputFloats2[ndx]       = 1.f - std::ldexp(1.f, -23); // 1 - 2^-23.
965                 // Result for (1 + 2^-23) * (1 - 2^-23) - 1. With NoContraction, the multiplication will be
966                 // conducted separately and the result is rounded to 1, or 0x1.fffffcp-1
967                 // So the final result will be 0.f or 0x1p-24.
968                 // If the operation is combined into a precise fused multiply-add, then the result would be
969                 // 2^-46 (0xa8800000).
970                 outputFloats[ndx]       = 0.f;
971         }
972
973         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
974         {
975                 map<string, string>             specializations;
976                 ComputeShaderSpec               spec;
977
978                 specializations["DECORATION"] = cases[caseNdx].param;
979                 spec.assembly = shaderTemplate.specialize(specializations);
980                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
981                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
982                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
983                 spec.numWorkGroups = IVec3(numElements, 1, 1);
984                 // Check against the two possible answers based on rounding mode.
985                 spec.verifyIO = &compareNoContractCase;
986
987                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
988         }
989         return group.release();
990 }
991
992 bool compareFRem(const std::vector<BufferSp>&, const vector<AllocationSp>& outputAllocs, const std::vector<BufferSp>& expectedOutputs, TestLog&)
993 {
994         if (outputAllocs.size() != 1)
995                 return false;
996
997         vector<deUint8> expectedBytes;
998         expectedOutputs[0]->getBytes(expectedBytes);
999
1000         const float*    expectedOutputAsFloat   = reinterpret_cast<const float*>(&expectedBytes.front());
1001         const float*    outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1002
1003         for (size_t idx = 0; idx < expectedBytes.size() / sizeof(float); ++idx)
1004         {
1005                 const float f0 = expectedOutputAsFloat[idx];
1006                 const float f1 = outputAsFloat[idx];
1007                 // \todo relative error needs to be fairly high because FRem may be implemented as
1008                 // (roughly) frac(a/b)*b, so LSB errors can be magnified. But this should be fine for now.
1009                 if (deFloatAbs((f1 - f0) / f0) > 0.02)
1010                         return false;
1011         }
1012
1013         return true;
1014 }
1015
1016 tcu::TestCaseGroup* createOpFRemGroup (tcu::TestContext& testCtx)
1017 {
1018         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opfrem", "Test the OpFRem instruction"));
1019         ComputeShaderSpec                               spec;
1020         de::Random                                              rnd                             (deStringHash(group->getName()));
1021         const int                                               numElements             = 200;
1022         vector<float>                                   inputFloats1    (numElements, 0);
1023         vector<float>                                   inputFloats2    (numElements, 0);
1024         vector<float>                                   outputFloats    (numElements, 0);
1025
1026         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1027         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats2[0], numElements);
1028
1029         for (size_t ndx = 0; ndx < numElements; ++ndx)
1030         {
1031                 // Guard against divisors near zero.
1032                 if (std::fabs(inputFloats2[ndx]) < 1e-3)
1033                         inputFloats2[ndx] = 8.f;
1034
1035                 // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1036                 outputFloats[ndx] = std::fmod(inputFloats1[ndx], inputFloats2[ndx]);
1037         }
1038
1039         spec.assembly =
1040                 string(getComputeAsmShaderPreamble()) +
1041
1042                 "OpName %main           \"main\"\n"
1043                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1044
1045                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1046
1047                 "OpDecorate %buf BufferBlock\n"
1048                 "OpDecorate %indata1 DescriptorSet 0\n"
1049                 "OpDecorate %indata1 Binding 0\n"
1050                 "OpDecorate %indata2 DescriptorSet 0\n"
1051                 "OpDecorate %indata2 Binding 1\n"
1052                 "OpDecorate %outdata DescriptorSet 0\n"
1053                 "OpDecorate %outdata Binding 2\n"
1054                 "OpDecorate %f32arr ArrayStride 4\n"
1055                 "OpMemberDecorate %buf 0 Offset 0\n"
1056
1057                 + string(getComputeAsmCommonTypes()) +
1058
1059                 "%buf        = OpTypeStruct %f32arr\n"
1060                 "%bufptr     = OpTypePointer Uniform %buf\n"
1061                 "%indata1    = OpVariable %bufptr Uniform\n"
1062                 "%indata2    = OpVariable %bufptr Uniform\n"
1063                 "%outdata    = OpVariable %bufptr Uniform\n"
1064
1065                 "%id        = OpVariable %uvec3ptr Input\n"
1066                 "%zero      = OpConstant %i32 0\n"
1067
1068                 "%main      = OpFunction %void None %voidf\n"
1069                 "%label     = OpLabel\n"
1070                 "%idval     = OpLoad %uvec3 %id\n"
1071                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1072                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1073                 "%inval1    = OpLoad %f32 %inloc1\n"
1074                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1075                 "%inval2    = OpLoad %f32 %inloc2\n"
1076                 "%rem       = OpFRem %f32 %inval1 %inval2\n"
1077                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1078                 "             OpStore %outloc %rem\n"
1079                 "             OpReturn\n"
1080                 "             OpFunctionEnd\n";
1081
1082         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1083         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1084         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1085         spec.numWorkGroups = IVec3(numElements, 1, 1);
1086         spec.verifyIO = &compareFRem;
1087
1088         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1089
1090         return group.release();
1091 }
1092
1093 bool compareNMin (const std::vector<BufferSp>&, const vector<AllocationSp>& outputAllocs, const std::vector<BufferSp>& expectedOutputs, TestLog&)
1094 {
1095         if (outputAllocs.size() != 1)
1096                 return false;
1097
1098         const BufferSp&                 expectedOutput                  (expectedOutputs[0]);
1099         std::vector<deUint8>    data;
1100         expectedOutput->getBytes(data);
1101
1102         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1103         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1104
1105         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float); ++idx)
1106         {
1107                 const float f0 = expectedOutputAsFloat[idx];
1108                 const float f1 = outputAsFloat[idx];
1109
1110                 // For NMin, we accept NaN as output if both inputs were NaN.
1111                 // Otherwise the NaN is the wrong choise, as on architectures that
1112                 // do not handle NaN, those are huge values.
1113                 if (!(tcu::Float32(f1).isNaN() && tcu::Float32(f0).isNaN()) && deFloatAbs(f1 - f0) > 0.00001f)
1114                         return false;
1115         }
1116
1117         return true;
1118 }
1119
1120 tcu::TestCaseGroup* createOpNMinGroup (tcu::TestContext& testCtx)
1121 {
1122         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnmin", "Test the OpNMin instruction"));
1123         ComputeShaderSpec                               spec;
1124         de::Random                                              rnd                             (deStringHash(group->getName()));
1125         const int                                               numElements             = 200;
1126         vector<float>                                   inputFloats1    (numElements, 0);
1127         vector<float>                                   inputFloats2    (numElements, 0);
1128         vector<float>                                   outputFloats    (numElements, 0);
1129
1130         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1131         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1132
1133         // Make the first case a full-NAN case.
1134         inputFloats1[0] = TCU_NAN;
1135         inputFloats2[0] = TCU_NAN;
1136
1137         for (size_t ndx = 0; ndx < numElements; ++ndx)
1138         {
1139                 // By default, pick the smallest
1140                 outputFloats[ndx] = std::min(inputFloats1[ndx], inputFloats2[ndx]);
1141
1142                 // Make half of the cases NaN cases
1143                 if ((ndx & 1) == 0)
1144                 {
1145                         // Alternate between the NaN operand
1146                         if ((ndx & 2) == 0)
1147                         {
1148                                 outputFloats[ndx] = inputFloats2[ndx];
1149                                 inputFloats1[ndx] = TCU_NAN;
1150                         }
1151                         else
1152                         {
1153                                 outputFloats[ndx] = inputFloats1[ndx];
1154                                 inputFloats2[ndx] = TCU_NAN;
1155                         }
1156                 }
1157         }
1158
1159         spec.assembly =
1160                 "OpCapability Shader\n"
1161                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1162                 "OpMemoryModel Logical GLSL450\n"
1163                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1164                 "OpExecutionMode %main LocalSize 1 1 1\n"
1165
1166                 "OpName %main           \"main\"\n"
1167                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1168
1169                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1170
1171                 "OpDecorate %buf BufferBlock\n"
1172                 "OpDecorate %indata1 DescriptorSet 0\n"
1173                 "OpDecorate %indata1 Binding 0\n"
1174                 "OpDecorate %indata2 DescriptorSet 0\n"
1175                 "OpDecorate %indata2 Binding 1\n"
1176                 "OpDecorate %outdata DescriptorSet 0\n"
1177                 "OpDecorate %outdata Binding 2\n"
1178                 "OpDecorate %f32arr ArrayStride 4\n"
1179                 "OpMemberDecorate %buf 0 Offset 0\n"
1180
1181                 + string(getComputeAsmCommonTypes()) +
1182
1183                 "%buf        = OpTypeStruct %f32arr\n"
1184                 "%bufptr     = OpTypePointer Uniform %buf\n"
1185                 "%indata1    = OpVariable %bufptr Uniform\n"
1186                 "%indata2    = OpVariable %bufptr Uniform\n"
1187                 "%outdata    = OpVariable %bufptr Uniform\n"
1188
1189                 "%id        = OpVariable %uvec3ptr Input\n"
1190                 "%zero      = OpConstant %i32 0\n"
1191
1192                 "%main      = OpFunction %void None %voidf\n"
1193                 "%label     = OpLabel\n"
1194                 "%idval     = OpLoad %uvec3 %id\n"
1195                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1196                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1197                 "%inval1    = OpLoad %f32 %inloc1\n"
1198                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1199                 "%inval2    = OpLoad %f32 %inloc2\n"
1200                 "%rem       = OpExtInst %f32 %std450 NMin %inval1 %inval2\n"
1201                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1202                 "             OpStore %outloc %rem\n"
1203                 "             OpReturn\n"
1204                 "             OpFunctionEnd\n";
1205
1206         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1207         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1208         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1209         spec.numWorkGroups = IVec3(numElements, 1, 1);
1210         spec.verifyIO = &compareNMin;
1211
1212         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1213
1214         return group.release();
1215 }
1216
1217 bool compareNMax (const std::vector<BufferSp>&, const vector<AllocationSp>& outputAllocs, const std::vector<BufferSp>& expectedOutputs, TestLog&)
1218 {
1219         if (outputAllocs.size() != 1)
1220                 return false;
1221
1222         const BufferSp&                 expectedOutput                  = expectedOutputs[0];
1223         std::vector<deUint8>    data;
1224         expectedOutput->getBytes(data);
1225
1226         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1227         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1228
1229         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float); ++idx)
1230         {
1231                 const float f0 = expectedOutputAsFloat[idx];
1232                 const float f1 = outputAsFloat[idx];
1233
1234                 // For NMax, NaN is considered acceptable result, since in
1235                 // architectures that do not handle NaNs, those are huge values.
1236                 if (!tcu::Float32(f1).isNaN() && deFloatAbs(f1 - f0) > 0.00001f)
1237                         return false;
1238         }
1239
1240         return true;
1241 }
1242
1243 tcu::TestCaseGroup* createOpNMaxGroup (tcu::TestContext& testCtx)
1244 {
1245         de::MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "opnmax", "Test the OpNMax instruction"));
1246         ComputeShaderSpec                               spec;
1247         de::Random                                              rnd                             (deStringHash(group->getName()));
1248         const int                                               numElements             = 200;
1249         vector<float>                                   inputFloats1    (numElements, 0);
1250         vector<float>                                   inputFloats2    (numElements, 0);
1251         vector<float>                                   outputFloats    (numElements, 0);
1252
1253         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1254         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1255
1256         // Make the first case a full-NAN case.
1257         inputFloats1[0] = TCU_NAN;
1258         inputFloats2[0] = TCU_NAN;
1259
1260         for (size_t ndx = 0; ndx < numElements; ++ndx)
1261         {
1262                 // By default, pick the biggest
1263                 outputFloats[ndx] = std::max(inputFloats1[ndx], inputFloats2[ndx]);
1264
1265                 // Make half of the cases NaN cases
1266                 if ((ndx & 1) == 0)
1267                 {
1268                         // Alternate between the NaN operand
1269                         if ((ndx & 2) == 0)
1270                         {
1271                                 outputFloats[ndx] = inputFloats2[ndx];
1272                                 inputFloats1[ndx] = TCU_NAN;
1273                         }
1274                         else
1275                         {
1276                                 outputFloats[ndx] = inputFloats1[ndx];
1277                                 inputFloats2[ndx] = TCU_NAN;
1278                         }
1279                 }
1280         }
1281
1282         spec.assembly =
1283                 "OpCapability Shader\n"
1284                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1285                 "OpMemoryModel Logical GLSL450\n"
1286                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1287                 "OpExecutionMode %main LocalSize 1 1 1\n"
1288
1289                 "OpName %main           \"main\"\n"
1290                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1291
1292                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1293
1294                 "OpDecorate %buf BufferBlock\n"
1295                 "OpDecorate %indata1 DescriptorSet 0\n"
1296                 "OpDecorate %indata1 Binding 0\n"
1297                 "OpDecorate %indata2 DescriptorSet 0\n"
1298                 "OpDecorate %indata2 Binding 1\n"
1299                 "OpDecorate %outdata DescriptorSet 0\n"
1300                 "OpDecorate %outdata Binding 2\n"
1301                 "OpDecorate %f32arr ArrayStride 4\n"
1302                 "OpMemberDecorate %buf 0 Offset 0\n"
1303
1304                 + string(getComputeAsmCommonTypes()) +
1305
1306                 "%buf        = OpTypeStruct %f32arr\n"
1307                 "%bufptr     = OpTypePointer Uniform %buf\n"
1308                 "%indata1    = OpVariable %bufptr Uniform\n"
1309                 "%indata2    = OpVariable %bufptr Uniform\n"
1310                 "%outdata    = OpVariable %bufptr Uniform\n"
1311
1312                 "%id        = OpVariable %uvec3ptr Input\n"
1313                 "%zero      = OpConstant %i32 0\n"
1314
1315                 "%main      = OpFunction %void None %voidf\n"
1316                 "%label     = OpLabel\n"
1317                 "%idval     = OpLoad %uvec3 %id\n"
1318                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1319                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1320                 "%inval1    = OpLoad %f32 %inloc1\n"
1321                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1322                 "%inval2    = OpLoad %f32 %inloc2\n"
1323                 "%rem       = OpExtInst %f32 %std450 NMax %inval1 %inval2\n"
1324                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1325                 "             OpStore %outloc %rem\n"
1326                 "             OpReturn\n"
1327                 "             OpFunctionEnd\n";
1328
1329         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1330         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1331         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1332         spec.numWorkGroups = IVec3(numElements, 1, 1);
1333         spec.verifyIO = &compareNMax;
1334
1335         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1336
1337         return group.release();
1338 }
1339
1340 bool compareNClamp (const std::vector<BufferSp>&, const vector<AllocationSp>& outputAllocs, const std::vector<BufferSp>& expectedOutputs, TestLog&)
1341 {
1342         if (outputAllocs.size() != 1)
1343                 return false;
1344
1345         const BufferSp&                 expectedOutput                  = expectedOutputs[0];
1346         std::vector<deUint8>    data;
1347         expectedOutput->getBytes(data);
1348
1349         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1350         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1351
1352         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float) / 2; ++idx)
1353         {
1354                 const float e0 = expectedOutputAsFloat[idx * 2];
1355                 const float e1 = expectedOutputAsFloat[idx * 2 + 1];
1356                 const float res = outputAsFloat[idx];
1357
1358                 // For NClamp, we have two possible outcomes based on
1359                 // whether NaNs are handled or not.
1360                 // If either min or max value is NaN, the result is undefined,
1361                 // so this test doesn't stress those. If the clamped value is
1362                 // NaN, and NaNs are handled, the result is min; if NaNs are not
1363                 // handled, they are big values that result in max.
1364                 // If all three parameters are NaN, the result should be NaN.
1365                 if (!((tcu::Float32(e0).isNaN() && tcu::Float32(res).isNaN()) ||
1366                          (deFloatAbs(e0 - res) < 0.00001f) ||
1367                          (deFloatAbs(e1 - res) < 0.00001f)))
1368                         return false;
1369         }
1370
1371         return true;
1372 }
1373
1374 tcu::TestCaseGroup* createOpNClampGroup (tcu::TestContext& testCtx)
1375 {
1376         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnclamp", "Test the OpNClamp instruction"));
1377         ComputeShaderSpec                               spec;
1378         de::Random                                              rnd                             (deStringHash(group->getName()));
1379         const int                                               numElements             = 200;
1380         vector<float>                                   inputFloats1    (numElements, 0);
1381         vector<float>                                   inputFloats2    (numElements, 0);
1382         vector<float>                                   inputFloats3    (numElements, 0);
1383         vector<float>                                   outputFloats    (numElements * 2, 0);
1384
1385         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1386         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1387         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats3[0], numElements);
1388
1389         for (size_t ndx = 0; ndx < numElements; ++ndx)
1390         {
1391                 // Results are only defined if max value is bigger than min value.
1392                 if (inputFloats2[ndx] > inputFloats3[ndx])
1393                 {
1394                         float t = inputFloats2[ndx];
1395                         inputFloats2[ndx] = inputFloats3[ndx];
1396                         inputFloats3[ndx] = t;
1397                 }
1398
1399                 // By default, do the clamp, setting both possible answers
1400                 float defaultRes = std::min(std::max(inputFloats1[ndx], inputFloats2[ndx]), inputFloats3[ndx]);
1401
1402                 float maxResA = std::max(inputFloats1[ndx], inputFloats2[ndx]);
1403                 float maxResB = maxResA;
1404
1405                 // Alternate between the NaN cases
1406                 if (ndx & 1)
1407                 {
1408                         inputFloats1[ndx] = TCU_NAN;
1409                         // If NaN is handled, the result should be same as the clamp minimum.
1410                         // If NaN is not handled, the result should clamp to the clamp maximum.
1411                         maxResA = inputFloats2[ndx];
1412                         maxResB = inputFloats3[ndx];
1413                 }
1414                 else
1415                 {
1416                         // Not a NaN case - only one legal result.
1417                         maxResA = defaultRes;
1418                         maxResB = defaultRes;
1419                 }
1420
1421                 outputFloats[ndx * 2] = maxResA;
1422                 outputFloats[ndx * 2 + 1] = maxResB;
1423         }
1424
1425         // Make the first case a full-NAN case.
1426         inputFloats1[0] = TCU_NAN;
1427         inputFloats2[0] = TCU_NAN;
1428         inputFloats3[0] = TCU_NAN;
1429         outputFloats[0] = TCU_NAN;
1430         outputFloats[1] = TCU_NAN;
1431
1432         spec.assembly =
1433                 "OpCapability Shader\n"
1434                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1435                 "OpMemoryModel Logical GLSL450\n"
1436                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1437                 "OpExecutionMode %main LocalSize 1 1 1\n"
1438
1439                 "OpName %main           \"main\"\n"
1440                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1441
1442                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1443
1444                 "OpDecorate %buf BufferBlock\n"
1445                 "OpDecorate %indata1 DescriptorSet 0\n"
1446                 "OpDecorate %indata1 Binding 0\n"
1447                 "OpDecorate %indata2 DescriptorSet 0\n"
1448                 "OpDecorate %indata2 Binding 1\n"
1449                 "OpDecorate %indata3 DescriptorSet 0\n"
1450                 "OpDecorate %indata3 Binding 2\n"
1451                 "OpDecorate %outdata DescriptorSet 0\n"
1452                 "OpDecorate %outdata Binding 3\n"
1453                 "OpDecorate %f32arr ArrayStride 4\n"
1454                 "OpMemberDecorate %buf 0 Offset 0\n"
1455
1456                 + string(getComputeAsmCommonTypes()) +
1457
1458                 "%buf        = OpTypeStruct %f32arr\n"
1459                 "%bufptr     = OpTypePointer Uniform %buf\n"
1460                 "%indata1    = OpVariable %bufptr Uniform\n"
1461                 "%indata2    = OpVariable %bufptr Uniform\n"
1462                 "%indata3    = OpVariable %bufptr Uniform\n"
1463                 "%outdata    = OpVariable %bufptr Uniform\n"
1464
1465                 "%id        = OpVariable %uvec3ptr Input\n"
1466                 "%zero      = OpConstant %i32 0\n"
1467
1468                 "%main      = OpFunction %void None %voidf\n"
1469                 "%label     = OpLabel\n"
1470                 "%idval     = OpLoad %uvec3 %id\n"
1471                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1472                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1473                 "%inval1    = OpLoad %f32 %inloc1\n"
1474                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1475                 "%inval2    = OpLoad %f32 %inloc2\n"
1476                 "%inloc3    = OpAccessChain %f32ptr %indata3 %zero %x\n"
1477                 "%inval3    = OpLoad %f32 %inloc3\n"
1478                 "%rem       = OpExtInst %f32 %std450 NClamp %inval1 %inval2 %inval3\n"
1479                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1480                 "             OpStore %outloc %rem\n"
1481                 "             OpReturn\n"
1482                 "             OpFunctionEnd\n";
1483
1484         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1485         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1486         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
1487         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1488         spec.numWorkGroups = IVec3(numElements, 1, 1);
1489         spec.verifyIO = &compareNClamp;
1490
1491         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1492
1493         return group.release();
1494 }
1495
1496 tcu::TestCaseGroup* createOpSRemComputeGroup (tcu::TestContext& testCtx, qpTestResult negFailResult)
1497 {
1498         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsrem", "Test the OpSRem instruction"));
1499         de::Random                                              rnd                             (deStringHash(group->getName()));
1500         const int                                               numElements             = 200;
1501
1502         const struct CaseParams
1503         {
1504                 const char*             name;
1505                 const char*             failMessage;            // customized status message
1506                 qpTestResult    failResult;                     // override status on failure
1507                 int                             op1Min, op1Max;         // operand ranges
1508                 int                             op2Min, op2Max;
1509         } cases[] =
1510         {
1511                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    0,              65536,  0,              100 },
1512                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  -65536, 65536,  -100,   100 },  // see below
1513         };
1514         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1515
1516         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1517         {
1518                 const CaseParams&       params          = cases[caseNdx];
1519                 ComputeShaderSpec       spec;
1520                 vector<deInt32>         inputInts1      (numElements, 0);
1521                 vector<deInt32>         inputInts2      (numElements, 0);
1522                 vector<deInt32>         outputInts      (numElements, 0);
1523
1524                 fillRandomScalars(rnd, params.op1Min, params.op1Max, &inputInts1[0], numElements);
1525                 fillRandomScalars(rnd, params.op2Min, params.op2Max, &inputInts2[0], numElements, filterNotZero);
1526
1527                 for (int ndx = 0; ndx < numElements; ++ndx)
1528                 {
1529                         // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1530                         outputInts[ndx] = inputInts1[ndx] % inputInts2[ndx];
1531                 }
1532
1533                 spec.assembly =
1534                         string(getComputeAsmShaderPreamble()) +
1535
1536                         "OpName %main           \"main\"\n"
1537                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1538
1539                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1540
1541                         "OpDecorate %buf BufferBlock\n"
1542                         "OpDecorate %indata1 DescriptorSet 0\n"
1543                         "OpDecorate %indata1 Binding 0\n"
1544                         "OpDecorate %indata2 DescriptorSet 0\n"
1545                         "OpDecorate %indata2 Binding 1\n"
1546                         "OpDecorate %outdata DescriptorSet 0\n"
1547                         "OpDecorate %outdata Binding 2\n"
1548                         "OpDecorate %i32arr ArrayStride 4\n"
1549                         "OpMemberDecorate %buf 0 Offset 0\n"
1550
1551                         + string(getComputeAsmCommonTypes()) +
1552
1553                         "%buf        = OpTypeStruct %i32arr\n"
1554                         "%bufptr     = OpTypePointer Uniform %buf\n"
1555                         "%indata1    = OpVariable %bufptr Uniform\n"
1556                         "%indata2    = OpVariable %bufptr Uniform\n"
1557                         "%outdata    = OpVariable %bufptr Uniform\n"
1558
1559                         "%id        = OpVariable %uvec3ptr Input\n"
1560                         "%zero      = OpConstant %i32 0\n"
1561
1562                         "%main      = OpFunction %void None %voidf\n"
1563                         "%label     = OpLabel\n"
1564                         "%idval     = OpLoad %uvec3 %id\n"
1565                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1566                         "%inloc1    = OpAccessChain %i32ptr %indata1 %zero %x\n"
1567                         "%inval1    = OpLoad %i32 %inloc1\n"
1568                         "%inloc2    = OpAccessChain %i32ptr %indata2 %zero %x\n"
1569                         "%inval2    = OpLoad %i32 %inloc2\n"
1570                         "%rem       = OpSRem %i32 %inval1 %inval2\n"
1571                         "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
1572                         "             OpStore %outloc %rem\n"
1573                         "             OpReturn\n"
1574                         "             OpFunctionEnd\n";
1575
1576                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts1)));
1577                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts2)));
1578                 spec.outputs.push_back  (BufferSp(new Int32Buffer(outputInts)));
1579                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1580                 spec.failResult                 = params.failResult;
1581                 spec.failMessage                = params.failMessage;
1582
1583                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1584         }
1585
1586         return group.release();
1587 }
1588
1589 tcu::TestCaseGroup* createOpSRemComputeGroup64 (tcu::TestContext& testCtx, qpTestResult negFailResult)
1590 {
1591         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsrem64", "Test the 64-bit OpSRem instruction"));
1592         de::Random                                              rnd                             (deStringHash(group->getName()));
1593         const int                                               numElements             = 200;
1594
1595         const struct CaseParams
1596         {
1597                 const char*             name;
1598                 const char*             failMessage;            // customized status message
1599                 qpTestResult    failResult;                     // override status on failure
1600                 bool                    positive;
1601         } cases[] =
1602         {
1603                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    true },
1604                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  false },        // see below
1605         };
1606         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1607
1608         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1609         {
1610                 const CaseParams&       params          = cases[caseNdx];
1611                 ComputeShaderSpec       spec;
1612                 vector<deInt64>         inputInts1      (numElements, 0);
1613                 vector<deInt64>         inputInts2      (numElements, 0);
1614                 vector<deInt64>         outputInts      (numElements, 0);
1615
1616                 if (params.positive)
1617                 {
1618                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements, filterNonNegative);
1619                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterPositive);
1620                 }
1621                 else
1622                 {
1623                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements);
1624                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterNotZero);
1625                 }
1626
1627                 for (int ndx = 0; ndx < numElements; ++ndx)
1628                 {
1629                         // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1630                         outputInts[ndx] = inputInts1[ndx] % inputInts2[ndx];
1631                 }
1632
1633                 spec.assembly =
1634                         "OpCapability Int64\n"
1635
1636                         + string(getComputeAsmShaderPreamble()) +
1637
1638                         "OpName %main           \"main\"\n"
1639                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1640
1641                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1642
1643                         "OpDecorate %buf BufferBlock\n"
1644                         "OpDecorate %indata1 DescriptorSet 0\n"
1645                         "OpDecorate %indata1 Binding 0\n"
1646                         "OpDecorate %indata2 DescriptorSet 0\n"
1647                         "OpDecorate %indata2 Binding 1\n"
1648                         "OpDecorate %outdata DescriptorSet 0\n"
1649                         "OpDecorate %outdata Binding 2\n"
1650                         "OpDecorate %i64arr ArrayStride 8\n"
1651                         "OpMemberDecorate %buf 0 Offset 0\n"
1652
1653                         + string(getComputeAsmCommonTypes())
1654                         + string(getComputeAsmCommonInt64Types()) +
1655
1656                         "%buf        = OpTypeStruct %i64arr\n"
1657                         "%bufptr     = OpTypePointer Uniform %buf\n"
1658                         "%indata1    = OpVariable %bufptr Uniform\n"
1659                         "%indata2    = OpVariable %bufptr Uniform\n"
1660                         "%outdata    = OpVariable %bufptr Uniform\n"
1661
1662                         "%id        = OpVariable %uvec3ptr Input\n"
1663                         "%zero      = OpConstant %i64 0\n"
1664
1665                         "%main      = OpFunction %void None %voidf\n"
1666                         "%label     = OpLabel\n"
1667                         "%idval     = OpLoad %uvec3 %id\n"
1668                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1669                         "%inloc1    = OpAccessChain %i64ptr %indata1 %zero %x\n"
1670                         "%inval1    = OpLoad %i64 %inloc1\n"
1671                         "%inloc2    = OpAccessChain %i64ptr %indata2 %zero %x\n"
1672                         "%inval2    = OpLoad %i64 %inloc2\n"
1673                         "%rem       = OpSRem %i64 %inval1 %inval2\n"
1674                         "%outloc    = OpAccessChain %i64ptr %outdata %zero %x\n"
1675                         "             OpStore %outloc %rem\n"
1676                         "             OpReturn\n"
1677                         "             OpFunctionEnd\n";
1678
1679                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts1)));
1680                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts2)));
1681                 spec.outputs.push_back  (BufferSp(new Int64Buffer(outputInts)));
1682                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1683                 spec.failResult                 = params.failResult;
1684                 spec.failMessage                = params.failMessage;
1685
1686                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec, COMPUTE_TEST_USES_INT64));
1687         }
1688
1689         return group.release();
1690 }
1691
1692 tcu::TestCaseGroup* createOpSModComputeGroup (tcu::TestContext& testCtx, qpTestResult negFailResult)
1693 {
1694         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsmod", "Test the OpSMod instruction"));
1695         de::Random                                              rnd                             (deStringHash(group->getName()));
1696         const int                                               numElements             = 200;
1697
1698         const struct CaseParams
1699         {
1700                 const char*             name;
1701                 const char*             failMessage;            // customized status message
1702                 qpTestResult    failResult;                     // override status on failure
1703                 int                             op1Min, op1Max;         // operand ranges
1704                 int                             op2Min, op2Max;
1705         } cases[] =
1706         {
1707                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    0,              65536,  0,              100 },
1708                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  -65536, 65536,  -100,   100 },  // see below
1709         };
1710         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1711
1712         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1713         {
1714                 const CaseParams&       params          = cases[caseNdx];
1715
1716                 ComputeShaderSpec       spec;
1717                 vector<deInt32>         inputInts1      (numElements, 0);
1718                 vector<deInt32>         inputInts2      (numElements, 0);
1719                 vector<deInt32>         outputInts      (numElements, 0);
1720
1721                 fillRandomScalars(rnd, params.op1Min, params.op1Max, &inputInts1[0], numElements);
1722                 fillRandomScalars(rnd, params.op2Min, params.op2Max, &inputInts2[0], numElements, filterNotZero);
1723
1724                 for (int ndx = 0; ndx < numElements; ++ndx)
1725                 {
1726                         deInt32 rem = inputInts1[ndx] % inputInts2[ndx];
1727                         if (rem == 0)
1728                         {
1729                                 outputInts[ndx] = 0;
1730                         }
1731                         else if ((inputInts1[ndx] >= 0) == (inputInts2[ndx] >= 0))
1732                         {
1733                                 // They have the same sign
1734                                 outputInts[ndx] = rem;
1735                         }
1736                         else
1737                         {
1738                                 // They have opposite sign.  The remainder operation takes the
1739                                 // sign inputInts1[ndx] but OpSMod is supposed to take ths sign
1740                                 // of inputInts2[ndx].  Adding inputInts2[ndx] will ensure that
1741                                 // the result has the correct sign and that it is still
1742                                 // congruent to inputInts1[ndx] modulo inputInts2[ndx]
1743                                 //
1744                                 // See also http://mathforum.org/library/drmath/view/52343.html
1745                                 outputInts[ndx] = rem + inputInts2[ndx];
1746                         }
1747                 }
1748
1749                 spec.assembly =
1750                         string(getComputeAsmShaderPreamble()) +
1751
1752                         "OpName %main           \"main\"\n"
1753                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1754
1755                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1756
1757                         "OpDecorate %buf BufferBlock\n"
1758                         "OpDecorate %indata1 DescriptorSet 0\n"
1759                         "OpDecorate %indata1 Binding 0\n"
1760                         "OpDecorate %indata2 DescriptorSet 0\n"
1761                         "OpDecorate %indata2 Binding 1\n"
1762                         "OpDecorate %outdata DescriptorSet 0\n"
1763                         "OpDecorate %outdata Binding 2\n"
1764                         "OpDecorate %i32arr ArrayStride 4\n"
1765                         "OpMemberDecorate %buf 0 Offset 0\n"
1766
1767                         + string(getComputeAsmCommonTypes()) +
1768
1769                         "%buf        = OpTypeStruct %i32arr\n"
1770                         "%bufptr     = OpTypePointer Uniform %buf\n"
1771                         "%indata1    = OpVariable %bufptr Uniform\n"
1772                         "%indata2    = OpVariable %bufptr Uniform\n"
1773                         "%outdata    = OpVariable %bufptr Uniform\n"
1774
1775                         "%id        = OpVariable %uvec3ptr Input\n"
1776                         "%zero      = OpConstant %i32 0\n"
1777
1778                         "%main      = OpFunction %void None %voidf\n"
1779                         "%label     = OpLabel\n"
1780                         "%idval     = OpLoad %uvec3 %id\n"
1781                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1782                         "%inloc1    = OpAccessChain %i32ptr %indata1 %zero %x\n"
1783                         "%inval1    = OpLoad %i32 %inloc1\n"
1784                         "%inloc2    = OpAccessChain %i32ptr %indata2 %zero %x\n"
1785                         "%inval2    = OpLoad %i32 %inloc2\n"
1786                         "%rem       = OpSMod %i32 %inval1 %inval2\n"
1787                         "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
1788                         "             OpStore %outloc %rem\n"
1789                         "             OpReturn\n"
1790                         "             OpFunctionEnd\n";
1791
1792                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts1)));
1793                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts2)));
1794                 spec.outputs.push_back  (BufferSp(new Int32Buffer(outputInts)));
1795                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1796                 spec.failResult                 = params.failResult;
1797                 spec.failMessage                = params.failMessage;
1798
1799                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1800         }
1801
1802         return group.release();
1803 }
1804
1805 tcu::TestCaseGroup* createOpSModComputeGroup64 (tcu::TestContext& testCtx, qpTestResult negFailResult)
1806 {
1807         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsmod64", "Test the OpSMod instruction"));
1808         de::Random                                              rnd                             (deStringHash(group->getName()));
1809         const int                                               numElements             = 200;
1810
1811         const struct CaseParams
1812         {
1813                 const char*             name;
1814                 const char*             failMessage;            // customized status message
1815                 qpTestResult    failResult;                     // override status on failure
1816                 bool                    positive;
1817         } cases[] =
1818         {
1819                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    true },
1820                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  false },        // see below
1821         };
1822         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1823
1824         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1825         {
1826                 const CaseParams&       params          = cases[caseNdx];
1827
1828                 ComputeShaderSpec       spec;
1829                 vector<deInt64>         inputInts1      (numElements, 0);
1830                 vector<deInt64>         inputInts2      (numElements, 0);
1831                 vector<deInt64>         outputInts      (numElements, 0);
1832
1833
1834                 if (params.positive)
1835                 {
1836                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements, filterNonNegative);
1837                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterPositive);
1838                 }
1839                 else
1840                 {
1841                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements);
1842                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterNotZero);
1843                 }
1844
1845                 for (int ndx = 0; ndx < numElements; ++ndx)
1846                 {
1847                         deInt64 rem = inputInts1[ndx] % inputInts2[ndx];
1848                         if (rem == 0)
1849                         {
1850                                 outputInts[ndx] = 0;
1851                         }
1852                         else if ((inputInts1[ndx] >= 0) == (inputInts2[ndx] >= 0))
1853                         {
1854                                 // They have the same sign
1855                                 outputInts[ndx] = rem;
1856                         }
1857                         else
1858                         {
1859                                 // They have opposite sign.  The remainder operation takes the
1860                                 // sign inputInts1[ndx] but OpSMod is supposed to take ths sign
1861                                 // of inputInts2[ndx].  Adding inputInts2[ndx] will ensure that
1862                                 // the result has the correct sign and that it is still
1863                                 // congruent to inputInts1[ndx] modulo inputInts2[ndx]
1864                                 //
1865                                 // See also http://mathforum.org/library/drmath/view/52343.html
1866                                 outputInts[ndx] = rem + inputInts2[ndx];
1867                         }
1868                 }
1869
1870                 spec.assembly =
1871                         "OpCapability Int64\n"
1872
1873                         + string(getComputeAsmShaderPreamble()) +
1874
1875                         "OpName %main           \"main\"\n"
1876                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1877
1878                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1879
1880                         "OpDecorate %buf BufferBlock\n"
1881                         "OpDecorate %indata1 DescriptorSet 0\n"
1882                         "OpDecorate %indata1 Binding 0\n"
1883                         "OpDecorate %indata2 DescriptorSet 0\n"
1884                         "OpDecorate %indata2 Binding 1\n"
1885                         "OpDecorate %outdata DescriptorSet 0\n"
1886                         "OpDecorate %outdata Binding 2\n"
1887                         "OpDecorate %i64arr ArrayStride 8\n"
1888                         "OpMemberDecorate %buf 0 Offset 0\n"
1889
1890                         + string(getComputeAsmCommonTypes())
1891                         + string(getComputeAsmCommonInt64Types()) +
1892
1893                         "%buf        = OpTypeStruct %i64arr\n"
1894                         "%bufptr     = OpTypePointer Uniform %buf\n"
1895                         "%indata1    = OpVariable %bufptr Uniform\n"
1896                         "%indata2    = OpVariable %bufptr Uniform\n"
1897                         "%outdata    = OpVariable %bufptr Uniform\n"
1898
1899                         "%id        = OpVariable %uvec3ptr Input\n"
1900                         "%zero      = OpConstant %i64 0\n"
1901
1902                         "%main      = OpFunction %void None %voidf\n"
1903                         "%label     = OpLabel\n"
1904                         "%idval     = OpLoad %uvec3 %id\n"
1905                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1906                         "%inloc1    = OpAccessChain %i64ptr %indata1 %zero %x\n"
1907                         "%inval1    = OpLoad %i64 %inloc1\n"
1908                         "%inloc2    = OpAccessChain %i64ptr %indata2 %zero %x\n"
1909                         "%inval2    = OpLoad %i64 %inloc2\n"
1910                         "%rem       = OpSMod %i64 %inval1 %inval2\n"
1911                         "%outloc    = OpAccessChain %i64ptr %outdata %zero %x\n"
1912                         "             OpStore %outloc %rem\n"
1913                         "             OpReturn\n"
1914                         "             OpFunctionEnd\n";
1915
1916                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts1)));
1917                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts2)));
1918                 spec.outputs.push_back  (BufferSp(new Int64Buffer(outputInts)));
1919                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1920                 spec.failResult                 = params.failResult;
1921                 spec.failMessage                = params.failMessage;
1922
1923                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec, COMPUTE_TEST_USES_INT64));
1924         }
1925
1926         return group.release();
1927 }
1928
1929 // Copy contents in the input buffer to the output buffer.
1930 tcu::TestCaseGroup* createOpCopyMemoryGroup (tcu::TestContext& testCtx)
1931 {
1932         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opcopymemory", "Test the OpCopyMemory instruction"));
1933         de::Random                                              rnd                             (deStringHash(group->getName()));
1934         const int                                               numElements             = 100;
1935
1936         // 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.
1937         ComputeShaderSpec                               spec1;
1938         vector<Vec4>                                    inputFloats1    (numElements);
1939         vector<Vec4>                                    outputFloats1   (numElements);
1940
1941         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats1[0], numElements * 4);
1942
1943         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
1944         floorAll(inputFloats1);
1945
1946         for (size_t ndx = 0; ndx < numElements; ++ndx)
1947                 outputFloats1[ndx] = inputFloats1[ndx] + Vec4(0.f, 0.5f, 1.5f, 2.5f);
1948
1949         spec1.assembly =
1950                 string(getComputeAsmShaderPreamble()) +
1951
1952                 "OpName %main           \"main\"\n"
1953                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1954
1955                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1956                 "OpDecorate %vec4arr ArrayStride 16\n"
1957
1958                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
1959
1960                 "%vec4       = OpTypeVector %f32 4\n"
1961                 "%vec4ptr_u  = OpTypePointer Uniform %vec4\n"
1962                 "%vec4ptr_f  = OpTypePointer Function %vec4\n"
1963                 "%vec4arr    = OpTypeRuntimeArray %vec4\n"
1964                 "%buf        = OpTypeStruct %vec4arr\n"
1965                 "%bufptr     = OpTypePointer Uniform %buf\n"
1966                 "%indata     = OpVariable %bufptr Uniform\n"
1967                 "%outdata    = OpVariable %bufptr Uniform\n"
1968
1969                 "%id         = OpVariable %uvec3ptr Input\n"
1970                 "%zero       = OpConstant %i32 0\n"
1971                 "%c_f_0      = OpConstant %f32 0.\n"
1972                 "%c_f_0_5    = OpConstant %f32 0.5\n"
1973                 "%c_f_1_5    = OpConstant %f32 1.5\n"
1974                 "%c_f_2_5    = OpConstant %f32 2.5\n"
1975                 "%c_vec4     = OpConstantComposite %vec4 %c_f_0 %c_f_0_5 %c_f_1_5 %c_f_2_5\n"
1976
1977                 "%main       = OpFunction %void None %voidf\n"
1978                 "%label      = OpLabel\n"
1979                 "%v_vec4     = OpVariable %vec4ptr_f Function\n"
1980                 "%idval      = OpLoad %uvec3 %id\n"
1981                 "%x          = OpCompositeExtract %u32 %idval 0\n"
1982                 "%inloc      = OpAccessChain %vec4ptr_u %indata %zero %x\n"
1983                 "%outloc     = OpAccessChain %vec4ptr_u %outdata %zero %x\n"
1984                 "              OpCopyMemory %v_vec4 %inloc\n"
1985                 "%v_vec4_val = OpLoad %vec4 %v_vec4\n"
1986                 "%add        = OpFAdd %vec4 %v_vec4_val %c_vec4\n"
1987                 "              OpStore %outloc %add\n"
1988                 "              OpReturn\n"
1989                 "              OpFunctionEnd\n";
1990
1991         spec1.inputs.push_back(BufferSp(new Vec4Buffer(inputFloats1)));
1992         spec1.outputs.push_back(BufferSp(new Vec4Buffer(outputFloats1)));
1993         spec1.numWorkGroups = IVec3(numElements, 1, 1);
1994
1995         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector", "OpCopyMemory elements of vector type", spec1));
1996
1997         // The following case copies a float[100] variable from the input buffer to the output buffer.
1998         ComputeShaderSpec                               spec2;
1999         vector<float>                                   inputFloats2    (numElements);
2000         vector<float>                                   outputFloats2   (numElements);
2001
2002         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats2[0], numElements);
2003
2004         for (size_t ndx = 0; ndx < numElements; ++ndx)
2005                 outputFloats2[ndx] = inputFloats2[ndx];
2006
2007         spec2.assembly =
2008                 string(getComputeAsmShaderPreamble()) +
2009
2010                 "OpName %main           \"main\"\n"
2011                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2012
2013                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2014                 "OpDecorate %f32arr100 ArrayStride 4\n"
2015
2016                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2017
2018                 "%hundred        = OpConstant %u32 100\n"
2019                 "%f32arr100      = OpTypeArray %f32 %hundred\n"
2020                 "%f32arr100ptr_f = OpTypePointer Function %f32arr100\n"
2021                 "%f32arr100ptr_u = OpTypePointer Uniform %f32arr100\n"
2022                 "%buf            = OpTypeStruct %f32arr100\n"
2023                 "%bufptr         = OpTypePointer Uniform %buf\n"
2024                 "%indata         = OpVariable %bufptr Uniform\n"
2025                 "%outdata        = OpVariable %bufptr Uniform\n"
2026
2027                 "%id             = OpVariable %uvec3ptr Input\n"
2028                 "%zero           = OpConstant %i32 0\n"
2029
2030                 "%main           = OpFunction %void None %voidf\n"
2031                 "%label          = OpLabel\n"
2032                 "%var            = OpVariable %f32arr100ptr_f Function\n"
2033                 "%inarr          = OpAccessChain %f32arr100ptr_u %indata %zero\n"
2034                 "%outarr         = OpAccessChain %f32arr100ptr_u %outdata %zero\n"
2035                 "                  OpCopyMemory %var %inarr\n"
2036                 "                  OpCopyMemory %outarr %var\n"
2037                 "                  OpReturn\n"
2038                 "                  OpFunctionEnd\n";
2039
2040         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
2041         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
2042         spec2.numWorkGroups = IVec3(1, 1, 1);
2043
2044         group->addChild(new SpvAsmComputeShaderCase(testCtx, "array", "OpCopyMemory elements of array type", spec2));
2045
2046         // The following case copies a struct{vec4, vec4, vec4, vec4} variable from the input buffer to the output buffer.
2047         ComputeShaderSpec                               spec3;
2048         vector<float>                                   inputFloats3    (16);
2049         vector<float>                                   outputFloats3   (16);
2050
2051         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats3[0], 16);
2052
2053         for (size_t ndx = 0; ndx < 16; ++ndx)
2054                 outputFloats3[ndx] = inputFloats3[ndx];
2055
2056         spec3.assembly =
2057                 string(getComputeAsmShaderPreamble()) +
2058
2059                 "OpName %main           \"main\"\n"
2060                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2061
2062                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2063                 "OpMemberDecorate %buf 0 Offset 0\n"
2064                 "OpMemberDecorate %buf 1 Offset 16\n"
2065                 "OpMemberDecorate %buf 2 Offset 32\n"
2066                 "OpMemberDecorate %buf 3 Offset 48\n"
2067
2068                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2069
2070                 "%vec4      = OpTypeVector %f32 4\n"
2071                 "%buf       = OpTypeStruct %vec4 %vec4 %vec4 %vec4\n"
2072                 "%bufptr    = OpTypePointer Uniform %buf\n"
2073                 "%indata    = OpVariable %bufptr Uniform\n"
2074                 "%outdata   = OpVariable %bufptr Uniform\n"
2075                 "%vec4stptr = OpTypePointer Function %buf\n"
2076
2077                 "%id        = OpVariable %uvec3ptr Input\n"
2078                 "%zero      = OpConstant %i32 0\n"
2079
2080                 "%main      = OpFunction %void None %voidf\n"
2081                 "%label     = OpLabel\n"
2082                 "%var       = OpVariable %vec4stptr Function\n"
2083                 "             OpCopyMemory %var %indata\n"
2084                 "             OpCopyMemory %outdata %var\n"
2085                 "             OpReturn\n"
2086                 "             OpFunctionEnd\n";
2087
2088         spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
2089         spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
2090         spec3.numWorkGroups = IVec3(1, 1, 1);
2091
2092         group->addChild(new SpvAsmComputeShaderCase(testCtx, "struct", "OpCopyMemory elements of struct type", spec3));
2093
2094         // The following case negates multiple float variables from the input buffer and stores the results to the output buffer.
2095         ComputeShaderSpec                               spec4;
2096         vector<float>                                   inputFloats4    (numElements);
2097         vector<float>                                   outputFloats4   (numElements);
2098
2099         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats4[0], numElements);
2100
2101         for (size_t ndx = 0; ndx < numElements; ++ndx)
2102                 outputFloats4[ndx] = -inputFloats4[ndx];
2103
2104         spec4.assembly =
2105                 string(getComputeAsmShaderPreamble()) +
2106
2107                 "OpName %main           \"main\"\n"
2108                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2109
2110                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2111
2112                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2113
2114                 "%f32ptr_f  = OpTypePointer Function %f32\n"
2115                 "%id        = OpVariable %uvec3ptr Input\n"
2116                 "%zero      = OpConstant %i32 0\n"
2117
2118                 "%main      = OpFunction %void None %voidf\n"
2119                 "%label     = OpLabel\n"
2120                 "%var       = OpVariable %f32ptr_f Function\n"
2121                 "%idval     = OpLoad %uvec3 %id\n"
2122                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2123                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
2124                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
2125                 "             OpCopyMemory %var %inloc\n"
2126                 "%val       = OpLoad %f32 %var\n"
2127                 "%neg       = OpFNegate %f32 %val\n"
2128                 "             OpStore %outloc %neg\n"
2129                 "             OpReturn\n"
2130                 "             OpFunctionEnd\n";
2131
2132         spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
2133         spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
2134         spec4.numWorkGroups = IVec3(numElements, 1, 1);
2135
2136         group->addChild(new SpvAsmComputeShaderCase(testCtx, "float", "OpCopyMemory elements of float type", spec4));
2137
2138         return group.release();
2139 }
2140
2141 tcu::TestCaseGroup* createOpCopyObjectGroup (tcu::TestContext& testCtx)
2142 {
2143         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opcopyobject", "Test the OpCopyObject instruction"));
2144         ComputeShaderSpec                               spec;
2145         de::Random                                              rnd                             (deStringHash(group->getName()));
2146         const int                                               numElements             = 100;
2147         vector<float>                                   inputFloats             (numElements, 0);
2148         vector<float>                                   outputFloats    (numElements, 0);
2149
2150         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
2151
2152         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2153         floorAll(inputFloats);
2154
2155         for (size_t ndx = 0; ndx < numElements; ++ndx)
2156                 outputFloats[ndx] = inputFloats[ndx] + 7.5f;
2157
2158         spec.assembly =
2159                 string(getComputeAsmShaderPreamble()) +
2160
2161                 "OpName %main           \"main\"\n"
2162                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2163
2164                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2165
2166                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2167
2168                 "%fmat     = OpTypeMatrix %fvec3 3\n"
2169                 "%three    = OpConstant %u32 3\n"
2170                 "%farr     = OpTypeArray %f32 %three\n"
2171                 "%fst      = OpTypeStruct %f32 %f32\n"
2172
2173                 + string(getComputeAsmInputOutputBuffer()) +
2174
2175                 "%id            = OpVariable %uvec3ptr Input\n"
2176                 "%zero          = OpConstant %i32 0\n"
2177                 "%c_f           = OpConstant %f32 1.5\n"
2178                 "%c_fvec3       = OpConstantComposite %fvec3 %c_f %c_f %c_f\n"
2179                 "%c_fmat        = OpConstantComposite %fmat %c_fvec3 %c_fvec3 %c_fvec3\n"
2180                 "%c_farr        = OpConstantComposite %farr %c_f %c_f %c_f\n"
2181                 "%c_fst         = OpConstantComposite %fst %c_f %c_f\n"
2182
2183                 "%main          = OpFunction %void None %voidf\n"
2184                 "%label         = OpLabel\n"
2185                 "%c_f_copy      = OpCopyObject %f32   %c_f\n"
2186                 "%c_fvec3_copy  = OpCopyObject %fvec3 %c_fvec3\n"
2187                 "%c_fmat_copy   = OpCopyObject %fmat  %c_fmat\n"
2188                 "%c_farr_copy   = OpCopyObject %farr  %c_farr\n"
2189                 "%c_fst_copy    = OpCopyObject %fst   %c_fst\n"
2190                 "%fvec3_elem    = OpCompositeExtract %f32 %c_fvec3_copy 0\n"
2191                 "%fmat_elem     = OpCompositeExtract %f32 %c_fmat_copy 1 2\n"
2192                 "%farr_elem     = OpCompositeExtract %f32 %c_farr_copy 2\n"
2193                 "%fst_elem      = OpCompositeExtract %f32 %c_fst_copy 1\n"
2194                 // Add up. 1.5 * 5 = 7.5.
2195                 "%add1          = OpFAdd %f32 %c_f_copy %fvec3_elem\n"
2196                 "%add2          = OpFAdd %f32 %add1     %fmat_elem\n"
2197                 "%add3          = OpFAdd %f32 %add2     %farr_elem\n"
2198                 "%add4          = OpFAdd %f32 %add3     %fst_elem\n"
2199
2200                 "%idval         = OpLoad %uvec3 %id\n"
2201                 "%x             = OpCompositeExtract %u32 %idval 0\n"
2202                 "%inloc         = OpAccessChain %f32ptr %indata %zero %x\n"
2203                 "%outloc        = OpAccessChain %f32ptr %outdata %zero %x\n"
2204                 "%inval         = OpLoad %f32 %inloc\n"
2205                 "%add           = OpFAdd %f32 %add4 %inval\n"
2206                 "                 OpStore %outloc %add\n"
2207                 "                 OpReturn\n"
2208                 "                 OpFunctionEnd\n";
2209         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2210         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2211         spec.numWorkGroups = IVec3(numElements, 1, 1);
2212
2213         group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "OpCopyObject on different types", spec));
2214
2215         return group.release();
2216 }
2217 // Assembly code used for testing OpUnreachable is based on GLSL source code:
2218 //
2219 // #version 430
2220 //
2221 // layout(std140, set = 0, binding = 0) readonly buffer Input {
2222 //   float elements[];
2223 // } input_data;
2224 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
2225 //   float elements[];
2226 // } output_data;
2227 //
2228 // void not_called_func() {
2229 //   // place OpUnreachable here
2230 // }
2231 //
2232 // uint modulo4(uint val) {
2233 //   switch (val % uint(4)) {
2234 //     case 0:  return 3;
2235 //     case 1:  return 2;
2236 //     case 2:  return 1;
2237 //     case 3:  return 0;
2238 //     default: return 100; // place OpUnreachable here
2239 //   }
2240 // }
2241 //
2242 // uint const5() {
2243 //   return 5;
2244 //   // place OpUnreachable here
2245 // }
2246 //
2247 // void main() {
2248 //   uint x = gl_GlobalInvocationID.x;
2249 //   if (const5() > modulo4(1000)) {
2250 //     output_data.elements[x] = -input_data.elements[x];
2251 //   } else {
2252 //     // place OpUnreachable here
2253 //     output_data.elements[x] = input_data.elements[x];
2254 //   }
2255 // }
2256
2257 tcu::TestCaseGroup* createOpUnreachableGroup (tcu::TestContext& testCtx)
2258 {
2259         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opunreachable", "Test the OpUnreachable instruction"));
2260         ComputeShaderSpec                               spec;
2261         de::Random                                              rnd                             (deStringHash(group->getName()));
2262         const int                                               numElements             = 100;
2263         vector<float>                                   positiveFloats  (numElements, 0);
2264         vector<float>                                   negativeFloats  (numElements, 0);
2265
2266         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
2267
2268         for (size_t ndx = 0; ndx < numElements; ++ndx)
2269                 negativeFloats[ndx] = -positiveFloats[ndx];
2270
2271         spec.assembly =
2272                 string(getComputeAsmShaderPreamble()) +
2273
2274                 "OpSource GLSL 430\n"
2275                 "OpName %main            \"main\"\n"
2276                 "OpName %func_not_called_func \"not_called_func(\"\n"
2277                 "OpName %func_modulo4         \"modulo4(u1;\"\n"
2278                 "OpName %func_const5          \"const5(\"\n"
2279                 "OpName %id                   \"gl_GlobalInvocationID\"\n"
2280
2281                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2282
2283                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2284
2285                 "%u32ptr    = OpTypePointer Function %u32\n"
2286                 "%uintfuint = OpTypeFunction %u32 %u32ptr\n"
2287                 "%unitf     = OpTypeFunction %u32\n"
2288
2289                 "%id        = OpVariable %uvec3ptr Input\n"
2290                 "%zero      = OpConstant %u32 0\n"
2291                 "%one       = OpConstant %u32 1\n"
2292                 "%two       = OpConstant %u32 2\n"
2293                 "%three     = OpConstant %u32 3\n"
2294                 "%four      = OpConstant %u32 4\n"
2295                 "%five      = OpConstant %u32 5\n"
2296                 "%hundred   = OpConstant %u32 100\n"
2297                 "%thousand  = OpConstant %u32 1000\n"
2298
2299                 + string(getComputeAsmInputOutputBuffer()) +
2300
2301                 // Main()
2302                 "%main   = OpFunction %void None %voidf\n"
2303                 "%main_entry  = OpLabel\n"
2304                 "%v_thousand  = OpVariable %u32ptr Function %thousand\n"
2305                 "%idval       = OpLoad %uvec3 %id\n"
2306                 "%x           = OpCompositeExtract %u32 %idval 0\n"
2307                 "%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
2308                 "%inval       = OpLoad %f32 %inloc\n"
2309                 "%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
2310                 "%ret_const5  = OpFunctionCall %u32 %func_const5\n"
2311                 "%ret_modulo4 = OpFunctionCall %u32 %func_modulo4 %v_thousand\n"
2312                 "%cmp_gt      = OpUGreaterThan %bool %ret_const5 %ret_modulo4\n"
2313                 "               OpSelectionMerge %if_end None\n"
2314                 "               OpBranchConditional %cmp_gt %if_true %if_false\n"
2315                 "%if_true     = OpLabel\n"
2316                 "%negate      = OpFNegate %f32 %inval\n"
2317                 "               OpStore %outloc %negate\n"
2318                 "               OpBranch %if_end\n"
2319                 "%if_false    = OpLabel\n"
2320                 "               OpUnreachable\n" // Unreachable else branch for if statement
2321                 "%if_end      = OpLabel\n"
2322                 "               OpReturn\n"
2323                 "               OpFunctionEnd\n"
2324
2325                 // not_called_function()
2326                 "%func_not_called_func  = OpFunction %void None %voidf\n"
2327                 "%not_called_func_entry = OpLabel\n"
2328                 "                         OpUnreachable\n" // Unreachable entry block in not called static function
2329                 "                         OpFunctionEnd\n"
2330
2331                 // modulo4()
2332                 "%func_modulo4  = OpFunction %u32 None %uintfuint\n"
2333                 "%valptr        = OpFunctionParameter %u32ptr\n"
2334                 "%modulo4_entry = OpLabel\n"
2335                 "%val           = OpLoad %u32 %valptr\n"
2336                 "%modulo        = OpUMod %u32 %val %four\n"
2337                 "                 OpSelectionMerge %switch_merge None\n"
2338                 "                 OpSwitch %modulo %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
2339                 "%case0         = OpLabel\n"
2340                 "                 OpReturnValue %three\n"
2341                 "%case1         = OpLabel\n"
2342                 "                 OpReturnValue %two\n"
2343                 "%case2         = OpLabel\n"
2344                 "                 OpReturnValue %one\n"
2345                 "%case3         = OpLabel\n"
2346                 "                 OpReturnValue %zero\n"
2347                 "%default       = OpLabel\n"
2348                 "                 OpUnreachable\n" // Unreachable default case for switch statement
2349                 "%switch_merge  = OpLabel\n"
2350                 "                 OpUnreachable\n" // Unreachable merge block for switch statement
2351                 "                 OpFunctionEnd\n"
2352
2353                 // const5()
2354                 "%func_const5  = OpFunction %u32 None %unitf\n"
2355                 "%const5_entry = OpLabel\n"
2356                 "                OpReturnValue %five\n"
2357                 "%unreachable  = OpLabel\n"
2358                 "                OpUnreachable\n" // Unreachable block in function
2359                 "                OpFunctionEnd\n";
2360         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
2361         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
2362         spec.numWorkGroups = IVec3(numElements, 1, 1);
2363
2364         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpUnreachable appearing at different places", spec));
2365
2366         return group.release();
2367 }
2368
2369 // Assembly code used for testing decoration group is based on GLSL source code:
2370 //
2371 // #version 430
2372 //
2373 // layout(std140, set = 0, binding = 0) readonly buffer Input0 {
2374 //   float elements[];
2375 // } input_data0;
2376 // layout(std140, set = 0, binding = 1) readonly buffer Input1 {
2377 //   float elements[];
2378 // } input_data1;
2379 // layout(std140, set = 0, binding = 2) readonly buffer Input2 {
2380 //   float elements[];
2381 // } input_data2;
2382 // layout(std140, set = 0, binding = 3) readonly buffer Input3 {
2383 //   float elements[];
2384 // } input_data3;
2385 // layout(std140, set = 0, binding = 4) readonly buffer Input4 {
2386 //   float elements[];
2387 // } input_data4;
2388 // layout(std140, set = 0, binding = 5) writeonly buffer Output {
2389 //   float elements[];
2390 // } output_data;
2391 //
2392 // void main() {
2393 //   uint x = gl_GlobalInvocationID.x;
2394 //   output_data.elements[x] = input_data0.elements[x] + input_data1.elements[x] + input_data2.elements[x] + input_data3.elements[x] + input_data4.elements[x];
2395 // }
2396 tcu::TestCaseGroup* createDecorationGroupGroup (tcu::TestContext& testCtx)
2397 {
2398         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "decoration_group", "Test the OpDecorationGroup & OpGroupDecorate instruction"));
2399         ComputeShaderSpec                               spec;
2400         de::Random                                              rnd                             (deStringHash(group->getName()));
2401         const int                                               numElements             = 100;
2402         vector<float>                                   inputFloats0    (numElements, 0);
2403         vector<float>                                   inputFloats1    (numElements, 0);
2404         vector<float>                                   inputFloats2    (numElements, 0);
2405         vector<float>                                   inputFloats3    (numElements, 0);
2406         vector<float>                                   inputFloats4    (numElements, 0);
2407         vector<float>                                   outputFloats    (numElements, 0);
2408
2409         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats0[0], numElements);
2410         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats1[0], numElements);
2411         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats2[0], numElements);
2412         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats3[0], numElements);
2413         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats4[0], numElements);
2414
2415         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2416         floorAll(inputFloats0);
2417         floorAll(inputFloats1);
2418         floorAll(inputFloats2);
2419         floorAll(inputFloats3);
2420         floorAll(inputFloats4);
2421
2422         for (size_t ndx = 0; ndx < numElements; ++ndx)
2423                 outputFloats[ndx] = inputFloats0[ndx] + inputFloats1[ndx] + inputFloats2[ndx] + inputFloats3[ndx] + inputFloats4[ndx];
2424
2425         spec.assembly =
2426                 string(getComputeAsmShaderPreamble()) +
2427
2428                 "OpSource GLSL 430\n"
2429                 "OpName %main \"main\"\n"
2430                 "OpName %id \"gl_GlobalInvocationID\"\n"
2431
2432                 // Not using group decoration on variable.
2433                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2434                 // Not using group decoration on type.
2435                 "OpDecorate %f32arr ArrayStride 4\n"
2436
2437                 "OpDecorate %groups BufferBlock\n"
2438                 "OpDecorate %groupm Offset 0\n"
2439                 "%groups = OpDecorationGroup\n"
2440                 "%groupm = OpDecorationGroup\n"
2441
2442                 // Group decoration on multiple structs.
2443                 "OpGroupDecorate %groups %outbuf %inbuf0 %inbuf1 %inbuf2 %inbuf3 %inbuf4\n"
2444                 // Group decoration on multiple struct members.
2445                 "OpGroupMemberDecorate %groupm %outbuf 0 %inbuf0 0 %inbuf1 0 %inbuf2 0 %inbuf3 0 %inbuf4 0\n"
2446
2447                 "OpDecorate %group1 DescriptorSet 0\n"
2448                 "OpDecorate %group3 DescriptorSet 0\n"
2449                 "OpDecorate %group3 NonWritable\n"
2450                 "OpDecorate %group3 Restrict\n"
2451                 "%group0 = OpDecorationGroup\n"
2452                 "%group1 = OpDecorationGroup\n"
2453                 "%group3 = OpDecorationGroup\n"
2454
2455                 // Applying the same decoration group multiple times.
2456                 "OpGroupDecorate %group1 %outdata\n"
2457                 "OpGroupDecorate %group1 %outdata\n"
2458                 "OpGroupDecorate %group1 %outdata\n"
2459                 "OpDecorate %outdata DescriptorSet 0\n"
2460                 "OpDecorate %outdata Binding 5\n"
2461                 // Applying decoration group containing nothing.
2462                 "OpGroupDecorate %group0 %indata0\n"
2463                 "OpDecorate %indata0 DescriptorSet 0\n"
2464                 "OpDecorate %indata0 Binding 0\n"
2465                 // Applying decoration group containing one decoration.
2466                 "OpGroupDecorate %group1 %indata1\n"
2467                 "OpDecorate %indata1 Binding 1\n"
2468                 // Applying decoration group containing multiple decorations.
2469                 "OpGroupDecorate %group3 %indata2 %indata3\n"
2470                 "OpDecorate %indata2 Binding 2\n"
2471                 "OpDecorate %indata3 Binding 3\n"
2472                 // Applying multiple decoration groups (with overlapping).
2473                 "OpGroupDecorate %group0 %indata4\n"
2474                 "OpGroupDecorate %group1 %indata4\n"
2475                 "OpGroupDecorate %group3 %indata4\n"
2476                 "OpDecorate %indata4 Binding 4\n"
2477
2478                 + string(getComputeAsmCommonTypes()) +
2479
2480                 "%id   = OpVariable %uvec3ptr Input\n"
2481                 "%zero = OpConstant %i32 0\n"
2482
2483                 "%outbuf    = OpTypeStruct %f32arr\n"
2484                 "%outbufptr = OpTypePointer Uniform %outbuf\n"
2485                 "%outdata   = OpVariable %outbufptr Uniform\n"
2486                 "%inbuf0    = OpTypeStruct %f32arr\n"
2487                 "%inbuf0ptr = OpTypePointer Uniform %inbuf0\n"
2488                 "%indata0   = OpVariable %inbuf0ptr Uniform\n"
2489                 "%inbuf1    = OpTypeStruct %f32arr\n"
2490                 "%inbuf1ptr = OpTypePointer Uniform %inbuf1\n"
2491                 "%indata1   = OpVariable %inbuf1ptr Uniform\n"
2492                 "%inbuf2    = OpTypeStruct %f32arr\n"
2493                 "%inbuf2ptr = OpTypePointer Uniform %inbuf2\n"
2494                 "%indata2   = OpVariable %inbuf2ptr Uniform\n"
2495                 "%inbuf3    = OpTypeStruct %f32arr\n"
2496                 "%inbuf3ptr = OpTypePointer Uniform %inbuf3\n"
2497                 "%indata3   = OpVariable %inbuf3ptr Uniform\n"
2498                 "%inbuf4    = OpTypeStruct %f32arr\n"
2499                 "%inbufptr  = OpTypePointer Uniform %inbuf4\n"
2500                 "%indata4   = OpVariable %inbufptr Uniform\n"
2501
2502                 "%main   = OpFunction %void None %voidf\n"
2503                 "%label  = OpLabel\n"
2504                 "%idval  = OpLoad %uvec3 %id\n"
2505                 "%x      = OpCompositeExtract %u32 %idval 0\n"
2506                 "%inloc0 = OpAccessChain %f32ptr %indata0 %zero %x\n"
2507                 "%inloc1 = OpAccessChain %f32ptr %indata1 %zero %x\n"
2508                 "%inloc2 = OpAccessChain %f32ptr %indata2 %zero %x\n"
2509                 "%inloc3 = OpAccessChain %f32ptr %indata3 %zero %x\n"
2510                 "%inloc4 = OpAccessChain %f32ptr %indata4 %zero %x\n"
2511                 "%outloc = OpAccessChain %f32ptr %outdata %zero %x\n"
2512                 "%inval0 = OpLoad %f32 %inloc0\n"
2513                 "%inval1 = OpLoad %f32 %inloc1\n"
2514                 "%inval2 = OpLoad %f32 %inloc2\n"
2515                 "%inval3 = OpLoad %f32 %inloc3\n"
2516                 "%inval4 = OpLoad %f32 %inloc4\n"
2517                 "%add0   = OpFAdd %f32 %inval0 %inval1\n"
2518                 "%add1   = OpFAdd %f32 %add0 %inval2\n"
2519                 "%add2   = OpFAdd %f32 %add1 %inval3\n"
2520                 "%add    = OpFAdd %f32 %add2 %inval4\n"
2521                 "          OpStore %outloc %add\n"
2522                 "          OpReturn\n"
2523                 "          OpFunctionEnd\n";
2524         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats0)));
2525         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
2526         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
2527         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
2528         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
2529         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2530         spec.numWorkGroups = IVec3(numElements, 1, 1);
2531
2532         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "decoration group cases", spec));
2533
2534         return group.release();
2535 }
2536
2537 struct SpecConstantTwoIntCase
2538 {
2539         const char*             caseName;
2540         const char*             scDefinition0;
2541         const char*             scDefinition1;
2542         const char*             scResultType;
2543         const char*             scOperation;
2544         deInt32                 scActualValue0;
2545         deInt32                 scActualValue1;
2546         const char*             resultOperation;
2547         vector<deInt32> expectedOutput;
2548
2549                                         SpecConstantTwoIntCase (const char* name,
2550                                                                                         const char* definition0,
2551                                                                                         const char* definition1,
2552                                                                                         const char* resultType,
2553                                                                                         const char* operation,
2554                                                                                         deInt32 value0,
2555                                                                                         deInt32 value1,
2556                                                                                         const char* resultOp,
2557                                                                                         const vector<deInt32>& output)
2558                                                 : caseName                      (name)
2559                                                 , scDefinition0         (definition0)
2560                                                 , scDefinition1         (definition1)
2561                                                 , scResultType          (resultType)
2562                                                 , scOperation           (operation)
2563                                                 , scActualValue0        (value0)
2564                                                 , scActualValue1        (value1)
2565                                                 , resultOperation       (resultOp)
2566                                                 , expectedOutput        (output) {}
2567 };
2568
2569 tcu::TestCaseGroup* createSpecConstantGroup (tcu::TestContext& testCtx)
2570 {
2571         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
2572         vector<SpecConstantTwoIntCase>  cases;
2573         de::Random                                              rnd                             (deStringHash(group->getName()));
2574         const int                                               numElements             = 100;
2575         vector<deInt32>                                 inputInts               (numElements, 0);
2576         vector<deInt32>                                 outputInts1             (numElements, 0);
2577         vector<deInt32>                                 outputInts2             (numElements, 0);
2578         vector<deInt32>                                 outputInts3             (numElements, 0);
2579         vector<deInt32>                                 outputInts4             (numElements, 0);
2580         const StringTemplate                    shaderTemplate  (
2581                 "${CAPABILITIES:opt}"
2582                 + string(getComputeAsmShaderPreamble()) +
2583
2584                 "OpName %main           \"main\"\n"
2585                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2586
2587                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2588                 "OpDecorate %sc_0  SpecId 0\n"
2589                 "OpDecorate %sc_1  SpecId 1\n"
2590                 "OpDecorate %i32arr ArrayStride 4\n"
2591
2592                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2593
2594                 "${OPTYPE_DEFINITIONS:opt}"
2595                 "%buf     = OpTypeStruct %i32arr\n"
2596                 "%bufptr  = OpTypePointer Uniform %buf\n"
2597                 "%indata    = OpVariable %bufptr Uniform\n"
2598                 "%outdata   = OpVariable %bufptr Uniform\n"
2599
2600                 "%id        = OpVariable %uvec3ptr Input\n"
2601                 "%zero      = OpConstant %i32 0\n"
2602
2603                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
2604                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
2605                 "%sc_final  = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n"
2606
2607                 "%main      = OpFunction %void None %voidf\n"
2608                 "%label     = OpLabel\n"
2609                 "${TYPE_CONVERT:opt}"
2610                 "%idval     = OpLoad %uvec3 %id\n"
2611                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2612                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
2613                 "%inval     = OpLoad %i32 %inloc\n"
2614                 "%final     = ${GEN_RESULT}\n"
2615                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2616                 "             OpStore %outloc %final\n"
2617                 "             OpReturn\n"
2618                 "             OpFunctionEnd\n");
2619
2620         fillRandomScalars(rnd, -65536, 65536, &inputInts[0], numElements);
2621
2622         for (size_t ndx = 0; ndx < numElements; ++ndx)
2623         {
2624                 outputInts1[ndx] = inputInts[ndx] + 42;
2625                 outputInts2[ndx] = inputInts[ndx];
2626                 outputInts3[ndx] = inputInts[ndx] - 11200;
2627                 outputInts4[ndx] = inputInts[ndx] + 1;
2628         }
2629
2630         const char addScToInput[]               = "OpIAdd %i32 %inval %sc_final";
2631         const char addSc32ToInput[]             = "OpIAdd %i32 %inval %sc_final32";
2632         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_final %inval %zero";
2633         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_final %zero %inval";
2634
2635         cases.push_back(SpecConstantTwoIntCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                     62,             -20,    addScToInput,           outputInts1));
2636         cases.push_back(SpecConstantTwoIntCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                     100,    58,             addScToInput,           outputInts1));
2637         cases.push_back(SpecConstantTwoIntCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                     -2,             -21,    addScToInput,           outputInts1));
2638         cases.push_back(SpecConstantTwoIntCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                     -126,   -3,             addScToInput,           outputInts1));
2639         cases.push_back(SpecConstantTwoIntCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                     126,    3,              addScToInput,           outputInts1));
2640         cases.push_back(SpecConstantTwoIntCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
2641         cases.push_back(SpecConstantTwoIntCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
2642         cases.push_back(SpecConstantTwoIntCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                     342,    50,             addScToInput,           outputInts1));
2643         cases.push_back(SpecConstantTwoIntCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                     42,             63,             addScToInput,           outputInts1));
2644         cases.push_back(SpecConstantTwoIntCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                     34,             8,              addScToInput,           outputInts1));
2645         cases.push_back(SpecConstantTwoIntCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                     18,             56,             addScToInput,           outputInts1));
2646         cases.push_back(SpecConstantTwoIntCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
2647         cases.push_back(SpecConstantTwoIntCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
2648         cases.push_back(SpecConstantTwoIntCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                     21,             1,              addScToInput,           outputInts1));
2649         cases.push_back(SpecConstantTwoIntCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                     -20,    -10,    selectTrueUsingSc,      outputInts2));
2650         cases.push_back(SpecConstantTwoIntCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                     10,             20,             selectTrueUsingSc,      outputInts2));
2651         cases.push_back(SpecConstantTwoIntCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
2652         cases.push_back(SpecConstantTwoIntCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                     10,             5,              selectTrueUsingSc,      outputInts2));
2653         cases.push_back(SpecConstantTwoIntCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                     -10,    -10,    selectTrueUsingSc,      outputInts2));
2654         cases.push_back(SpecConstantTwoIntCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                     50,             100,    selectTrueUsingSc,      outputInts2));
2655         cases.push_back(SpecConstantTwoIntCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
2656         cases.push_back(SpecConstantTwoIntCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                     10,             10,             selectTrueUsingSc,      outputInts2));
2657         cases.push_back(SpecConstantTwoIntCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                     42,             24,             selectFalseUsingSc,     outputInts2));
2658         cases.push_back(SpecConstantTwoIntCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
2659         cases.push_back(SpecConstantTwoIntCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
2660         cases.push_back(SpecConstantTwoIntCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
2661         cases.push_back(SpecConstantTwoIntCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
2662         cases.push_back(SpecConstantTwoIntCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                           -42,    0,              addScToInput,           outputInts1));
2663         cases.push_back(SpecConstantTwoIntCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                           -43,    0,              addScToInput,           outputInts1));
2664         cases.push_back(SpecConstantTwoIntCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                           1,              0,              selectFalseUsingSc,     outputInts2));
2665         cases.push_back(SpecConstantTwoIntCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %zero",       1,              42,             addScToInput,           outputInts1));
2666         cases.push_back(SpecConstantTwoIntCase("sconvert",                              " %i32 0",              " %i32 0",              "%i16",         "SConvert             %sc_0",                           -11200, 0,              addSc32ToInput,         outputInts3));
2667         // -969998336 stored as 32-bit two's complement is the binary representation of -11200 as IEEE-754 Float
2668         cases.push_back(SpecConstantTwoIntCase("fconvert",                              " %f32 0",              " %f32 0",              "%f64",         "FConvert             %sc_0",                           -969998336, 0,  addSc32ToInput,         outputInts3));
2669
2670         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
2671         {
2672                 map<string, string>             specializations;
2673                 ComputeShaderSpec               spec;
2674                 ComputeTestFeatures             features = COMPUTE_TEST_USES_NONE;
2675
2676                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
2677                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
2678                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
2679                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
2680                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
2681
2682                 // Special SPIR-V code for SConvert-case
2683                 if (strcmp(cases[caseNdx].caseName, "sconvert") == 0)
2684                 {
2685                         features                                                                = COMPUTE_TEST_USES_INT16;
2686                         specializations["CAPABILITIES"]                 = "OpCapability Int16\n";                                                       // Adds 16-bit integer capability
2687                         specializations["OPTYPE_DEFINITIONS"]   = "%i16 = OpTypeInt 16 1\n";                                            // Adds 16-bit integer type
2688                         specializations["TYPE_CONVERT"]                 = "%sc_final32 = OpSConvert %i32 %sc_final\n";          // Converts 16-bit integer to 32-bit integer
2689                 }
2690
2691                 // Special SPIR-V code for FConvert-case
2692                 if (strcmp(cases[caseNdx].caseName, "fconvert") == 0)
2693                 {
2694                         features                                                                = COMPUTE_TEST_USES_FLOAT64;
2695                         specializations["CAPABILITIES"]                 = "OpCapability Float64\n";                                                     // Adds 64-bit float capability
2696                         specializations["OPTYPE_DEFINITIONS"]   = "%f64 = OpTypeFloat 64\n";                                            // Adds 64-bit float type
2697                         specializations["TYPE_CONVERT"]                 = "%sc_final32 = OpConvertFToS %i32 %sc_final\n";       // Converts 64-bit float to 32-bit integer
2698                 }
2699
2700                 spec.assembly = shaderTemplate.specialize(specializations);
2701                 spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
2702                 spec.outputs.push_back(BufferSp(new Int32Buffer(cases[caseNdx].expectedOutput)));
2703                 spec.numWorkGroups = IVec3(numElements, 1, 1);
2704                 spec.specConstants.push_back(cases[caseNdx].scActualValue0);
2705                 spec.specConstants.push_back(cases[caseNdx].scActualValue1);
2706
2707                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].caseName, cases[caseNdx].caseName, spec, features));
2708         }
2709
2710         ComputeShaderSpec                               spec;
2711
2712         spec.assembly =
2713                 string(getComputeAsmShaderPreamble()) +
2714
2715                 "OpName %main           \"main\"\n"
2716                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2717
2718                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2719                 "OpDecorate %sc_0  SpecId 0\n"
2720                 "OpDecorate %sc_1  SpecId 1\n"
2721                 "OpDecorate %sc_2  SpecId 2\n"
2722                 "OpDecorate %i32arr ArrayStride 4\n"
2723
2724                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2725
2726                 "%ivec3       = OpTypeVector %i32 3\n"
2727                 "%buf         = OpTypeStruct %i32arr\n"
2728                 "%bufptr      = OpTypePointer Uniform %buf\n"
2729                 "%indata      = OpVariable %bufptr Uniform\n"
2730                 "%outdata     = OpVariable %bufptr Uniform\n"
2731
2732                 "%id          = OpVariable %uvec3ptr Input\n"
2733                 "%zero        = OpConstant %i32 0\n"
2734                 "%ivec3_0     = OpConstantComposite %ivec3 %zero %zero %zero\n"
2735                 "%vec3_undef  = OpUndef %ivec3\n"
2736
2737                 "%sc_0        = OpSpecConstant %i32 0\n"
2738                 "%sc_1        = OpSpecConstant %i32 0\n"
2739                 "%sc_2        = OpSpecConstant %i32 0\n"
2740                 "%sc_vec3_0   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_0        %ivec3_0     0\n"                                                 // (sc_0, 0, 0)
2741                 "%sc_vec3_1   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_1        %ivec3_0     1\n"                                                 // (0, sc_1, 0)
2742                 "%sc_vec3_2   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_2        %ivec3_0     2\n"                                                 // (0, 0, sc_2)
2743                 "%sc_vec3_0_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0   %vec3_undef  0          0xFFFFFFFF 2\n"   // (sc_0, ???,  0)
2744                 "%sc_vec3_1_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_1   %vec3_undef  0xFFFFFFFF 1          0\n"   // (???,  sc_1, 0)
2745                 "%sc_vec3_2_s = OpSpecConstantOp %ivec3 VectorShuffle    %vec3_undef  %sc_vec3_2   5          0xFFFFFFFF 5\n"   // (sc_2, ???,  sc_2)
2746                 "%sc_vec3_01  = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0_s %sc_vec3_1_s 1 0 4\n"                                             // (0,    sc_0, sc_1)
2747                 "%sc_vec3_012 = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_01  %sc_vec3_2_s 5 1 2\n"                                             // (sc_2, sc_0, sc_1)
2748                 "%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              0\n"                                                 // sc_2
2749                 "%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              1\n"                                                 // sc_0
2750                 "%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              2\n"                                                 // sc_1
2751                 "%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"                                                              // (sc_2 - sc_0)
2752                 "%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n"                                                              // (sc_2 - sc_0) * sc_1
2753
2754                 "%main      = OpFunction %void None %voidf\n"
2755                 "%label     = OpLabel\n"
2756                 "%idval     = OpLoad %uvec3 %id\n"
2757                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2758                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
2759                 "%inval     = OpLoad %i32 %inloc\n"
2760                 "%final     = OpIAdd %i32 %inval %sc_final\n"
2761                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2762                 "             OpStore %outloc %final\n"
2763                 "             OpReturn\n"
2764                 "             OpFunctionEnd\n";
2765         spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
2766         spec.outputs.push_back(BufferSp(new Int32Buffer(outputInts3)));
2767         spec.numWorkGroups = IVec3(numElements, 1, 1);
2768         spec.specConstants.push_back(123);
2769         spec.specConstants.push_back(56);
2770         spec.specConstants.push_back(-77);
2771
2772         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector_related", "VectorShuffle, CompositeExtract, & CompositeInsert", spec));
2773
2774         return group.release();
2775 }
2776
2777 void createOpPhiVartypeTests (de::MovePtr<tcu::TestCaseGroup>& group, tcu::TestContext& testCtx)
2778 {
2779         ComputeShaderSpec       specInt;
2780         ComputeShaderSpec       specFloat;
2781         ComputeShaderSpec       specVec3;
2782         ComputeShaderSpec       specMat4;
2783         ComputeShaderSpec       specArray;
2784         ComputeShaderSpec       specStruct;
2785         de::Random                      rnd                             (deStringHash(group->getName()));
2786         const int                       numElements             = 100;
2787         vector<float>           inputFloats             (numElements, 0);
2788         vector<float>           outputFloats    (numElements, 0);
2789
2790         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
2791
2792         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2793         floorAll(inputFloats);
2794
2795         for (size_t ndx = 0; ndx < numElements; ++ndx)
2796         {
2797                 // Just check if the value is positive or not
2798                 outputFloats[ndx] = (inputFloats[ndx] > 0) ? 1.0f : -1.0f;
2799         }
2800
2801         // All of the tests are of the form:
2802         //
2803         // testtype r
2804         //
2805         // if (inputdata > 0)
2806         //   r = 1
2807         // else
2808         //   r = -1
2809         //
2810         // return (float)r
2811
2812         specFloat.assembly =
2813                 string(getComputeAsmShaderPreamble()) +
2814
2815                 "OpSource GLSL 430\n"
2816                 "OpName %main \"main\"\n"
2817                 "OpName %id \"gl_GlobalInvocationID\"\n"
2818
2819                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2820
2821                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2822
2823                 "%id = OpVariable %uvec3ptr Input\n"
2824                 "%zero       = OpConstant %i32 0\n"
2825                 "%float_0    = OpConstant %f32 0.0\n"
2826                 "%float_1    = OpConstant %f32 1.0\n"
2827                 "%float_n1   = OpConstant %f32 -1.0\n"
2828
2829                 "%main     = OpFunction %void None %voidf\n"
2830                 "%entry    = OpLabel\n"
2831                 "%idval    = OpLoad %uvec3 %id\n"
2832                 "%x        = OpCompositeExtract %u32 %idval 0\n"
2833                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
2834                 "%inval    = OpLoad %f32 %inloc\n"
2835
2836                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
2837                 "            OpSelectionMerge %cm None\n"
2838                 "            OpBranchConditional %comp %tb %fb\n"
2839                 "%tb       = OpLabel\n"
2840                 "            OpBranch %cm\n"
2841                 "%fb       = OpLabel\n"
2842                 "            OpBranch %cm\n"
2843                 "%cm       = OpLabel\n"
2844                 "%res      = OpPhi %f32 %float_1 %tb %float_n1 %fb\n"
2845
2846                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
2847                 "            OpStore %outloc %res\n"
2848                 "            OpReturn\n"
2849
2850                 "            OpFunctionEnd\n";
2851         specFloat.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2852         specFloat.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2853         specFloat.numWorkGroups = IVec3(numElements, 1, 1);
2854
2855         specMat4.assembly =
2856                 string(getComputeAsmShaderPreamble()) +
2857
2858                 "OpSource GLSL 430\n"
2859                 "OpName %main \"main\"\n"
2860                 "OpName %id \"gl_GlobalInvocationID\"\n"
2861
2862                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2863
2864                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2865
2866                 "%id = OpVariable %uvec3ptr Input\n"
2867                 "%v4f32      = OpTypeVector %f32 4\n"
2868                 "%mat4v4f32  = OpTypeMatrix %v4f32 4\n"
2869                 "%zero       = OpConstant %i32 0\n"
2870                 "%float_0    = OpConstant %f32 0.0\n"
2871                 "%float_1    = OpConstant %f32 1.0\n"
2872                 "%float_n1   = OpConstant %f32 -1.0\n"
2873                 "%m11        = OpConstantComposite %v4f32 %float_1 %float_0 %float_0 %float_0\n"
2874                 "%m12        = OpConstantComposite %v4f32 %float_0 %float_1 %float_0 %float_0\n"
2875                 "%m13        = OpConstantComposite %v4f32 %float_0 %float_0 %float_1 %float_0\n"
2876                 "%m14        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_1\n"
2877                 "%m1         = OpConstantComposite %mat4v4f32 %m11 %m12 %m13 %m14\n"
2878                 "%m21        = OpConstantComposite %v4f32 %float_n1 %float_0 %float_0 %float_0\n"
2879                 "%m22        = OpConstantComposite %v4f32 %float_0 %float_n1 %float_0 %float_0\n"
2880                 "%m23        = OpConstantComposite %v4f32 %float_0 %float_0 %float_n1 %float_0\n"
2881                 "%m24        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_n1\n"
2882                 "%m2         = OpConstantComposite %mat4v4f32 %m21 %m22 %m23 %m24\n"
2883
2884                 "%main     = OpFunction %void None %voidf\n"
2885                 "%entry    = OpLabel\n"
2886                 "%idval    = OpLoad %uvec3 %id\n"
2887                 "%x        = OpCompositeExtract %u32 %idval 0\n"
2888                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
2889                 "%inval    = OpLoad %f32 %inloc\n"
2890
2891                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
2892                 "            OpSelectionMerge %cm None\n"
2893                 "            OpBranchConditional %comp %tb %fb\n"
2894                 "%tb       = OpLabel\n"
2895                 "            OpBranch %cm\n"
2896                 "%fb       = OpLabel\n"
2897                 "            OpBranch %cm\n"
2898                 "%cm       = OpLabel\n"
2899                 "%mres     = OpPhi %mat4v4f32 %m1 %tb %m2 %fb\n"
2900                 "%res      = OpCompositeExtract %f32 %mres 2 2\n"
2901
2902                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
2903                 "            OpStore %outloc %res\n"
2904                 "            OpReturn\n"
2905
2906                 "            OpFunctionEnd\n";
2907         specMat4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2908         specMat4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2909         specMat4.numWorkGroups = IVec3(numElements, 1, 1);
2910
2911         specVec3.assembly =
2912                 string(getComputeAsmShaderPreamble()) +
2913
2914                 "OpSource GLSL 430\n"
2915                 "OpName %main \"main\"\n"
2916                 "OpName %id \"gl_GlobalInvocationID\"\n"
2917
2918                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2919
2920                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2921
2922                 "%id = OpVariable %uvec3ptr Input\n"
2923                 "%zero       = OpConstant %i32 0\n"
2924                 "%float_0    = OpConstant %f32 0.0\n"
2925                 "%float_1    = OpConstant %f32 1.0\n"
2926                 "%float_n1   = OpConstant %f32 -1.0\n"
2927                 "%v1         = OpConstantComposite %fvec3 %float_1 %float_1 %float_1\n"
2928                 "%v2         = OpConstantComposite %fvec3 %float_n1 %float_n1 %float_n1\n"
2929
2930                 "%main     = OpFunction %void None %voidf\n"
2931                 "%entry    = OpLabel\n"
2932                 "%idval    = OpLoad %uvec3 %id\n"
2933                 "%x        = OpCompositeExtract %u32 %idval 0\n"
2934                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
2935                 "%inval    = OpLoad %f32 %inloc\n"
2936
2937                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
2938                 "            OpSelectionMerge %cm None\n"
2939                 "            OpBranchConditional %comp %tb %fb\n"
2940                 "%tb       = OpLabel\n"
2941                 "            OpBranch %cm\n"
2942                 "%fb       = OpLabel\n"
2943                 "            OpBranch %cm\n"
2944                 "%cm       = OpLabel\n"
2945                 "%vres     = OpPhi %fvec3 %v1 %tb %v2 %fb\n"
2946                 "%res      = OpCompositeExtract %f32 %vres 2\n"
2947
2948                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
2949                 "            OpStore %outloc %res\n"
2950                 "            OpReturn\n"
2951
2952                 "            OpFunctionEnd\n";
2953         specVec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2954         specVec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2955         specVec3.numWorkGroups = IVec3(numElements, 1, 1);
2956
2957         specInt.assembly =
2958                 string(getComputeAsmShaderPreamble()) +
2959
2960                 "OpSource GLSL 430\n"
2961                 "OpName %main \"main\"\n"
2962                 "OpName %id \"gl_GlobalInvocationID\"\n"
2963
2964                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2965
2966                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2967
2968                 "%id = OpVariable %uvec3ptr Input\n"
2969                 "%zero       = OpConstant %i32 0\n"
2970                 "%float_0    = OpConstant %f32 0.0\n"
2971                 "%i1         = OpConstant %i32 1\n"
2972                 "%i2         = OpConstant %i32 -1\n"
2973
2974                 "%main     = OpFunction %void None %voidf\n"
2975                 "%entry    = OpLabel\n"
2976                 "%idval    = OpLoad %uvec3 %id\n"
2977                 "%x        = OpCompositeExtract %u32 %idval 0\n"
2978                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
2979                 "%inval    = OpLoad %f32 %inloc\n"
2980
2981                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
2982                 "            OpSelectionMerge %cm None\n"
2983                 "            OpBranchConditional %comp %tb %fb\n"
2984                 "%tb       = OpLabel\n"
2985                 "            OpBranch %cm\n"
2986                 "%fb       = OpLabel\n"
2987                 "            OpBranch %cm\n"
2988                 "%cm       = OpLabel\n"
2989                 "%ires     = OpPhi %i32 %i1 %tb %i2 %fb\n"
2990                 "%res      = OpConvertSToF %f32 %ires\n"
2991
2992                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
2993                 "            OpStore %outloc %res\n"
2994                 "            OpReturn\n"
2995
2996                 "            OpFunctionEnd\n";
2997         specInt.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2998         specInt.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2999         specInt.numWorkGroups = IVec3(numElements, 1, 1);
3000
3001         specArray.assembly =
3002                 string(getComputeAsmShaderPreamble()) +
3003
3004                 "OpSource GLSL 430\n"
3005                 "OpName %main \"main\"\n"
3006                 "OpName %id \"gl_GlobalInvocationID\"\n"
3007
3008                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3009
3010                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3011
3012                 "%id = OpVariable %uvec3ptr Input\n"
3013                 "%zero       = OpConstant %i32 0\n"
3014                 "%u7         = OpConstant %u32 7\n"
3015                 "%float_0    = OpConstant %f32 0.0\n"
3016                 "%float_1    = OpConstant %f32 1.0\n"
3017                 "%float_n1   = OpConstant %f32 -1.0\n"
3018                 "%f32a7      = OpTypeArray %f32 %u7\n"
3019                 "%a1         = OpConstantComposite %f32a7 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1\n"
3020                 "%a2         = OpConstantComposite %f32a7 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1\n"
3021                 "%main     = OpFunction %void None %voidf\n"
3022                 "%entry    = OpLabel\n"
3023                 "%idval    = OpLoad %uvec3 %id\n"
3024                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3025                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3026                 "%inval    = OpLoad %f32 %inloc\n"
3027
3028                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3029                 "            OpSelectionMerge %cm None\n"
3030                 "            OpBranchConditional %comp %tb %fb\n"
3031                 "%tb       = OpLabel\n"
3032                 "            OpBranch %cm\n"
3033                 "%fb       = OpLabel\n"
3034                 "            OpBranch %cm\n"
3035                 "%cm       = OpLabel\n"
3036                 "%ares     = OpPhi %f32a7 %a1 %tb %a2 %fb\n"
3037                 "%res      = OpCompositeExtract %f32 %ares 5\n"
3038
3039                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3040                 "            OpStore %outloc %res\n"
3041                 "            OpReturn\n"
3042
3043                 "            OpFunctionEnd\n";
3044         specArray.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3045         specArray.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3046         specArray.numWorkGroups = IVec3(numElements, 1, 1);
3047
3048         specStruct.assembly =
3049                 string(getComputeAsmShaderPreamble()) +
3050
3051                 "OpSource GLSL 430\n"
3052                 "OpName %main \"main\"\n"
3053                 "OpName %id \"gl_GlobalInvocationID\"\n"
3054
3055                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3056
3057                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3058
3059                 "%id = OpVariable %uvec3ptr Input\n"
3060                 "%zero       = OpConstant %i32 0\n"
3061                 "%float_0    = OpConstant %f32 0.0\n"
3062                 "%float_1    = OpConstant %f32 1.0\n"
3063                 "%float_n1   = OpConstant %f32 -1.0\n"
3064
3065                 "%v2f32      = OpTypeVector %f32 2\n"
3066                 "%Data2      = OpTypeStruct %f32 %v2f32\n"
3067                 "%Data       = OpTypeStruct %Data2 %f32\n"
3068
3069                 "%in1a       = OpConstantComposite %v2f32 %float_1 %float_1\n"
3070                 "%in1b       = OpConstantComposite %Data2 %float_1 %in1a\n"
3071                 "%s1         = OpConstantComposite %Data %in1b %float_1\n"
3072                 "%in2a       = OpConstantComposite %v2f32 %float_n1 %float_n1\n"
3073                 "%in2b       = OpConstantComposite %Data2 %float_n1 %in2a\n"
3074                 "%s2         = OpConstantComposite %Data %in2b %float_n1\n"
3075
3076                 "%main     = OpFunction %void None %voidf\n"
3077                 "%entry    = OpLabel\n"
3078                 "%idval    = OpLoad %uvec3 %id\n"
3079                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3080                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3081                 "%inval    = OpLoad %f32 %inloc\n"
3082
3083                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3084                 "            OpSelectionMerge %cm None\n"
3085                 "            OpBranchConditional %comp %tb %fb\n"
3086                 "%tb       = OpLabel\n"
3087                 "            OpBranch %cm\n"
3088                 "%fb       = OpLabel\n"
3089                 "            OpBranch %cm\n"
3090                 "%cm       = OpLabel\n"
3091                 "%sres     = OpPhi %Data %s1 %tb %s2 %fb\n"
3092                 "%res      = OpCompositeExtract %f32 %sres 0 0\n"
3093
3094                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3095                 "            OpStore %outloc %res\n"
3096                 "            OpReturn\n"
3097
3098                 "            OpFunctionEnd\n";
3099         specStruct.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3100         specStruct.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3101         specStruct.numWorkGroups = IVec3(numElements, 1, 1);
3102
3103         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_int", "OpPhi with int variables", specInt));
3104         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_float", "OpPhi with float variables", specFloat));
3105         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_vec3", "OpPhi with vec3 variables", specVec3));
3106         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_mat4", "OpPhi with mat4 variables", specMat4));
3107         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_array", "OpPhi with array variables", specArray));
3108         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_struct", "OpPhi with struct variables", specStruct));
3109 }
3110
3111 string generateConstantDefinitions (int count)
3112 {
3113         std::ostringstream      r;
3114         for (int i = 0; i < count; i++)
3115                 r << "%cf" << (i * 10 + 5) << " = OpConstant %f32 " <<(i * 10 + 5) << ".0\n";
3116         r << "\n";
3117         return r.str();
3118 }
3119
3120 string generateSwitchCases (int count)
3121 {
3122         std::ostringstream      r;
3123         for (int i = 0; i < count; i++)
3124                 r << " " << i << " %case" << i;
3125         r << "\n";
3126         return r.str();
3127 }
3128
3129 string generateSwitchTargets (int count)
3130 {
3131         std::ostringstream      r;
3132         for (int i = 0; i < count; i++)
3133                 r << "%case" << i << " = OpLabel\n            OpBranch %phi\n";
3134         r << "\n";
3135         return r.str();
3136 }
3137
3138 string generateOpPhiParams (int count)
3139 {
3140         std::ostringstream      r;
3141         for (int i = 0; i < count; i++)
3142                 r << " %cf" << (i * 10 + 5) << " %case" << i;
3143         r << "\n";
3144         return r.str();
3145 }
3146
3147 string generateIntWidth (int value)
3148 {
3149         std::ostringstream      r;
3150         r << value;
3151         return r.str();
3152 }
3153
3154 // Expand input string by injecting "ABC" between the input
3155 // string characters. The acc/add/treshold parameters are used
3156 // to skip some of the injections to make the result less
3157 // uniform (and a lot shorter).
3158 string expandOpPhiCase5 (const string& s, int &acc, int add, int treshold)
3159 {
3160         std::ostringstream      res;
3161         const char*                     p = s.c_str();
3162
3163         while (*p)
3164         {
3165                 res << *p;
3166                 acc += add;
3167                 if (acc > treshold)
3168                 {
3169                         acc -= treshold;
3170                         res << "ABC";
3171                 }
3172                 p++;
3173         }
3174         return res.str();
3175 }
3176
3177 // Calculate expected result based on the code string
3178 float calcOpPhiCase5 (float val, const string& s)
3179 {
3180         const char*             p               = s.c_str();
3181         float                   x[8];
3182         bool                    b[8];
3183         const float             tv[8]   = { 0.5f, 1.5f, 3.5f, 7.5f, 15.5f, 31.5f, 63.5f, 127.5f };
3184         const float             v               = deFloatAbs(val);
3185         float                   res             = 0;
3186         int                             depth   = -1;
3187         int                             skip    = 0;
3188
3189         for (int i = 7; i >= 0; --i)
3190                 x[i] = std::fmod((float)v, (float)(2 << i));
3191         for (int i = 7; i >= 0; --i)
3192                 b[i] = x[i] > tv[i];
3193
3194         while (*p)
3195         {
3196                 if (*p == 'A')
3197                 {
3198                         depth++;
3199                         if (skip == 0 && b[depth])
3200                         {
3201                                 res++;
3202                         }
3203                         else
3204                                 skip++;
3205                 }
3206                 if (*p == 'B')
3207                 {
3208                         if (skip)
3209                                 skip--;
3210                         if (b[depth] || skip)
3211                                 skip++;
3212                 }
3213                 if (*p == 'C')
3214                 {
3215                         depth--;
3216                         if (skip)
3217                                 skip--;
3218                 }
3219                 p++;
3220         }
3221         return res;
3222 }
3223
3224 // In the code string, the letters represent the following:
3225 //
3226 // A:
3227 //     if (certain bit is set)
3228 //     {
3229 //       result++;
3230 //
3231 // B:
3232 //     } else {
3233 //
3234 // C:
3235 //     }
3236 //
3237 // examples:
3238 // AABCBC leads to if(){r++;if(){r++;}else{}}else{}
3239 // ABABCC leads to if(){r++;}else{if(){r++;}else{}}
3240 // ABCABC leads to if(){r++;}else{}if(){r++;}else{}
3241 //
3242 // Code generation gets a bit complicated due to the else-branches,
3243 // which do not generate new values. Thus, the generator needs to
3244 // keep track of the previous variable change seen by the else
3245 // branch.
3246 string generateOpPhiCase5 (const string& s)
3247 {
3248         std::stack<int>                         idStack;
3249         std::stack<std::string>         value;
3250         std::stack<std::string>         valueLabel;
3251         std::stack<std::string>         mergeLeft;
3252         std::stack<std::string>         mergeRight;
3253         std::ostringstream                      res;
3254         const char*                                     p                       = s.c_str();
3255         int                                                     depth           = -1;
3256         int                                                     currId          = 0;
3257         int                                                     iter            = 0;
3258
3259         idStack.push(-1);
3260         value.push("%f32_0");
3261         valueLabel.push("%f32_0 %entry");
3262
3263         while (*p)
3264         {
3265                 if (*p == 'A')
3266                 {
3267                         depth++;
3268                         currId = iter;
3269                         idStack.push(currId);
3270                         res << "\tOpSelectionMerge %m" << currId << " None\n";
3271                         res << "\tOpBranchConditional %b" << depth << " %t" << currId << " %f" << currId << "\n";
3272                         res << "%t" << currId << " = OpLabel\n";
3273                         res << "%rt" << currId << " = OpFAdd %f32 " << value.top() << " %f32_1\n";
3274                         std::ostringstream tag;
3275                         tag << "%rt" << currId;
3276                         value.push(tag.str());
3277                         tag << " %t" << currId;
3278                         valueLabel.push(tag.str());
3279                 }
3280
3281                 if (*p == 'B')
3282                 {
3283                         mergeLeft.push(valueLabel.top());
3284                         value.pop();
3285                         valueLabel.pop();
3286                         res << "\tOpBranch %m" << currId << "\n";
3287                         res << "%f" << currId << " = OpLabel\n";
3288                         std::ostringstream tag;
3289                         tag << value.top() << " %f" << currId;
3290                         valueLabel.pop();
3291                         valueLabel.push(tag.str());
3292                 }
3293
3294                 if (*p == 'C')
3295                 {
3296                         mergeRight.push(valueLabel.top());
3297                         res << "\tOpBranch %m" << currId << "\n";
3298                         res << "%m" << currId << " = OpLabel\n";
3299                         if (*(p + 1) == 0)
3300                                 res << "%res"; // last result goes to %res
3301                         else
3302                                 res << "%rm" << currId;
3303                         res << " = OpPhi %f32  " << mergeLeft.top() << "  " << mergeRight.top() << "\n";
3304                         std::ostringstream tag;
3305                         tag << "%rm" << currId;
3306                         value.pop();
3307                         value.push(tag.str());
3308                         tag << " %m" << currId;
3309                         valueLabel.pop();
3310                         valueLabel.push(tag.str());
3311                         mergeLeft.pop();
3312                         mergeRight.pop();
3313                         depth--;
3314                         idStack.pop();
3315                         currId = idStack.top();
3316                 }
3317                 p++;
3318                 iter++;
3319         }
3320         return res.str();
3321 }
3322
3323 tcu::TestCaseGroup* createOpPhiGroup (tcu::TestContext& testCtx)
3324 {
3325         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
3326         ComputeShaderSpec                               spec1;
3327         ComputeShaderSpec                               spec2;
3328         ComputeShaderSpec                               spec3;
3329         ComputeShaderSpec                               spec4;
3330         ComputeShaderSpec                               spec5;
3331         de::Random                                              rnd                             (deStringHash(group->getName()));
3332         const int                                               numElements             = 100;
3333         vector<float>                                   inputFloats             (numElements, 0);
3334         vector<float>                                   outputFloats1   (numElements, 0);
3335         vector<float>                                   outputFloats2   (numElements, 0);
3336         vector<float>                                   outputFloats3   (numElements, 0);
3337         vector<float>                                   outputFloats4   (numElements, 0);
3338         vector<float>                                   outputFloats5   (numElements, 0);
3339         std::string                                             codestring              = "ABC";
3340         const int                                               test4Width              = 1024;
3341
3342         // Build case 5 code string. Each iteration makes the hierarchy more complicated.
3343         // 9 iterations with (7, 24) parameters makes the hierarchy 8 deep with about 1500 lines of
3344         // shader code.
3345         for (int i = 0, acc = 0; i < 9; i++)
3346                 codestring = expandOpPhiCase5(codestring, acc, 7, 24);
3347
3348         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
3349
3350         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3351         floorAll(inputFloats);
3352
3353         for (size_t ndx = 0; ndx < numElements; ++ndx)
3354         {
3355                 switch (ndx % 3)
3356                 {
3357                         case 0:         outputFloats1[ndx] = inputFloats[ndx] + 5.5f;   break;
3358                         case 1:         outputFloats1[ndx] = inputFloats[ndx] + 20.5f;  break;
3359                         case 2:         outputFloats1[ndx] = inputFloats[ndx] + 1.75f;  break;
3360                         default:        break;
3361                 }
3362                 outputFloats2[ndx] = inputFloats[ndx] + 6.5f * 3;
3363                 outputFloats3[ndx] = 8.5f - inputFloats[ndx];
3364
3365                 int index4 = (int)deFloor(deAbs((float)ndx * inputFloats[ndx]));
3366                 outputFloats4[ndx] = (float)(index4 % test4Width) * 10.0f + 5.0f;
3367
3368                 outputFloats5[ndx] = calcOpPhiCase5(inputFloats[ndx], codestring);
3369         }
3370
3371         spec1.assembly =
3372                 string(getComputeAsmShaderPreamble()) +
3373
3374                 "OpSource GLSL 430\n"
3375                 "OpName %main \"main\"\n"
3376                 "OpName %id \"gl_GlobalInvocationID\"\n"
3377
3378                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3379
3380                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3381
3382                 "%id = OpVariable %uvec3ptr Input\n"
3383                 "%zero       = OpConstant %i32 0\n"
3384                 "%three      = OpConstant %u32 3\n"
3385                 "%constf5p5  = OpConstant %f32 5.5\n"
3386                 "%constf20p5 = OpConstant %f32 20.5\n"
3387                 "%constf1p75 = OpConstant %f32 1.75\n"
3388                 "%constf8p5  = OpConstant %f32 8.5\n"
3389                 "%constf6p5  = OpConstant %f32 6.5\n"
3390
3391                 "%main     = OpFunction %void None %voidf\n"
3392                 "%entry    = OpLabel\n"
3393                 "%idval    = OpLoad %uvec3 %id\n"
3394                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3395                 "%selector = OpUMod %u32 %x %three\n"
3396                 "            OpSelectionMerge %phi None\n"
3397                 "            OpSwitch %selector %default 0 %case0 1 %case1 2 %case2\n"
3398
3399                 // Case 1 before OpPhi.
3400                 "%case1    = OpLabel\n"
3401                 "            OpBranch %phi\n"
3402
3403                 "%default  = OpLabel\n"
3404                 "            OpUnreachable\n"
3405
3406                 "%phi      = OpLabel\n"
3407                 "%operand  = OpPhi %f32   %constf1p75 %case2   %constf20p5 %case1   %constf5p5 %case0\n" // not in the order of blocks
3408                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3409                 "%inval    = OpLoad %f32 %inloc\n"
3410                 "%add      = OpFAdd %f32 %inval %operand\n"
3411                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3412                 "            OpStore %outloc %add\n"
3413                 "            OpReturn\n"
3414
3415                 // Case 0 after OpPhi.
3416                 "%case0    = OpLabel\n"
3417                 "            OpBranch %phi\n"
3418
3419
3420                 // Case 2 after OpPhi.
3421                 "%case2    = OpLabel\n"
3422                 "            OpBranch %phi\n"
3423
3424                 "            OpFunctionEnd\n";
3425         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3426         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
3427         spec1.numWorkGroups = IVec3(numElements, 1, 1);
3428
3429         group->addChild(new SpvAsmComputeShaderCase(testCtx, "block", "out-of-order and unreachable blocks for OpPhi", spec1));
3430
3431         spec2.assembly =
3432                 string(getComputeAsmShaderPreamble()) +
3433
3434                 "OpName %main \"main\"\n"
3435                 "OpName %id \"gl_GlobalInvocationID\"\n"
3436
3437                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3438
3439                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3440
3441                 "%id         = OpVariable %uvec3ptr Input\n"
3442                 "%zero       = OpConstant %i32 0\n"
3443                 "%one        = OpConstant %i32 1\n"
3444                 "%three      = OpConstant %i32 3\n"
3445                 "%constf6p5  = OpConstant %f32 6.5\n"
3446
3447                 "%main       = OpFunction %void None %voidf\n"
3448                 "%entry      = OpLabel\n"
3449                 "%idval      = OpLoad %uvec3 %id\n"
3450                 "%x          = OpCompositeExtract %u32 %idval 0\n"
3451                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3452                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3453                 "%inval      = OpLoad %f32 %inloc\n"
3454                 "              OpBranch %phi\n"
3455
3456                 "%phi        = OpLabel\n"
3457                 "%step       = OpPhi %i32 %zero  %entry %step_next  %phi\n"
3458                 "%accum      = OpPhi %f32 %inval %entry %accum_next %phi\n"
3459                 "%step_next  = OpIAdd %i32 %step %one\n"
3460                 "%accum_next = OpFAdd %f32 %accum %constf6p5\n"
3461                 "%still_loop = OpSLessThan %bool %step %three\n"
3462                 "              OpLoopMerge %exit %phi None\n"
3463                 "              OpBranchConditional %still_loop %phi %exit\n"
3464
3465                 "%exit       = OpLabel\n"
3466                 "              OpStore %outloc %accum\n"
3467                 "              OpReturn\n"
3468                 "              OpFunctionEnd\n";
3469         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3470         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
3471         spec2.numWorkGroups = IVec3(numElements, 1, 1);
3472
3473         group->addChild(new SpvAsmComputeShaderCase(testCtx, "induction", "The usual way induction variables are handled in LLVM IR", spec2));
3474
3475         spec3.assembly =
3476                 string(getComputeAsmShaderPreamble()) +
3477
3478                 "OpName %main \"main\"\n"
3479                 "OpName %id \"gl_GlobalInvocationID\"\n"
3480
3481                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3482
3483                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3484
3485                 "%f32ptr_f   = OpTypePointer Function %f32\n"
3486                 "%id         = OpVariable %uvec3ptr Input\n"
3487                 "%true       = OpConstantTrue %bool\n"
3488                 "%false      = OpConstantFalse %bool\n"
3489                 "%zero       = OpConstant %i32 0\n"
3490                 "%constf8p5  = OpConstant %f32 8.5\n"
3491
3492                 "%main       = OpFunction %void None %voidf\n"
3493                 "%entry      = OpLabel\n"
3494                 "%b          = OpVariable %f32ptr_f Function %constf8p5\n"
3495                 "%idval      = OpLoad %uvec3 %id\n"
3496                 "%x          = OpCompositeExtract %u32 %idval 0\n"
3497                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3498                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3499                 "%a_init     = OpLoad %f32 %inloc\n"
3500                 "%b_init     = OpLoad %f32 %b\n"
3501                 "              OpBranch %phi\n"
3502
3503                 "%phi        = OpLabel\n"
3504                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
3505                 "%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
3506                 "%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
3507                 "              OpLoopMerge %exit %phi None\n"
3508                 "              OpBranchConditional %still_loop %phi %exit\n"
3509
3510                 "%exit       = OpLabel\n"
3511                 "%sub        = OpFSub %f32 %a_next %b_next\n"
3512                 "              OpStore %outloc %sub\n"
3513                 "              OpReturn\n"
3514                 "              OpFunctionEnd\n";
3515         spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3516         spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
3517         spec3.numWorkGroups = IVec3(numElements, 1, 1);
3518
3519         group->addChild(new SpvAsmComputeShaderCase(testCtx, "swap", "Swap the values of two variables using OpPhi", spec3));
3520
3521         spec4.assembly =
3522                 "OpCapability Shader\n"
3523                 "%ext = OpExtInstImport \"GLSL.std.450\"\n"
3524                 "OpMemoryModel Logical GLSL450\n"
3525                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3526                 "OpExecutionMode %main LocalSize 1 1 1\n"
3527
3528                 "OpSource GLSL 430\n"
3529                 "OpName %main \"main\"\n"
3530                 "OpName %id \"gl_GlobalInvocationID\"\n"
3531
3532                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3533
3534                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3535
3536                 "%id       = OpVariable %uvec3ptr Input\n"
3537                 "%zero     = OpConstant %i32 0\n"
3538                 "%cimod    = OpConstant %u32 " + generateIntWidth(test4Width) + "\n"
3539
3540                 + generateConstantDefinitions(test4Width) +
3541
3542                 "%main     = OpFunction %void None %voidf\n"
3543                 "%entry    = OpLabel\n"
3544                 "%idval    = OpLoad %uvec3 %id\n"
3545                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3546                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3547                 "%inval    = OpLoad %f32 %inloc\n"
3548                 "%xf       = OpConvertUToF %f32 %x\n"
3549                 "%xm       = OpFMul %f32 %xf %inval\n"
3550                 "%xa       = OpExtInst %f32 %ext FAbs %xm\n"
3551                 "%xi       = OpConvertFToU %u32 %xa\n"
3552                 "%selector = OpUMod %u32 %xi %cimod\n"
3553                 "            OpSelectionMerge %phi None\n"
3554                 "            OpSwitch %selector %default "
3555
3556                 + generateSwitchCases(test4Width) +
3557
3558                 "%default  = OpLabel\n"
3559                 "            OpUnreachable\n"
3560
3561                 + generateSwitchTargets(test4Width) +
3562
3563                 "%phi      = OpLabel\n"
3564                 "%result   = OpPhi %f32"
3565
3566                 + generateOpPhiParams(test4Width) +
3567
3568                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3569                 "            OpStore %outloc %result\n"
3570                 "            OpReturn\n"
3571
3572                 "            OpFunctionEnd\n";
3573         spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3574         spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
3575         spec4.numWorkGroups = IVec3(numElements, 1, 1);
3576
3577         group->addChild(new SpvAsmComputeShaderCase(testCtx, "wide", "OpPhi with a lot of parameters", spec4));
3578
3579         spec5.assembly =
3580                 "OpCapability Shader\n"
3581                 "%ext      = OpExtInstImport \"GLSL.std.450\"\n"
3582                 "OpMemoryModel Logical GLSL450\n"
3583                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3584                 "OpExecutionMode %main LocalSize 1 1 1\n"
3585                 "%code     = OpString \"" + codestring + "\"\n"
3586
3587                 "OpSource GLSL 430\n"
3588                 "OpName %main \"main\"\n"
3589                 "OpName %id \"gl_GlobalInvocationID\"\n"
3590
3591                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3592
3593                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3594
3595                 "%id       = OpVariable %uvec3ptr Input\n"
3596                 "%zero     = OpConstant %i32 0\n"
3597                 "%f32_0    = OpConstant %f32 0.0\n"
3598                 "%f32_0_5  = OpConstant %f32 0.5\n"
3599                 "%f32_1    = OpConstant %f32 1.0\n"
3600                 "%f32_1_5  = OpConstant %f32 1.5\n"
3601                 "%f32_2    = OpConstant %f32 2.0\n"
3602                 "%f32_3_5  = OpConstant %f32 3.5\n"
3603                 "%f32_4    = OpConstant %f32 4.0\n"
3604                 "%f32_7_5  = OpConstant %f32 7.5\n"
3605                 "%f32_8    = OpConstant %f32 8.0\n"
3606                 "%f32_15_5 = OpConstant %f32 15.5\n"
3607                 "%f32_16   = OpConstant %f32 16.0\n"
3608                 "%f32_31_5 = OpConstant %f32 31.5\n"
3609                 "%f32_32   = OpConstant %f32 32.0\n"
3610                 "%f32_63_5 = OpConstant %f32 63.5\n"
3611                 "%f32_64   = OpConstant %f32 64.0\n"
3612                 "%f32_127_5 = OpConstant %f32 127.5\n"
3613                 "%f32_128  = OpConstant %f32 128.0\n"
3614                 "%f32_256  = OpConstant %f32 256.0\n"
3615
3616                 "%main     = OpFunction %void None %voidf\n"
3617                 "%entry    = OpLabel\n"
3618                 "%idval    = OpLoad %uvec3 %id\n"
3619                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3620                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3621                 "%inval    = OpLoad %f32 %inloc\n"
3622
3623                 "%xabs     = OpExtInst %f32 %ext FAbs %inval\n"
3624                 "%x8       = OpFMod %f32 %xabs %f32_256\n"
3625                 "%x7       = OpFMod %f32 %xabs %f32_128\n"
3626                 "%x6       = OpFMod %f32 %xabs %f32_64\n"
3627                 "%x5       = OpFMod %f32 %xabs %f32_32\n"
3628                 "%x4       = OpFMod %f32 %xabs %f32_16\n"
3629                 "%x3       = OpFMod %f32 %xabs %f32_8\n"
3630                 "%x2       = OpFMod %f32 %xabs %f32_4\n"
3631                 "%x1       = OpFMod %f32 %xabs %f32_2\n"
3632
3633                 "%b7       = OpFOrdGreaterThanEqual %bool %x8 %f32_127_5\n"
3634                 "%b6       = OpFOrdGreaterThanEqual %bool %x7 %f32_63_5\n"
3635                 "%b5       = OpFOrdGreaterThanEqual %bool %x6 %f32_31_5\n"
3636                 "%b4       = OpFOrdGreaterThanEqual %bool %x5 %f32_15_5\n"
3637                 "%b3       = OpFOrdGreaterThanEqual %bool %x4 %f32_7_5\n"
3638                 "%b2       = OpFOrdGreaterThanEqual %bool %x3 %f32_3_5\n"
3639                 "%b1       = OpFOrdGreaterThanEqual %bool %x2 %f32_1_5\n"
3640                 "%b0       = OpFOrdGreaterThanEqual %bool %x1 %f32_0_5\n"
3641
3642                 + generateOpPhiCase5(codestring) +
3643
3644                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3645                 "            OpStore %outloc %res\n"
3646                 "            OpReturn\n"
3647
3648                 "            OpFunctionEnd\n";
3649         spec5.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3650         spec5.outputs.push_back(BufferSp(new Float32Buffer(outputFloats5)));
3651         spec5.numWorkGroups = IVec3(numElements, 1, 1);
3652
3653         group->addChild(new SpvAsmComputeShaderCase(testCtx, "nested", "Stress OpPhi with a lot of nesting", spec5));
3654
3655         createOpPhiVartypeTests(group, testCtx);
3656
3657         return group.release();
3658 }
3659
3660 // Assembly code used for testing block order is based on GLSL source code:
3661 //
3662 // #version 430
3663 //
3664 // layout(std140, set = 0, binding = 0) readonly buffer Input {
3665 //   float elements[];
3666 // } input_data;
3667 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
3668 //   float elements[];
3669 // } output_data;
3670 //
3671 // void main() {
3672 //   uint x = gl_GlobalInvocationID.x;
3673 //   output_data.elements[x] = input_data.elements[x];
3674 //   if (x > uint(50)) {
3675 //     switch (x % uint(3)) {
3676 //       case 0: output_data.elements[x] += 1.5f; break;
3677 //       case 1: output_data.elements[x] += 42.f; break;
3678 //       case 2: output_data.elements[x] -= 27.f; break;
3679 //       default: break;
3680 //     }
3681 //   } else {
3682 //     output_data.elements[x] = -input_data.elements[x];
3683 //   }
3684 // }
3685 tcu::TestCaseGroup* createBlockOrderGroup (tcu::TestContext& testCtx)
3686 {
3687         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "block_order", "Test block orders"));
3688         ComputeShaderSpec                               spec;
3689         de::Random                                              rnd                             (deStringHash(group->getName()));
3690         const int                                               numElements             = 100;
3691         vector<float>                                   inputFloats             (numElements, 0);
3692         vector<float>                                   outputFloats    (numElements, 0);
3693
3694         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
3695
3696         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3697         floorAll(inputFloats);
3698
3699         for (size_t ndx = 0; ndx <= 50; ++ndx)
3700                 outputFloats[ndx] = -inputFloats[ndx];
3701
3702         for (size_t ndx = 51; ndx < numElements; ++ndx)
3703         {
3704                 switch (ndx % 3)
3705                 {
3706                         case 0:         outputFloats[ndx] = inputFloats[ndx] + 1.5f; break;
3707                         case 1:         outputFloats[ndx] = inputFloats[ndx] + 42.f; break;
3708                         case 2:         outputFloats[ndx] = inputFloats[ndx] - 27.f; break;
3709                         default:        break;
3710                 }
3711         }
3712
3713         spec.assembly =
3714                 string(getComputeAsmShaderPreamble()) +
3715
3716                 "OpSource GLSL 430\n"
3717                 "OpName %main \"main\"\n"
3718                 "OpName %id \"gl_GlobalInvocationID\"\n"
3719
3720                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3721
3722                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
3723
3724                 "%u32ptr       = OpTypePointer Function %u32\n"
3725                 "%u32ptr_input = OpTypePointer Input %u32\n"
3726
3727                 + string(getComputeAsmInputOutputBuffer()) +
3728
3729                 "%id        = OpVariable %uvec3ptr Input\n"
3730                 "%zero      = OpConstant %i32 0\n"
3731                 "%const3    = OpConstant %u32 3\n"
3732                 "%const50   = OpConstant %u32 50\n"
3733                 "%constf1p5 = OpConstant %f32 1.5\n"
3734                 "%constf27  = OpConstant %f32 27.0\n"
3735                 "%constf42  = OpConstant %f32 42.0\n"
3736
3737                 "%main = OpFunction %void None %voidf\n"
3738
3739                 // entry block.
3740                 "%entry    = OpLabel\n"
3741
3742                 // Create a temporary variable to hold the value of gl_GlobalInvocationID.x.
3743                 "%xvar     = OpVariable %u32ptr Function\n"
3744                 "%xptr     = OpAccessChain %u32ptr_input %id %zero\n"
3745                 "%x        = OpLoad %u32 %xptr\n"
3746                 "            OpStore %xvar %x\n"
3747
3748                 "%cmp      = OpUGreaterThan %bool %x %const50\n"
3749                 "            OpSelectionMerge %if_merge None\n"
3750                 "            OpBranchConditional %cmp %if_true %if_false\n"
3751
3752                 // False branch for if-statement: placed in the middle of switch cases and before true branch.
3753                 "%if_false = OpLabel\n"
3754                 "%x_f      = OpLoad %u32 %xvar\n"
3755                 "%inloc_f  = OpAccessChain %f32ptr %indata %zero %x_f\n"
3756                 "%inval_f  = OpLoad %f32 %inloc_f\n"
3757                 "%negate   = OpFNegate %f32 %inval_f\n"
3758                 "%outloc_f = OpAccessChain %f32ptr %outdata %zero %x_f\n"
3759                 "            OpStore %outloc_f %negate\n"
3760                 "            OpBranch %if_merge\n"
3761
3762                 // Merge block for if-statement: placed in the middle of true and false branch.
3763                 "%if_merge = OpLabel\n"
3764                 "            OpReturn\n"
3765
3766                 // True branch for if-statement: placed in the middle of swtich cases and after the false branch.
3767                 "%if_true  = OpLabel\n"
3768                 "%xval_t   = OpLoad %u32 %xvar\n"
3769                 "%mod      = OpUMod %u32 %xval_t %const3\n"
3770                 "            OpSelectionMerge %switch_merge None\n"
3771                 "            OpSwitch %mod %default 0 %case0 1 %case1 2 %case2\n"
3772
3773                 // Merge block for switch-statement: placed before the case
3774                 // bodies.  But it must follow OpSwitch which dominates it.
3775                 "%switch_merge = OpLabel\n"
3776                 "                OpBranch %if_merge\n"
3777
3778                 // Case 1 for switch-statement: placed before case 0.
3779                 // It must follow the OpSwitch that dominates it.
3780                 "%case1    = OpLabel\n"
3781                 "%x_1      = OpLoad %u32 %xvar\n"
3782                 "%inloc_1  = OpAccessChain %f32ptr %indata %zero %x_1\n"
3783                 "%inval_1  = OpLoad %f32 %inloc_1\n"
3784                 "%addf42   = OpFAdd %f32 %inval_1 %constf42\n"
3785                 "%outloc_1 = OpAccessChain %f32ptr %outdata %zero %x_1\n"
3786                 "            OpStore %outloc_1 %addf42\n"
3787                 "            OpBranch %switch_merge\n"
3788
3789                 // Case 2 for switch-statement.
3790                 "%case2    = OpLabel\n"
3791                 "%x_2      = OpLoad %u32 %xvar\n"
3792                 "%inloc_2  = OpAccessChain %f32ptr %indata %zero %x_2\n"
3793                 "%inval_2  = OpLoad %f32 %inloc_2\n"
3794                 "%subf27   = OpFSub %f32 %inval_2 %constf27\n"
3795                 "%outloc_2 = OpAccessChain %f32ptr %outdata %zero %x_2\n"
3796                 "            OpStore %outloc_2 %subf27\n"
3797                 "            OpBranch %switch_merge\n"
3798
3799                 // Default case for switch-statement: placed in the middle of normal cases.
3800                 "%default = OpLabel\n"
3801                 "           OpBranch %switch_merge\n"
3802
3803                 // Case 0 for switch-statement: out of order.
3804                 "%case0    = OpLabel\n"
3805                 "%x_0      = OpLoad %u32 %xvar\n"
3806                 "%inloc_0  = OpAccessChain %f32ptr %indata %zero %x_0\n"
3807                 "%inval_0  = OpLoad %f32 %inloc_0\n"
3808                 "%addf1p5  = OpFAdd %f32 %inval_0 %constf1p5\n"
3809                 "%outloc_0 = OpAccessChain %f32ptr %outdata %zero %x_0\n"
3810                 "            OpStore %outloc_0 %addf1p5\n"
3811                 "            OpBranch %switch_merge\n"
3812
3813                 "            OpFunctionEnd\n";
3814         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3815         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3816         spec.numWorkGroups = IVec3(numElements, 1, 1);
3817
3818         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "various out-of-order blocks", spec));
3819
3820         return group.release();
3821 }
3822
3823 tcu::TestCaseGroup* createMultipleShaderGroup (tcu::TestContext& testCtx)
3824 {
3825         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "multiple_shaders", "Test multiple shaders in the same module"));
3826         ComputeShaderSpec                               spec1;
3827         ComputeShaderSpec                               spec2;
3828         de::Random                                              rnd                             (deStringHash(group->getName()));
3829         const int                                               numElements             = 100;
3830         vector<float>                                   inputFloats             (numElements, 0);
3831         vector<float>                                   outputFloats1   (numElements, 0);
3832         vector<float>                                   outputFloats2   (numElements, 0);
3833         fillRandomScalars(rnd, -500.f, 500.f, &inputFloats[0], numElements);
3834
3835         for (size_t ndx = 0; ndx < numElements; ++ndx)
3836         {
3837                 outputFloats1[ndx] = inputFloats[ndx] + inputFloats[ndx];
3838                 outputFloats2[ndx] = -inputFloats[ndx];
3839         }
3840
3841         const string assembly(
3842                 "OpCapability Shader\n"
3843                 "OpCapability ClipDistance\n"
3844                 "OpMemoryModel Logical GLSL450\n"
3845                 "OpEntryPoint GLCompute %comp_main1 \"entrypoint1\" %id\n"
3846                 "OpEntryPoint GLCompute %comp_main2 \"entrypoint2\" %id\n"
3847                 // A module cannot have two OpEntryPoint instructions with the same Execution Model and the same Name string.
3848                 "OpEntryPoint Vertex    %vert_main  \"entrypoint2\" %vert_builtins %vertexIndex %instanceIndex\n"
3849                 "OpExecutionMode %comp_main1 LocalSize 1 1 1\n"
3850                 "OpExecutionMode %comp_main2 LocalSize 1 1 1\n"
3851
3852                 "OpName %comp_main1              \"entrypoint1\"\n"
3853                 "OpName %comp_main2              \"entrypoint2\"\n"
3854                 "OpName %vert_main               \"entrypoint2\"\n"
3855                 "OpName %id                      \"gl_GlobalInvocationID\"\n"
3856                 "OpName %vert_builtin_st         \"gl_PerVertex\"\n"
3857                 "OpName %vertexIndex             \"gl_VertexIndex\"\n"
3858                 "OpName %instanceIndex           \"gl_InstanceIndex\"\n"
3859                 "OpMemberName %vert_builtin_st 0 \"gl_Position\"\n"
3860                 "OpMemberName %vert_builtin_st 1 \"gl_PointSize\"\n"
3861                 "OpMemberName %vert_builtin_st 2 \"gl_ClipDistance\"\n"
3862
3863                 "OpDecorate %id                      BuiltIn GlobalInvocationId\n"
3864                 "OpDecorate %vertexIndex             BuiltIn VertexIndex\n"
3865                 "OpDecorate %instanceIndex           BuiltIn InstanceIndex\n"
3866                 "OpDecorate %vert_builtin_st         Block\n"
3867                 "OpMemberDecorate %vert_builtin_st 0 BuiltIn Position\n"
3868                 "OpMemberDecorate %vert_builtin_st 1 BuiltIn PointSize\n"
3869                 "OpMemberDecorate %vert_builtin_st 2 BuiltIn ClipDistance\n"
3870
3871                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3872
3873                 "%zero       = OpConstant %i32 0\n"
3874                 "%one        = OpConstant %u32 1\n"
3875                 "%c_f32_1    = OpConstant %f32 1\n"
3876
3877                 "%i32inputptr         = OpTypePointer Input %i32\n"
3878                 "%vec4                = OpTypeVector %f32 4\n"
3879                 "%vec4ptr             = OpTypePointer Output %vec4\n"
3880                 "%f32arr1             = OpTypeArray %f32 %one\n"
3881                 "%vert_builtin_st     = OpTypeStruct %vec4 %f32 %f32arr1\n"
3882                 "%vert_builtin_st_ptr = OpTypePointer Output %vert_builtin_st\n"
3883                 "%vert_builtins       = OpVariable %vert_builtin_st_ptr Output\n"
3884
3885                 "%id         = OpVariable %uvec3ptr Input\n"
3886                 "%vertexIndex = OpVariable %i32inputptr Input\n"
3887                 "%instanceIndex = OpVariable %i32inputptr Input\n"
3888                 "%c_vec4_1   = OpConstantComposite %vec4 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
3889
3890                 // gl_Position = vec4(1.);
3891                 "%vert_main  = OpFunction %void None %voidf\n"
3892                 "%vert_entry = OpLabel\n"
3893                 "%position   = OpAccessChain %vec4ptr %vert_builtins %zero\n"
3894                 "              OpStore %position %c_vec4_1\n"
3895                 "              OpReturn\n"
3896                 "              OpFunctionEnd\n"
3897
3898                 // Double inputs.
3899                 "%comp_main1  = OpFunction %void None %voidf\n"
3900                 "%comp1_entry = OpLabel\n"
3901                 "%idval1      = OpLoad %uvec3 %id\n"
3902                 "%x1          = OpCompositeExtract %u32 %idval1 0\n"
3903                 "%inloc1      = OpAccessChain %f32ptr %indata %zero %x1\n"
3904                 "%inval1      = OpLoad %f32 %inloc1\n"
3905                 "%add         = OpFAdd %f32 %inval1 %inval1\n"
3906                 "%outloc1     = OpAccessChain %f32ptr %outdata %zero %x1\n"
3907                 "               OpStore %outloc1 %add\n"
3908                 "               OpReturn\n"
3909                 "               OpFunctionEnd\n"
3910
3911                 // Negate inputs.
3912                 "%comp_main2  = OpFunction %void None %voidf\n"
3913                 "%comp2_entry = OpLabel\n"
3914                 "%idval2      = OpLoad %uvec3 %id\n"
3915                 "%x2          = OpCompositeExtract %u32 %idval2 0\n"
3916                 "%inloc2      = OpAccessChain %f32ptr %indata %zero %x2\n"
3917                 "%inval2      = OpLoad %f32 %inloc2\n"
3918                 "%neg         = OpFNegate %f32 %inval2\n"
3919                 "%outloc2     = OpAccessChain %f32ptr %outdata %zero %x2\n"
3920                 "               OpStore %outloc2 %neg\n"
3921                 "               OpReturn\n"
3922                 "               OpFunctionEnd\n");
3923
3924         spec1.assembly = assembly;
3925         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3926         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
3927         spec1.numWorkGroups = IVec3(numElements, 1, 1);
3928         spec1.entryPoint = "entrypoint1";
3929
3930         spec2.assembly = assembly;
3931         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3932         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
3933         spec2.numWorkGroups = IVec3(numElements, 1, 1);
3934         spec2.entryPoint = "entrypoint2";
3935
3936         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader1", "multiple shaders in the same module", spec1));
3937         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader2", "multiple shaders in the same module", spec2));
3938
3939         return group.release();
3940 }
3941
3942 inline std::string makeLongUTF8String (size_t num4ByteChars)
3943 {
3944         // An example of a longest valid UTF-8 character.  Be explicit about the
3945         // character type because Microsoft compilers can otherwise interpret the
3946         // character string as being over wide (16-bit) characters. Ideally, we
3947         // would just use a C++11 UTF-8 string literal, but we want to support older
3948         // Microsoft compilers.
3949         const std::basic_string<char> earthAfrica("\xF0\x9F\x8C\x8D");
3950         std::string longString;
3951         longString.reserve(num4ByteChars * 4);
3952         for (size_t count = 0; count < num4ByteChars; count++)
3953         {
3954                 longString += earthAfrica;
3955         }
3956         return longString;
3957 }
3958
3959 tcu::TestCaseGroup* createOpSourceGroup (tcu::TestContext& testCtx)
3960 {
3961         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsource", "Tests the OpSource & OpSourceContinued instruction"));
3962         vector<CaseParameter>                   cases;
3963         de::Random                                              rnd                             (deStringHash(group->getName()));
3964         const int                                               numElements             = 100;
3965         vector<float>                                   positiveFloats  (numElements, 0);
3966         vector<float>                                   negativeFloats  (numElements, 0);
3967         const StringTemplate                    shaderTemplate  (
3968                 "OpCapability Shader\n"
3969                 "OpMemoryModel Logical GLSL450\n"
3970
3971                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3972                 "OpExecutionMode %main LocalSize 1 1 1\n"
3973
3974                 "${SOURCE}\n"
3975
3976                 "OpName %main           \"main\"\n"
3977                 "OpName %id             \"gl_GlobalInvocationID\"\n"
3978
3979                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3980
3981                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3982
3983                 "%id        = OpVariable %uvec3ptr Input\n"
3984                 "%zero      = OpConstant %i32 0\n"
3985
3986                 "%main      = OpFunction %void None %voidf\n"
3987                 "%label     = OpLabel\n"
3988                 "%idval     = OpLoad %uvec3 %id\n"
3989                 "%x         = OpCompositeExtract %u32 %idval 0\n"
3990                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
3991                 "%inval     = OpLoad %f32 %inloc\n"
3992                 "%neg       = OpFNegate %f32 %inval\n"
3993                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
3994                 "             OpStore %outloc %neg\n"
3995                 "             OpReturn\n"
3996                 "             OpFunctionEnd\n");
3997
3998         cases.push_back(CaseParameter("unknown_source",                                                 "OpSource Unknown 0"));
3999         cases.push_back(CaseParameter("wrong_source",                                                   "OpSource OpenCL_C 210"));
4000         cases.push_back(CaseParameter("normal_filename",                                                "%fname = OpString \"filename\"\n"
4001                                                                                                                                                         "OpSource GLSL 430 %fname"));
4002         cases.push_back(CaseParameter("empty_filename",                                                 "%fname = OpString \"\"\n"
4003                                                                                                                                                         "OpSource GLSL 430 %fname"));
4004         cases.push_back(CaseParameter("normal_source_code",                                             "%fname = OpString \"filename\"\n"
4005                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\""));
4006         cases.push_back(CaseParameter("empty_source_code",                                              "%fname = OpString \"filename\"\n"
4007                                                                                                                                                         "OpSource GLSL 430 %fname \"\""));
4008         cases.push_back(CaseParameter("long_source_code",                                               "%fname = OpString \"filename\"\n"
4009                                                                                                                                                         "OpSource GLSL 430 %fname \"" + makeLongUTF8String(65530) + "ccc\"")); // word count: 65535
4010         cases.push_back(CaseParameter("utf8_source_code",                                               "%fname = OpString \"filename\"\n"
4011                                                                                                                                                         "OpSource GLSL 430 %fname \"\xE2\x98\x82\xE2\x98\x85\"")); // umbrella & black star symbol
4012         cases.push_back(CaseParameter("normal_sourcecontinued",                                 "%fname = OpString \"filename\"\n"
4013                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvo\"\n"
4014                                                                                                                                                         "OpSourceContinued \"id main() {}\""));
4015         cases.push_back(CaseParameter("empty_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
4016                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4017                                                                                                                                                         "OpSourceContinued \"\""));
4018         cases.push_back(CaseParameter("long_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
4019                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4020                                                                                                                                                         "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\"")); // word count: 65535
4021         cases.push_back(CaseParameter("utf8_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
4022                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4023                                                                                                                                                         "OpSourceContinued \"\xE2\x98\x8E\xE2\x9A\x91\"")); // white telephone & black flag symbol
4024         cases.push_back(CaseParameter("multi_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
4025                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\n\"\n"
4026                                                                                                                                                         "OpSourceContinued \"void\"\n"
4027                                                                                                                                                         "OpSourceContinued \"main()\"\n"
4028                                                                                                                                                         "OpSourceContinued \"{}\""));
4029         cases.push_back(CaseParameter("empty_source_before_sourcecontinued",    "%fname = OpString \"filename\"\n"
4030                                                                                                                                                         "OpSource GLSL 430 %fname \"\"\n"
4031                                                                                                                                                         "OpSourceContinued \"#version 430\nvoid main() {}\""));
4032
4033         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4034
4035         for (size_t ndx = 0; ndx < numElements; ++ndx)
4036                 negativeFloats[ndx] = -positiveFloats[ndx];
4037
4038         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4039         {
4040                 map<string, string>             specializations;
4041                 ComputeShaderSpec               spec;
4042
4043                 specializations["SOURCE"] = cases[caseNdx].param;
4044                 spec.assembly = shaderTemplate.specialize(specializations);
4045                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4046                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4047                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4048
4049                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4050         }
4051
4052         return group.release();
4053 }
4054
4055 tcu::TestCaseGroup* createOpSourceExtensionGroup (tcu::TestContext& testCtx)
4056 {
4057         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsourceextension", "Tests the OpSource instruction"));
4058         vector<CaseParameter>                   cases;
4059         de::Random                                              rnd                             (deStringHash(group->getName()));
4060         const int                                               numElements             = 100;
4061         vector<float>                                   inputFloats             (numElements, 0);
4062         vector<float>                                   outputFloats    (numElements, 0);
4063         const StringTemplate                    shaderTemplate  (
4064                 string(getComputeAsmShaderPreamble()) +
4065
4066                 "OpSourceExtension \"${EXTENSION}\"\n"
4067
4068                 "OpName %main           \"main\"\n"
4069                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4070
4071                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4072
4073                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4074
4075                 "%id        = OpVariable %uvec3ptr Input\n"
4076                 "%zero      = OpConstant %i32 0\n"
4077
4078                 "%main      = OpFunction %void None %voidf\n"
4079                 "%label     = OpLabel\n"
4080                 "%idval     = OpLoad %uvec3 %id\n"
4081                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4082                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4083                 "%inval     = OpLoad %f32 %inloc\n"
4084                 "%neg       = OpFNegate %f32 %inval\n"
4085                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4086                 "             OpStore %outloc %neg\n"
4087                 "             OpReturn\n"
4088                 "             OpFunctionEnd\n");
4089
4090         cases.push_back(CaseParameter("empty_extension",        ""));
4091         cases.push_back(CaseParameter("real_extension",         "GL_ARB_texture_rectangle"));
4092         cases.push_back(CaseParameter("fake_extension",         "GL_ARB_im_the_ultimate_extension"));
4093         cases.push_back(CaseParameter("utf8_extension",         "GL_ARB_\xE2\x98\x82\xE2\x98\x85"));
4094         cases.push_back(CaseParameter("long_extension",         makeLongUTF8String(65533) + "ccc")); // word count: 65535
4095
4096         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
4097
4098         for (size_t ndx = 0; ndx < numElements; ++ndx)
4099                 outputFloats[ndx] = -inputFloats[ndx];
4100
4101         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4102         {
4103                 map<string, string>             specializations;
4104                 ComputeShaderSpec               spec;
4105
4106                 specializations["EXTENSION"] = cases[caseNdx].param;
4107                 spec.assembly = shaderTemplate.specialize(specializations);
4108                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4109                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
4110                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4111
4112                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4113         }
4114
4115         return group.release();
4116 }
4117
4118 // Checks that a compute shader can generate a constant null value of various types, without exercising a computation on it.
4119 tcu::TestCaseGroup* createOpConstantNullGroup (tcu::TestContext& testCtx)
4120 {
4121         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnull", "Tests the OpConstantNull instruction"));
4122         vector<CaseParameter>                   cases;
4123         de::Random                                              rnd                             (deStringHash(group->getName()));
4124         const int                                               numElements             = 100;
4125         vector<float>                                   positiveFloats  (numElements, 0);
4126         vector<float>                                   negativeFloats  (numElements, 0);
4127         const StringTemplate                    shaderTemplate  (
4128                 string(getComputeAsmShaderPreamble()) +
4129
4130                 "OpSource GLSL 430\n"
4131                 "OpName %main           \"main\"\n"
4132                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4133
4134                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4135
4136                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4137                 "%uvec2     = OpTypeVector %u32 2\n"
4138                 "%bvec3     = OpTypeVector %bool 3\n"
4139                 "%fvec4     = OpTypeVector %f32 4\n"
4140                 "%fmat33    = OpTypeMatrix %fvec3 3\n"
4141                 "%const100  = OpConstant %u32 100\n"
4142                 "%uarr100   = OpTypeArray %i32 %const100\n"
4143                 "%struct    = OpTypeStruct %f32 %i32 %u32\n"
4144                 "%pointer   = OpTypePointer Function %i32\n"
4145                 + string(getComputeAsmInputOutputBuffer()) +
4146
4147                 "%null      = OpConstantNull ${TYPE}\n"
4148
4149                 "%id        = OpVariable %uvec3ptr Input\n"
4150                 "%zero      = OpConstant %i32 0\n"
4151
4152                 "%main      = OpFunction %void None %voidf\n"
4153                 "%label     = OpLabel\n"
4154                 "%idval     = OpLoad %uvec3 %id\n"
4155                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4156                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4157                 "%inval     = OpLoad %f32 %inloc\n"
4158                 "%neg       = OpFNegate %f32 %inval\n"
4159                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4160                 "             OpStore %outloc %neg\n"
4161                 "             OpReturn\n"
4162                 "             OpFunctionEnd\n");
4163
4164         cases.push_back(CaseParameter("bool",                   "%bool"));
4165         cases.push_back(CaseParameter("sint32",                 "%i32"));
4166         cases.push_back(CaseParameter("uint32",                 "%u32"));
4167         cases.push_back(CaseParameter("float32",                "%f32"));
4168         cases.push_back(CaseParameter("vec4float32",    "%fvec4"));
4169         cases.push_back(CaseParameter("vec3bool",               "%bvec3"));
4170         cases.push_back(CaseParameter("vec2uint32",             "%uvec2"));
4171         cases.push_back(CaseParameter("matrix",                 "%fmat33"));
4172         cases.push_back(CaseParameter("array",                  "%uarr100"));
4173         cases.push_back(CaseParameter("struct",                 "%struct"));
4174         cases.push_back(CaseParameter("pointer",                "%pointer"));
4175
4176         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4177
4178         for (size_t ndx = 0; ndx < numElements; ++ndx)
4179                 negativeFloats[ndx] = -positiveFloats[ndx];
4180
4181         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4182         {
4183                 map<string, string>             specializations;
4184                 ComputeShaderSpec               spec;
4185
4186                 specializations["TYPE"] = cases[caseNdx].param;
4187                 spec.assembly = shaderTemplate.specialize(specializations);
4188                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4189                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4190                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4191
4192                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4193         }
4194
4195         return group.release();
4196 }
4197
4198 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
4199 tcu::TestCaseGroup* createOpConstantCompositeGroup (tcu::TestContext& testCtx)
4200 {
4201         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "Tests the OpConstantComposite instruction"));
4202         vector<CaseParameter>                   cases;
4203         de::Random                                              rnd                             (deStringHash(group->getName()));
4204         const int                                               numElements             = 100;
4205         vector<float>                                   positiveFloats  (numElements, 0);
4206         vector<float>                                   negativeFloats  (numElements, 0);
4207         const StringTemplate                    shaderTemplate  (
4208                 string(getComputeAsmShaderPreamble()) +
4209
4210                 "OpSource GLSL 430\n"
4211                 "OpName %main           \"main\"\n"
4212                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4213
4214                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4215
4216                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4217
4218                 "%id        = OpVariable %uvec3ptr Input\n"
4219                 "%zero      = OpConstant %i32 0\n"
4220
4221                 "${CONSTANT}\n"
4222
4223                 "%main      = OpFunction %void None %voidf\n"
4224                 "%label     = OpLabel\n"
4225                 "%idval     = OpLoad %uvec3 %id\n"
4226                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4227                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4228                 "%inval     = OpLoad %f32 %inloc\n"
4229                 "%neg       = OpFNegate %f32 %inval\n"
4230                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4231                 "             OpStore %outloc %neg\n"
4232                 "             OpReturn\n"
4233                 "             OpFunctionEnd\n");
4234
4235         cases.push_back(CaseParameter("vector",                 "%five = OpConstant %u32 5\n"
4236                                                                                                         "%const = OpConstantComposite %uvec3 %five %zero %five"));
4237         cases.push_back(CaseParameter("matrix",                 "%m3fvec3 = OpTypeMatrix %fvec3 3\n"
4238                                                                                                         "%ten = OpConstant %f32 10.\n"
4239                                                                                                         "%fzero = OpConstant %f32 0.\n"
4240                                                                                                         "%vec = OpConstantComposite %fvec3 %ten %fzero %ten\n"
4241                                                                                                         "%mat = OpConstantComposite %m3fvec3 %vec %vec %vec"));
4242         cases.push_back(CaseParameter("struct",                 "%m2vec3 = OpTypeMatrix %fvec3 2\n"
4243                                                                                                         "%struct = OpTypeStruct %i32 %f32 %fvec3 %m2vec3\n"
4244                                                                                                         "%fzero = OpConstant %f32 0.\n"
4245                                                                                                         "%one = OpConstant %f32 1.\n"
4246                                                                                                         "%point5 = OpConstant %f32 0.5\n"
4247                                                                                                         "%vec = OpConstantComposite %fvec3 %one %one %fzero\n"
4248                                                                                                         "%mat = OpConstantComposite %m2vec3 %vec %vec\n"
4249                                                                                                         "%const = OpConstantComposite %struct %zero %point5 %vec %mat"));
4250         cases.push_back(CaseParameter("nested_struct",  "%st1 = OpTypeStruct %u32 %f32\n"
4251                                                                                                         "%st2 = OpTypeStruct %i32 %i32\n"
4252                                                                                                         "%struct = OpTypeStruct %st1 %st2\n"
4253                                                                                                         "%point5 = OpConstant %f32 0.5\n"
4254                                                                                                         "%one = OpConstant %u32 1\n"
4255                                                                                                         "%ten = OpConstant %i32 10\n"
4256                                                                                                         "%st1val = OpConstantComposite %st1 %one %point5\n"
4257                                                                                                         "%st2val = OpConstantComposite %st2 %ten %ten\n"
4258                                                                                                         "%const = OpConstantComposite %struct %st1val %st2val"));
4259
4260         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4261
4262         for (size_t ndx = 0; ndx < numElements; ++ndx)
4263                 negativeFloats[ndx] = -positiveFloats[ndx];
4264
4265         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4266         {
4267                 map<string, string>             specializations;
4268                 ComputeShaderSpec               spec;
4269
4270                 specializations["CONSTANT"] = cases[caseNdx].param;
4271                 spec.assembly = shaderTemplate.specialize(specializations);
4272                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4273                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4274                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4275
4276                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4277         }
4278
4279         return group.release();
4280 }
4281
4282 // Creates a floating point number with the given exponent, and significand
4283 // bits set. It can only create normalized numbers. Only the least significant
4284 // 24 bits of the significand will be examined. The final bit of the
4285 // significand will also be ignored. This allows alignment to be written
4286 // similarly to C99 hex-floats.
4287 // For example if you wanted to write 0x1.7f34p-12 you would call
4288 // constructNormalizedFloat(-12, 0x7f3400)
4289 float constructNormalizedFloat (deInt32 exponent, deUint32 significand)
4290 {
4291         float f = 1.0f;
4292
4293         for (deInt32 idx = 0; idx < 23; ++idx)
4294         {
4295                 f += ((significand & 0x800000) == 0) ? 0.f : std::ldexp(1.0f, -(idx + 1));
4296                 significand <<= 1;
4297         }
4298
4299         return std::ldexp(f, exponent);
4300 }
4301
4302 // Compare instruction for the OpQuantizeF16 compute exact case.
4303 // Returns true if the output is what is expected from the test case.
4304 bool compareOpQuantizeF16ComputeExactCase (const std::vector<BufferSp>&, const vector<AllocationSp>& outputAllocs, const std::vector<BufferSp>& expectedOutputs, TestLog&)
4305 {
4306         if (outputAllocs.size() != 1)
4307                 return false;
4308
4309         // Only size is needed because we cannot compare Nans.
4310         size_t byteSize = expectedOutputs[0]->getByteSize();
4311
4312         const float*    outputAsFloat   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
4313
4314         if (byteSize != 4*sizeof(float)) {
4315                 return false;
4316         }
4317
4318         if (*outputAsFloat != constructNormalizedFloat(8, 0x304000) &&
4319                 *outputAsFloat != constructNormalizedFloat(8, 0x300000)) {
4320                 return false;
4321         }
4322         outputAsFloat++;
4323
4324         if (*outputAsFloat != -constructNormalizedFloat(-7, 0x600000) &&
4325                 *outputAsFloat != -constructNormalizedFloat(-7, 0x604000)) {
4326                 return false;
4327         }
4328         outputAsFloat++;
4329
4330         if (*outputAsFloat != constructNormalizedFloat(2, 0x01C000) &&
4331                 *outputAsFloat != constructNormalizedFloat(2, 0x020000)) {
4332                 return false;
4333         }
4334         outputAsFloat++;
4335
4336         if (*outputAsFloat != constructNormalizedFloat(1, 0xFFC000) &&
4337                 *outputAsFloat != constructNormalizedFloat(2, 0x000000)) {
4338                 return false;
4339         }
4340
4341         return true;
4342 }
4343
4344 // Checks that every output from a test-case is a float NaN.
4345 bool compareNan (const std::vector<BufferSp>&, const vector<AllocationSp>& outputAllocs, const std::vector<BufferSp>& expectedOutputs, TestLog&)
4346 {
4347         if (outputAllocs.size() != 1)
4348                 return false;
4349
4350         // Only size is needed because we cannot compare Nans.
4351         size_t byteSize = expectedOutputs[0]->getByteSize();
4352
4353         const float* const      output_as_float = static_cast<const float* const>(outputAllocs[0]->getHostPtr());
4354
4355         for (size_t idx = 0; idx < byteSize / sizeof(float); ++idx)
4356         {
4357                 if (!deFloatIsNaN(output_as_float[idx]))
4358                 {
4359                         return false;
4360                 }
4361         }
4362
4363         return true;
4364 }
4365
4366 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
4367 tcu::TestCaseGroup* createOpQuantizeToF16Group (tcu::TestContext& testCtx)
4368 {
4369         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opquantize", "Tests the OpQuantizeToF16 instruction"));
4370
4371         const std::string shader (
4372                 string(getComputeAsmShaderPreamble()) +
4373
4374                 "OpSource GLSL 430\n"
4375                 "OpName %main           \"main\"\n"
4376                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4377
4378                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4379
4380                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4381
4382                 "%id        = OpVariable %uvec3ptr Input\n"
4383                 "%zero      = OpConstant %i32 0\n"
4384
4385                 "%main      = OpFunction %void None %voidf\n"
4386                 "%label     = OpLabel\n"
4387                 "%idval     = OpLoad %uvec3 %id\n"
4388                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4389                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4390                 "%inval     = OpLoad %f32 %inloc\n"
4391                 "%quant     = OpQuantizeToF16 %f32 %inval\n"
4392                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4393                 "             OpStore %outloc %quant\n"
4394                 "             OpReturn\n"
4395                 "             OpFunctionEnd\n");
4396
4397         {
4398                 ComputeShaderSpec       spec;
4399                 const deUint32          numElements             = 100;
4400                 vector<float>           infinities;
4401                 vector<float>           results;
4402
4403                 infinities.reserve(numElements);
4404                 results.reserve(numElements);
4405
4406                 for (size_t idx = 0; idx < numElements; ++idx)
4407                 {
4408                         switch(idx % 4)
4409                         {
4410                                 case 0:
4411                                         infinities.push_back(std::numeric_limits<float>::infinity());
4412                                         results.push_back(std::numeric_limits<float>::infinity());
4413                                         break;
4414                                 case 1:
4415                                         infinities.push_back(-std::numeric_limits<float>::infinity());
4416                                         results.push_back(-std::numeric_limits<float>::infinity());
4417                                         break;
4418                                 case 2:
4419                                         infinities.push_back(std::ldexp(1.0f, 16));
4420                                         results.push_back(std::numeric_limits<float>::infinity());
4421                                         break;
4422                                 case 3:
4423                                         infinities.push_back(std::ldexp(-1.0f, 32));
4424                                         results.push_back(-std::numeric_limits<float>::infinity());
4425                                         break;
4426                         }
4427                 }
4428
4429                 spec.assembly = shader;
4430                 spec.inputs.push_back(BufferSp(new Float32Buffer(infinities)));
4431                 spec.outputs.push_back(BufferSp(new Float32Buffer(results)));
4432                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4433
4434                 group->addChild(new SpvAsmComputeShaderCase(
4435                         testCtx, "infinities", "Check that infinities propagated and created", spec));
4436         }
4437
4438         {
4439                 ComputeShaderSpec       spec;
4440                 vector<float>           nans;
4441                 const deUint32          numElements             = 100;
4442
4443                 nans.reserve(numElements);
4444
4445                 for (size_t idx = 0; idx < numElements; ++idx)
4446                 {
4447                         if (idx % 2 == 0)
4448                         {
4449                                 nans.push_back(std::numeric_limits<float>::quiet_NaN());
4450                         }
4451                         else
4452                         {
4453                                 nans.push_back(-std::numeric_limits<float>::quiet_NaN());
4454                         }
4455                 }
4456
4457                 spec.assembly = shader;
4458                 spec.inputs.push_back(BufferSp(new Float32Buffer(nans)));
4459                 spec.outputs.push_back(BufferSp(new Float32Buffer(nans)));
4460                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4461                 spec.verifyIO = &compareNan;
4462
4463                 group->addChild(new SpvAsmComputeShaderCase(
4464                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
4465         }
4466
4467         {
4468                 ComputeShaderSpec       spec;
4469                 vector<float>           small;
4470                 vector<float>           zeros;
4471                 const deUint32          numElements             = 100;
4472
4473                 small.reserve(numElements);
4474                 zeros.reserve(numElements);
4475
4476                 for (size_t idx = 0; idx < numElements; ++idx)
4477                 {
4478                         switch(idx % 6)
4479                         {
4480                                 case 0:
4481                                         small.push_back(0.f);
4482                                         zeros.push_back(0.f);
4483                                         break;
4484                                 case 1:
4485                                         small.push_back(-0.f);
4486                                         zeros.push_back(-0.f);
4487                                         break;
4488                                 case 2:
4489                                         small.push_back(std::ldexp(1.0f, -16));
4490                                         zeros.push_back(0.f);
4491                                         break;
4492                                 case 3:
4493                                         small.push_back(std::ldexp(-1.0f, -32));
4494                                         zeros.push_back(-0.f);
4495                                         break;
4496                                 case 4:
4497                                         small.push_back(std::ldexp(1.0f, -127));
4498                                         zeros.push_back(0.f);
4499                                         break;
4500                                 case 5:
4501                                         small.push_back(-std::ldexp(1.0f, -128));
4502                                         zeros.push_back(-0.f);
4503                                         break;
4504                         }
4505                 }
4506
4507                 spec.assembly = shader;
4508                 spec.inputs.push_back(BufferSp(new Float32Buffer(small)));
4509                 spec.outputs.push_back(BufferSp(new Float32Buffer(zeros)));
4510                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4511
4512                 group->addChild(new SpvAsmComputeShaderCase(
4513                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
4514         }
4515
4516         {
4517                 ComputeShaderSpec       spec;
4518                 vector<float>           exact;
4519                 const deUint32          numElements             = 200;
4520
4521                 exact.reserve(numElements);
4522
4523                 for (size_t idx = 0; idx < numElements; ++idx)
4524                         exact.push_back(static_cast<float>(static_cast<int>(idx) - 100));
4525
4526                 spec.assembly = shader;
4527                 spec.inputs.push_back(BufferSp(new Float32Buffer(exact)));
4528                 spec.outputs.push_back(BufferSp(new Float32Buffer(exact)));
4529                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4530
4531                 group->addChild(new SpvAsmComputeShaderCase(
4532                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
4533         }
4534
4535         {
4536                 ComputeShaderSpec       spec;
4537                 vector<float>           inputs;
4538                 const deUint32          numElements             = 4;
4539
4540                 inputs.push_back(constructNormalizedFloat(8,    0x300300));
4541                 inputs.push_back(-constructNormalizedFloat(-7,  0x600800));
4542                 inputs.push_back(constructNormalizedFloat(2,    0x01E000));
4543                 inputs.push_back(constructNormalizedFloat(1,    0xFFE000));
4544
4545                 spec.assembly = shader;
4546                 spec.verifyIO = &compareOpQuantizeF16ComputeExactCase;
4547                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4548                 spec.outputs.push_back(BufferSp(new Float32Buffer(inputs)));
4549                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4550
4551                 group->addChild(new SpvAsmComputeShaderCase(
4552                         testCtx, "rounded", "Check that are rounded when needed", spec));
4553         }
4554
4555         return group.release();
4556 }
4557
4558 tcu::TestCaseGroup* createSpecConstantOpQuantizeToF16Group (tcu::TestContext& testCtx)
4559 {
4560         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opspecconstantop_opquantize", "Tests the OpQuantizeToF16 opcode for the OpSpecConstantOp instruction"));
4561
4562         const std::string shader (
4563                 string(getComputeAsmShaderPreamble()) +
4564
4565                 "OpName %main           \"main\"\n"
4566                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4567
4568                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4569
4570                 "OpDecorate %sc_0  SpecId 0\n"
4571                 "OpDecorate %sc_1  SpecId 1\n"
4572                 "OpDecorate %sc_2  SpecId 2\n"
4573                 "OpDecorate %sc_3  SpecId 3\n"
4574                 "OpDecorate %sc_4  SpecId 4\n"
4575                 "OpDecorate %sc_5  SpecId 5\n"
4576
4577                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4578
4579                 "%id        = OpVariable %uvec3ptr Input\n"
4580                 "%zero      = OpConstant %i32 0\n"
4581                 "%c_u32_6   = OpConstant %u32 6\n"
4582
4583                 "%sc_0      = OpSpecConstant %f32 0.\n"
4584                 "%sc_1      = OpSpecConstant %f32 0.\n"
4585                 "%sc_2      = OpSpecConstant %f32 0.\n"
4586                 "%sc_3      = OpSpecConstant %f32 0.\n"
4587                 "%sc_4      = OpSpecConstant %f32 0.\n"
4588                 "%sc_5      = OpSpecConstant %f32 0.\n"
4589
4590                 "%sc_0_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_0\n"
4591                 "%sc_1_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_1\n"
4592                 "%sc_2_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_2\n"
4593                 "%sc_3_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_3\n"
4594                 "%sc_4_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_4\n"
4595                 "%sc_5_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_5\n"
4596
4597                 "%main      = OpFunction %void None %voidf\n"
4598                 "%label     = OpLabel\n"
4599                 "%idval     = OpLoad %uvec3 %id\n"
4600                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4601                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4602                 "%selector  = OpUMod %u32 %x %c_u32_6\n"
4603                 "            OpSelectionMerge %exit None\n"
4604                 "            OpSwitch %selector %exit 0 %case0 1 %case1 2 %case2 3 %case3 4 %case4 5 %case5\n"
4605
4606                 "%case0     = OpLabel\n"
4607                 "             OpStore %outloc %sc_0_quant\n"
4608                 "             OpBranch %exit\n"
4609
4610                 "%case1     = OpLabel\n"
4611                 "             OpStore %outloc %sc_1_quant\n"
4612                 "             OpBranch %exit\n"
4613
4614                 "%case2     = OpLabel\n"
4615                 "             OpStore %outloc %sc_2_quant\n"
4616                 "             OpBranch %exit\n"
4617
4618                 "%case3     = OpLabel\n"
4619                 "             OpStore %outloc %sc_3_quant\n"
4620                 "             OpBranch %exit\n"
4621
4622                 "%case4     = OpLabel\n"
4623                 "             OpStore %outloc %sc_4_quant\n"
4624                 "             OpBranch %exit\n"
4625
4626                 "%case5     = OpLabel\n"
4627                 "             OpStore %outloc %sc_5_quant\n"
4628                 "             OpBranch %exit\n"
4629
4630                 "%exit      = OpLabel\n"
4631                 "             OpReturn\n"
4632
4633                 "             OpFunctionEnd\n");
4634
4635         {
4636                 ComputeShaderSpec       spec;
4637                 const deUint8           numCases        = 4;
4638                 vector<float>           inputs          (numCases, 0.f);
4639                 vector<float>           outputs;
4640
4641                 spec.assembly           = shader;
4642                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4643
4644                 spec.specConstants.push_back(bitwiseCast<deUint32>(std::numeric_limits<float>::infinity()));
4645                 spec.specConstants.push_back(bitwiseCast<deUint32>(-std::numeric_limits<float>::infinity()));
4646                 spec.specConstants.push_back(bitwiseCast<deUint32>(std::ldexp(1.0f, 16)));
4647                 spec.specConstants.push_back(bitwiseCast<deUint32>(std::ldexp(-1.0f, 32)));
4648
4649                 outputs.push_back(std::numeric_limits<float>::infinity());
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
4654                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4655                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4656
4657                 group->addChild(new SpvAsmComputeShaderCase(
4658                         testCtx, "infinities", "Check that infinities propagated and created", spec));
4659         }
4660
4661         {
4662                 ComputeShaderSpec       spec;
4663                 const deUint8           numCases        = 2;
4664                 vector<float>           inputs          (numCases, 0.f);
4665                 vector<float>           outputs;
4666
4667                 spec.assembly           = shader;
4668                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4669                 spec.verifyIO           = &compareNan;
4670
4671                 outputs.push_back(std::numeric_limits<float>::quiet_NaN());
4672                 outputs.push_back(-std::numeric_limits<float>::quiet_NaN());
4673
4674                 for (deUint8 idx = 0; idx < numCases; ++idx)
4675                         spec.specConstants.push_back(bitwiseCast<deUint32>(outputs[idx]));
4676
4677                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4678                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4679
4680                 group->addChild(new SpvAsmComputeShaderCase(
4681                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
4682         }
4683
4684         {
4685                 ComputeShaderSpec       spec;
4686                 const deUint8           numCases        = 6;
4687                 vector<float>           inputs          (numCases, 0.f);
4688                 vector<float>           outputs;
4689
4690                 spec.assembly           = shader;
4691                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4692
4693                 spec.specConstants.push_back(bitwiseCast<deUint32>(0.f));
4694                 spec.specConstants.push_back(bitwiseCast<deUint32>(-0.f));
4695                 spec.specConstants.push_back(bitwiseCast<deUint32>(std::ldexp(1.0f, -16)));
4696                 spec.specConstants.push_back(bitwiseCast<deUint32>(std::ldexp(-1.0f, -32)));
4697                 spec.specConstants.push_back(bitwiseCast<deUint32>(std::ldexp(1.0f, -127)));
4698                 spec.specConstants.push_back(bitwiseCast<deUint32>(-std::ldexp(1.0f, -128)));
4699
4700                 outputs.push_back(0.f);
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
4707                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4708                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4709
4710                 group->addChild(new SpvAsmComputeShaderCase(
4711                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
4712         }
4713
4714         {
4715                 ComputeShaderSpec       spec;
4716                 const deUint8           numCases        = 6;
4717                 vector<float>           inputs          (numCases, 0.f);
4718                 vector<float>           outputs;
4719
4720                 spec.assembly           = shader;
4721                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4722
4723                 for (deUint8 idx = 0; idx < 6; ++idx)
4724                 {
4725                         const float f = static_cast<float>(idx * 10 - 30) / 4.f;
4726                         spec.specConstants.push_back(bitwiseCast<deUint32>(f));
4727                         outputs.push_back(f);
4728                 }
4729
4730                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4731                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4732
4733                 group->addChild(new SpvAsmComputeShaderCase(
4734                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
4735         }
4736
4737         {
4738                 ComputeShaderSpec       spec;
4739                 const deUint8           numCases        = 4;
4740                 vector<float>           inputs          (numCases, 0.f);
4741                 vector<float>           outputs;
4742
4743                 spec.assembly           = shader;
4744                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4745                 spec.verifyIO           = &compareOpQuantizeF16ComputeExactCase;
4746
4747                 outputs.push_back(constructNormalizedFloat(8, 0x300300));
4748                 outputs.push_back(-constructNormalizedFloat(-7, 0x600800));
4749                 outputs.push_back(constructNormalizedFloat(2, 0x01E000));
4750                 outputs.push_back(constructNormalizedFloat(1, 0xFFE000));
4751
4752                 for (deUint8 idx = 0; idx < numCases; ++idx)
4753                         spec.specConstants.push_back(bitwiseCast<deUint32>(outputs[idx]));
4754
4755                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4756                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4757
4758                 group->addChild(new SpvAsmComputeShaderCase(
4759                         testCtx, "rounded", "Check that are rounded when needed", spec));
4760         }
4761
4762         return group.release();
4763 }
4764
4765 // Checks that constant null/composite values can be used in computation.
4766 tcu::TestCaseGroup* createOpConstantUsageGroup (tcu::TestContext& testCtx)
4767 {
4768         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnullcomposite", "Spotcheck the OpConstantNull & OpConstantComposite instruction"));
4769         ComputeShaderSpec                               spec;
4770         de::Random                                              rnd                             (deStringHash(group->getName()));
4771         const int                                               numElements             = 100;
4772         vector<float>                                   positiveFloats  (numElements, 0);
4773         vector<float>                                   negativeFloats  (numElements, 0);
4774
4775         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4776
4777         for (size_t ndx = 0; ndx < numElements; ++ndx)
4778                 negativeFloats[ndx] = -positiveFloats[ndx];
4779
4780         spec.assembly =
4781                 "OpCapability Shader\n"
4782                 "%std450 = OpExtInstImport \"GLSL.std.450\"\n"
4783                 "OpMemoryModel Logical GLSL450\n"
4784                 "OpEntryPoint GLCompute %main \"main\" %id\n"
4785                 "OpExecutionMode %main LocalSize 1 1 1\n"
4786
4787                 "OpSource GLSL 430\n"
4788                 "OpName %main           \"main\"\n"
4789                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4790
4791                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4792
4793                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4794
4795                 "%fmat      = OpTypeMatrix %fvec3 3\n"
4796                 "%ten       = OpConstant %u32 10\n"
4797                 "%f32arr10  = OpTypeArray %f32 %ten\n"
4798                 "%fst       = OpTypeStruct %f32 %f32\n"
4799
4800                 + string(getComputeAsmInputOutputBuffer()) +
4801
4802                 "%id        = OpVariable %uvec3ptr Input\n"
4803                 "%zero      = OpConstant %i32 0\n"
4804
4805                 // Create a bunch of null values
4806                 "%unull     = OpConstantNull %u32\n"
4807                 "%fnull     = OpConstantNull %f32\n"
4808                 "%vnull     = OpConstantNull %fvec3\n"
4809                 "%mnull     = OpConstantNull %fmat\n"
4810                 "%anull     = OpConstantNull %f32arr10\n"
4811                 "%snull     = OpConstantComposite %fst %fnull %fnull\n"
4812
4813                 "%main      = OpFunction %void None %voidf\n"
4814                 "%label     = OpLabel\n"
4815                 "%idval     = OpLoad %uvec3 %id\n"
4816                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4817                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4818                 "%inval     = OpLoad %f32 %inloc\n"
4819                 "%neg       = OpFNegate %f32 %inval\n"
4820
4821                 // Get the abs() of (a certain element of) those null values
4822                 "%unull_cov = OpConvertUToF %f32 %unull\n"
4823                 "%unull_abs = OpExtInst %f32 %std450 FAbs %unull_cov\n"
4824                 "%fnull_abs = OpExtInst %f32 %std450 FAbs %fnull\n"
4825                 "%vnull_0   = OpCompositeExtract %f32 %vnull 0\n"
4826                 "%vnull_abs = OpExtInst %f32 %std450 FAbs %vnull_0\n"
4827                 "%mnull_12  = OpCompositeExtract %f32 %mnull 1 2\n"
4828                 "%mnull_abs = OpExtInst %f32 %std450 FAbs %mnull_12\n"
4829                 "%anull_3   = OpCompositeExtract %f32 %anull 3\n"
4830                 "%anull_abs = OpExtInst %f32 %std450 FAbs %anull_3\n"
4831                 "%snull_1   = OpCompositeExtract %f32 %snull 1\n"
4832                 "%snull_abs = OpExtInst %f32 %std450 FAbs %snull_1\n"
4833
4834                 // Add them all
4835                 "%add1      = OpFAdd %f32 %neg  %unull_abs\n"
4836                 "%add2      = OpFAdd %f32 %add1 %fnull_abs\n"
4837                 "%add3      = OpFAdd %f32 %add2 %vnull_abs\n"
4838                 "%add4      = OpFAdd %f32 %add3 %mnull_abs\n"
4839                 "%add5      = OpFAdd %f32 %add4 %anull_abs\n"
4840                 "%final     = OpFAdd %f32 %add5 %snull_abs\n"
4841
4842                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4843                 "             OpStore %outloc %final\n" // write to output
4844                 "             OpReturn\n"
4845                 "             OpFunctionEnd\n";
4846         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4847         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4848         spec.numWorkGroups = IVec3(numElements, 1, 1);
4849
4850         group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "Check that values constructed via OpConstantNull & OpConstantComposite can be used", spec));
4851
4852         return group.release();
4853 }
4854
4855 // Assembly code used for testing loop control is based on GLSL source code:
4856 // #version 430
4857 //
4858 // layout(std140, set = 0, binding = 0) readonly buffer Input {
4859 //   float elements[];
4860 // } input_data;
4861 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
4862 //   float elements[];
4863 // } output_data;
4864 //
4865 // void main() {
4866 //   uint x = gl_GlobalInvocationID.x;
4867 //   output_data.elements[x] = input_data.elements[x];
4868 //   for (uint i = 0; i < 4; ++i)
4869 //     output_data.elements[x] += 1.f;
4870 // }
4871 tcu::TestCaseGroup* createLoopControlGroup (tcu::TestContext& testCtx)
4872 {
4873         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "loop_control", "Tests loop control cases"));
4874         vector<CaseParameter>                   cases;
4875         de::Random                                              rnd                             (deStringHash(group->getName()));
4876         const int                                               numElements             = 100;
4877         vector<float>                                   inputFloats             (numElements, 0);
4878         vector<float>                                   outputFloats    (numElements, 0);
4879         const StringTemplate                    shaderTemplate  (
4880                 string(getComputeAsmShaderPreamble()) +
4881
4882                 "OpSource GLSL 430\n"
4883                 "OpName %main \"main\"\n"
4884                 "OpName %id \"gl_GlobalInvocationID\"\n"
4885
4886                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4887
4888                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4889
4890                 "%u32ptr      = OpTypePointer Function %u32\n"
4891
4892                 "%id          = OpVariable %uvec3ptr Input\n"
4893                 "%zero        = OpConstant %i32 0\n"
4894                 "%uzero       = OpConstant %u32 0\n"
4895                 "%one         = OpConstant %i32 1\n"
4896                 "%constf1     = OpConstant %f32 1.0\n"
4897                 "%four        = OpConstant %u32 4\n"
4898
4899                 "%main        = OpFunction %void None %voidf\n"
4900                 "%entry       = OpLabel\n"
4901                 "%i           = OpVariable %u32ptr Function\n"
4902                 "               OpStore %i %uzero\n"
4903
4904                 "%idval       = OpLoad %uvec3 %id\n"
4905                 "%x           = OpCompositeExtract %u32 %idval 0\n"
4906                 "%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
4907                 "%inval       = OpLoad %f32 %inloc\n"
4908                 "%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
4909                 "               OpStore %outloc %inval\n"
4910                 "               OpBranch %loop_entry\n"
4911
4912                 "%loop_entry  = OpLabel\n"
4913                 "%i_val       = OpLoad %u32 %i\n"
4914                 "%cmp_lt      = OpULessThan %bool %i_val %four\n"
4915                 "               OpLoopMerge %loop_merge %loop_body ${CONTROL}\n"
4916                 "               OpBranchConditional %cmp_lt %loop_body %loop_merge\n"
4917                 "%loop_body   = OpLabel\n"
4918                 "%outval      = OpLoad %f32 %outloc\n"
4919                 "%addf1       = OpFAdd %f32 %outval %constf1\n"
4920                 "               OpStore %outloc %addf1\n"
4921                 "%new_i       = OpIAdd %u32 %i_val %one\n"
4922                 "               OpStore %i %new_i\n"
4923                 "               OpBranch %loop_entry\n"
4924                 "%loop_merge  = OpLabel\n"
4925                 "               OpReturn\n"
4926                 "               OpFunctionEnd\n");
4927
4928         cases.push_back(CaseParameter("none",                           "None"));
4929         cases.push_back(CaseParameter("unroll",                         "Unroll"));
4930         cases.push_back(CaseParameter("dont_unroll",            "DontUnroll"));
4931         cases.push_back(CaseParameter("unroll_dont_unroll",     "Unroll|DontUnroll"));
4932
4933         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
4934
4935         for (size_t ndx = 0; ndx < numElements; ++ndx)
4936                 outputFloats[ndx] = inputFloats[ndx] + 4.f;
4937
4938         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4939         {
4940                 map<string, string>             specializations;
4941                 ComputeShaderSpec               spec;
4942
4943                 specializations["CONTROL"] = cases[caseNdx].param;
4944                 spec.assembly = shaderTemplate.specialize(specializations);
4945                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4946                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
4947                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4948
4949                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4950         }
4951
4952         group->addChild(new SpvAsmLoopControlDependencyLengthCase(testCtx, "dependency_length", "dependency_length"));
4953         group->addChild(new SpvAsmLoopControlDependencyInfiniteCase(testCtx, "dependency_infinite", "dependency_infinite"));
4954
4955         return group.release();
4956 }
4957
4958 // Assembly code used for testing selection control is based on GLSL source code:
4959 // #version 430
4960 //
4961 // layout(std140, set = 0, binding = 0) readonly buffer Input {
4962 //   float elements[];
4963 // } input_data;
4964 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
4965 //   float elements[];
4966 // } output_data;
4967 //
4968 // void main() {
4969 //   uint x = gl_GlobalInvocationID.x;
4970 //   float val = input_data.elements[x];
4971 //   if (val > 10.f)
4972 //     output_data.elements[x] = val + 1.f;
4973 //   else
4974 //     output_data.elements[x] = val - 1.f;
4975 // }
4976 tcu::TestCaseGroup* createSelectionControlGroup (tcu::TestContext& testCtx)
4977 {
4978         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "selection_control", "Tests selection control cases"));
4979         vector<CaseParameter>                   cases;
4980         de::Random                                              rnd                             (deStringHash(group->getName()));
4981         const int                                               numElements             = 100;
4982         vector<float>                                   inputFloats             (numElements, 0);
4983         vector<float>                                   outputFloats    (numElements, 0);
4984         const StringTemplate                    shaderTemplate  (
4985                 string(getComputeAsmShaderPreamble()) +
4986
4987                 "OpSource GLSL 430\n"
4988                 "OpName %main \"main\"\n"
4989                 "OpName %id \"gl_GlobalInvocationID\"\n"
4990
4991                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4992
4993                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4994
4995                 "%id       = OpVariable %uvec3ptr Input\n"
4996                 "%zero     = OpConstant %i32 0\n"
4997                 "%constf1  = OpConstant %f32 1.0\n"
4998                 "%constf10 = OpConstant %f32 10.0\n"
4999
5000                 "%main     = OpFunction %void None %voidf\n"
5001                 "%entry    = OpLabel\n"
5002                 "%idval    = OpLoad %uvec3 %id\n"
5003                 "%x        = OpCompositeExtract %u32 %idval 0\n"
5004                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
5005                 "%inval    = OpLoad %f32 %inloc\n"
5006                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
5007                 "%cmp_gt   = OpFOrdGreaterThan %bool %inval %constf10\n"
5008
5009                 "            OpSelectionMerge %if_end ${CONTROL}\n"
5010                 "            OpBranchConditional %cmp_gt %if_true %if_false\n"
5011                 "%if_true  = OpLabel\n"
5012                 "%addf1    = OpFAdd %f32 %inval %constf1\n"
5013                 "            OpStore %outloc %addf1\n"
5014                 "            OpBranch %if_end\n"
5015                 "%if_false = OpLabel\n"
5016                 "%subf1    = OpFSub %f32 %inval %constf1\n"
5017                 "            OpStore %outloc %subf1\n"
5018                 "            OpBranch %if_end\n"
5019                 "%if_end   = OpLabel\n"
5020                 "            OpReturn\n"
5021                 "            OpFunctionEnd\n");
5022
5023         cases.push_back(CaseParameter("none",                                   "None"));
5024         cases.push_back(CaseParameter("flatten",                                "Flatten"));
5025         cases.push_back(CaseParameter("dont_flatten",                   "DontFlatten"));
5026         cases.push_back(CaseParameter("flatten_dont_flatten",   "DontFlatten|Flatten"));
5027
5028         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5029
5030         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
5031         floorAll(inputFloats);
5032
5033         for (size_t ndx = 0; ndx < numElements; ++ndx)
5034                 outputFloats[ndx] = inputFloats[ndx] + (inputFloats[ndx] > 10.f ? 1.f : -1.f);
5035
5036         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5037         {
5038                 map<string, string>             specializations;
5039                 ComputeShaderSpec               spec;
5040
5041                 specializations["CONTROL"] = cases[caseNdx].param;
5042                 spec.assembly = shaderTemplate.specialize(specializations);
5043                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5044                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5045                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5046
5047                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5048         }
5049
5050         return group.release();
5051 }
5052
5053 // Assembly code used for testing function control is based on GLSL source code:
5054 //
5055 // #version 430
5056 //
5057 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5058 //   float elements[];
5059 // } input_data;
5060 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5061 //   float elements[];
5062 // } output_data;
5063 //
5064 // float const10() { return 10.f; }
5065 //
5066 // void main() {
5067 //   uint x = gl_GlobalInvocationID.x;
5068 //   output_data.elements[x] = input_data.elements[x] + const10();
5069 // }
5070 tcu::TestCaseGroup* createFunctionControlGroup (tcu::TestContext& testCtx)
5071 {
5072         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "function_control", "Tests function control cases"));
5073         vector<CaseParameter>                   cases;
5074         de::Random                                              rnd                             (deStringHash(group->getName()));
5075         const int                                               numElements             = 100;
5076         vector<float>                                   inputFloats             (numElements, 0);
5077         vector<float>                                   outputFloats    (numElements, 0);
5078         const StringTemplate                    shaderTemplate  (
5079                 string(getComputeAsmShaderPreamble()) +
5080
5081                 "OpSource GLSL 430\n"
5082                 "OpName %main \"main\"\n"
5083                 "OpName %func_const10 \"const10(\"\n"
5084                 "OpName %id \"gl_GlobalInvocationID\"\n"
5085
5086                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5087
5088                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5089
5090                 "%f32f = OpTypeFunction %f32\n"
5091                 "%id = OpVariable %uvec3ptr Input\n"
5092                 "%zero = OpConstant %i32 0\n"
5093                 "%constf10 = OpConstant %f32 10.0\n"
5094
5095                 "%main         = OpFunction %void None %voidf\n"
5096                 "%entry        = OpLabel\n"
5097                 "%idval        = OpLoad %uvec3 %id\n"
5098                 "%x            = OpCompositeExtract %u32 %idval 0\n"
5099                 "%inloc        = OpAccessChain %f32ptr %indata %zero %x\n"
5100                 "%inval        = OpLoad %f32 %inloc\n"
5101                 "%ret_10       = OpFunctionCall %f32 %func_const10\n"
5102                 "%fadd         = OpFAdd %f32 %inval %ret_10\n"
5103                 "%outloc       = OpAccessChain %f32ptr %outdata %zero %x\n"
5104                 "                OpStore %outloc %fadd\n"
5105                 "                OpReturn\n"
5106                 "                OpFunctionEnd\n"
5107
5108                 "%func_const10 = OpFunction %f32 ${CONTROL} %f32f\n"
5109                 "%label        = OpLabel\n"
5110                 "                OpReturnValue %constf10\n"
5111                 "                OpFunctionEnd\n");
5112
5113         cases.push_back(CaseParameter("none",                                           "None"));
5114         cases.push_back(CaseParameter("inline",                                         "Inline"));
5115         cases.push_back(CaseParameter("dont_inline",                            "DontInline"));
5116         cases.push_back(CaseParameter("pure",                                           "Pure"));
5117         cases.push_back(CaseParameter("const",                                          "Const"));
5118         cases.push_back(CaseParameter("inline_pure",                            "Inline|Pure"));
5119         cases.push_back(CaseParameter("const_dont_inline",                      "Const|DontInline"));
5120         cases.push_back(CaseParameter("inline_dont_inline",                     "Inline|DontInline"));
5121         cases.push_back(CaseParameter("pure_inline_dont_inline",        "Pure|Inline|DontInline"));
5122
5123         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5124
5125         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
5126         floorAll(inputFloats);
5127
5128         for (size_t ndx = 0; ndx < numElements; ++ndx)
5129                 outputFloats[ndx] = inputFloats[ndx] + 10.f;
5130
5131         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5132         {
5133                 map<string, string>             specializations;
5134                 ComputeShaderSpec               spec;
5135
5136                 specializations["CONTROL"] = cases[caseNdx].param;
5137                 spec.assembly = shaderTemplate.specialize(specializations);
5138                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5139                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5140                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5141
5142                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5143         }
5144
5145         return group.release();
5146 }
5147
5148 tcu::TestCaseGroup* createMemoryAccessGroup (tcu::TestContext& testCtx)
5149 {
5150         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "memory_access", "Tests memory access cases"));
5151         vector<CaseParameter>                   cases;
5152         de::Random                                              rnd                             (deStringHash(group->getName()));
5153         const int                                               numElements             = 100;
5154         vector<float>                                   inputFloats             (numElements, 0);
5155         vector<float>                                   outputFloats    (numElements, 0);
5156         const StringTemplate                    shaderTemplate  (
5157                 string(getComputeAsmShaderPreamble()) +
5158
5159                 "OpSource GLSL 430\n"
5160                 "OpName %main           \"main\"\n"
5161                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5162
5163                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5164
5165                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5166
5167                 "%f32ptr_f  = OpTypePointer Function %f32\n"
5168
5169                 "%id        = OpVariable %uvec3ptr Input\n"
5170                 "%zero      = OpConstant %i32 0\n"
5171                 "%four      = OpConstant %i32 4\n"
5172
5173                 "%main      = OpFunction %void None %voidf\n"
5174                 "%label     = OpLabel\n"
5175                 "%copy      = OpVariable %f32ptr_f Function\n"
5176                 "%idval     = OpLoad %uvec3 %id ${ACCESS}\n"
5177                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5178                 "%inloc     = OpAccessChain %f32ptr %indata  %zero %x\n"
5179                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5180                 "             OpCopyMemory %copy %inloc ${ACCESS}\n"
5181                 "%val1      = OpLoad %f32 %copy\n"
5182                 "%val2      = OpLoad %f32 %inloc\n"
5183                 "%add       = OpFAdd %f32 %val1 %val2\n"
5184                 "             OpStore %outloc %add ${ACCESS}\n"
5185                 "             OpReturn\n"
5186                 "             OpFunctionEnd\n");
5187
5188         cases.push_back(CaseParameter("null",                                   ""));
5189         cases.push_back(CaseParameter("none",                                   "None"));
5190         cases.push_back(CaseParameter("volatile",                               "Volatile"));
5191         cases.push_back(CaseParameter("aligned",                                "Aligned 4"));
5192         cases.push_back(CaseParameter("nontemporal",                    "Nontemporal"));
5193         cases.push_back(CaseParameter("aligned_nontemporal",    "Aligned|Nontemporal 4"));
5194         cases.push_back(CaseParameter("aligned_volatile",               "Volatile|Aligned 4"));
5195
5196         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5197
5198         for (size_t ndx = 0; ndx < numElements; ++ndx)
5199                 outputFloats[ndx] = inputFloats[ndx] + inputFloats[ndx];
5200
5201         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5202         {
5203                 map<string, string>             specializations;
5204                 ComputeShaderSpec               spec;
5205
5206                 specializations["ACCESS"] = cases[caseNdx].param;
5207                 spec.assembly = shaderTemplate.specialize(specializations);
5208                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5209                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5210                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5211
5212                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5213         }
5214
5215         return group.release();
5216 }
5217
5218 // Checks that we can get undefined values for various types, without exercising a computation with it.
5219 tcu::TestCaseGroup* createOpUndefGroup (tcu::TestContext& testCtx)
5220 {
5221         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opundef", "Tests the OpUndef instruction"));
5222         vector<CaseParameter>                   cases;
5223         de::Random                                              rnd                             (deStringHash(group->getName()));
5224         const int                                               numElements             = 100;
5225         vector<float>                                   positiveFloats  (numElements, 0);
5226         vector<float>                                   negativeFloats  (numElements, 0);
5227         const StringTemplate                    shaderTemplate  (
5228                 string(getComputeAsmShaderPreamble()) +
5229
5230                 "OpSource GLSL 430\n"
5231                 "OpName %main           \"main\"\n"
5232                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5233
5234                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5235
5236                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
5237                 "%uvec2     = OpTypeVector %u32 2\n"
5238                 "%fvec4     = OpTypeVector %f32 4\n"
5239                 "%fmat33    = OpTypeMatrix %fvec3 3\n"
5240                 "%image     = OpTypeImage %f32 2D 0 0 0 1 Unknown\n"
5241                 "%sampler   = OpTypeSampler\n"
5242                 "%simage    = OpTypeSampledImage %image\n"
5243                 "%const100  = OpConstant %u32 100\n"
5244                 "%uarr100   = OpTypeArray %i32 %const100\n"
5245                 "%struct    = OpTypeStruct %f32 %i32 %u32\n"
5246                 "%pointer   = OpTypePointer Function %i32\n"
5247                 + string(getComputeAsmInputOutputBuffer()) +
5248
5249                 "%id        = OpVariable %uvec3ptr Input\n"
5250                 "%zero      = OpConstant %i32 0\n"
5251
5252                 "%main      = OpFunction %void None %voidf\n"
5253                 "%label     = OpLabel\n"
5254
5255                 "%undef     = OpUndef ${TYPE}\n"
5256
5257                 "%idval     = OpLoad %uvec3 %id\n"
5258                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5259
5260                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5261                 "%inval     = OpLoad %f32 %inloc\n"
5262                 "%neg       = OpFNegate %f32 %inval\n"
5263                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5264                 "             OpStore %outloc %neg\n"
5265                 "             OpReturn\n"
5266                 "             OpFunctionEnd\n");
5267
5268         cases.push_back(CaseParameter("bool",                   "%bool"));
5269         cases.push_back(CaseParameter("sint32",                 "%i32"));
5270         cases.push_back(CaseParameter("uint32",                 "%u32"));
5271         cases.push_back(CaseParameter("float32",                "%f32"));
5272         cases.push_back(CaseParameter("vec4float32",    "%fvec4"));
5273         cases.push_back(CaseParameter("vec2uint32",             "%uvec2"));
5274         cases.push_back(CaseParameter("matrix",                 "%fmat33"));
5275         cases.push_back(CaseParameter("image",                  "%image"));
5276         cases.push_back(CaseParameter("sampler",                "%sampler"));
5277         cases.push_back(CaseParameter("sampledimage",   "%simage"));
5278         cases.push_back(CaseParameter("array",                  "%uarr100"));
5279         cases.push_back(CaseParameter("runtimearray",   "%f32arr"));
5280         cases.push_back(CaseParameter("struct",                 "%struct"));
5281         cases.push_back(CaseParameter("pointer",                "%pointer"));
5282
5283         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
5284
5285         for (size_t ndx = 0; ndx < numElements; ++ndx)
5286                 negativeFloats[ndx] = -positiveFloats[ndx];
5287
5288         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5289         {
5290                 map<string, string>             specializations;
5291                 ComputeShaderSpec               spec;
5292
5293                 specializations["TYPE"] = cases[caseNdx].param;
5294                 spec.assembly = shaderTemplate.specialize(specializations);
5295                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
5296                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
5297                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5298
5299                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5300         }
5301
5302                 return group.release();
5303 }
5304 } // anonymous
5305
5306 tcu::TestCaseGroup* createOpSourceTests (tcu::TestContext& testCtx)
5307 {
5308         struct NameCodePair { string name, code; };
5309         RGBA                                                    defaultColors[4];
5310         de::MovePtr<tcu::TestCaseGroup> opSourceTests                   (new tcu::TestCaseGroup(testCtx, "opsource", "OpSource instruction"));
5311         const std::string                               opsourceGLSLWithFile    = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile ";
5312         map<string, string>                             fragments                               = passthruFragments();
5313         const NameCodePair                              tests[]                                 =
5314         {
5315                 {"unknown", "OpSource Unknown 321"},
5316                 {"essl", "OpSource ESSL 310"},
5317                 {"glsl", "OpSource GLSL 450"},
5318                 {"opencl_cpp", "OpSource OpenCL_CPP 120"},
5319                 {"opencl_c", "OpSource OpenCL_C 120"},
5320                 {"multiple", "OpSource GLSL 450\nOpSource GLSL 450"},
5321                 {"file", opsourceGLSLWithFile},
5322                 {"source", opsourceGLSLWithFile + "\"void main(){}\""},
5323                 // Longest possible source string: SPIR-V limits instructions to 65535
5324                 // words, of which the first 4 are opsourceGLSLWithFile; the rest will
5325                 // contain 65530 UTF8 characters (one word each) plus one last word
5326                 // containing 3 ASCII characters and \0.
5327                 {"longsource", opsourceGLSLWithFile + '"' + makeLongUTF8String(65530) + "ccc" + '"'}
5328         };
5329
5330         getDefaultColors(defaultColors);
5331         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
5332         {
5333                 fragments["debug"] = tests[testNdx].code;
5334                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
5335         }
5336
5337         return opSourceTests.release();
5338 }
5339
5340 tcu::TestCaseGroup* createOpSourceContinuedTests (tcu::TestContext& testCtx)
5341 {
5342         struct NameCodePair { string name, code; };
5343         RGBA                                                            defaultColors[4];
5344         de::MovePtr<tcu::TestCaseGroup>         opSourceTests           (new tcu::TestCaseGroup(testCtx, "opsourcecontinued", "OpSourceContinued instruction"));
5345         map<string, string>                                     fragments                       = passthruFragments();
5346         const std::string                                       opsource                        = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile \"void main(){}\"\n";
5347         const NameCodePair                                      tests[]                         =
5348         {
5349                 {"empty", opsource + "OpSourceContinued \"\""},
5350                 {"short", opsource + "OpSourceContinued \"abcde\""},
5351                 {"multiple", opsource + "OpSourceContinued \"abcde\"\nOpSourceContinued \"fghij\""},
5352                 // Longest possible source string: SPIR-V limits instructions to 65535
5353                 // words, of which the first one is OpSourceContinued/length; the rest
5354                 // will contain 65533 UTF8 characters (one word each) plus one last word
5355                 // containing 3 ASCII characters and \0.
5356                 {"long", opsource + "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\""}
5357         };
5358
5359         getDefaultColors(defaultColors);
5360         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
5361         {
5362                 fragments["debug"] = tests[testNdx].code;
5363                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
5364         }
5365
5366         return opSourceTests.release();
5367 }
5368 tcu::TestCaseGroup* createOpNoLineTests(tcu::TestContext& testCtx)
5369 {
5370         RGBA                                                             defaultColors[4];
5371         de::MovePtr<tcu::TestCaseGroup>          opLineTests             (new tcu::TestCaseGroup(testCtx, "opnoline", "OpNoLine instruction"));
5372         map<string, string>                                      fragments;
5373         getDefaultColors(defaultColors);
5374         fragments["debug"]                      =
5375                 "%name = OpString \"name\"\n";
5376
5377         fragments["pre_main"]   =
5378                 "OpNoLine\n"
5379                 "OpNoLine\n"
5380                 "OpLine %name 1 1\n"
5381                 "OpNoLine\n"
5382                 "OpLine %name 1 1\n"
5383                 "OpLine %name 1 1\n"
5384                 "%second_function = OpFunction %v4f32 None %v4f32_function\n"
5385                 "OpNoLine\n"
5386                 "OpLine %name 1 1\n"
5387                 "OpNoLine\n"
5388                 "OpLine %name 1 1\n"
5389                 "OpLine %name 1 1\n"
5390                 "%second_param1 = OpFunctionParameter %v4f32\n"
5391                 "OpNoLine\n"
5392                 "OpNoLine\n"
5393                 "%label_secondfunction = OpLabel\n"
5394                 "OpNoLine\n"
5395                 "OpReturnValue %second_param1\n"
5396                 "OpFunctionEnd\n"
5397                 "OpNoLine\n"
5398                 "OpNoLine\n";
5399
5400         fragments["testfun"]            =
5401                 // A %test_code function that returns its argument unchanged.
5402                 "OpNoLine\n"
5403                 "OpNoLine\n"
5404                 "OpLine %name 1 1\n"
5405                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
5406                 "OpNoLine\n"
5407                 "%param1 = OpFunctionParameter %v4f32\n"
5408                 "OpNoLine\n"
5409                 "OpNoLine\n"
5410                 "%label_testfun = OpLabel\n"
5411                 "OpNoLine\n"
5412                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
5413                 "OpReturnValue %val1\n"
5414                 "OpFunctionEnd\n"
5415                 "OpLine %name 1 1\n"
5416                 "OpNoLine\n";
5417
5418         createTestsForAllStages("opnoline", defaultColors, defaultColors, fragments, opLineTests.get());
5419
5420         return opLineTests.release();
5421 }
5422
5423 tcu::TestCaseGroup* createOpModuleProcessedTests(tcu::TestContext& testCtx)
5424 {
5425         RGBA                                                            defaultColors[4];
5426         de::MovePtr<tcu::TestCaseGroup>         opModuleProcessedTests                  (new tcu::TestCaseGroup(testCtx, "opmoduleprocessed", "OpModuleProcessed instruction"));
5427         map<string, string>                                     fragments;
5428         std::vector<std::string>                        noExtensions;
5429         GraphicsResources                                       resources;
5430
5431         getDefaultColors(defaultColors);
5432         resources.verifyBinary = veryfiBinaryShader;
5433         resources.spirvVersion = SPIRV_VERSION_1_3;
5434
5435         fragments["moduleprocessed"]                                                    =
5436                 "OpModuleProcessed \"VULKAN CTS\"\n"
5437                 "OpModuleProcessed \"Negative values\"\n"
5438                 "OpModuleProcessed \"Date: 2017/09/21\"\n";
5439
5440         fragments["pre_main"]   =
5441                 "%second_function = OpFunction %v4f32 None %v4f32_function\n"
5442                 "%second_param1 = OpFunctionParameter %v4f32\n"
5443                 "%label_secondfunction = OpLabel\n"
5444                 "OpReturnValue %second_param1\n"
5445                 "OpFunctionEnd\n";
5446
5447         fragments["testfun"]            =
5448                 // A %test_code function that returns its argument unchanged.
5449                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
5450                 "%param1 = OpFunctionParameter %v4f32\n"
5451                 "%label_testfun = OpLabel\n"
5452                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
5453                 "OpReturnValue %val1\n"
5454                 "OpFunctionEnd\n";
5455
5456         createTestsForAllStages ("opmoduleprocessed", defaultColors, defaultColors, fragments, resources, noExtensions, opModuleProcessedTests.get());
5457
5458         return opModuleProcessedTests.release();
5459 }
5460
5461
5462 tcu::TestCaseGroup* createOpLineTests(tcu::TestContext& testCtx)
5463 {
5464         RGBA                                                                                                    defaultColors[4];
5465         de::MovePtr<tcu::TestCaseGroup>                                                 opLineTests                     (new tcu::TestCaseGroup(testCtx, "opline", "OpLine instruction"));
5466         map<string, string>                                                                             fragments;
5467         std::vector<std::pair<std::string, std::string> >               problemStrings;
5468
5469         problemStrings.push_back(std::make_pair<std::string, std::string>("empty_name", ""));
5470         problemStrings.push_back(std::make_pair<std::string, std::string>("short_name", "short_name"));
5471         problemStrings.push_back(std::make_pair<std::string, std::string>("long_name", makeLongUTF8String(65530) + "ccc"));
5472         getDefaultColors(defaultColors);
5473
5474         fragments["debug"]                      =
5475                 "%other_name = OpString \"other_name\"\n";
5476
5477         fragments["pre_main"]   =
5478                 "OpLine %file_name 32 0\n"
5479                 "OpLine %file_name 32 32\n"
5480                 "OpLine %file_name 32 40\n"
5481                 "OpLine %other_name 32 40\n"
5482                 "OpLine %other_name 0 100\n"
5483                 "OpLine %other_name 0 4294967295\n"
5484                 "OpLine %other_name 4294967295 0\n"
5485                 "OpLine %other_name 32 40\n"
5486                 "OpLine %file_name 0 0\n"
5487                 "%second_function = OpFunction %v4f32 None %v4f32_function\n"
5488                 "OpLine %file_name 1 0\n"
5489                 "%second_param1 = OpFunctionParameter %v4f32\n"
5490                 "OpLine %file_name 1 3\n"
5491                 "OpLine %file_name 1 2\n"
5492                 "%label_secondfunction = OpLabel\n"
5493                 "OpLine %file_name 0 2\n"
5494                 "OpReturnValue %second_param1\n"
5495                 "OpFunctionEnd\n"
5496                 "OpLine %file_name 0 2\n"
5497                 "OpLine %file_name 0 2\n";
5498
5499         fragments["testfun"]            =
5500                 // A %test_code function that returns its argument unchanged.
5501                 "OpLine %file_name 1 0\n"
5502                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
5503                 "OpLine %file_name 16 330\n"
5504                 "%param1 = OpFunctionParameter %v4f32\n"
5505                 "OpLine %file_name 14 442\n"
5506                 "%label_testfun = OpLabel\n"
5507                 "OpLine %file_name 11 1024\n"
5508                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
5509                 "OpLine %file_name 2 97\n"
5510                 "OpReturnValue %val1\n"
5511                 "OpFunctionEnd\n"
5512                 "OpLine %file_name 5 32\n";
5513
5514         for (size_t i = 0; i < problemStrings.size(); ++i)
5515         {
5516                 map<string, string> testFragments = fragments;
5517                 testFragments["debug"] += "%file_name = OpString \"" + problemStrings[i].second + "\"\n";
5518                 createTestsForAllStages(string("opline") + "_" + problemStrings[i].first, defaultColors, defaultColors, testFragments, opLineTests.get());
5519         }
5520
5521         return opLineTests.release();
5522 }
5523
5524 tcu::TestCaseGroup* createOpConstantNullTests(tcu::TestContext& testCtx)
5525 {
5526         de::MovePtr<tcu::TestCaseGroup> opConstantNullTests             (new tcu::TestCaseGroup(testCtx, "opconstantnull", "OpConstantNull instruction"));
5527         RGBA                                                    colors[4];
5528
5529
5530         const char                                              functionStart[] =
5531                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
5532                 "%param1 = OpFunctionParameter %v4f32\n"
5533                 "%lbl    = OpLabel\n";
5534
5535         const char                                              functionEnd[]   =
5536                 "OpReturnValue %transformed_param\n"
5537                 "OpFunctionEnd\n";
5538
5539         struct NameConstantsCode
5540         {
5541                 string name;
5542                 string constants;
5543                 string code;
5544         };
5545
5546         NameConstantsCode tests[] =
5547         {
5548                 {
5549                         "vec4",
5550                         "%cnull = OpConstantNull %v4f32\n",
5551                         "%transformed_param = OpFAdd %v4f32 %param1 %cnull\n"
5552                 },
5553                 {
5554                         "float",
5555                         "%cnull = OpConstantNull %f32\n",
5556                         "%vp = OpVariable %fp_v4f32 Function\n"
5557                         "%v  = OpLoad %v4f32 %vp\n"
5558                         "%v0 = OpVectorInsertDynamic %v4f32 %v %cnull %c_i32_0\n"
5559                         "%v1 = OpVectorInsertDynamic %v4f32 %v0 %cnull %c_i32_1\n"
5560                         "%v2 = OpVectorInsertDynamic %v4f32 %v1 %cnull %c_i32_2\n"
5561                         "%v3 = OpVectorInsertDynamic %v4f32 %v2 %cnull %c_i32_3\n"
5562                         "%transformed_param = OpFAdd %v4f32 %param1 %v3\n"
5563                 },
5564                 {
5565                         "bool",
5566                         "%cnull             = OpConstantNull %bool\n",
5567                         "%v                 = OpVariable %fp_v4f32 Function\n"
5568                         "                     OpStore %v %param1\n"
5569                         "                     OpSelectionMerge %false_label None\n"
5570                         "                     OpBranchConditional %cnull %true_label %false_label\n"
5571                         "%true_label        = OpLabel\n"
5572                         "                     OpStore %v %c_v4f32_0_5_0_5_0_5_0_5\n"
5573                         "                     OpBranch %false_label\n"
5574                         "%false_label       = OpLabel\n"
5575                         "%transformed_param = OpLoad %v4f32 %v\n"
5576                 },
5577                 {
5578                         "i32",
5579                         "%cnull             = OpConstantNull %i32\n",
5580                         "%v                 = OpVariable %fp_v4f32 Function %c_v4f32_0_5_0_5_0_5_0_5\n"
5581                         "%b                 = OpIEqual %bool %cnull %c_i32_0\n"
5582                         "                     OpSelectionMerge %false_label None\n"
5583                         "                     OpBranchConditional %b %true_label %false_label\n"
5584                         "%true_label        = OpLabel\n"
5585                         "                     OpStore %v %param1\n"
5586                         "                     OpBranch %false_label\n"
5587                         "%false_label       = OpLabel\n"
5588                         "%transformed_param = OpLoad %v4f32 %v\n"
5589                 },
5590                 {
5591                         "struct",
5592                         "%stype             = OpTypeStruct %f32 %v4f32\n"
5593                         "%fp_stype          = OpTypePointer Function %stype\n"
5594                         "%cnull             = OpConstantNull %stype\n",
5595                         "%v                 = OpVariable %fp_stype Function %cnull\n"
5596                         "%f                 = OpAccessChain %fp_v4f32 %v %c_i32_1\n"
5597                         "%f_val             = OpLoad %v4f32 %f\n"
5598                         "%transformed_param = OpFAdd %v4f32 %param1 %f_val\n"
5599                 },
5600                 {
5601                         "array",
5602                         "%a4_v4f32          = OpTypeArray %v4f32 %c_u32_4\n"
5603                         "%fp_a4_v4f32       = OpTypePointer Function %a4_v4f32\n"
5604                         "%cnull             = OpConstantNull %a4_v4f32\n",
5605                         "%v                 = OpVariable %fp_a4_v4f32 Function %cnull\n"
5606                         "%f                 = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
5607                         "%f1                = OpAccessChain %fp_v4f32 %v %c_u32_1\n"
5608                         "%f2                = OpAccessChain %fp_v4f32 %v %c_u32_2\n"
5609                         "%f3                = OpAccessChain %fp_v4f32 %v %c_u32_3\n"
5610                         "%f_val             = OpLoad %v4f32 %f\n"
5611                         "%f1_val            = OpLoad %v4f32 %f1\n"
5612                         "%f2_val            = OpLoad %v4f32 %f2\n"
5613                         "%f3_val            = OpLoad %v4f32 %f3\n"
5614                         "%t0                = OpFAdd %v4f32 %param1 %f_val\n"
5615                         "%t1                = OpFAdd %v4f32 %t0 %f1_val\n"
5616                         "%t2                = OpFAdd %v4f32 %t1 %f2_val\n"
5617                         "%transformed_param = OpFAdd %v4f32 %t2 %f3_val\n"
5618                 },
5619                 {
5620                         "matrix",
5621                         "%mat4x4_f32        = OpTypeMatrix %v4f32 4\n"
5622                         "%cnull             = OpConstantNull %mat4x4_f32\n",
5623                         // Our null matrix * any vector should result in a zero vector.
5624                         "%v                 = OpVectorTimesMatrix %v4f32 %param1 %cnull\n"
5625                         "%transformed_param = OpFAdd %v4f32 %param1 %v\n"
5626                 }
5627         };
5628
5629         getHalfColorsFullAlpha(colors);
5630
5631         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
5632         {
5633                 map<string, string> fragments;
5634                 fragments["pre_main"] = tests[testNdx].constants;
5635                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
5636                 createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, opConstantNullTests.get());
5637         }
5638         return opConstantNullTests.release();
5639 }
5640 tcu::TestCaseGroup* createOpConstantCompositeTests(tcu::TestContext& testCtx)
5641 {
5642         de::MovePtr<tcu::TestCaseGroup> opConstantCompositeTests                (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "OpConstantComposite instruction"));
5643         RGBA                                                    inputColors[4];
5644         RGBA                                                    outputColors[4];
5645
5646
5647         const char                                              functionStart[]  =
5648                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
5649                 "%param1 = OpFunctionParameter %v4f32\n"
5650                 "%lbl    = OpLabel\n";
5651
5652         const char                                              functionEnd[]           =
5653                 "OpReturnValue %transformed_param\n"
5654                 "OpFunctionEnd\n";
5655
5656         struct NameConstantsCode
5657         {
5658                 string name;
5659                 string constants;
5660                 string code;
5661         };
5662
5663         NameConstantsCode tests[] =
5664         {
5665                 {
5666                         "vec4",
5667
5668                         "%cval              = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0\n",
5669                         "%transformed_param = OpFAdd %v4f32 %param1 %cval\n"
5670                 },
5671                 {
5672                         "struct",
5673
5674                         "%stype             = OpTypeStruct %v4f32 %f32\n"
5675                         "%fp_stype          = OpTypePointer Function %stype\n"
5676                         "%f32_n_1           = OpConstant %f32 -1.0\n"
5677                         "%f32_1_5           = OpConstant %f32 !0x3fc00000\n" // +1.5
5678                         "%cvec              = OpConstantComposite %v4f32 %f32_1_5 %f32_1_5 %f32_1_5 %c_f32_1\n"
5679                         "%cval              = OpConstantComposite %stype %cvec %f32_n_1\n",
5680
5681                         "%v                 = OpVariable %fp_stype Function %cval\n"
5682                         "%vec_ptr           = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
5683                         "%f32_ptr           = OpAccessChain %fp_f32 %v %c_u32_1\n"
5684                         "%vec_val           = OpLoad %v4f32 %vec_ptr\n"
5685                         "%f32_val           = OpLoad %f32 %f32_ptr\n"
5686                         "%tmp1              = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_1 %f32_val\n" // vec4(-1)
5687                         "%tmp2              = OpFAdd %v4f32 %tmp1 %param1\n" // param1 + vec4(-1)
5688                         "%transformed_param = OpFAdd %v4f32 %tmp2 %vec_val\n" // param1 + vec4(-1) + vec4(1.5, 1.5, 1.5, 1.0)
5689                 },
5690                 {
5691                         // [1|0|0|0.5] [x] = x + 0.5
5692                         // [0|1|0|0.5] [y] = y + 0.5
5693                         // [0|0|1|0.5] [z] = z + 0.5
5694                         // [0|0|0|1  ] [1] = 1
5695                         "matrix",
5696
5697                         "%mat4x4_f32          = OpTypeMatrix %v4f32 4\n"
5698                     "%v4f32_1_0_0_0       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_0 %c_f32_0 %c_f32_0\n"
5699                     "%v4f32_0_1_0_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_1 %c_f32_0 %c_f32_0\n"
5700                     "%v4f32_0_0_1_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_1 %c_f32_0\n"
5701                     "%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"
5702                         "%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",
5703
5704                         "%transformed_param   = OpMatrixTimesVector %v4f32 %cval %param1\n"
5705                 },
5706                 {
5707                         "array",
5708
5709                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
5710                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
5711                         "%f32_n_1             = OpConstant %f32 -1.0\n"
5712                         "%f32_1_5             = OpConstant %f32 !0x3fc00000\n" // +1.5
5713                         "%carr                = OpConstantComposite %a4f32 %c_f32_0 %f32_n_1 %f32_1_5 %c_f32_0\n",
5714
5715                         "%v                   = OpVariable %fp_a4f32 Function %carr\n"
5716                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_0\n"
5717                         "%f1                  = OpAccessChain %fp_f32 %v %c_u32_1\n"
5718                         "%f2                  = OpAccessChain %fp_f32 %v %c_u32_2\n"
5719                         "%f3                  = OpAccessChain %fp_f32 %v %c_u32_3\n"
5720                         "%f_val               = OpLoad %f32 %f\n"
5721                         "%f1_val              = OpLoad %f32 %f1\n"
5722                         "%f2_val              = OpLoad %f32 %f2\n"
5723                         "%f3_val              = OpLoad %f32 %f3\n"
5724                         "%ftot1               = OpFAdd %f32 %f_val %f1_val\n"
5725                         "%ftot2               = OpFAdd %f32 %ftot1 %f2_val\n"
5726                         "%ftot3               = OpFAdd %f32 %ftot2 %f3_val\n"  // 0 - 1 + 1.5 + 0
5727                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %ftot3\n"
5728                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
5729                 },
5730                 {
5731                         //
5732                         // [
5733                         //   {
5734                         //      0.0,
5735                         //      [ 1.0, 1.0, 1.0, 1.0]
5736                         //   },
5737                         //   {
5738                         //      1.0,
5739                         //      [ 0.0, 0.5, 0.0, 0.0]
5740                         //   }, //     ^^^
5741                         //   {
5742                         //      0.0,
5743                         //      [ 1.0, 1.0, 1.0, 1.0]
5744                         //   }
5745                         // ]
5746                         "array_of_struct_of_array",
5747
5748                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
5749                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
5750                         "%stype               = OpTypeStruct %f32 %a4f32\n"
5751                         "%a3stype             = OpTypeArray %stype %c_u32_3\n"
5752                         "%fp_a3stype          = OpTypePointer Function %a3stype\n"
5753                         "%ca4f32_0            = OpConstantComposite %a4f32 %c_f32_0 %c_f32_0_5 %c_f32_0 %c_f32_0\n"
5754                         "%ca4f32_1            = OpConstantComposite %a4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
5755                         "%cstype1             = OpConstantComposite %stype %c_f32_0 %ca4f32_1\n"
5756                         "%cstype2             = OpConstantComposite %stype %c_f32_1 %ca4f32_0\n"
5757                         "%carr                = OpConstantComposite %a3stype %cstype1 %cstype2 %cstype1",
5758
5759                         "%v                   = OpVariable %fp_a3stype Function %carr\n"
5760                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_1 %c_u32_1 %c_u32_1\n"
5761                         "%f_l                 = OpLoad %f32 %f\n"
5762                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %f_l\n"
5763                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
5764                 }
5765         };
5766
5767         getHalfColorsFullAlpha(inputColors);
5768         outputColors[0] = RGBA(255, 255, 255, 255);
5769         outputColors[1] = RGBA(255, 127, 127, 255);
5770         outputColors[2] = RGBA(127, 255, 127, 255);
5771         outputColors[3] = RGBA(127, 127, 255, 255);
5772
5773         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
5774         {
5775                 map<string, string> fragments;
5776                 fragments["pre_main"] = tests[testNdx].constants;
5777                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
5778                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, opConstantCompositeTests.get());
5779         }
5780         return opConstantCompositeTests.release();
5781 }
5782
5783 tcu::TestCaseGroup* createSelectionBlockOrderTests(tcu::TestContext& testCtx)
5784 {
5785         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "selection_block_order", "Out-of-order blocks for selection"));
5786         RGBA                                                    inputColors[4];
5787         RGBA                                                    outputColors[4];
5788         map<string, string>                             fragments;
5789
5790         // vec4 test_code(vec4 param) {
5791         //   vec4 result = param;
5792         //   for (int i = 0; i < 4; ++i) {
5793         //     if (i == 0) result[i] = 0.;
5794         //     else        result[i] = 1. - result[i];
5795         //   }
5796         //   return result;
5797         // }
5798         const char                                              function[]                      =
5799                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
5800                 "%param1    = OpFunctionParameter %v4f32\n"
5801                 "%lbl       = OpLabel\n"
5802                 "%iptr      = OpVariable %fp_i32 Function\n"
5803                 "%result    = OpVariable %fp_v4f32 Function\n"
5804                 "             OpStore %iptr %c_i32_0\n"
5805                 "             OpStore %result %param1\n"
5806                 "             OpBranch %loop\n"
5807
5808                 // Loop entry block.
5809                 "%loop      = OpLabel\n"
5810                 "%ival      = OpLoad %i32 %iptr\n"
5811                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
5812                 "             OpLoopMerge %exit %if_entry None\n"
5813                 "             OpBranchConditional %lt_4 %if_entry %exit\n"
5814
5815                 // Merge block for loop.
5816                 "%exit      = OpLabel\n"
5817                 "%ret       = OpLoad %v4f32 %result\n"
5818                 "             OpReturnValue %ret\n"
5819
5820                 // If-statement entry block.
5821                 "%if_entry  = OpLabel\n"
5822                 "%loc       = OpAccessChain %fp_f32 %result %ival\n"
5823                 "%eq_0      = OpIEqual %bool %ival %c_i32_0\n"
5824                 "             OpSelectionMerge %if_exit None\n"
5825                 "             OpBranchConditional %eq_0 %if_true %if_false\n"
5826
5827                 // False branch for if-statement.
5828                 "%if_false  = OpLabel\n"
5829                 "%val       = OpLoad %f32 %loc\n"
5830                 "%sub       = OpFSub %f32 %c_f32_1 %val\n"
5831                 "             OpStore %loc %sub\n"
5832                 "             OpBranch %if_exit\n"
5833
5834                 // Merge block for if-statement.
5835                 "%if_exit   = OpLabel\n"
5836                 "%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
5837                 "             OpStore %iptr %ival_next\n"
5838                 "             OpBranch %loop\n"
5839
5840                 // True branch for if-statement.
5841                 "%if_true   = OpLabel\n"
5842                 "             OpStore %loc %c_f32_0\n"
5843                 "             OpBranch %if_exit\n"
5844
5845                 "             OpFunctionEnd\n";
5846
5847         fragments["testfun"]    = function;
5848
5849         inputColors[0]                  = RGBA(127, 127, 127, 0);
5850         inputColors[1]                  = RGBA(127, 0,   0,   0);
5851         inputColors[2]                  = RGBA(0,   127, 0,   0);
5852         inputColors[3]                  = RGBA(0,   0,   127, 0);
5853
5854         outputColors[0]                 = RGBA(0, 128, 128, 255);
5855         outputColors[1]                 = RGBA(0, 255, 255, 255);
5856         outputColors[2]                 = RGBA(0, 128, 255, 255);
5857         outputColors[3]                 = RGBA(0, 255, 128, 255);
5858
5859         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
5860
5861         return group.release();
5862 }
5863
5864 tcu::TestCaseGroup* createSwitchBlockOrderTests(tcu::TestContext& testCtx)
5865 {
5866         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "switch_block_order", "Out-of-order blocks for switch"));
5867         RGBA                                                    inputColors[4];
5868         RGBA                                                    outputColors[4];
5869         map<string, string>                             fragments;
5870
5871         const char                                              typesAndConstants[]     =
5872                 "%c_f32_p2  = OpConstant %f32 0.2\n"
5873                 "%c_f32_p4  = OpConstant %f32 0.4\n"
5874                 "%c_f32_p6  = OpConstant %f32 0.6\n"
5875                 "%c_f32_p8  = OpConstant %f32 0.8\n";
5876
5877         // vec4 test_code(vec4 param) {
5878         //   vec4 result = param;
5879         //   for (int i = 0; i < 4; ++i) {
5880         //     switch (i) {
5881         //       case 0: result[i] += .2; break;
5882         //       case 1: result[i] += .6; break;
5883         //       case 2: result[i] += .4; break;
5884         //       case 3: result[i] += .8; break;
5885         //       default: break; // unreachable
5886         //     }
5887         //   }
5888         //   return result;
5889         // }
5890         const char                                              function[]                      =
5891                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
5892                 "%param1    = OpFunctionParameter %v4f32\n"
5893                 "%lbl       = OpLabel\n"
5894                 "%iptr      = OpVariable %fp_i32 Function\n"
5895                 "%result    = OpVariable %fp_v4f32 Function\n"
5896                 "             OpStore %iptr %c_i32_0\n"
5897                 "             OpStore %result %param1\n"
5898                 "             OpBranch %loop\n"
5899
5900                 // Loop entry block.
5901                 "%loop      = OpLabel\n"
5902                 "%ival      = OpLoad %i32 %iptr\n"
5903                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
5904                 "             OpLoopMerge %exit %switch_exit None\n"
5905                 "             OpBranchConditional %lt_4 %switch_entry %exit\n"
5906
5907                 // Merge block for loop.
5908                 "%exit      = OpLabel\n"
5909                 "%ret       = OpLoad %v4f32 %result\n"
5910                 "             OpReturnValue %ret\n"
5911
5912                 // Switch-statement entry block.
5913                 "%switch_entry   = OpLabel\n"
5914                 "%loc            = OpAccessChain %fp_f32 %result %ival\n"
5915                 "%val            = OpLoad %f32 %loc\n"
5916                 "                  OpSelectionMerge %switch_exit None\n"
5917                 "                  OpSwitch %ival %switch_default 0 %case0 1 %case1 2 %case2 3 %case3\n"
5918
5919                 "%case2          = OpLabel\n"
5920                 "%addp4          = OpFAdd %f32 %val %c_f32_p4\n"
5921                 "                  OpStore %loc %addp4\n"
5922                 "                  OpBranch %switch_exit\n"
5923
5924                 "%switch_default = OpLabel\n"
5925                 "                  OpUnreachable\n"
5926
5927                 "%case3          = OpLabel\n"
5928                 "%addp8          = OpFAdd %f32 %val %c_f32_p8\n"
5929                 "                  OpStore %loc %addp8\n"
5930                 "                  OpBranch %switch_exit\n"
5931
5932                 "%case0          = OpLabel\n"
5933                 "%addp2          = OpFAdd %f32 %val %c_f32_p2\n"
5934                 "                  OpStore %loc %addp2\n"
5935                 "                  OpBranch %switch_exit\n"
5936
5937                 // Merge block for switch-statement.
5938                 "%switch_exit    = OpLabel\n"
5939                 "%ival_next      = OpIAdd %i32 %ival %c_i32_1\n"
5940                 "                  OpStore %iptr %ival_next\n"
5941                 "                  OpBranch %loop\n"
5942
5943                 "%case1          = OpLabel\n"
5944                 "%addp6          = OpFAdd %f32 %val %c_f32_p6\n"
5945                 "                  OpStore %loc %addp6\n"
5946                 "                  OpBranch %switch_exit\n"
5947
5948                 "                  OpFunctionEnd\n";
5949
5950         fragments["pre_main"]   = typesAndConstants;
5951         fragments["testfun"]    = function;
5952
5953         inputColors[0]                  = RGBA(127, 27,  127, 51);
5954         inputColors[1]                  = RGBA(127, 0,   0,   51);
5955         inputColors[2]                  = RGBA(0,   27,  0,   51);
5956         inputColors[3]                  = RGBA(0,   0,   127, 51);
5957
5958         outputColors[0]                 = RGBA(178, 180, 229, 255);
5959         outputColors[1]                 = RGBA(178, 153, 102, 255);
5960         outputColors[2]                 = RGBA(51,  180, 102, 255);
5961         outputColors[3]                 = RGBA(51,  153, 229, 255);
5962
5963         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
5964
5965         return group.release();
5966 }
5967
5968 tcu::TestCaseGroup* createDecorationGroupTests(tcu::TestContext& testCtx)
5969 {
5970         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "decoration_group", "Decoration group tests"));
5971         RGBA                                                    inputColors[4];
5972         RGBA                                                    outputColors[4];
5973         map<string, string>                             fragments;
5974
5975         const char                                              decorations[]           =
5976                 "OpDecorate %array_group         ArrayStride 4\n"
5977                 "OpDecorate %struct_member_group Offset 0\n"
5978                 "%array_group         = OpDecorationGroup\n"
5979                 "%struct_member_group = OpDecorationGroup\n"
5980
5981                 "OpDecorate %group1 RelaxedPrecision\n"
5982                 "OpDecorate %group3 RelaxedPrecision\n"
5983                 "OpDecorate %group3 Invariant\n"
5984                 "OpDecorate %group3 Restrict\n"
5985                 "%group0 = OpDecorationGroup\n"
5986                 "%group1 = OpDecorationGroup\n"
5987                 "%group3 = OpDecorationGroup\n";
5988
5989         const char                                              typesAndConstants[]     =
5990                 "%a3f32     = OpTypeArray %f32 %c_u32_3\n"
5991                 "%struct1   = OpTypeStruct %a3f32\n"
5992                 "%struct2   = OpTypeStruct %a3f32\n"
5993                 "%fp_struct1 = OpTypePointer Function %struct1\n"
5994                 "%fp_struct2 = OpTypePointer Function %struct2\n"
5995                 "%c_f32_2    = OpConstant %f32 2.\n"
5996                 "%c_f32_n2   = OpConstant %f32 -2.\n"
5997
5998                 "%c_a3f32_1 = OpConstantComposite %a3f32 %c_f32_1 %c_f32_2 %c_f32_1\n"
5999                 "%c_a3f32_2 = OpConstantComposite %a3f32 %c_f32_n1 %c_f32_n2 %c_f32_n1\n"
6000                 "%c_struct1 = OpConstantComposite %struct1 %c_a3f32_1\n"
6001                 "%c_struct2 = OpConstantComposite %struct2 %c_a3f32_2\n";
6002
6003         const char                                              function[]                      =
6004                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6005                 "%param     = OpFunctionParameter %v4f32\n"
6006                 "%entry     = OpLabel\n"
6007                 "%result    = OpVariable %fp_v4f32 Function\n"
6008                 "%v_struct1 = OpVariable %fp_struct1 Function\n"
6009                 "%v_struct2 = OpVariable %fp_struct2 Function\n"
6010                 "             OpStore %result %param\n"
6011                 "             OpStore %v_struct1 %c_struct1\n"
6012                 "             OpStore %v_struct2 %c_struct2\n"
6013                 "%ptr1      = OpAccessChain %fp_f32 %v_struct1 %c_i32_0 %c_i32_2\n"
6014                 "%val1      = OpLoad %f32 %ptr1\n"
6015                 "%ptr2      = OpAccessChain %fp_f32 %v_struct2 %c_i32_0 %c_i32_2\n"
6016                 "%val2      = OpLoad %f32 %ptr2\n"
6017                 "%addvalues = OpFAdd %f32 %val1 %val2\n"
6018                 "%ptr       = OpAccessChain %fp_f32 %result %c_i32_1\n"
6019                 "%val       = OpLoad %f32 %ptr\n"
6020                 "%addresult = OpFAdd %f32 %addvalues %val\n"
6021                 "             OpStore %ptr %addresult\n"
6022                 "%ret       = OpLoad %v4f32 %result\n"
6023                 "             OpReturnValue %ret\n"
6024                 "             OpFunctionEnd\n";
6025
6026         struct CaseNameDecoration
6027         {
6028                 string name;
6029                 string decoration;
6030         };
6031
6032         CaseNameDecoration tests[] =
6033         {
6034                 {
6035                         "same_decoration_group_on_multiple_types",
6036                         "OpGroupMemberDecorate %struct_member_group %struct1 0 %struct2 0\n"
6037                 },
6038                 {
6039                         "empty_decoration_group",
6040                         "OpGroupDecorate %group0      %a3f32\n"
6041                         "OpGroupDecorate %group0      %result\n"
6042                 },
6043                 {
6044                         "one_element_decoration_group",
6045                         "OpGroupDecorate %array_group %a3f32\n"
6046                 },
6047                 {
6048                         "multiple_elements_decoration_group",
6049                         "OpGroupDecorate %group3      %v_struct1\n"
6050                 },
6051                 {
6052                         "multiple_decoration_groups_on_same_variable",
6053                         "OpGroupDecorate %group0      %v_struct2\n"
6054                         "OpGroupDecorate %group1      %v_struct2\n"
6055                         "OpGroupDecorate %group3      %v_struct2\n"
6056                 },
6057                 {
6058                         "same_decoration_group_multiple_times",
6059                         "OpGroupDecorate %group1      %addvalues\n"
6060                         "OpGroupDecorate %group1      %addvalues\n"
6061                         "OpGroupDecorate %group1      %addvalues\n"
6062                 },
6063
6064         };
6065
6066         getHalfColorsFullAlpha(inputColors);
6067         getHalfColorsFullAlpha(outputColors);
6068
6069         for (size_t idx = 0; idx < (sizeof(tests) / sizeof(tests[0])); ++idx)
6070         {
6071                 fragments["decoration"] = decorations + tests[idx].decoration;
6072                 fragments["pre_main"]   = typesAndConstants;
6073                 fragments["testfun"]    = function;
6074
6075                 createTestsForAllStages(tests[idx].name, inputColors, outputColors, fragments, group.get());
6076         }
6077
6078         return group.release();
6079 }
6080
6081 struct SpecConstantTwoIntGraphicsCase
6082 {
6083         const char*             caseName;
6084         const char*             scDefinition0;
6085         const char*             scDefinition1;
6086         const char*             scResultType;
6087         const char*             scOperation;
6088         deInt32                 scActualValue0;
6089         deInt32                 scActualValue1;
6090         const char*             resultOperation;
6091         RGBA                    expectedColors[4];
6092
6093                                         SpecConstantTwoIntGraphicsCase (const char* name,
6094                                                                                         const char* definition0,
6095                                                                                         const char* definition1,
6096                                                                                         const char* resultType,
6097                                                                                         const char* operation,
6098                                                                                         deInt32         value0,
6099                                                                                         deInt32         value1,
6100                                                                                         const char* resultOp,
6101                                                                                         const RGBA      (&output)[4])
6102                                                 : caseName                      (name)
6103                                                 , scDefinition0         (definition0)
6104                                                 , scDefinition1         (definition1)
6105                                                 , scResultType          (resultType)
6106                                                 , scOperation           (operation)
6107                                                 , scActualValue0        (value0)
6108                                                 , scActualValue1        (value1)
6109                                                 , resultOperation       (resultOp)
6110         {
6111                 expectedColors[0] = output[0];
6112                 expectedColors[1] = output[1];
6113                 expectedColors[2] = output[2];
6114                 expectedColors[3] = output[3];
6115         }
6116 };
6117
6118 tcu::TestCaseGroup* createSpecConstantTests (tcu::TestContext& testCtx)
6119 {
6120         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
6121         vector<SpecConstantTwoIntGraphicsCase>  cases;
6122         RGBA                                                    inputColors[4];
6123         RGBA                                                    outputColors0[4];
6124         RGBA                                                    outputColors1[4];
6125         RGBA                                                    outputColors2[4];
6126
6127         const char      decorations1[]                  =
6128                 "OpDecorate %sc_0  SpecId 0\n"
6129                 "OpDecorate %sc_1  SpecId 1\n";
6130
6131         const char      typesAndConstants1[]    =
6132                 "${OPTYPE_DEFINITIONS:opt}"
6133                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
6134                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
6135                 "%sc_op     = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n";
6136
6137         const char      function1[]                             =
6138                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6139                 "%param     = OpFunctionParameter %v4f32\n"
6140                 "%label     = OpLabel\n"
6141                 "${TYPE_CONVERT:opt}"
6142                 "%result    = OpVariable %fp_v4f32 Function\n"
6143                 "             OpStore %result %param\n"
6144                 "%gen       = ${GEN_RESULT}\n"
6145                 "%index     = OpIAdd %i32 %gen %c_i32_1\n"
6146                 "%loc       = OpAccessChain %fp_f32 %result %index\n"
6147                 "%val       = OpLoad %f32 %loc\n"
6148                 "%add       = OpFAdd %f32 %val %c_f32_0_5\n"
6149                 "             OpStore %loc %add\n"
6150                 "%ret       = OpLoad %v4f32 %result\n"
6151                 "             OpReturnValue %ret\n"
6152                 "             OpFunctionEnd\n";
6153
6154         inputColors[0] = RGBA(127, 127, 127, 255);
6155         inputColors[1] = RGBA(127, 0,   0,   255);
6156         inputColors[2] = RGBA(0,   127, 0,   255);
6157         inputColors[3] = RGBA(0,   0,   127, 255);
6158
6159         // Derived from inputColors[x] by adding 128 to inputColors[x][0].
6160         outputColors0[0] = RGBA(255, 127, 127, 255);
6161         outputColors0[1] = RGBA(255, 0,   0,   255);
6162         outputColors0[2] = RGBA(128, 127, 0,   255);
6163         outputColors0[3] = RGBA(128, 0,   127, 255);
6164
6165         // Derived from inputColors[x] by adding 128 to inputColors[x][1].
6166         outputColors1[0] = RGBA(127, 255, 127, 255);
6167         outputColors1[1] = RGBA(127, 128, 0,   255);
6168         outputColors1[2] = RGBA(0,   255, 0,   255);
6169         outputColors1[3] = RGBA(0,   128, 127, 255);
6170
6171         // Derived from inputColors[x] by adding 128 to inputColors[x][2].
6172         outputColors2[0] = RGBA(127, 127, 255, 255);
6173         outputColors2[1] = RGBA(127, 0,   128, 255);
6174         outputColors2[2] = RGBA(0,   127, 128, 255);
6175         outputColors2[3] = RGBA(0,   0,   255, 255);
6176
6177         const char addZeroToSc[]                = "OpIAdd %i32 %c_i32_0 %sc_op";
6178         const char addZeroToSc32[]              = "OpIAdd %i32 %c_i32_0 %sc_op32";
6179         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_op %c_i32_1 %c_i32_0";
6180         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_op %c_i32_0 %c_i32_1";
6181
6182         cases.push_back(SpecConstantTwoIntGraphicsCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                             19,             -20,    addZeroToSc,            outputColors0));
6183         cases.push_back(SpecConstantTwoIntGraphicsCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                             19,             20,             addZeroToSc,            outputColors0));
6184         cases.push_back(SpecConstantTwoIntGraphicsCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                             -1,             -1,             addZeroToSc,            outputColors2));
6185         cases.push_back(SpecConstantTwoIntGraphicsCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                             -126,   126,    addZeroToSc,            outputColors0));
6186         cases.push_back(SpecConstantTwoIntGraphicsCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                             126,    126,    addZeroToSc,            outputColors2));
6187         cases.push_back(SpecConstantTwoIntGraphicsCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
6188         cases.push_back(SpecConstantTwoIntGraphicsCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
6189         cases.push_back(SpecConstantTwoIntGraphicsCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                             1001,   500,    addZeroToSc,            outputColors2));
6190         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                             0x33,   0x0d,   addZeroToSc,            outputColors2));
6191         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                             0,              1,              addZeroToSc,            outputColors2));
6192         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                             0x2e,   0x2f,   addZeroToSc,            outputColors2));
6193         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                             2,              1,              addZeroToSc,            outputColors2));
6194         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                             -4,             2,              addZeroToSc,            outputColors0));
6195         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                             1,              0,              addZeroToSc,            outputColors2));
6196         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                             -20,    -10,    selectTrueUsingSc,      outputColors2));
6197         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                             10,             20,             selectTrueUsingSc,      outputColors2));
6198         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
6199         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                             10,             5,              selectTrueUsingSc,      outputColors2));
6200         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                             -10,    -10,    selectTrueUsingSc,      outputColors2));
6201         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                             50,             100,    selectTrueUsingSc,      outputColors2));
6202         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
6203         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                             10,             10,             selectTrueUsingSc,      outputColors2));
6204         cases.push_back(SpecConstantTwoIntGraphicsCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                             42,             24,             selectFalseUsingSc,     outputColors2));
6205         cases.push_back(SpecConstantTwoIntGraphicsCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
6206         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
6207         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
6208         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
6209         cases.push_back(SpecConstantTwoIntGraphicsCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                                   -1,             0,              addZeroToSc,            outputColors2));
6210         cases.push_back(SpecConstantTwoIntGraphicsCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                                   -2,             0,              addZeroToSc,            outputColors2));
6211         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                                   1,              0,              selectFalseUsingSc,     outputColors2));
6212         cases.push_back(SpecConstantTwoIntGraphicsCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %c_i32_0",    1,              1,              addZeroToSc,            outputColors2));
6213         cases.push_back(SpecConstantTwoIntGraphicsCase("sconvert",                              " %i32 0",              " %i32 0",              "%i16",         "SConvert             %sc_0",                                   -1,             0,              addZeroToSc32,          outputColors0));
6214         // -1082130432 stored as 32-bit two's complement is the binary representation of -1 as IEEE-754 Float
6215         cases.push_back(SpecConstantTwoIntGraphicsCase("fconvert",                              " %f32 0",              " %f32 0",              "%f64",         "FConvert             %sc_0",                                   -1082130432, 0, addZeroToSc32,          outputColors0));
6216         // \todo[2015-12-1 antiagainst] OpQuantizeToF16
6217
6218         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
6219         {
6220                 map<string, string>                     specializations;
6221                 map<string, string>                     fragments;
6222                 vector<deInt32>                         specConstants;
6223                 vector<string>                          features;
6224                 PushConstants                           noPushConstants;
6225                 GraphicsResources                       noResources;
6226                 GraphicsInterfaces                      noInterfaces;
6227                 std::vector<std::string>        noExtensions;
6228
6229                 // Special SPIR-V code for SConvert-case
6230                 if (strcmp(cases[caseNdx].caseName, "sconvert") == 0)
6231                 {
6232                         features.push_back("shaderInt16");
6233                         fragments["capability"]                                 = "OpCapability Int16\n";                                       // Adds 16-bit integer capability
6234                         specializations["OPTYPE_DEFINITIONS"]   = "%i16 = OpTypeInt 16 1\n";                            // Adds 16-bit integer type
6235                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpSConvert %i32 %sc_op\n";        // Converts 16-bit integer to 32-bit integer
6236                 }
6237
6238                 // Special SPIR-V code for FConvert-case
6239                 if (strcmp(cases[caseNdx].caseName, "fconvert") == 0)
6240                 {
6241                         features.push_back("shaderFloat64");
6242                         fragments["capability"]                                 = "OpCapability Float64\n";                                     // Adds 64-bit float capability
6243                         specializations["OPTYPE_DEFINITIONS"]   = "%f64 = OpTypeFloat 64\n";                            // Adds 64-bit float type
6244                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpConvertFToS %i32 %sc_op\n";     // Converts 64-bit float to 32-bit integer
6245                 }
6246
6247                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
6248                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
6249                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
6250                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
6251                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
6252
6253                 fragments["decoration"]                         = tcu::StringTemplate(decorations1).specialize(specializations);
6254                 fragments["pre_main"]                           = tcu::StringTemplate(typesAndConstants1).specialize(specializations);
6255                 fragments["testfun"]                            = tcu::StringTemplate(function1).specialize(specializations);
6256
6257                 specConstants.push_back(cases[caseNdx].scActualValue0);
6258                 specConstants.push_back(cases[caseNdx].scActualValue1);
6259
6260                 createTestsForAllStages(
6261                         cases[caseNdx].caseName, inputColors, cases[caseNdx].expectedColors, fragments, specConstants,
6262                         noPushConstants, noResources, noInterfaces, noExtensions, features, VulkanFeatures(), group.get());
6263         }
6264
6265         const char      decorations2[]                  =
6266                 "OpDecorate %sc_0  SpecId 0\n"
6267                 "OpDecorate %sc_1  SpecId 1\n"
6268                 "OpDecorate %sc_2  SpecId 2\n";
6269
6270         const char      typesAndConstants2[]    =
6271                 "%v3i32       = OpTypeVector %i32 3\n"
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(create16BitStorageComputeGroup(testCtx));
9006         computeTests->addChild(createUboMatrixPaddingComputeGroup(testCtx));
9007         computeTests->addChild(createConditionalBranchComputeGroup(testCtx));
9008         computeTests->addChild(createIndexingComputeGroup(testCtx));
9009         computeTests->addChild(createVariablePointersComputeGroup(testCtx));
9010         computeTests->addChild(createImageSamplerComputeGroup(testCtx));
9011         graphicsTests->addChild(createSpivVersionCheckTests(testCtx, !testComputePipeline));
9012         graphicsTests->addChild(createOpNopTests(testCtx));
9013         graphicsTests->addChild(createOpSourceTests(testCtx));
9014         graphicsTests->addChild(createOpSourceContinuedTests(testCtx));
9015         graphicsTests->addChild(createOpModuleProcessedTests(testCtx));
9016         graphicsTests->addChild(createOpLineTests(testCtx));
9017         graphicsTests->addChild(createOpNoLineTests(testCtx));
9018         graphicsTests->addChild(createOpConstantNullTests(testCtx));
9019         graphicsTests->addChild(createOpConstantCompositeTests(testCtx));
9020         graphicsTests->addChild(createMemoryAccessTests(testCtx));
9021         graphicsTests->addChild(createOpUndefTests(testCtx));
9022         graphicsTests->addChild(createSelectionBlockOrderTests(testCtx));
9023         graphicsTests->addChild(createModuleTests(testCtx));
9024         graphicsTests->addChild(createSwitchBlockOrderTests(testCtx));
9025         graphicsTests->addChild(createOpPhiTests(testCtx));
9026         graphicsTests->addChild(createNoContractionTests(testCtx));
9027         graphicsTests->addChild(createOpQuantizeTests(testCtx));
9028         graphicsTests->addChild(createLoopTests(testCtx));
9029         graphicsTests->addChild(createSpecConstantTests(testCtx));
9030         graphicsTests->addChild(createSpecConstantOpQuantizeToF16Group(testCtx));
9031         graphicsTests->addChild(createBarrierTests(testCtx));
9032         graphicsTests->addChild(createDecorationGroupTests(testCtx));
9033         graphicsTests->addChild(createFRemTests(testCtx));
9034         graphicsTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
9035         graphicsTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
9036
9037         {
9038                 de::MovePtr<tcu::TestCaseGroup> graphicsAndroidTests    (new tcu::TestCaseGroup(testCtx, "android", "Android CTS Tests"));
9039
9040                 graphicsAndroidTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
9041                 graphicsAndroidTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
9042
9043                 graphicsTests->addChild(graphicsAndroidTests.release());
9044         }
9045
9046         graphicsTests->addChild(create16BitStorageGraphicsGroup(testCtx));
9047         graphicsTests->addChild(createUboMatrixPaddingGraphicsGroup(testCtx));
9048         graphicsTests->addChild(createConditionalBranchGraphicsGroup(testCtx));
9049         graphicsTests->addChild(createIndexingGraphicsGroup(testCtx));
9050         graphicsTests->addChild(createVariablePointersGraphicsGroup(testCtx));
9051         graphicsTests->addChild(createImageSamplerGraphicsGroup(testCtx));
9052
9053         instructionTests->addChild(computeTests.release());
9054         instructionTests->addChild(graphicsTests.release());
9055
9056         return instructionTests.release();
9057 }
9058
9059 } // SpirVAssembly
9060 } // vkt