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