Remove duplicated definitions in spirv_assembly tests
[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                 string(getComputeAsmShaderPreamble()) +
2482
2483                 "OpName %main           \"main\"\n"
2484                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2485
2486                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2487                 "OpDecorate %sc_0  SpecId 0\n"
2488                 "OpDecorate %sc_1  SpecId 1\n"
2489                 "OpDecorate %i32arr ArrayStride 4\n"
2490
2491                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2492
2493                 "%buf     = OpTypeStruct %i32arr\n"
2494                 "%bufptr  = OpTypePointer Uniform %buf\n"
2495                 "%indata    = OpVariable %bufptr Uniform\n"
2496                 "%outdata   = OpVariable %bufptr Uniform\n"
2497
2498                 "%id        = OpVariable %uvec3ptr Input\n"
2499                 "%zero      = OpConstant %i32 0\n"
2500
2501                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
2502                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
2503                 "%sc_final  = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n"
2504
2505                 "%main      = OpFunction %void None %voidf\n"
2506                 "%label     = OpLabel\n"
2507                 "%idval     = OpLoad %uvec3 %id\n"
2508                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2509                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
2510                 "%inval     = OpLoad %i32 %inloc\n"
2511                 "%final     = ${GEN_RESULT}\n"
2512                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2513                 "             OpStore %outloc %final\n"
2514                 "             OpReturn\n"
2515                 "             OpFunctionEnd\n");
2516
2517         fillRandomScalars(rnd, -65536, 65536, &inputInts[0], numElements);
2518
2519         for (size_t ndx = 0; ndx < numElements; ++ndx)
2520         {
2521                 outputInts1[ndx] = inputInts[ndx] + 42;
2522                 outputInts2[ndx] = inputInts[ndx];
2523                 outputInts3[ndx] = inputInts[ndx] - 11200;
2524                 outputInts4[ndx] = inputInts[ndx] + 1;
2525         }
2526
2527         const char addScToInput[]               = "OpIAdd %i32 %inval %sc_final";
2528         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_final %inval %zero";
2529         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_final %zero %inval";
2530
2531         cases.push_back(SpecConstantTwoIntCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                     62,             -20,    addScToInput,           outputInts1));
2532         cases.push_back(SpecConstantTwoIntCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                     100,    58,             addScToInput,           outputInts1));
2533         cases.push_back(SpecConstantTwoIntCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                     -2,             -21,    addScToInput,           outputInts1));
2534         cases.push_back(SpecConstantTwoIntCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                     -126,   -3,             addScToInput,           outputInts1));
2535         cases.push_back(SpecConstantTwoIntCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                     126,    3,              addScToInput,           outputInts1));
2536         cases.push_back(SpecConstantTwoIntCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
2537         cases.push_back(SpecConstantTwoIntCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
2538         cases.push_back(SpecConstantTwoIntCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                     342,    50,             addScToInput,           outputInts1));
2539         cases.push_back(SpecConstantTwoIntCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                     42,             63,             addScToInput,           outputInts1));
2540         cases.push_back(SpecConstantTwoIntCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                     34,             8,              addScToInput,           outputInts1));
2541         cases.push_back(SpecConstantTwoIntCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                     18,             56,             addScToInput,           outputInts1));
2542         cases.push_back(SpecConstantTwoIntCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
2543         cases.push_back(SpecConstantTwoIntCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
2544         cases.push_back(SpecConstantTwoIntCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                     21,             1,              addScToInput,           outputInts1));
2545         cases.push_back(SpecConstantTwoIntCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                     -20,    -10,    selectTrueUsingSc,      outputInts2));
2546         cases.push_back(SpecConstantTwoIntCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                     10,             20,             selectTrueUsingSc,      outputInts2));
2547         cases.push_back(SpecConstantTwoIntCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
2548         cases.push_back(SpecConstantTwoIntCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                     10,             5,              selectTrueUsingSc,      outputInts2));
2549         cases.push_back(SpecConstantTwoIntCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                     -10,    -10,    selectTrueUsingSc,      outputInts2));
2550         cases.push_back(SpecConstantTwoIntCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                     50,             100,    selectTrueUsingSc,      outputInts2));
2551         cases.push_back(SpecConstantTwoIntCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
2552         cases.push_back(SpecConstantTwoIntCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                     10,             10,             selectTrueUsingSc,      outputInts2));
2553         cases.push_back(SpecConstantTwoIntCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                     42,             24,             selectFalseUsingSc,     outputInts2));
2554         cases.push_back(SpecConstantTwoIntCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
2555         cases.push_back(SpecConstantTwoIntCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
2556         cases.push_back(SpecConstantTwoIntCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
2557         cases.push_back(SpecConstantTwoIntCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
2558         cases.push_back(SpecConstantTwoIntCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                           -42,    0,              addScToInput,           outputInts1));
2559         cases.push_back(SpecConstantTwoIntCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                           -43,    0,              addScToInput,           outputInts1));
2560         cases.push_back(SpecConstantTwoIntCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                           1,              0,              selectFalseUsingSc,     outputInts2));
2561         cases.push_back(SpecConstantTwoIntCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %zero",       1,              42,             addScToInput,           outputInts1));
2562         // OpSConvert, OpFConvert: these two instructions involve ints/floats of different bitwidths.
2563
2564         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
2565         {
2566                 map<string, string>             specializations;
2567                 ComputeShaderSpec               spec;
2568
2569                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
2570                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
2571                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
2572                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
2573                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
2574
2575                 spec.assembly = shaderTemplate.specialize(specializations);
2576                 spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
2577                 spec.outputs.push_back(BufferSp(new Int32Buffer(cases[caseNdx].expectedOutput)));
2578                 spec.numWorkGroups = IVec3(numElements, 1, 1);
2579                 spec.specConstants.push_back(cases[caseNdx].scActualValue0);
2580                 spec.specConstants.push_back(cases[caseNdx].scActualValue1);
2581
2582                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].caseName, cases[caseNdx].caseName, spec));
2583         }
2584
2585         ComputeShaderSpec                               spec;
2586
2587         spec.assembly =
2588                 string(getComputeAsmShaderPreamble()) +
2589
2590                 "OpName %main           \"main\"\n"
2591                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2592
2593                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2594                 "OpDecorate %sc_0  SpecId 0\n"
2595                 "OpDecorate %sc_1  SpecId 1\n"
2596                 "OpDecorate %sc_2  SpecId 2\n"
2597                 "OpDecorate %i32arr ArrayStride 4\n"
2598
2599                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2600
2601                 "%ivec3       = OpTypeVector %i32 3\n"
2602                 "%buf         = OpTypeStruct %i32arr\n"
2603                 "%bufptr      = OpTypePointer Uniform %buf\n"
2604                 "%indata      = OpVariable %bufptr Uniform\n"
2605                 "%outdata     = OpVariable %bufptr Uniform\n"
2606
2607                 "%id          = OpVariable %uvec3ptr Input\n"
2608                 "%zero        = OpConstant %i32 0\n"
2609                 "%ivec3_0     = OpConstantComposite %ivec3 %zero %zero %zero\n"
2610                 "%vec3_undef  = OpUndef %ivec3\n"
2611
2612                 "%sc_0        = OpSpecConstant %i32 0\n"
2613                 "%sc_1        = OpSpecConstant %i32 0\n"
2614                 "%sc_2        = OpSpecConstant %i32 0\n"
2615                 "%sc_vec3_0   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_0        %ivec3_0     0\n"                                                 // (sc_0, 0, 0)
2616                 "%sc_vec3_1   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_1        %ivec3_0     1\n"                                                 // (0, sc_1, 0)
2617                 "%sc_vec3_2   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_2        %ivec3_0     2\n"                                                 // (0, 0, sc_2)
2618                 "%sc_vec3_0_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0   %vec3_undef  0          0xFFFFFFFF 2\n"   // (sc_0, ???,  0)
2619                 "%sc_vec3_1_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_1   %vec3_undef  0xFFFFFFFF 1          0\n"   // (???,  sc_1, 0)
2620                 "%sc_vec3_2_s = OpSpecConstantOp %ivec3 VectorShuffle    %vec3_undef  %sc_vec3_2   5          0xFFFFFFFF 5\n"   // (sc_2, ???,  sc_2)
2621                 "%sc_vec3_01  = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0_s %sc_vec3_1_s 1 0 4\n"                                             // (0,    sc_0, sc_1)
2622                 "%sc_vec3_012 = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_01  %sc_vec3_2_s 5 1 2\n"                                             // (sc_2, sc_0, sc_1)
2623                 "%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              0\n"                                                 // sc_2
2624                 "%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              1\n"                                                 // sc_0
2625                 "%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              2\n"                                                 // sc_1
2626                 "%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"                                                              // (sc_2 - sc_0)
2627                 "%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n"                                                              // (sc_2 - sc_0) * sc_1
2628
2629                 "%main      = OpFunction %void None %voidf\n"
2630                 "%label     = OpLabel\n"
2631                 "%idval     = OpLoad %uvec3 %id\n"
2632                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2633                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
2634                 "%inval     = OpLoad %i32 %inloc\n"
2635                 "%final     = OpIAdd %i32 %inval %sc_final\n"
2636                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2637                 "             OpStore %outloc %final\n"
2638                 "             OpReturn\n"
2639                 "             OpFunctionEnd\n";
2640         spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
2641         spec.outputs.push_back(BufferSp(new Int32Buffer(outputInts3)));
2642         spec.numWorkGroups = IVec3(numElements, 1, 1);
2643         spec.specConstants.push_back(123);
2644         spec.specConstants.push_back(56);
2645         spec.specConstants.push_back(-77);
2646
2647         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector_related", "VectorShuffle, CompositeExtract, & CompositeInsert", spec));
2648
2649         return group.release();
2650 }
2651
2652 void createOpPhiVartypeTests (de::MovePtr<tcu::TestCaseGroup>& group, tcu::TestContext& testCtx)
2653 {
2654         ComputeShaderSpec       specInt;
2655         ComputeShaderSpec       specFloat;
2656         ComputeShaderSpec       specVec3;
2657         ComputeShaderSpec       specMat4;
2658         ComputeShaderSpec       specArray;
2659         ComputeShaderSpec       specStruct;
2660         de::Random                      rnd                             (deStringHash(group->getName()));
2661         const int                       numElements             = 100;
2662         vector<float>           inputFloats             (numElements, 0);
2663         vector<float>           outputFloats    (numElements, 0);
2664
2665         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
2666
2667         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2668         floorAll(inputFloats);
2669
2670         for (size_t ndx = 0; ndx < numElements; ++ndx)
2671         {
2672                 // Just check if the value is positive or not
2673                 outputFloats[ndx] = (inputFloats[ndx] > 0) ? 1.0f : -1.0f;
2674         }
2675
2676         // All of the tests are of the form:
2677         //
2678         // testtype r
2679         //
2680         // if (inputdata > 0)
2681         //   r = 1
2682         // else
2683         //   r = -1
2684         //
2685         // return (float)r
2686
2687         specFloat.assembly =
2688                 string(getComputeAsmShaderPreamble()) +
2689
2690                 "OpSource GLSL 430\n"
2691                 "OpName %main \"main\"\n"
2692                 "OpName %id \"gl_GlobalInvocationID\"\n"
2693
2694                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2695
2696                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2697
2698                 "%id = OpVariable %uvec3ptr Input\n"
2699                 "%zero       = OpConstant %i32 0\n"
2700                 "%float_0    = OpConstant %f32 0.0\n"
2701                 "%float_1    = OpConstant %f32 1.0\n"
2702                 "%float_n1   = OpConstant %f32 -1.0\n"
2703
2704                 "%main     = OpFunction %void None %voidf\n"
2705                 "%entry    = OpLabel\n"
2706                 "%idval    = OpLoad %uvec3 %id\n"
2707                 "%x        = OpCompositeExtract %u32 %idval 0\n"
2708                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
2709                 "%inval    = OpLoad %f32 %inloc\n"
2710
2711                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
2712                 "            OpSelectionMerge %cm None\n"
2713                 "            OpBranchConditional %comp %tb %fb\n"
2714                 "%tb       = OpLabel\n"
2715                 "            OpBranch %cm\n"
2716                 "%fb       = OpLabel\n"
2717                 "            OpBranch %cm\n"
2718                 "%cm       = OpLabel\n"
2719                 "%res      = OpPhi %f32 %float_1 %tb %float_n1 %fb\n"
2720
2721                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
2722                 "            OpStore %outloc %res\n"
2723                 "            OpReturn\n"
2724
2725                 "            OpFunctionEnd\n";
2726         specFloat.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2727         specFloat.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2728         specFloat.numWorkGroups = IVec3(numElements, 1, 1);
2729
2730         specMat4.assembly =
2731                 string(getComputeAsmShaderPreamble()) +
2732
2733                 "OpSource GLSL 430\n"
2734                 "OpName %main \"main\"\n"
2735                 "OpName %id \"gl_GlobalInvocationID\"\n"
2736
2737                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2738
2739                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2740
2741                 "%id = OpVariable %uvec3ptr Input\n"
2742                 "%v4f32      = OpTypeVector %f32 4\n"
2743                 "%mat4v4f32  = OpTypeMatrix %v4f32 4\n"
2744                 "%zero       = OpConstant %i32 0\n"
2745                 "%float_0    = OpConstant %f32 0.0\n"
2746                 "%float_1    = OpConstant %f32 1.0\n"
2747                 "%float_n1   = OpConstant %f32 -1.0\n"
2748                 "%m11        = OpConstantComposite %v4f32 %float_1 %float_0 %float_0 %float_0\n"
2749                 "%m12        = OpConstantComposite %v4f32 %float_0 %float_1 %float_0 %float_0\n"
2750                 "%m13        = OpConstantComposite %v4f32 %float_0 %float_0 %float_1 %float_0\n"
2751                 "%m14        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_1\n"
2752                 "%m1         = OpConstantComposite %mat4v4f32 %m11 %m12 %m13 %m14\n"
2753                 "%m21        = OpConstantComposite %v4f32 %float_n1 %float_0 %float_0 %float_0\n"
2754                 "%m22        = OpConstantComposite %v4f32 %float_0 %float_n1 %float_0 %float_0\n"
2755                 "%m23        = OpConstantComposite %v4f32 %float_0 %float_0 %float_n1 %float_0\n"
2756                 "%m24        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_n1\n"
2757                 "%m2         = OpConstantComposite %mat4v4f32 %m21 %m22 %m23 %m24\n"
2758
2759                 "%main     = OpFunction %void None %voidf\n"
2760                 "%entry    = OpLabel\n"
2761                 "%idval    = OpLoad %uvec3 %id\n"
2762                 "%x        = OpCompositeExtract %u32 %idval 0\n"
2763                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
2764                 "%inval    = OpLoad %f32 %inloc\n"
2765
2766                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
2767                 "            OpSelectionMerge %cm None\n"
2768                 "            OpBranchConditional %comp %tb %fb\n"
2769                 "%tb       = OpLabel\n"
2770                 "            OpBranch %cm\n"
2771                 "%fb       = OpLabel\n"
2772                 "            OpBranch %cm\n"
2773                 "%cm       = OpLabel\n"
2774                 "%mres     = OpPhi %mat4v4f32 %m1 %tb %m2 %fb\n"
2775                 "%res      = OpCompositeExtract %f32 %mres 2 2\n"
2776
2777                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
2778                 "            OpStore %outloc %res\n"
2779                 "            OpReturn\n"
2780
2781                 "            OpFunctionEnd\n";
2782         specMat4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2783         specMat4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2784         specMat4.numWorkGroups = IVec3(numElements, 1, 1);
2785
2786         specVec3.assembly =
2787                 string(getComputeAsmShaderPreamble()) +
2788
2789                 "OpSource GLSL 430\n"
2790                 "OpName %main \"main\"\n"
2791                 "OpName %id \"gl_GlobalInvocationID\"\n"
2792
2793                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2794
2795                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2796
2797                 "%id = OpVariable %uvec3ptr Input\n"
2798                 "%zero       = OpConstant %i32 0\n"
2799                 "%float_0    = OpConstant %f32 0.0\n"
2800                 "%float_1    = OpConstant %f32 1.0\n"
2801                 "%float_n1   = OpConstant %f32 -1.0\n"
2802                 "%v1         = OpConstantComposite %fvec3 %float_1 %float_1 %float_1\n"
2803                 "%v2         = OpConstantComposite %fvec3 %float_n1 %float_n1 %float_n1\n"
2804
2805                 "%main     = OpFunction %void None %voidf\n"
2806                 "%entry    = OpLabel\n"
2807                 "%idval    = OpLoad %uvec3 %id\n"
2808                 "%x        = OpCompositeExtract %u32 %idval 0\n"
2809                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
2810                 "%inval    = OpLoad %f32 %inloc\n"
2811
2812                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
2813                 "            OpSelectionMerge %cm None\n"
2814                 "            OpBranchConditional %comp %tb %fb\n"
2815                 "%tb       = OpLabel\n"
2816                 "            OpBranch %cm\n"
2817                 "%fb       = OpLabel\n"
2818                 "            OpBranch %cm\n"
2819                 "%cm       = OpLabel\n"
2820                 "%vres     = OpPhi %fvec3 %v1 %tb %v2 %fb\n"
2821                 "%res      = OpCompositeExtract %f32 %vres 2\n"
2822
2823                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
2824                 "            OpStore %outloc %res\n"
2825                 "            OpReturn\n"
2826
2827                 "            OpFunctionEnd\n";
2828         specVec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2829         specVec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2830         specVec3.numWorkGroups = IVec3(numElements, 1, 1);
2831
2832         specInt.assembly =
2833                 string(getComputeAsmShaderPreamble()) +
2834
2835                 "OpSource GLSL 430\n"
2836                 "OpName %main \"main\"\n"
2837                 "OpName %id \"gl_GlobalInvocationID\"\n"
2838
2839                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2840
2841                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2842
2843                 "%id = OpVariable %uvec3ptr Input\n"
2844                 "%zero       = OpConstant %i32 0\n"
2845                 "%float_0    = OpConstant %f32 0.0\n"
2846                 "%i1         = OpConstant %i32 1\n"
2847                 "%i2         = OpConstant %i32 -1\n"
2848
2849                 "%main     = OpFunction %void None %voidf\n"
2850                 "%entry    = OpLabel\n"
2851                 "%idval    = OpLoad %uvec3 %id\n"
2852                 "%x        = OpCompositeExtract %u32 %idval 0\n"
2853                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
2854                 "%inval    = OpLoad %f32 %inloc\n"
2855
2856                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
2857                 "            OpSelectionMerge %cm None\n"
2858                 "            OpBranchConditional %comp %tb %fb\n"
2859                 "%tb       = OpLabel\n"
2860                 "            OpBranch %cm\n"
2861                 "%fb       = OpLabel\n"
2862                 "            OpBranch %cm\n"
2863                 "%cm       = OpLabel\n"
2864                 "%ires     = OpPhi %i32 %i1 %tb %i2 %fb\n"
2865                 "%res      = OpConvertSToF %f32 %ires\n"
2866
2867                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
2868                 "            OpStore %outloc %res\n"
2869                 "            OpReturn\n"
2870
2871                 "            OpFunctionEnd\n";
2872         specInt.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2873         specInt.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2874         specInt.numWorkGroups = IVec3(numElements, 1, 1);
2875
2876         specArray.assembly =
2877                 string(getComputeAsmShaderPreamble()) +
2878
2879                 "OpSource GLSL 430\n"
2880                 "OpName %main \"main\"\n"
2881                 "OpName %id \"gl_GlobalInvocationID\"\n"
2882
2883                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2884
2885                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2886
2887                 "%id = OpVariable %uvec3ptr Input\n"
2888                 "%zero       = OpConstant %i32 0\n"
2889                 "%u7         = OpConstant %u32 7\n"
2890                 "%float_0    = OpConstant %f32 0.0\n"
2891                 "%float_1    = OpConstant %f32 1.0\n"
2892                 "%float_n1   = OpConstant %f32 -1.0\n"
2893                 "%f32a7      = OpTypeArray %f32 %u7\n"
2894                 "%a1         = OpConstantComposite %f32a7 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1\n"
2895                 "%a2         = OpConstantComposite %f32a7 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1\n"
2896                 "%main     = OpFunction %void None %voidf\n"
2897                 "%entry    = OpLabel\n"
2898                 "%idval    = OpLoad %uvec3 %id\n"
2899                 "%x        = OpCompositeExtract %u32 %idval 0\n"
2900                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
2901                 "%inval    = OpLoad %f32 %inloc\n"
2902
2903                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
2904                 "            OpSelectionMerge %cm None\n"
2905                 "            OpBranchConditional %comp %tb %fb\n"
2906                 "%tb       = OpLabel\n"
2907                 "            OpBranch %cm\n"
2908                 "%fb       = OpLabel\n"
2909                 "            OpBranch %cm\n"
2910                 "%cm       = OpLabel\n"
2911                 "%ares     = OpPhi %f32a7 %a1 %tb %a2 %fb\n"
2912                 "%res      = OpCompositeExtract %f32 %ares 5\n"
2913
2914                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
2915                 "            OpStore %outloc %res\n"
2916                 "            OpReturn\n"
2917
2918                 "            OpFunctionEnd\n";
2919         specArray.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2920         specArray.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2921         specArray.numWorkGroups = IVec3(numElements, 1, 1);
2922
2923         specStruct.assembly =
2924                 string(getComputeAsmShaderPreamble()) +
2925
2926                 "OpSource GLSL 430\n"
2927                 "OpName %main \"main\"\n"
2928                 "OpName %id \"gl_GlobalInvocationID\"\n"
2929
2930                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2931
2932                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2933
2934                 "%id = OpVariable %uvec3ptr Input\n"
2935                 "%zero       = OpConstant %i32 0\n"
2936                 "%float_0    = OpConstant %f32 0.0\n"
2937                 "%float_1    = OpConstant %f32 1.0\n"
2938                 "%float_n1   = OpConstant %f32 -1.0\n"
2939
2940                 "%v2f32      = OpTypeVector %f32 2\n"
2941                 "%Data2      = OpTypeStruct %f32 %v2f32\n"
2942                 "%Data       = OpTypeStruct %Data2 %f32\n"
2943
2944                 "%in1a       = OpConstantComposite %v2f32 %float_1 %float_1\n"
2945                 "%in1b       = OpConstantComposite %Data2 %float_1 %in1a\n"
2946                 "%s1         = OpConstantComposite %Data %in1b %float_1\n"
2947                 "%in2a       = OpConstantComposite %v2f32 %float_n1 %float_n1\n"
2948                 "%in2b       = OpConstantComposite %Data2 %float_n1 %in2a\n"
2949                 "%s2         = OpConstantComposite %Data %in2b %float_n1\n"
2950
2951                 "%main     = OpFunction %void None %voidf\n"
2952                 "%entry    = OpLabel\n"
2953                 "%idval    = OpLoad %uvec3 %id\n"
2954                 "%x        = OpCompositeExtract %u32 %idval 0\n"
2955                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
2956                 "%inval    = OpLoad %f32 %inloc\n"
2957
2958                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
2959                 "            OpSelectionMerge %cm None\n"
2960                 "            OpBranchConditional %comp %tb %fb\n"
2961                 "%tb       = OpLabel\n"
2962                 "            OpBranch %cm\n"
2963                 "%fb       = OpLabel\n"
2964                 "            OpBranch %cm\n"
2965                 "%cm       = OpLabel\n"
2966                 "%sres     = OpPhi %Data %s1 %tb %s2 %fb\n"
2967                 "%res      = OpCompositeExtract %f32 %sres 0 0\n"
2968
2969                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
2970                 "            OpStore %outloc %res\n"
2971                 "            OpReturn\n"
2972
2973                 "            OpFunctionEnd\n";
2974         specStruct.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2975         specStruct.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2976         specStruct.numWorkGroups = IVec3(numElements, 1, 1);
2977
2978         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_int", "OpPhi with int variables", specInt));
2979         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_float", "OpPhi with float variables", specFloat));
2980         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_vec3", "OpPhi with vec3 variables", specVec3));
2981         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_mat4", "OpPhi with mat4 variables", specMat4));
2982         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_array", "OpPhi with array variables", specArray));
2983         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_struct", "OpPhi with struct variables", specStruct));
2984 }
2985
2986 string generateConstantDefinitions (int count)
2987 {
2988         std::ostringstream      r;
2989         for (int i = 0; i < count; i++)
2990                 r << "%cf" << (i * 10 + 5) << " = OpConstant %f32 " <<(i * 10 + 5) << ".0\n";
2991         r << "\n";
2992         return r.str();
2993 }
2994
2995 string generateSwitchCases (int count)
2996 {
2997         std::ostringstream      r;
2998         for (int i = 0; i < count; i++)
2999                 r << " " << i << " %case" << i;
3000         r << "\n";
3001         return r.str();
3002 }
3003
3004 string generateSwitchTargets (int count)
3005 {
3006         std::ostringstream      r;
3007         for (int i = 0; i < count; i++)
3008                 r << "%case" << i << " = OpLabel\n            OpBranch %phi\n";
3009         r << "\n";
3010         return r.str();
3011 }
3012
3013 string generateOpPhiParams (int count)
3014 {
3015         std::ostringstream      r;
3016         for (int i = 0; i < count; i++)
3017                 r << " %cf" << (i * 10 + 5) << " %case" << i;
3018         r << "\n";
3019         return r.str();
3020 }
3021
3022 string generateIntWidth (int value)
3023 {
3024         std::ostringstream      r;
3025         r << value;
3026         return r.str();
3027 }
3028
3029 // Expand input string by injecting "ABC" between the input
3030 // string characters. The acc/add/treshold parameters are used
3031 // to skip some of the injections to make the result less
3032 // uniform (and a lot shorter).
3033 string expandOpPhiCase5 (const string& s, int &acc, int add, int treshold)
3034 {
3035         std::ostringstream      res;
3036         const char*                     p = s.c_str();
3037
3038         while (*p)
3039         {
3040                 res << *p;
3041                 acc += add;
3042                 if (acc > treshold)
3043                 {
3044                         acc -= treshold;
3045                         res << "ABC";
3046                 }
3047                 p++;
3048         }
3049         return res.str();
3050 }
3051
3052 // Calculate expected result based on the code string
3053 float calcOpPhiCase5 (float val, const string& s)
3054 {
3055         const char*             p               = s.c_str();
3056         float                   x[8];
3057         bool                    b[8];
3058         const float             tv[8]   = { 0.5f, 1.5f, 3.5f, 7.5f, 15.5f, 31.5f, 63.5f, 127.5f };
3059         const float             v               = deFloatAbs(val);
3060         float                   res             = 0;
3061         int                             depth   = -1;
3062         int                             skip    = 0;
3063
3064         for (int i = 7; i >= 0; --i)
3065                 x[i] = std::fmod((float)v, (float)(2 << i));
3066         for (int i = 7; i >= 0; --i)
3067                 b[i] = x[i] > tv[i];
3068
3069         while (*p)
3070         {
3071                 if (*p == 'A')
3072                 {
3073                         depth++;
3074                         if (skip == 0 && b[depth])
3075                         {
3076                                 res++;
3077                         }
3078                         else
3079                                 skip++;
3080                 }
3081                 if (*p == 'B')
3082                 {
3083                         if (skip)
3084                                 skip--;
3085                         if (b[depth] || skip)
3086                                 skip++;
3087                 }
3088                 if (*p == 'C')
3089                 {
3090                         depth--;
3091                         if (skip)
3092                                 skip--;
3093                 }
3094                 p++;
3095         }
3096         return res;
3097 }
3098
3099 // In the code string, the letters represent the following:
3100 //
3101 // A:
3102 //     if (certain bit is set)
3103 //     {
3104 //       result++;
3105 //
3106 // B:
3107 //     } else {
3108 //
3109 // C:
3110 //     }
3111 //
3112 // examples:
3113 // AABCBC leads to if(){r++;if(){r++;}else{}}else{}
3114 // ABABCC leads to if(){r++;}else{if(){r++;}else{}}
3115 // ABCABC leads to if(){r++;}else{}if(){r++;}else{}
3116 //
3117 // Code generation gets a bit complicated due to the else-branches,
3118 // which do not generate new values. Thus, the generator needs to
3119 // keep track of the previous variable change seen by the else
3120 // branch.
3121 string generateOpPhiCase5 (const string& s)
3122 {
3123         std::stack<int>                         idStack;
3124         std::stack<std::string>         value;
3125         std::stack<std::string>         valueLabel;
3126         std::stack<std::string>         mergeLeft;
3127         std::stack<std::string>         mergeRight;
3128         std::ostringstream                      res;
3129         const char*                                     p                       = s.c_str();
3130         int                                                     depth           = -1;
3131         int                                                     currId          = 0;
3132         int                                                     iter            = 0;
3133
3134         idStack.push(-1);
3135         value.push("%f32_0");
3136         valueLabel.push("%f32_0 %entry");
3137
3138         while (*p)
3139         {
3140                 if (*p == 'A')
3141                 {
3142                         depth++;
3143                         currId = iter;
3144                         idStack.push(currId);
3145                         res << "\tOpSelectionMerge %m" << currId << " None\n";
3146                         res << "\tOpBranchConditional %b" << depth << " %t" << currId << " %f" << currId << "\n";
3147                         res << "%t" << currId << " = OpLabel\n";
3148                         res << "%rt" << currId << " = OpFAdd %f32 " << value.top() << " %f32_1\n";
3149                         std::ostringstream tag;
3150                         tag << "%rt" << currId;
3151                         value.push(tag.str());
3152                         tag << " %t" << currId;
3153                         valueLabel.push(tag.str());
3154                 }
3155
3156                 if (*p == 'B')
3157                 {
3158                         mergeLeft.push(valueLabel.top());
3159                         value.pop();
3160                         valueLabel.pop();
3161                         res << "\tOpBranch %m" << currId << "\n";
3162                         res << "%f" << currId << " = OpLabel\n";
3163                         std::ostringstream tag;
3164                         tag << value.top() << " %f" << currId;
3165                         valueLabel.pop();
3166                         valueLabel.push(tag.str());
3167                 }
3168
3169                 if (*p == 'C')
3170                 {
3171                         mergeRight.push(valueLabel.top());
3172                         res << "\tOpBranch %m" << currId << "\n";
3173                         res << "%m" << currId << " = OpLabel\n";
3174                         if (*(p + 1) == 0)
3175                                 res << "%res"; // last result goes to %res
3176                         else
3177                                 res << "%rm" << currId;
3178                         res << " = OpPhi %f32  " << mergeLeft.top() << "  " << mergeRight.top() << "\n";
3179                         std::ostringstream tag;
3180                         tag << "%rm" << currId;
3181                         value.pop();
3182                         value.push(tag.str());
3183                         tag << " %m" << currId;
3184                         valueLabel.pop();
3185                         valueLabel.push(tag.str());
3186                         mergeLeft.pop();
3187                         mergeRight.pop();
3188                         depth--;
3189                         idStack.pop();
3190                         currId = idStack.top();
3191                 }
3192                 p++;
3193                 iter++;
3194         }
3195         return res.str();
3196 }
3197
3198 tcu::TestCaseGroup* createOpPhiGroup (tcu::TestContext& testCtx)
3199 {
3200         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
3201         ComputeShaderSpec                               spec1;
3202         ComputeShaderSpec                               spec2;
3203         ComputeShaderSpec                               spec3;
3204         ComputeShaderSpec                               spec4;
3205         ComputeShaderSpec                               spec5;
3206         de::Random                                              rnd                             (deStringHash(group->getName()));
3207         const int                                               numElements             = 100;
3208         vector<float>                                   inputFloats             (numElements, 0);
3209         vector<float>                                   outputFloats1   (numElements, 0);
3210         vector<float>                                   outputFloats2   (numElements, 0);
3211         vector<float>                                   outputFloats3   (numElements, 0);
3212         vector<float>                                   outputFloats4   (numElements, 0);
3213         vector<float>                                   outputFloats5   (numElements, 0);
3214         std::string                                             codestring              = "ABC";
3215         const int                                               test4Width              = 1024;
3216
3217         // Build case 5 code string. Each iteration makes the hierarchy more complicated.
3218         // 9 iterations with (7, 24) parameters makes the hierarchy 8 deep with about 1500 lines of
3219         // shader code.
3220         for (int i = 0, acc = 0; i < 9; i++)
3221                 codestring = expandOpPhiCase5(codestring, acc, 7, 24);
3222
3223         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
3224
3225         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3226         floorAll(inputFloats);
3227
3228         for (size_t ndx = 0; ndx < numElements; ++ndx)
3229         {
3230                 switch (ndx % 3)
3231                 {
3232                         case 0:         outputFloats1[ndx] = inputFloats[ndx] + 5.5f;   break;
3233                         case 1:         outputFloats1[ndx] = inputFloats[ndx] + 20.5f;  break;
3234                         case 2:         outputFloats1[ndx] = inputFloats[ndx] + 1.75f;  break;
3235                         default:        break;
3236                 }
3237                 outputFloats2[ndx] = inputFloats[ndx] + 6.5f * 3;
3238                 outputFloats3[ndx] = 8.5f - inputFloats[ndx];
3239
3240                 int index4 = (int)deFloor(deAbs((float)ndx * inputFloats[ndx]));
3241                 outputFloats4[ndx] = (float)(index4 % test4Width) * 10.0f + 5.0f;
3242
3243                 outputFloats5[ndx] = calcOpPhiCase5(inputFloats[ndx], codestring);
3244         }
3245
3246         spec1.assembly =
3247                 string(getComputeAsmShaderPreamble()) +
3248
3249                 "OpSource GLSL 430\n"
3250                 "OpName %main \"main\"\n"
3251                 "OpName %id \"gl_GlobalInvocationID\"\n"
3252
3253                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3254
3255                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3256
3257                 "%id = OpVariable %uvec3ptr Input\n"
3258                 "%zero       = OpConstant %i32 0\n"
3259                 "%three      = OpConstant %u32 3\n"
3260                 "%constf5p5  = OpConstant %f32 5.5\n"
3261                 "%constf20p5 = OpConstant %f32 20.5\n"
3262                 "%constf1p75 = OpConstant %f32 1.75\n"
3263                 "%constf8p5  = OpConstant %f32 8.5\n"
3264                 "%constf6p5  = OpConstant %f32 6.5\n"
3265
3266                 "%main     = OpFunction %void None %voidf\n"
3267                 "%entry    = OpLabel\n"
3268                 "%idval    = OpLoad %uvec3 %id\n"
3269                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3270                 "%selector = OpUMod %u32 %x %three\n"
3271                 "            OpSelectionMerge %phi None\n"
3272                 "            OpSwitch %selector %default 0 %case0 1 %case1 2 %case2\n"
3273
3274                 // Case 1 before OpPhi.
3275                 "%case1    = OpLabel\n"
3276                 "            OpBranch %phi\n"
3277
3278                 "%default  = OpLabel\n"
3279                 "            OpUnreachable\n"
3280
3281                 "%phi      = OpLabel\n"
3282                 "%operand  = OpPhi %f32   %constf1p75 %case2   %constf20p5 %case1   %constf5p5 %case0\n" // not in the order of blocks
3283                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3284                 "%inval    = OpLoad %f32 %inloc\n"
3285                 "%add      = OpFAdd %f32 %inval %operand\n"
3286                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3287                 "            OpStore %outloc %add\n"
3288                 "            OpReturn\n"
3289
3290                 // Case 0 after OpPhi.
3291                 "%case0    = OpLabel\n"
3292                 "            OpBranch %phi\n"
3293
3294
3295                 // Case 2 after OpPhi.
3296                 "%case2    = OpLabel\n"
3297                 "            OpBranch %phi\n"
3298
3299                 "            OpFunctionEnd\n";
3300         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3301         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
3302         spec1.numWorkGroups = IVec3(numElements, 1, 1);
3303
3304         group->addChild(new SpvAsmComputeShaderCase(testCtx, "block", "out-of-order and unreachable blocks for OpPhi", spec1));
3305
3306         spec2.assembly =
3307                 string(getComputeAsmShaderPreamble()) +
3308
3309                 "OpName %main \"main\"\n"
3310                 "OpName %id \"gl_GlobalInvocationID\"\n"
3311
3312                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3313
3314                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3315
3316                 "%id         = OpVariable %uvec3ptr Input\n"
3317                 "%zero       = OpConstant %i32 0\n"
3318                 "%one        = OpConstant %i32 1\n"
3319                 "%three      = OpConstant %i32 3\n"
3320                 "%constf6p5  = OpConstant %f32 6.5\n"
3321
3322                 "%main       = OpFunction %void None %voidf\n"
3323                 "%entry      = OpLabel\n"
3324                 "%idval      = OpLoad %uvec3 %id\n"
3325                 "%x          = OpCompositeExtract %u32 %idval 0\n"
3326                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3327                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3328                 "%inval      = OpLoad %f32 %inloc\n"
3329                 "              OpBranch %phi\n"
3330
3331                 "%phi        = OpLabel\n"
3332                 "%step       = OpPhi %i32 %zero  %entry %step_next  %phi\n"
3333                 "%accum      = OpPhi %f32 %inval %entry %accum_next %phi\n"
3334                 "%step_next  = OpIAdd %i32 %step %one\n"
3335                 "%accum_next = OpFAdd %f32 %accum %constf6p5\n"
3336                 "%still_loop = OpSLessThan %bool %step %three\n"
3337                 "              OpLoopMerge %exit %phi None\n"
3338                 "              OpBranchConditional %still_loop %phi %exit\n"
3339
3340                 "%exit       = OpLabel\n"
3341                 "              OpStore %outloc %accum\n"
3342                 "              OpReturn\n"
3343                 "              OpFunctionEnd\n";
3344         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3345         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
3346         spec2.numWorkGroups = IVec3(numElements, 1, 1);
3347
3348         group->addChild(new SpvAsmComputeShaderCase(testCtx, "induction", "The usual way induction variables are handled in LLVM IR", spec2));
3349
3350         spec3.assembly =
3351                 string(getComputeAsmShaderPreamble()) +
3352
3353                 "OpName %main \"main\"\n"
3354                 "OpName %id \"gl_GlobalInvocationID\"\n"
3355
3356                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3357
3358                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3359
3360                 "%f32ptr_f   = OpTypePointer Function %f32\n"
3361                 "%id         = OpVariable %uvec3ptr Input\n"
3362                 "%true       = OpConstantTrue %bool\n"
3363                 "%false      = OpConstantFalse %bool\n"
3364                 "%zero       = OpConstant %i32 0\n"
3365                 "%constf8p5  = OpConstant %f32 8.5\n"
3366
3367                 "%main       = OpFunction %void None %voidf\n"
3368                 "%entry      = OpLabel\n"
3369                 "%b          = OpVariable %f32ptr_f Function %constf8p5\n"
3370                 "%idval      = OpLoad %uvec3 %id\n"
3371                 "%x          = OpCompositeExtract %u32 %idval 0\n"
3372                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3373                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3374                 "%a_init     = OpLoad %f32 %inloc\n"
3375                 "%b_init     = OpLoad %f32 %b\n"
3376                 "              OpBranch %phi\n"
3377
3378                 "%phi        = OpLabel\n"
3379                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
3380                 "%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
3381                 "%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
3382                 "              OpLoopMerge %exit %phi None\n"
3383                 "              OpBranchConditional %still_loop %phi %exit\n"
3384
3385                 "%exit       = OpLabel\n"
3386                 "%sub        = OpFSub %f32 %a_next %b_next\n"
3387                 "              OpStore %outloc %sub\n"
3388                 "              OpReturn\n"
3389                 "              OpFunctionEnd\n";
3390         spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3391         spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
3392         spec3.numWorkGroups = IVec3(numElements, 1, 1);
3393
3394         group->addChild(new SpvAsmComputeShaderCase(testCtx, "swap", "Swap the values of two variables using OpPhi", spec3));
3395
3396         spec4.assembly =
3397                 "OpCapability Shader\n"
3398                 "%ext = OpExtInstImport \"GLSL.std.450\"\n"
3399                 "OpMemoryModel Logical GLSL450\n"
3400                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3401                 "OpExecutionMode %main LocalSize 1 1 1\n"
3402
3403                 "OpSource GLSL 430\n"
3404                 "OpName %main \"main\"\n"
3405                 "OpName %id \"gl_GlobalInvocationID\"\n"
3406
3407                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3408
3409                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3410
3411                 "%id       = OpVariable %uvec3ptr Input\n"
3412                 "%zero     = OpConstant %i32 0\n"
3413                 "%cimod    = OpConstant %u32 " + generateIntWidth(test4Width) + "\n"
3414
3415                 + generateConstantDefinitions(test4Width) +
3416
3417                 "%main     = OpFunction %void None %voidf\n"
3418                 "%entry    = OpLabel\n"
3419                 "%idval    = OpLoad %uvec3 %id\n"
3420                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3421                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3422                 "%inval    = OpLoad %f32 %inloc\n"
3423                 "%xf       = OpConvertUToF %f32 %x\n"
3424                 "%xm       = OpFMul %f32 %xf %inval\n"
3425                 "%xa       = OpExtInst %f32 %ext FAbs %xm\n"
3426                 "%xi       = OpConvertFToU %u32 %xa\n"
3427                 "%selector = OpUMod %u32 %xi %cimod\n"
3428                 "            OpSelectionMerge %phi None\n"
3429                 "            OpSwitch %selector %default "
3430
3431                 + generateSwitchCases(test4Width) +
3432
3433                 "%default  = OpLabel\n"
3434                 "            OpUnreachable\n"
3435
3436                 + generateSwitchTargets(test4Width) +
3437
3438                 "%phi      = OpLabel\n"
3439                 "%result   = OpPhi %f32"
3440
3441                 + generateOpPhiParams(test4Width) +
3442
3443                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3444                 "            OpStore %outloc %result\n"
3445                 "            OpReturn\n"
3446
3447                 "            OpFunctionEnd\n";
3448         spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3449         spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
3450         spec4.numWorkGroups = IVec3(numElements, 1, 1);
3451
3452         group->addChild(new SpvAsmComputeShaderCase(testCtx, "wide", "OpPhi with a lot of parameters", spec4));
3453
3454         spec5.assembly =
3455                 "OpCapability Shader\n"
3456                 "%ext      = OpExtInstImport \"GLSL.std.450\"\n"
3457                 "OpMemoryModel Logical GLSL450\n"
3458                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3459                 "OpExecutionMode %main LocalSize 1 1 1\n"
3460                 "%code     = OpString \"" + codestring + "\"\n"
3461
3462                 "OpSource GLSL 430\n"
3463                 "OpName %main \"main\"\n"
3464                 "OpName %id \"gl_GlobalInvocationID\"\n"
3465
3466                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3467
3468                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3469
3470                 "%id       = OpVariable %uvec3ptr Input\n"
3471                 "%zero     = OpConstant %i32 0\n"
3472                 "%f32_0    = OpConstant %f32 0.0\n"
3473                 "%f32_0_5  = OpConstant %f32 0.5\n"
3474                 "%f32_1    = OpConstant %f32 1.0\n"
3475                 "%f32_1_5  = OpConstant %f32 1.5\n"
3476                 "%f32_2    = OpConstant %f32 2.0\n"
3477                 "%f32_3_5  = OpConstant %f32 3.5\n"
3478                 "%f32_4    = OpConstant %f32 4.0\n"
3479                 "%f32_7_5  = OpConstant %f32 7.5\n"
3480                 "%f32_8    = OpConstant %f32 8.0\n"
3481                 "%f32_15_5 = OpConstant %f32 15.5\n"
3482                 "%f32_16   = OpConstant %f32 16.0\n"
3483                 "%f32_31_5 = OpConstant %f32 31.5\n"
3484                 "%f32_32   = OpConstant %f32 32.0\n"
3485                 "%f32_63_5 = OpConstant %f32 63.5\n"
3486                 "%f32_64   = OpConstant %f32 64.0\n"
3487                 "%f32_127_5 = OpConstant %f32 127.5\n"
3488                 "%f32_128  = OpConstant %f32 128.0\n"
3489                 "%f32_256  = OpConstant %f32 256.0\n"
3490
3491                 "%main     = OpFunction %void None %voidf\n"
3492                 "%entry    = OpLabel\n"
3493                 "%idval    = OpLoad %uvec3 %id\n"
3494                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3495                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3496                 "%inval    = OpLoad %f32 %inloc\n"
3497
3498                 "%xabs     = OpExtInst %f32 %ext FAbs %inval\n"
3499                 "%x8       = OpFMod %f32 %xabs %f32_256\n"
3500                 "%x7       = OpFMod %f32 %xabs %f32_128\n"
3501                 "%x6       = OpFMod %f32 %xabs %f32_64\n"
3502                 "%x5       = OpFMod %f32 %xabs %f32_32\n"
3503                 "%x4       = OpFMod %f32 %xabs %f32_16\n"
3504                 "%x3       = OpFMod %f32 %xabs %f32_8\n"
3505                 "%x2       = OpFMod %f32 %xabs %f32_4\n"
3506                 "%x1       = OpFMod %f32 %xabs %f32_2\n"
3507
3508                 "%b7       = OpFOrdGreaterThanEqual %bool %x8 %f32_127_5\n"
3509                 "%b6       = OpFOrdGreaterThanEqual %bool %x7 %f32_63_5\n"
3510                 "%b5       = OpFOrdGreaterThanEqual %bool %x6 %f32_31_5\n"
3511                 "%b4       = OpFOrdGreaterThanEqual %bool %x5 %f32_15_5\n"
3512                 "%b3       = OpFOrdGreaterThanEqual %bool %x4 %f32_7_5\n"
3513                 "%b2       = OpFOrdGreaterThanEqual %bool %x3 %f32_3_5\n"
3514                 "%b1       = OpFOrdGreaterThanEqual %bool %x2 %f32_1_5\n"
3515                 "%b0       = OpFOrdGreaterThanEqual %bool %x1 %f32_0_5\n"
3516
3517                 + generateOpPhiCase5(codestring) +
3518
3519                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3520                 "            OpStore %outloc %res\n"
3521                 "            OpReturn\n"
3522
3523                 "            OpFunctionEnd\n";
3524         spec5.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3525         spec5.outputs.push_back(BufferSp(new Float32Buffer(outputFloats5)));
3526         spec5.numWorkGroups = IVec3(numElements, 1, 1);
3527
3528         group->addChild(new SpvAsmComputeShaderCase(testCtx, "nested", "Stress OpPhi with a lot of nesting", spec5));
3529
3530         createOpPhiVartypeTests(group, testCtx);
3531
3532         return group.release();
3533 }
3534
3535 // Assembly code used for testing block order is based on GLSL source code:
3536 //
3537 // #version 430
3538 //
3539 // layout(std140, set = 0, binding = 0) readonly buffer Input {
3540 //   float elements[];
3541 // } input_data;
3542 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
3543 //   float elements[];
3544 // } output_data;
3545 //
3546 // void main() {
3547 //   uint x = gl_GlobalInvocationID.x;
3548 //   output_data.elements[x] = input_data.elements[x];
3549 //   if (x > uint(50)) {
3550 //     switch (x % uint(3)) {
3551 //       case 0: output_data.elements[x] += 1.5f; break;
3552 //       case 1: output_data.elements[x] += 42.f; break;
3553 //       case 2: output_data.elements[x] -= 27.f; break;
3554 //       default: break;
3555 //     }
3556 //   } else {
3557 //     output_data.elements[x] = -input_data.elements[x];
3558 //   }
3559 // }
3560 tcu::TestCaseGroup* createBlockOrderGroup (tcu::TestContext& testCtx)
3561 {
3562         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "block_order", "Test block orders"));
3563         ComputeShaderSpec                               spec;
3564         de::Random                                              rnd                             (deStringHash(group->getName()));
3565         const int                                               numElements             = 100;
3566         vector<float>                                   inputFloats             (numElements, 0);
3567         vector<float>                                   outputFloats    (numElements, 0);
3568
3569         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
3570
3571         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3572         floorAll(inputFloats);
3573
3574         for (size_t ndx = 0; ndx <= 50; ++ndx)
3575                 outputFloats[ndx] = -inputFloats[ndx];
3576
3577         for (size_t ndx = 51; ndx < numElements; ++ndx)
3578         {
3579                 switch (ndx % 3)
3580                 {
3581                         case 0:         outputFloats[ndx] = inputFloats[ndx] + 1.5f; break;
3582                         case 1:         outputFloats[ndx] = inputFloats[ndx] + 42.f; break;
3583                         case 2:         outputFloats[ndx] = inputFloats[ndx] - 27.f; break;
3584                         default:        break;
3585                 }
3586         }
3587
3588         spec.assembly =
3589                 string(getComputeAsmShaderPreamble()) +
3590
3591                 "OpSource GLSL 430\n"
3592                 "OpName %main \"main\"\n"
3593                 "OpName %id \"gl_GlobalInvocationID\"\n"
3594
3595                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3596
3597                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
3598
3599                 "%u32ptr       = OpTypePointer Function %u32\n"
3600                 "%u32ptr_input = OpTypePointer Input %u32\n"
3601
3602                 + string(getComputeAsmInputOutputBuffer()) +
3603
3604                 "%id        = OpVariable %uvec3ptr Input\n"
3605                 "%zero      = OpConstant %i32 0\n"
3606                 "%const3    = OpConstant %u32 3\n"
3607                 "%const50   = OpConstant %u32 50\n"
3608                 "%constf1p5 = OpConstant %f32 1.5\n"
3609                 "%constf27  = OpConstant %f32 27.0\n"
3610                 "%constf42  = OpConstant %f32 42.0\n"
3611
3612                 "%main = OpFunction %void None %voidf\n"
3613
3614                 // entry block.
3615                 "%entry    = OpLabel\n"
3616
3617                 // Create a temporary variable to hold the value of gl_GlobalInvocationID.x.
3618                 "%xvar     = OpVariable %u32ptr Function\n"
3619                 "%xptr     = OpAccessChain %u32ptr_input %id %zero\n"
3620                 "%x        = OpLoad %u32 %xptr\n"
3621                 "            OpStore %xvar %x\n"
3622
3623                 "%cmp      = OpUGreaterThan %bool %x %const50\n"
3624                 "            OpSelectionMerge %if_merge None\n"
3625                 "            OpBranchConditional %cmp %if_true %if_false\n"
3626
3627                 // False branch for if-statement: placed in the middle of switch cases and before true branch.
3628                 "%if_false = OpLabel\n"
3629                 "%x_f      = OpLoad %u32 %xvar\n"
3630                 "%inloc_f  = OpAccessChain %f32ptr %indata %zero %x_f\n"
3631                 "%inval_f  = OpLoad %f32 %inloc_f\n"
3632                 "%negate   = OpFNegate %f32 %inval_f\n"
3633                 "%outloc_f = OpAccessChain %f32ptr %outdata %zero %x_f\n"
3634                 "            OpStore %outloc_f %negate\n"
3635                 "            OpBranch %if_merge\n"
3636
3637                 // Merge block for if-statement: placed in the middle of true and false branch.
3638                 "%if_merge = OpLabel\n"
3639                 "            OpReturn\n"
3640
3641                 // True branch for if-statement: placed in the middle of swtich cases and after the false branch.
3642                 "%if_true  = OpLabel\n"
3643                 "%xval_t   = OpLoad %u32 %xvar\n"
3644                 "%mod      = OpUMod %u32 %xval_t %const3\n"
3645                 "            OpSelectionMerge %switch_merge None\n"
3646                 "            OpSwitch %mod %default 0 %case0 1 %case1 2 %case2\n"
3647
3648                 // Merge block for switch-statement: placed before the case
3649                 // bodies.  But it must follow OpSwitch which dominates it.
3650                 "%switch_merge = OpLabel\n"
3651                 "                OpBranch %if_merge\n"
3652
3653                 // Case 1 for switch-statement: placed before case 0.
3654                 // It must follow the OpSwitch that dominates it.
3655                 "%case1    = OpLabel\n"
3656                 "%x_1      = OpLoad %u32 %xvar\n"
3657                 "%inloc_1  = OpAccessChain %f32ptr %indata %zero %x_1\n"
3658                 "%inval_1  = OpLoad %f32 %inloc_1\n"
3659                 "%addf42   = OpFAdd %f32 %inval_1 %constf42\n"
3660                 "%outloc_1 = OpAccessChain %f32ptr %outdata %zero %x_1\n"
3661                 "            OpStore %outloc_1 %addf42\n"
3662                 "            OpBranch %switch_merge\n"
3663
3664                 // Case 2 for switch-statement.
3665                 "%case2    = OpLabel\n"
3666                 "%x_2      = OpLoad %u32 %xvar\n"
3667                 "%inloc_2  = OpAccessChain %f32ptr %indata %zero %x_2\n"
3668                 "%inval_2  = OpLoad %f32 %inloc_2\n"
3669                 "%subf27   = OpFSub %f32 %inval_2 %constf27\n"
3670                 "%outloc_2 = OpAccessChain %f32ptr %outdata %zero %x_2\n"
3671                 "            OpStore %outloc_2 %subf27\n"
3672                 "            OpBranch %switch_merge\n"
3673
3674                 // Default case for switch-statement: placed in the middle of normal cases.
3675                 "%default = OpLabel\n"
3676                 "           OpBranch %switch_merge\n"
3677
3678                 // Case 0 for switch-statement: out of order.
3679                 "%case0    = OpLabel\n"
3680                 "%x_0      = OpLoad %u32 %xvar\n"
3681                 "%inloc_0  = OpAccessChain %f32ptr %indata %zero %x_0\n"
3682                 "%inval_0  = OpLoad %f32 %inloc_0\n"
3683                 "%addf1p5  = OpFAdd %f32 %inval_0 %constf1p5\n"
3684                 "%outloc_0 = OpAccessChain %f32ptr %outdata %zero %x_0\n"
3685                 "            OpStore %outloc_0 %addf1p5\n"
3686                 "            OpBranch %switch_merge\n"
3687
3688                 "            OpFunctionEnd\n";
3689         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3690         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3691         spec.numWorkGroups = IVec3(numElements, 1, 1);
3692
3693         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "various out-of-order blocks", spec));
3694
3695         return group.release();
3696 }
3697
3698 tcu::TestCaseGroup* createMultipleShaderGroup (tcu::TestContext& testCtx)
3699 {
3700         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "multiple_shaders", "Test multiple shaders in the same module"));
3701         ComputeShaderSpec                               spec1;
3702         ComputeShaderSpec                               spec2;
3703         de::Random                                              rnd                             (deStringHash(group->getName()));
3704         const int                                               numElements             = 100;
3705         vector<float>                                   inputFloats             (numElements, 0);
3706         vector<float>                                   outputFloats1   (numElements, 0);
3707         vector<float>                                   outputFloats2   (numElements, 0);
3708         fillRandomScalars(rnd, -500.f, 500.f, &inputFloats[0], numElements);
3709
3710         for (size_t ndx = 0; ndx < numElements; ++ndx)
3711         {
3712                 outputFloats1[ndx] = inputFloats[ndx] + inputFloats[ndx];
3713                 outputFloats2[ndx] = -inputFloats[ndx];
3714         }
3715
3716         const string assembly(
3717                 "OpCapability Shader\n"
3718                 "OpCapability ClipDistance\n"
3719                 "OpMemoryModel Logical GLSL450\n"
3720                 "OpEntryPoint GLCompute %comp_main1 \"entrypoint1\" %id\n"
3721                 "OpEntryPoint GLCompute %comp_main2 \"entrypoint2\" %id\n"
3722                 // A module cannot have two OpEntryPoint instructions with the same Execution Model and the same Name string.
3723                 "OpEntryPoint Vertex    %vert_main  \"entrypoint2\" %vert_builtins %vertexIndex %instanceIndex\n"
3724                 "OpExecutionMode %comp_main1 LocalSize 1 1 1\n"
3725                 "OpExecutionMode %comp_main2 LocalSize 1 1 1\n"
3726
3727                 "OpName %comp_main1              \"entrypoint1\"\n"
3728                 "OpName %comp_main2              \"entrypoint2\"\n"
3729                 "OpName %vert_main               \"entrypoint2\"\n"
3730                 "OpName %id                      \"gl_GlobalInvocationID\"\n"
3731                 "OpName %vert_builtin_st         \"gl_PerVertex\"\n"
3732                 "OpName %vertexIndex             \"gl_VertexIndex\"\n"
3733                 "OpName %instanceIndex           \"gl_InstanceIndex\"\n"
3734                 "OpMemberName %vert_builtin_st 0 \"gl_Position\"\n"
3735                 "OpMemberName %vert_builtin_st 1 \"gl_PointSize\"\n"
3736                 "OpMemberName %vert_builtin_st 2 \"gl_ClipDistance\"\n"
3737
3738                 "OpDecorate %id                      BuiltIn GlobalInvocationId\n"
3739                 "OpDecorate %vertexIndex             BuiltIn VertexIndex\n"
3740                 "OpDecorate %instanceIndex           BuiltIn InstanceIndex\n"
3741                 "OpDecorate %vert_builtin_st         Block\n"
3742                 "OpMemberDecorate %vert_builtin_st 0 BuiltIn Position\n"
3743                 "OpMemberDecorate %vert_builtin_st 1 BuiltIn PointSize\n"
3744                 "OpMemberDecorate %vert_builtin_st 2 BuiltIn ClipDistance\n"
3745
3746                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3747
3748                 "%zero       = OpConstant %i32 0\n"
3749                 "%one        = OpConstant %u32 1\n"
3750                 "%c_f32_1    = OpConstant %f32 1\n"
3751
3752                 "%i32inputptr         = OpTypePointer Input %i32\n"
3753                 "%vec4                = OpTypeVector %f32 4\n"
3754                 "%vec4ptr             = OpTypePointer Output %vec4\n"
3755                 "%f32arr1             = OpTypeArray %f32 %one\n"
3756                 "%vert_builtin_st     = OpTypeStruct %vec4 %f32 %f32arr1\n"
3757                 "%vert_builtin_st_ptr = OpTypePointer Output %vert_builtin_st\n"
3758                 "%vert_builtins       = OpVariable %vert_builtin_st_ptr Output\n"
3759
3760                 "%id         = OpVariable %uvec3ptr Input\n"
3761                 "%vertexIndex = OpVariable %i32inputptr Input\n"
3762                 "%instanceIndex = OpVariable %i32inputptr Input\n"
3763                 "%c_vec4_1   = OpConstantComposite %vec4 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
3764
3765                 // gl_Position = vec4(1.);
3766                 "%vert_main  = OpFunction %void None %voidf\n"
3767                 "%vert_entry = OpLabel\n"
3768                 "%position   = OpAccessChain %vec4ptr %vert_builtins %zero\n"
3769                 "              OpStore %position %c_vec4_1\n"
3770                 "              OpReturn\n"
3771                 "              OpFunctionEnd\n"
3772
3773                 // Double inputs.
3774                 "%comp_main1  = OpFunction %void None %voidf\n"
3775                 "%comp1_entry = OpLabel\n"
3776                 "%idval1      = OpLoad %uvec3 %id\n"
3777                 "%x1          = OpCompositeExtract %u32 %idval1 0\n"
3778                 "%inloc1      = OpAccessChain %f32ptr %indata %zero %x1\n"
3779                 "%inval1      = OpLoad %f32 %inloc1\n"
3780                 "%add         = OpFAdd %f32 %inval1 %inval1\n"
3781                 "%outloc1     = OpAccessChain %f32ptr %outdata %zero %x1\n"
3782                 "               OpStore %outloc1 %add\n"
3783                 "               OpReturn\n"
3784                 "               OpFunctionEnd\n"
3785
3786                 // Negate inputs.
3787                 "%comp_main2  = OpFunction %void None %voidf\n"
3788                 "%comp2_entry = OpLabel\n"
3789                 "%idval2      = OpLoad %uvec3 %id\n"
3790                 "%x2          = OpCompositeExtract %u32 %idval2 0\n"
3791                 "%inloc2      = OpAccessChain %f32ptr %indata %zero %x2\n"
3792                 "%inval2      = OpLoad %f32 %inloc2\n"
3793                 "%neg         = OpFNegate %f32 %inval2\n"
3794                 "%outloc2     = OpAccessChain %f32ptr %outdata %zero %x2\n"
3795                 "               OpStore %outloc2 %neg\n"
3796                 "               OpReturn\n"
3797                 "               OpFunctionEnd\n");
3798
3799         spec1.assembly = assembly;
3800         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3801         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
3802         spec1.numWorkGroups = IVec3(numElements, 1, 1);
3803         spec1.entryPoint = "entrypoint1";
3804
3805         spec2.assembly = assembly;
3806         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3807         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
3808         spec2.numWorkGroups = IVec3(numElements, 1, 1);
3809         spec2.entryPoint = "entrypoint2";
3810
3811         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader1", "multiple shaders in the same module", spec1));
3812         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader2", "multiple shaders in the same module", spec2));
3813
3814         return group.release();
3815 }
3816
3817 inline std::string makeLongUTF8String (size_t num4ByteChars)
3818 {
3819         // An example of a longest valid UTF-8 character.  Be explicit about the
3820         // character type because Microsoft compilers can otherwise interpret the
3821         // character string as being over wide (16-bit) characters. Ideally, we
3822         // would just use a C++11 UTF-8 string literal, but we want to support older
3823         // Microsoft compilers.
3824         const std::basic_string<char> earthAfrica("\xF0\x9F\x8C\x8D");
3825         std::string longString;
3826         longString.reserve(num4ByteChars * 4);
3827         for (size_t count = 0; count < num4ByteChars; count++)
3828         {
3829                 longString += earthAfrica;
3830         }
3831         return longString;
3832 }
3833
3834 tcu::TestCaseGroup* createOpSourceGroup (tcu::TestContext& testCtx)
3835 {
3836         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsource", "Tests the OpSource & OpSourceContinued instruction"));
3837         vector<CaseParameter>                   cases;
3838         de::Random                                              rnd                             (deStringHash(group->getName()));
3839         const int                                               numElements             = 100;
3840         vector<float>                                   positiveFloats  (numElements, 0);
3841         vector<float>                                   negativeFloats  (numElements, 0);
3842         const StringTemplate                    shaderTemplate  (
3843                 "OpCapability Shader\n"
3844                 "OpMemoryModel Logical GLSL450\n"
3845
3846                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3847                 "OpExecutionMode %main LocalSize 1 1 1\n"
3848
3849                 "${SOURCE}\n"
3850
3851                 "OpName %main           \"main\"\n"
3852                 "OpName %id             \"gl_GlobalInvocationID\"\n"
3853
3854                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3855
3856                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3857
3858                 "%id        = OpVariable %uvec3ptr Input\n"
3859                 "%zero      = OpConstant %i32 0\n"
3860
3861                 "%main      = OpFunction %void None %voidf\n"
3862                 "%label     = OpLabel\n"
3863                 "%idval     = OpLoad %uvec3 %id\n"
3864                 "%x         = OpCompositeExtract %u32 %idval 0\n"
3865                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
3866                 "%inval     = OpLoad %f32 %inloc\n"
3867                 "%neg       = OpFNegate %f32 %inval\n"
3868                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
3869                 "             OpStore %outloc %neg\n"
3870                 "             OpReturn\n"
3871                 "             OpFunctionEnd\n");
3872
3873         cases.push_back(CaseParameter("unknown_source",                                                 "OpSource Unknown 0"));
3874         cases.push_back(CaseParameter("wrong_source",                                                   "OpSource OpenCL_C 210"));
3875         cases.push_back(CaseParameter("normal_filename",                                                "%fname = OpString \"filename\"\n"
3876                                                                                                                                                         "OpSource GLSL 430 %fname"));
3877         cases.push_back(CaseParameter("empty_filename",                                                 "%fname = OpString \"\"\n"
3878                                                                                                                                                         "OpSource GLSL 430 %fname"));
3879         cases.push_back(CaseParameter("normal_source_code",                                             "%fname = OpString \"filename\"\n"
3880                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\""));
3881         cases.push_back(CaseParameter("empty_source_code",                                              "%fname = OpString \"filename\"\n"
3882                                                                                                                                                         "OpSource GLSL 430 %fname \"\""));
3883         cases.push_back(CaseParameter("long_source_code",                                               "%fname = OpString \"filename\"\n"
3884                                                                                                                                                         "OpSource GLSL 430 %fname \"" + makeLongUTF8String(65530) + "ccc\"")); // word count: 65535
3885         cases.push_back(CaseParameter("utf8_source_code",                                               "%fname = OpString \"filename\"\n"
3886                                                                                                                                                         "OpSource GLSL 430 %fname \"\xE2\x98\x82\xE2\x98\x85\"")); // umbrella & black star symbol
3887         cases.push_back(CaseParameter("normal_sourcecontinued",                                 "%fname = OpString \"filename\"\n"
3888                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvo\"\n"
3889                                                                                                                                                         "OpSourceContinued \"id main() {}\""));
3890         cases.push_back(CaseParameter("empty_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
3891                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
3892                                                                                                                                                         "OpSourceContinued \"\""));
3893         cases.push_back(CaseParameter("long_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
3894                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
3895                                                                                                                                                         "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\"")); // word count: 65535
3896         cases.push_back(CaseParameter("utf8_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
3897                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
3898                                                                                                                                                         "OpSourceContinued \"\xE2\x98\x8E\xE2\x9A\x91\"")); // white telephone & black flag symbol
3899         cases.push_back(CaseParameter("multi_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
3900                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\n\"\n"
3901                                                                                                                                                         "OpSourceContinued \"void\"\n"
3902                                                                                                                                                         "OpSourceContinued \"main()\"\n"
3903                                                                                                                                                         "OpSourceContinued \"{}\""));
3904         cases.push_back(CaseParameter("empty_source_before_sourcecontinued",    "%fname = OpString \"filename\"\n"
3905                                                                                                                                                         "OpSource GLSL 430 %fname \"\"\n"
3906                                                                                                                                                         "OpSourceContinued \"#version 430\nvoid main() {}\""));
3907
3908         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
3909
3910         for (size_t ndx = 0; ndx < numElements; ++ndx)
3911                 negativeFloats[ndx] = -positiveFloats[ndx];
3912
3913         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
3914         {
3915                 map<string, string>             specializations;
3916                 ComputeShaderSpec               spec;
3917
3918                 specializations["SOURCE"] = cases[caseNdx].param;
3919                 spec.assembly = shaderTemplate.specialize(specializations);
3920                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
3921                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
3922                 spec.numWorkGroups = IVec3(numElements, 1, 1);
3923
3924                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
3925         }
3926
3927         return group.release();
3928 }
3929
3930 tcu::TestCaseGroup* createOpSourceExtensionGroup (tcu::TestContext& testCtx)
3931 {
3932         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsourceextension", "Tests the OpSource instruction"));
3933         vector<CaseParameter>                   cases;
3934         de::Random                                              rnd                             (deStringHash(group->getName()));
3935         const int                                               numElements             = 100;
3936         vector<float>                                   inputFloats             (numElements, 0);
3937         vector<float>                                   outputFloats    (numElements, 0);
3938         const StringTemplate                    shaderTemplate  (
3939                 string(getComputeAsmShaderPreamble()) +
3940
3941                 "OpSourceExtension \"${EXTENSION}\"\n"
3942
3943                 "OpName %main           \"main\"\n"
3944                 "OpName %id             \"gl_GlobalInvocationID\"\n"
3945
3946                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3947
3948                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3949
3950                 "%id        = OpVariable %uvec3ptr Input\n"
3951                 "%zero      = OpConstant %i32 0\n"
3952
3953                 "%main      = OpFunction %void None %voidf\n"
3954                 "%label     = OpLabel\n"
3955                 "%idval     = OpLoad %uvec3 %id\n"
3956                 "%x         = OpCompositeExtract %u32 %idval 0\n"
3957                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
3958                 "%inval     = OpLoad %f32 %inloc\n"
3959                 "%neg       = OpFNegate %f32 %inval\n"
3960                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
3961                 "             OpStore %outloc %neg\n"
3962                 "             OpReturn\n"
3963                 "             OpFunctionEnd\n");
3964
3965         cases.push_back(CaseParameter("empty_extension",        ""));
3966         cases.push_back(CaseParameter("real_extension",         "GL_ARB_texture_rectangle"));
3967         cases.push_back(CaseParameter("fake_extension",         "GL_ARB_im_the_ultimate_extension"));
3968         cases.push_back(CaseParameter("utf8_extension",         "GL_ARB_\xE2\x98\x82\xE2\x98\x85"));
3969         cases.push_back(CaseParameter("long_extension",         makeLongUTF8String(65533) + "ccc")); // word count: 65535
3970
3971         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
3972
3973         for (size_t ndx = 0; ndx < numElements; ++ndx)
3974                 outputFloats[ndx] = -inputFloats[ndx];
3975
3976         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
3977         {
3978                 map<string, string>             specializations;
3979                 ComputeShaderSpec               spec;
3980
3981                 specializations["EXTENSION"] = cases[caseNdx].param;
3982                 spec.assembly = shaderTemplate.specialize(specializations);
3983                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3984                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3985                 spec.numWorkGroups = IVec3(numElements, 1, 1);
3986
3987                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
3988         }
3989
3990         return group.release();
3991 }
3992
3993 // Checks that a compute shader can generate a constant null value of various types, without exercising a computation on it.
3994 tcu::TestCaseGroup* createOpConstantNullGroup (tcu::TestContext& testCtx)
3995 {
3996         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnull", "Tests the OpConstantNull instruction"));
3997         vector<CaseParameter>                   cases;
3998         de::Random                                              rnd                             (deStringHash(group->getName()));
3999         const int                                               numElements             = 100;
4000         vector<float>                                   positiveFloats  (numElements, 0);
4001         vector<float>                                   negativeFloats  (numElements, 0);
4002         const StringTemplate                    shaderTemplate  (
4003                 string(getComputeAsmShaderPreamble()) +
4004
4005                 "OpSource GLSL 430\n"
4006                 "OpName %main           \"main\"\n"
4007                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4008
4009                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4010
4011                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4012                 "%uvec2     = OpTypeVector %u32 2\n"
4013                 "%bvec3     = OpTypeVector %bool 3\n"
4014                 "%fvec4     = OpTypeVector %f32 4\n"
4015                 "%fmat33    = OpTypeMatrix %fvec3 3\n"
4016                 "%const100  = OpConstant %u32 100\n"
4017                 "%uarr100   = OpTypeArray %i32 %const100\n"
4018                 "%struct    = OpTypeStruct %f32 %i32 %u32\n"
4019                 "%pointer   = OpTypePointer Function %i32\n"
4020                 + string(getComputeAsmInputOutputBuffer()) +
4021
4022                 "%null      = OpConstantNull ${TYPE}\n"
4023
4024                 "%id        = OpVariable %uvec3ptr Input\n"
4025                 "%zero      = OpConstant %i32 0\n"
4026
4027                 "%main      = OpFunction %void None %voidf\n"
4028                 "%label     = OpLabel\n"
4029                 "%idval     = OpLoad %uvec3 %id\n"
4030                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4031                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4032                 "%inval     = OpLoad %f32 %inloc\n"
4033                 "%neg       = OpFNegate %f32 %inval\n"
4034                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4035                 "             OpStore %outloc %neg\n"
4036                 "             OpReturn\n"
4037                 "             OpFunctionEnd\n");
4038
4039         cases.push_back(CaseParameter("bool",                   "%bool"));
4040         cases.push_back(CaseParameter("sint32",                 "%i32"));
4041         cases.push_back(CaseParameter("uint32",                 "%u32"));
4042         cases.push_back(CaseParameter("float32",                "%f32"));
4043         cases.push_back(CaseParameter("vec4float32",    "%fvec4"));
4044         cases.push_back(CaseParameter("vec3bool",               "%bvec3"));
4045         cases.push_back(CaseParameter("vec2uint32",             "%uvec2"));
4046         cases.push_back(CaseParameter("matrix",                 "%fmat33"));
4047         cases.push_back(CaseParameter("array",                  "%uarr100"));
4048         cases.push_back(CaseParameter("struct",                 "%struct"));
4049         cases.push_back(CaseParameter("pointer",                "%pointer"));
4050
4051         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4052
4053         for (size_t ndx = 0; ndx < numElements; ++ndx)
4054                 negativeFloats[ndx] = -positiveFloats[ndx];
4055
4056         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4057         {
4058                 map<string, string>             specializations;
4059                 ComputeShaderSpec               spec;
4060
4061                 specializations["TYPE"] = cases[caseNdx].param;
4062                 spec.assembly = shaderTemplate.specialize(specializations);
4063                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4064                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4065                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4066
4067                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4068         }
4069
4070         return group.release();
4071 }
4072
4073 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
4074 tcu::TestCaseGroup* createOpConstantCompositeGroup (tcu::TestContext& testCtx)
4075 {
4076         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "Tests the OpConstantComposite instruction"));
4077         vector<CaseParameter>                   cases;
4078         de::Random                                              rnd                             (deStringHash(group->getName()));
4079         const int                                               numElements             = 100;
4080         vector<float>                                   positiveFloats  (numElements, 0);
4081         vector<float>                                   negativeFloats  (numElements, 0);
4082         const StringTemplate                    shaderTemplate  (
4083                 string(getComputeAsmShaderPreamble()) +
4084
4085                 "OpSource GLSL 430\n"
4086                 "OpName %main           \"main\"\n"
4087                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4088
4089                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4090
4091                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4092
4093                 "%id        = OpVariable %uvec3ptr Input\n"
4094                 "%zero      = OpConstant %i32 0\n"
4095
4096                 "${CONSTANT}\n"
4097
4098                 "%main      = OpFunction %void None %voidf\n"
4099                 "%label     = OpLabel\n"
4100                 "%idval     = OpLoad %uvec3 %id\n"
4101                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4102                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4103                 "%inval     = OpLoad %f32 %inloc\n"
4104                 "%neg       = OpFNegate %f32 %inval\n"
4105                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4106                 "             OpStore %outloc %neg\n"
4107                 "             OpReturn\n"
4108                 "             OpFunctionEnd\n");
4109
4110         cases.push_back(CaseParameter("vector",                 "%five = OpConstant %u32 5\n"
4111                                                                                                         "%const = OpConstantComposite %uvec3 %five %zero %five"));
4112         cases.push_back(CaseParameter("matrix",                 "%m3fvec3 = OpTypeMatrix %fvec3 3\n"
4113                                                                                                         "%ten = OpConstant %f32 10.\n"
4114                                                                                                         "%fzero = OpConstant %f32 0.\n"
4115                                                                                                         "%vec = OpConstantComposite %fvec3 %ten %fzero %ten\n"
4116                                                                                                         "%mat = OpConstantComposite %m3fvec3 %vec %vec %vec"));
4117         cases.push_back(CaseParameter("struct",                 "%m2vec3 = OpTypeMatrix %fvec3 2\n"
4118                                                                                                         "%struct = OpTypeStruct %i32 %f32 %fvec3 %m2vec3\n"
4119                                                                                                         "%fzero = OpConstant %f32 0.\n"
4120                                                                                                         "%one = OpConstant %f32 1.\n"
4121                                                                                                         "%point5 = OpConstant %f32 0.5\n"
4122                                                                                                         "%vec = OpConstantComposite %fvec3 %one %one %fzero\n"
4123                                                                                                         "%mat = OpConstantComposite %m2vec3 %vec %vec\n"
4124                                                                                                         "%const = OpConstantComposite %struct %zero %point5 %vec %mat"));
4125         cases.push_back(CaseParameter("nested_struct",  "%st1 = OpTypeStruct %u32 %f32\n"
4126                                                                                                         "%st2 = OpTypeStruct %i32 %i32\n"
4127                                                                                                         "%struct = OpTypeStruct %st1 %st2\n"
4128                                                                                                         "%point5 = OpConstant %f32 0.5\n"
4129                                                                                                         "%one = OpConstant %u32 1\n"
4130                                                                                                         "%ten = OpConstant %i32 10\n"
4131                                                                                                         "%st1val = OpConstantComposite %st1 %one %point5\n"
4132                                                                                                         "%st2val = OpConstantComposite %st2 %ten %ten\n"
4133                                                                                                         "%const = OpConstantComposite %struct %st1val %st2val"));
4134
4135         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4136
4137         for (size_t ndx = 0; ndx < numElements; ++ndx)
4138                 negativeFloats[ndx] = -positiveFloats[ndx];
4139
4140         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4141         {
4142                 map<string, string>             specializations;
4143                 ComputeShaderSpec               spec;
4144
4145                 specializations["CONSTANT"] = cases[caseNdx].param;
4146                 spec.assembly = shaderTemplate.specialize(specializations);
4147                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4148                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4149                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4150
4151                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4152         }
4153
4154         return group.release();
4155 }
4156
4157 // Creates a floating point number with the given exponent, and significand
4158 // bits set. It can only create normalized numbers. Only the least significant
4159 // 24 bits of the significand will be examined. The final bit of the
4160 // significand will also be ignored. This allows alignment to be written
4161 // similarly to C99 hex-floats.
4162 // For example if you wanted to write 0x1.7f34p-12 you would call
4163 // constructNormalizedFloat(-12, 0x7f3400)
4164 float constructNormalizedFloat (deInt32 exponent, deUint32 significand)
4165 {
4166         float f = 1.0f;
4167
4168         for (deInt32 idx = 0; idx < 23; ++idx)
4169         {
4170                 f += ((significand & 0x800000) == 0) ? 0.f : std::ldexp(1.0f, -(idx + 1));
4171                 significand <<= 1;
4172         }
4173
4174         return std::ldexp(f, exponent);
4175 }
4176
4177 // Compare instruction for the OpQuantizeF16 compute exact case.
4178 // Returns true if the output is what is expected from the test case.
4179 bool compareOpQuantizeF16ComputeExactCase (const std::vector<BufferSp>&, const vector<AllocationSp>& outputAllocs, const std::vector<BufferSp>& expectedOutputs, TestLog&)
4180 {
4181         if (outputAllocs.size() != 1)
4182                 return false;
4183
4184         // Only size is needed because we cannot compare Nans.
4185         size_t byteSize = expectedOutputs[0]->getByteSize();
4186
4187         const float*    outputAsFloat   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
4188
4189         if (byteSize != 4*sizeof(float)) {
4190                 return false;
4191         }
4192
4193         if (*outputAsFloat != constructNormalizedFloat(8, 0x304000) &&
4194                 *outputAsFloat != constructNormalizedFloat(8, 0x300000)) {
4195                 return false;
4196         }
4197         outputAsFloat++;
4198
4199         if (*outputAsFloat != -constructNormalizedFloat(-7, 0x600000) &&
4200                 *outputAsFloat != -constructNormalizedFloat(-7, 0x604000)) {
4201                 return false;
4202         }
4203         outputAsFloat++;
4204
4205         if (*outputAsFloat != constructNormalizedFloat(2, 0x01C000) &&
4206                 *outputAsFloat != constructNormalizedFloat(2, 0x020000)) {
4207                 return false;
4208         }
4209         outputAsFloat++;
4210
4211         if (*outputAsFloat != constructNormalizedFloat(1, 0xFFC000) &&
4212                 *outputAsFloat != constructNormalizedFloat(2, 0x000000)) {
4213                 return false;
4214         }
4215
4216         return true;
4217 }
4218
4219 // Checks that every output from a test-case is a float NaN.
4220 bool compareNan (const std::vector<BufferSp>&, const vector<AllocationSp>& outputAllocs, const std::vector<BufferSp>& expectedOutputs, TestLog&)
4221 {
4222         if (outputAllocs.size() != 1)
4223                 return false;
4224
4225         // Only size is needed because we cannot compare Nans.
4226         size_t byteSize = expectedOutputs[0]->getByteSize();
4227
4228         const float* const      output_as_float = static_cast<const float* const>(outputAllocs[0]->getHostPtr());
4229
4230         for (size_t idx = 0; idx < byteSize / sizeof(float); ++idx)
4231         {
4232                 if (!deFloatIsNaN(output_as_float[idx]))
4233                 {
4234                         return false;
4235                 }
4236         }
4237
4238         return true;
4239 }
4240
4241 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
4242 tcu::TestCaseGroup* createOpQuantizeToF16Group (tcu::TestContext& testCtx)
4243 {
4244         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opquantize", "Tests the OpQuantizeToF16 instruction"));
4245
4246         const std::string shader (
4247                 string(getComputeAsmShaderPreamble()) +
4248
4249                 "OpSource GLSL 430\n"
4250                 "OpName %main           \"main\"\n"
4251                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4252
4253                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4254
4255                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4256
4257                 "%id        = OpVariable %uvec3ptr Input\n"
4258                 "%zero      = OpConstant %i32 0\n"
4259
4260                 "%main      = OpFunction %void None %voidf\n"
4261                 "%label     = OpLabel\n"
4262                 "%idval     = OpLoad %uvec3 %id\n"
4263                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4264                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4265                 "%inval     = OpLoad %f32 %inloc\n"
4266                 "%quant     = OpQuantizeToF16 %f32 %inval\n"
4267                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4268                 "             OpStore %outloc %quant\n"
4269                 "             OpReturn\n"
4270                 "             OpFunctionEnd\n");
4271
4272         {
4273                 ComputeShaderSpec       spec;
4274                 const deUint32          numElements             = 100;
4275                 vector<float>           infinities;
4276                 vector<float>           results;
4277
4278                 infinities.reserve(numElements);
4279                 results.reserve(numElements);
4280
4281                 for (size_t idx = 0; idx < numElements; ++idx)
4282                 {
4283                         switch(idx % 4)
4284                         {
4285                                 case 0:
4286                                         infinities.push_back(std::numeric_limits<float>::infinity());
4287                                         results.push_back(std::numeric_limits<float>::infinity());
4288                                         break;
4289                                 case 1:
4290                                         infinities.push_back(-std::numeric_limits<float>::infinity());
4291                                         results.push_back(-std::numeric_limits<float>::infinity());
4292                                         break;
4293                                 case 2:
4294                                         infinities.push_back(std::ldexp(1.0f, 16));
4295                                         results.push_back(std::numeric_limits<float>::infinity());
4296                                         break;
4297                                 case 3:
4298                                         infinities.push_back(std::ldexp(-1.0f, 32));
4299                                         results.push_back(-std::numeric_limits<float>::infinity());
4300                                         break;
4301                         }
4302                 }
4303
4304                 spec.assembly = shader;
4305                 spec.inputs.push_back(BufferSp(new Float32Buffer(infinities)));
4306                 spec.outputs.push_back(BufferSp(new Float32Buffer(results)));
4307                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4308
4309                 group->addChild(new SpvAsmComputeShaderCase(
4310                         testCtx, "infinities", "Check that infinities propagated and created", spec));
4311         }
4312
4313         {
4314                 ComputeShaderSpec       spec;
4315                 vector<float>           nans;
4316                 const deUint32          numElements             = 100;
4317
4318                 nans.reserve(numElements);
4319
4320                 for (size_t idx = 0; idx < numElements; ++idx)
4321                 {
4322                         if (idx % 2 == 0)
4323                         {
4324                                 nans.push_back(std::numeric_limits<float>::quiet_NaN());
4325                         }
4326                         else
4327                         {
4328                                 nans.push_back(-std::numeric_limits<float>::quiet_NaN());
4329                         }
4330                 }
4331
4332                 spec.assembly = shader;
4333                 spec.inputs.push_back(BufferSp(new Float32Buffer(nans)));
4334                 spec.outputs.push_back(BufferSp(new Float32Buffer(nans)));
4335                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4336                 spec.verifyIO = &compareNan;
4337
4338                 group->addChild(new SpvAsmComputeShaderCase(
4339                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
4340         }
4341
4342         {
4343                 ComputeShaderSpec       spec;
4344                 vector<float>           small;
4345                 vector<float>           zeros;
4346                 const deUint32          numElements             = 100;
4347
4348                 small.reserve(numElements);
4349                 zeros.reserve(numElements);
4350
4351                 for (size_t idx = 0; idx < numElements; ++idx)
4352                 {
4353                         switch(idx % 6)
4354                         {
4355                                 case 0:
4356                                         small.push_back(0.f);
4357                                         zeros.push_back(0.f);
4358                                         break;
4359                                 case 1:
4360                                         small.push_back(-0.f);
4361                                         zeros.push_back(-0.f);
4362                                         break;
4363                                 case 2:
4364                                         small.push_back(std::ldexp(1.0f, -16));
4365                                         zeros.push_back(0.f);
4366                                         break;
4367                                 case 3:
4368                                         small.push_back(std::ldexp(-1.0f, -32));
4369                                         zeros.push_back(-0.f);
4370                                         break;
4371                                 case 4:
4372                                         small.push_back(std::ldexp(1.0f, -127));
4373                                         zeros.push_back(0.f);
4374                                         break;
4375                                 case 5:
4376                                         small.push_back(-std::ldexp(1.0f, -128));
4377                                         zeros.push_back(-0.f);
4378                                         break;
4379                         }
4380                 }
4381
4382                 spec.assembly = shader;
4383                 spec.inputs.push_back(BufferSp(new Float32Buffer(small)));
4384                 spec.outputs.push_back(BufferSp(new Float32Buffer(zeros)));
4385                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4386
4387                 group->addChild(new SpvAsmComputeShaderCase(
4388                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
4389         }
4390
4391         {
4392                 ComputeShaderSpec       spec;
4393                 vector<float>           exact;
4394                 const deUint32          numElements             = 200;
4395
4396                 exact.reserve(numElements);
4397
4398                 for (size_t idx = 0; idx < numElements; ++idx)
4399                         exact.push_back(static_cast<float>(static_cast<int>(idx) - 100));
4400
4401                 spec.assembly = shader;
4402                 spec.inputs.push_back(BufferSp(new Float32Buffer(exact)));
4403                 spec.outputs.push_back(BufferSp(new Float32Buffer(exact)));
4404                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4405
4406                 group->addChild(new SpvAsmComputeShaderCase(
4407                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
4408         }
4409
4410         {
4411                 ComputeShaderSpec       spec;
4412                 vector<float>           inputs;
4413                 const deUint32          numElements             = 4;
4414
4415                 inputs.push_back(constructNormalizedFloat(8,    0x300300));
4416                 inputs.push_back(-constructNormalizedFloat(-7,  0x600800));
4417                 inputs.push_back(constructNormalizedFloat(2,    0x01E000));
4418                 inputs.push_back(constructNormalizedFloat(1,    0xFFE000));
4419
4420                 spec.assembly = shader;
4421                 spec.verifyIO = &compareOpQuantizeF16ComputeExactCase;
4422                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4423                 spec.outputs.push_back(BufferSp(new Float32Buffer(inputs)));
4424                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4425
4426                 group->addChild(new SpvAsmComputeShaderCase(
4427                         testCtx, "rounded", "Check that are rounded when needed", spec));
4428         }
4429
4430         return group.release();
4431 }
4432
4433 tcu::TestCaseGroup* createSpecConstantOpQuantizeToF16Group (tcu::TestContext& testCtx)
4434 {
4435         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opspecconstantop_opquantize", "Tests the OpQuantizeToF16 opcode for the OpSpecConstantOp instruction"));
4436
4437         const std::string shader (
4438                 string(getComputeAsmShaderPreamble()) +
4439
4440                 "OpName %main           \"main\"\n"
4441                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4442
4443                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4444
4445                 "OpDecorate %sc_0  SpecId 0\n"
4446                 "OpDecorate %sc_1  SpecId 1\n"
4447                 "OpDecorate %sc_2  SpecId 2\n"
4448                 "OpDecorate %sc_3  SpecId 3\n"
4449                 "OpDecorate %sc_4  SpecId 4\n"
4450                 "OpDecorate %sc_5  SpecId 5\n"
4451
4452                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4453
4454                 "%id        = OpVariable %uvec3ptr Input\n"
4455                 "%zero      = OpConstant %i32 0\n"
4456                 "%c_u32_6   = OpConstant %u32 6\n"
4457
4458                 "%sc_0      = OpSpecConstant %f32 0.\n"
4459                 "%sc_1      = OpSpecConstant %f32 0.\n"
4460                 "%sc_2      = OpSpecConstant %f32 0.\n"
4461                 "%sc_3      = OpSpecConstant %f32 0.\n"
4462                 "%sc_4      = OpSpecConstant %f32 0.\n"
4463                 "%sc_5      = OpSpecConstant %f32 0.\n"
4464
4465                 "%sc_0_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_0\n"
4466                 "%sc_1_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_1\n"
4467                 "%sc_2_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_2\n"
4468                 "%sc_3_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_3\n"
4469                 "%sc_4_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_4\n"
4470                 "%sc_5_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_5\n"
4471
4472                 "%main      = OpFunction %void None %voidf\n"
4473                 "%label     = OpLabel\n"
4474                 "%idval     = OpLoad %uvec3 %id\n"
4475                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4476                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4477                 "%selector  = OpUMod %u32 %x %c_u32_6\n"
4478                 "            OpSelectionMerge %exit None\n"
4479                 "            OpSwitch %selector %exit 0 %case0 1 %case1 2 %case2 3 %case3 4 %case4 5 %case5\n"
4480
4481                 "%case0     = OpLabel\n"
4482                 "             OpStore %outloc %sc_0_quant\n"
4483                 "             OpBranch %exit\n"
4484
4485                 "%case1     = OpLabel\n"
4486                 "             OpStore %outloc %sc_1_quant\n"
4487                 "             OpBranch %exit\n"
4488
4489                 "%case2     = OpLabel\n"
4490                 "             OpStore %outloc %sc_2_quant\n"
4491                 "             OpBranch %exit\n"
4492
4493                 "%case3     = OpLabel\n"
4494                 "             OpStore %outloc %sc_3_quant\n"
4495                 "             OpBranch %exit\n"
4496
4497                 "%case4     = OpLabel\n"
4498                 "             OpStore %outloc %sc_4_quant\n"
4499                 "             OpBranch %exit\n"
4500
4501                 "%case5     = OpLabel\n"
4502                 "             OpStore %outloc %sc_5_quant\n"
4503                 "             OpBranch %exit\n"
4504
4505                 "%exit      = OpLabel\n"
4506                 "             OpReturn\n"
4507
4508                 "             OpFunctionEnd\n");
4509
4510         {
4511                 ComputeShaderSpec       spec;
4512                 const deUint8           numCases        = 4;
4513                 vector<float>           inputs          (numCases, 0.f);
4514                 vector<float>           outputs;
4515
4516                 spec.assembly           = shader;
4517                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4518
4519                 spec.specConstants.push_back(bitwiseCast<deUint32>(std::numeric_limits<float>::infinity()));
4520                 spec.specConstants.push_back(bitwiseCast<deUint32>(-std::numeric_limits<float>::infinity()));
4521                 spec.specConstants.push_back(bitwiseCast<deUint32>(std::ldexp(1.0f, 16)));
4522                 spec.specConstants.push_back(bitwiseCast<deUint32>(std::ldexp(-1.0f, 32)));
4523
4524                 outputs.push_back(std::numeric_limits<float>::infinity());
4525                 outputs.push_back(-std::numeric_limits<float>::infinity());
4526                 outputs.push_back(std::numeric_limits<float>::infinity());
4527                 outputs.push_back(-std::numeric_limits<float>::infinity());
4528
4529                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4530                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4531
4532                 group->addChild(new SpvAsmComputeShaderCase(
4533                         testCtx, "infinities", "Check that infinities propagated and created", spec));
4534         }
4535
4536         {
4537                 ComputeShaderSpec       spec;
4538                 const deUint8           numCases        = 2;
4539                 vector<float>           inputs          (numCases, 0.f);
4540                 vector<float>           outputs;
4541
4542                 spec.assembly           = shader;
4543                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4544                 spec.verifyIO           = &compareNan;
4545
4546                 outputs.push_back(std::numeric_limits<float>::quiet_NaN());
4547                 outputs.push_back(-std::numeric_limits<float>::quiet_NaN());
4548
4549                 for (deUint8 idx = 0; idx < numCases; ++idx)
4550                         spec.specConstants.push_back(bitwiseCast<deUint32>(outputs[idx]));
4551
4552                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4553                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4554
4555                 group->addChild(new SpvAsmComputeShaderCase(
4556                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
4557         }
4558
4559         {
4560                 ComputeShaderSpec       spec;
4561                 const deUint8           numCases        = 6;
4562                 vector<float>           inputs          (numCases, 0.f);
4563                 vector<float>           outputs;
4564
4565                 spec.assembly           = shader;
4566                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4567
4568                 spec.specConstants.push_back(bitwiseCast<deUint32>(0.f));
4569                 spec.specConstants.push_back(bitwiseCast<deUint32>(-0.f));
4570                 spec.specConstants.push_back(bitwiseCast<deUint32>(std::ldexp(1.0f, -16)));
4571                 spec.specConstants.push_back(bitwiseCast<deUint32>(std::ldexp(-1.0f, -32)));
4572                 spec.specConstants.push_back(bitwiseCast<deUint32>(std::ldexp(1.0f, -127)));
4573                 spec.specConstants.push_back(bitwiseCast<deUint32>(-std::ldexp(1.0f, -128)));
4574
4575                 outputs.push_back(0.f);
4576                 outputs.push_back(-0.f);
4577                 outputs.push_back(0.f);
4578                 outputs.push_back(-0.f);
4579                 outputs.push_back(0.f);
4580                 outputs.push_back(-0.f);
4581
4582                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4583                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4584
4585                 group->addChild(new SpvAsmComputeShaderCase(
4586                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
4587         }
4588
4589         {
4590                 ComputeShaderSpec       spec;
4591                 const deUint8           numCases        = 6;
4592                 vector<float>           inputs          (numCases, 0.f);
4593                 vector<float>           outputs;
4594
4595                 spec.assembly           = shader;
4596                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4597
4598                 for (deUint8 idx = 0; idx < 6; ++idx)
4599                 {
4600                         const float f = static_cast<float>(idx * 10 - 30) / 4.f;
4601                         spec.specConstants.push_back(bitwiseCast<deUint32>(f));
4602                         outputs.push_back(f);
4603                 }
4604
4605                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4606                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4607
4608                 group->addChild(new SpvAsmComputeShaderCase(
4609                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
4610         }
4611
4612         {
4613                 ComputeShaderSpec       spec;
4614                 const deUint8           numCases        = 4;
4615                 vector<float>           inputs          (numCases, 0.f);
4616                 vector<float>           outputs;
4617
4618                 spec.assembly           = shader;
4619                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4620                 spec.verifyIO           = &compareOpQuantizeF16ComputeExactCase;
4621
4622                 outputs.push_back(constructNormalizedFloat(8, 0x300300));
4623                 outputs.push_back(-constructNormalizedFloat(-7, 0x600800));
4624                 outputs.push_back(constructNormalizedFloat(2, 0x01E000));
4625                 outputs.push_back(constructNormalizedFloat(1, 0xFFE000));
4626
4627                 for (deUint8 idx = 0; idx < numCases; ++idx)
4628                         spec.specConstants.push_back(bitwiseCast<deUint32>(outputs[idx]));
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, "rounded", "Check that are rounded when needed", spec));
4635         }
4636
4637         return group.release();
4638 }
4639
4640 // Checks that constant null/composite values can be used in computation.
4641 tcu::TestCaseGroup* createOpConstantUsageGroup (tcu::TestContext& testCtx)
4642 {
4643         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnullcomposite", "Spotcheck the OpConstantNull & OpConstantComposite instruction"));
4644         ComputeShaderSpec                               spec;
4645         de::Random                                              rnd                             (deStringHash(group->getName()));
4646         const int                                               numElements             = 100;
4647         vector<float>                                   positiveFloats  (numElements, 0);
4648         vector<float>                                   negativeFloats  (numElements, 0);
4649
4650         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4651
4652         for (size_t ndx = 0; ndx < numElements; ++ndx)
4653                 negativeFloats[ndx] = -positiveFloats[ndx];
4654
4655         spec.assembly =
4656                 "OpCapability Shader\n"
4657                 "%std450 = OpExtInstImport \"GLSL.std.450\"\n"
4658                 "OpMemoryModel Logical GLSL450\n"
4659                 "OpEntryPoint GLCompute %main \"main\" %id\n"
4660                 "OpExecutionMode %main LocalSize 1 1 1\n"
4661
4662                 "OpSource GLSL 430\n"
4663                 "OpName %main           \"main\"\n"
4664                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4665
4666                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4667
4668                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4669
4670                 "%fmat      = OpTypeMatrix %fvec3 3\n"
4671                 "%ten       = OpConstant %u32 10\n"
4672                 "%f32arr10  = OpTypeArray %f32 %ten\n"
4673                 "%fst       = OpTypeStruct %f32 %f32\n"
4674
4675                 + string(getComputeAsmInputOutputBuffer()) +
4676
4677                 "%id        = OpVariable %uvec3ptr Input\n"
4678                 "%zero      = OpConstant %i32 0\n"
4679
4680                 // Create a bunch of null values
4681                 "%unull     = OpConstantNull %u32\n"
4682                 "%fnull     = OpConstantNull %f32\n"
4683                 "%vnull     = OpConstantNull %fvec3\n"
4684                 "%mnull     = OpConstantNull %fmat\n"
4685                 "%anull     = OpConstantNull %f32arr10\n"
4686                 "%snull     = OpConstantComposite %fst %fnull %fnull\n"
4687
4688                 "%main      = OpFunction %void None %voidf\n"
4689                 "%label     = OpLabel\n"
4690                 "%idval     = OpLoad %uvec3 %id\n"
4691                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4692                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4693                 "%inval     = OpLoad %f32 %inloc\n"
4694                 "%neg       = OpFNegate %f32 %inval\n"
4695
4696                 // Get the abs() of (a certain element of) those null values
4697                 "%unull_cov = OpConvertUToF %f32 %unull\n"
4698                 "%unull_abs = OpExtInst %f32 %std450 FAbs %unull_cov\n"
4699                 "%fnull_abs = OpExtInst %f32 %std450 FAbs %fnull\n"
4700                 "%vnull_0   = OpCompositeExtract %f32 %vnull 0\n"
4701                 "%vnull_abs = OpExtInst %f32 %std450 FAbs %vnull_0\n"
4702                 "%mnull_12  = OpCompositeExtract %f32 %mnull 1 2\n"
4703                 "%mnull_abs = OpExtInst %f32 %std450 FAbs %mnull_12\n"
4704                 "%anull_3   = OpCompositeExtract %f32 %anull 3\n"
4705                 "%anull_abs = OpExtInst %f32 %std450 FAbs %anull_3\n"
4706                 "%snull_1   = OpCompositeExtract %f32 %snull 1\n"
4707                 "%snull_abs = OpExtInst %f32 %std450 FAbs %snull_1\n"
4708
4709                 // Add them all
4710                 "%add1      = OpFAdd %f32 %neg  %unull_abs\n"
4711                 "%add2      = OpFAdd %f32 %add1 %fnull_abs\n"
4712                 "%add3      = OpFAdd %f32 %add2 %vnull_abs\n"
4713                 "%add4      = OpFAdd %f32 %add3 %mnull_abs\n"
4714                 "%add5      = OpFAdd %f32 %add4 %anull_abs\n"
4715                 "%final     = OpFAdd %f32 %add5 %snull_abs\n"
4716
4717                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4718                 "             OpStore %outloc %final\n" // write to output
4719                 "             OpReturn\n"
4720                 "             OpFunctionEnd\n";
4721         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4722         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4723         spec.numWorkGroups = IVec3(numElements, 1, 1);
4724
4725         group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "Check that values constructed via OpConstantNull & OpConstantComposite can be used", spec));
4726
4727         return group.release();
4728 }
4729
4730 // Assembly code used for testing loop control is based on GLSL source code:
4731 // #version 430
4732 //
4733 // layout(std140, set = 0, binding = 0) readonly buffer Input {
4734 //   float elements[];
4735 // } input_data;
4736 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
4737 //   float elements[];
4738 // } output_data;
4739 //
4740 // void main() {
4741 //   uint x = gl_GlobalInvocationID.x;
4742 //   output_data.elements[x] = input_data.elements[x];
4743 //   for (uint i = 0; i < 4; ++i)
4744 //     output_data.elements[x] += 1.f;
4745 // }
4746 tcu::TestCaseGroup* createLoopControlGroup (tcu::TestContext& testCtx)
4747 {
4748         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "loop_control", "Tests loop control cases"));
4749         vector<CaseParameter>                   cases;
4750         de::Random                                              rnd                             (deStringHash(group->getName()));
4751         const int                                               numElements             = 100;
4752         vector<float>                                   inputFloats             (numElements, 0);
4753         vector<float>                                   outputFloats    (numElements, 0);
4754         const StringTemplate                    shaderTemplate  (
4755                 string(getComputeAsmShaderPreamble()) +
4756
4757                 "OpSource GLSL 430\n"
4758                 "OpName %main \"main\"\n"
4759                 "OpName %id \"gl_GlobalInvocationID\"\n"
4760
4761                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4762
4763                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4764
4765                 "%u32ptr      = OpTypePointer Function %u32\n"
4766
4767                 "%id          = OpVariable %uvec3ptr Input\n"
4768                 "%zero        = OpConstant %i32 0\n"
4769                 "%uzero       = OpConstant %u32 0\n"
4770                 "%one         = OpConstant %i32 1\n"
4771                 "%constf1     = OpConstant %f32 1.0\n"
4772                 "%four        = OpConstant %u32 4\n"
4773
4774                 "%main        = OpFunction %void None %voidf\n"
4775                 "%entry       = OpLabel\n"
4776                 "%i           = OpVariable %u32ptr Function\n"
4777                 "               OpStore %i %uzero\n"
4778
4779                 "%idval       = OpLoad %uvec3 %id\n"
4780                 "%x           = OpCompositeExtract %u32 %idval 0\n"
4781                 "%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
4782                 "%inval       = OpLoad %f32 %inloc\n"
4783                 "%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
4784                 "               OpStore %outloc %inval\n"
4785                 "               OpBranch %loop_entry\n"
4786
4787                 "%loop_entry  = OpLabel\n"
4788                 "%i_val       = OpLoad %u32 %i\n"
4789                 "%cmp_lt      = OpULessThan %bool %i_val %four\n"
4790                 "               OpLoopMerge %loop_merge %loop_body ${CONTROL}\n"
4791                 "               OpBranchConditional %cmp_lt %loop_body %loop_merge\n"
4792                 "%loop_body   = OpLabel\n"
4793                 "%outval      = OpLoad %f32 %outloc\n"
4794                 "%addf1       = OpFAdd %f32 %outval %constf1\n"
4795                 "               OpStore %outloc %addf1\n"
4796                 "%new_i       = OpIAdd %u32 %i_val %one\n"
4797                 "               OpStore %i %new_i\n"
4798                 "               OpBranch %loop_entry\n"
4799                 "%loop_merge  = OpLabel\n"
4800                 "               OpReturn\n"
4801                 "               OpFunctionEnd\n");
4802
4803         cases.push_back(CaseParameter("none",                           "None"));
4804         cases.push_back(CaseParameter("unroll",                         "Unroll"));
4805         cases.push_back(CaseParameter("dont_unroll",            "DontUnroll"));
4806         cases.push_back(CaseParameter("unroll_dont_unroll",     "Unroll|DontUnroll"));
4807
4808         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
4809
4810         for (size_t ndx = 0; ndx < numElements; ++ndx)
4811                 outputFloats[ndx] = inputFloats[ndx] + 4.f;
4812
4813         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4814         {
4815                 map<string, string>             specializations;
4816                 ComputeShaderSpec               spec;
4817
4818                 specializations["CONTROL"] = cases[caseNdx].param;
4819                 spec.assembly = shaderTemplate.specialize(specializations);
4820                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4821                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
4822                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4823
4824                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4825         }
4826
4827         return group.release();
4828 }
4829
4830 // Assembly code used for testing selection control is based on GLSL source code:
4831 // #version 430
4832 //
4833 // layout(std140, set = 0, binding = 0) readonly buffer Input {
4834 //   float elements[];
4835 // } input_data;
4836 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
4837 //   float elements[];
4838 // } output_data;
4839 //
4840 // void main() {
4841 //   uint x = gl_GlobalInvocationID.x;
4842 //   float val = input_data.elements[x];
4843 //   if (val > 10.f)
4844 //     output_data.elements[x] = val + 1.f;
4845 //   else
4846 //     output_data.elements[x] = val - 1.f;
4847 // }
4848 tcu::TestCaseGroup* createSelectionControlGroup (tcu::TestContext& testCtx)
4849 {
4850         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "selection_control", "Tests selection control cases"));
4851         vector<CaseParameter>                   cases;
4852         de::Random                                              rnd                             (deStringHash(group->getName()));
4853         const int                                               numElements             = 100;
4854         vector<float>                                   inputFloats             (numElements, 0);
4855         vector<float>                                   outputFloats    (numElements, 0);
4856         const StringTemplate                    shaderTemplate  (
4857                 string(getComputeAsmShaderPreamble()) +
4858
4859                 "OpSource GLSL 430\n"
4860                 "OpName %main \"main\"\n"
4861                 "OpName %id \"gl_GlobalInvocationID\"\n"
4862
4863                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4864
4865                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4866
4867                 "%id       = OpVariable %uvec3ptr Input\n"
4868                 "%zero     = OpConstant %i32 0\n"
4869                 "%constf1  = OpConstant %f32 1.0\n"
4870                 "%constf10 = OpConstant %f32 10.0\n"
4871
4872                 "%main     = OpFunction %void None %voidf\n"
4873                 "%entry    = OpLabel\n"
4874                 "%idval    = OpLoad %uvec3 %id\n"
4875                 "%x        = OpCompositeExtract %u32 %idval 0\n"
4876                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
4877                 "%inval    = OpLoad %f32 %inloc\n"
4878                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
4879                 "%cmp_gt   = OpFOrdGreaterThan %bool %inval %constf10\n"
4880
4881                 "            OpSelectionMerge %if_end ${CONTROL}\n"
4882                 "            OpBranchConditional %cmp_gt %if_true %if_false\n"
4883                 "%if_true  = OpLabel\n"
4884                 "%addf1    = OpFAdd %f32 %inval %constf1\n"
4885                 "            OpStore %outloc %addf1\n"
4886                 "            OpBranch %if_end\n"
4887                 "%if_false = OpLabel\n"
4888                 "%subf1    = OpFSub %f32 %inval %constf1\n"
4889                 "            OpStore %outloc %subf1\n"
4890                 "            OpBranch %if_end\n"
4891                 "%if_end   = OpLabel\n"
4892                 "            OpReturn\n"
4893                 "            OpFunctionEnd\n");
4894
4895         cases.push_back(CaseParameter("none",                                   "None"));
4896         cases.push_back(CaseParameter("flatten",                                "Flatten"));
4897         cases.push_back(CaseParameter("dont_flatten",                   "DontFlatten"));
4898         cases.push_back(CaseParameter("flatten_dont_flatten",   "DontFlatten|Flatten"));
4899
4900         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
4901
4902         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
4903         floorAll(inputFloats);
4904
4905         for (size_t ndx = 0; ndx < numElements; ++ndx)
4906                 outputFloats[ndx] = inputFloats[ndx] + (inputFloats[ndx] > 10.f ? 1.f : -1.f);
4907
4908         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4909         {
4910                 map<string, string>             specializations;
4911                 ComputeShaderSpec               spec;
4912
4913                 specializations["CONTROL"] = cases[caseNdx].param;
4914                 spec.assembly = shaderTemplate.specialize(specializations);
4915                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4916                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
4917                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4918
4919                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4920         }
4921
4922         return group.release();
4923 }
4924
4925 // Assembly code used for testing function control is based on GLSL source code:
4926 //
4927 // #version 430
4928 //
4929 // layout(std140, set = 0, binding = 0) readonly buffer Input {
4930 //   float elements[];
4931 // } input_data;
4932 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
4933 //   float elements[];
4934 // } output_data;
4935 //
4936 // float const10() { return 10.f; }
4937 //
4938 // void main() {
4939 //   uint x = gl_GlobalInvocationID.x;
4940 //   output_data.elements[x] = input_data.elements[x] + const10();
4941 // }
4942 tcu::TestCaseGroup* createFunctionControlGroup (tcu::TestContext& testCtx)
4943 {
4944         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "function_control", "Tests function control cases"));
4945         vector<CaseParameter>                   cases;
4946         de::Random                                              rnd                             (deStringHash(group->getName()));
4947         const int                                               numElements             = 100;
4948         vector<float>                                   inputFloats             (numElements, 0);
4949         vector<float>                                   outputFloats    (numElements, 0);
4950         const StringTemplate                    shaderTemplate  (
4951                 string(getComputeAsmShaderPreamble()) +
4952
4953                 "OpSource GLSL 430\n"
4954                 "OpName %main \"main\"\n"
4955                 "OpName %func_const10 \"const10(\"\n"
4956                 "OpName %id \"gl_GlobalInvocationID\"\n"
4957
4958                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4959
4960                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4961
4962                 "%f32f = OpTypeFunction %f32\n"
4963                 "%id = OpVariable %uvec3ptr Input\n"
4964                 "%zero = OpConstant %i32 0\n"
4965                 "%constf10 = OpConstant %f32 10.0\n"
4966
4967                 "%main         = OpFunction %void None %voidf\n"
4968                 "%entry        = OpLabel\n"
4969                 "%idval        = OpLoad %uvec3 %id\n"
4970                 "%x            = OpCompositeExtract %u32 %idval 0\n"
4971                 "%inloc        = OpAccessChain %f32ptr %indata %zero %x\n"
4972                 "%inval        = OpLoad %f32 %inloc\n"
4973                 "%ret_10       = OpFunctionCall %f32 %func_const10\n"
4974                 "%fadd         = OpFAdd %f32 %inval %ret_10\n"
4975                 "%outloc       = OpAccessChain %f32ptr %outdata %zero %x\n"
4976                 "                OpStore %outloc %fadd\n"
4977                 "                OpReturn\n"
4978                 "                OpFunctionEnd\n"
4979
4980                 "%func_const10 = OpFunction %f32 ${CONTROL} %f32f\n"
4981                 "%label        = OpLabel\n"
4982                 "                OpReturnValue %constf10\n"
4983                 "                OpFunctionEnd\n");
4984
4985         cases.push_back(CaseParameter("none",                                           "None"));
4986         cases.push_back(CaseParameter("inline",                                         "Inline"));
4987         cases.push_back(CaseParameter("dont_inline",                            "DontInline"));
4988         cases.push_back(CaseParameter("pure",                                           "Pure"));
4989         cases.push_back(CaseParameter("const",                                          "Const"));
4990         cases.push_back(CaseParameter("inline_pure",                            "Inline|Pure"));
4991         cases.push_back(CaseParameter("const_dont_inline",                      "Const|DontInline"));
4992         cases.push_back(CaseParameter("inline_dont_inline",                     "Inline|DontInline"));
4993         cases.push_back(CaseParameter("pure_inline_dont_inline",        "Pure|Inline|DontInline"));
4994
4995         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
4996
4997         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
4998         floorAll(inputFloats);
4999
5000         for (size_t ndx = 0; ndx < numElements; ++ndx)
5001                 outputFloats[ndx] = inputFloats[ndx] + 10.f;
5002
5003         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5004         {
5005                 map<string, string>             specializations;
5006                 ComputeShaderSpec               spec;
5007
5008                 specializations["CONTROL"] = cases[caseNdx].param;
5009                 spec.assembly = shaderTemplate.specialize(specializations);
5010                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5011                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5012                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5013
5014                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5015         }
5016
5017         return group.release();
5018 }
5019
5020 tcu::TestCaseGroup* createMemoryAccessGroup (tcu::TestContext& testCtx)
5021 {
5022         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "memory_access", "Tests memory access cases"));
5023         vector<CaseParameter>                   cases;
5024         de::Random                                              rnd                             (deStringHash(group->getName()));
5025         const int                                               numElements             = 100;
5026         vector<float>                                   inputFloats             (numElements, 0);
5027         vector<float>                                   outputFloats    (numElements, 0);
5028         const StringTemplate                    shaderTemplate  (
5029                 string(getComputeAsmShaderPreamble()) +
5030
5031                 "OpSource GLSL 430\n"
5032                 "OpName %main           \"main\"\n"
5033                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5034
5035                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5036
5037                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5038
5039                 "%f32ptr_f  = OpTypePointer Function %f32\n"
5040
5041                 "%id        = OpVariable %uvec3ptr Input\n"
5042                 "%zero      = OpConstant %i32 0\n"
5043                 "%four      = OpConstant %i32 4\n"
5044
5045                 "%main      = OpFunction %void None %voidf\n"
5046                 "%label     = OpLabel\n"
5047                 "%copy      = OpVariable %f32ptr_f Function\n"
5048                 "%idval     = OpLoad %uvec3 %id ${ACCESS}\n"
5049                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5050                 "%inloc     = OpAccessChain %f32ptr %indata  %zero %x\n"
5051                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5052                 "             OpCopyMemory %copy %inloc ${ACCESS}\n"
5053                 "%val1      = OpLoad %f32 %copy\n"
5054                 "%val2      = OpLoad %f32 %inloc\n"
5055                 "%add       = OpFAdd %f32 %val1 %val2\n"
5056                 "             OpStore %outloc %add ${ACCESS}\n"
5057                 "             OpReturn\n"
5058                 "             OpFunctionEnd\n");
5059
5060         cases.push_back(CaseParameter("null",                                   ""));
5061         cases.push_back(CaseParameter("none",                                   "None"));
5062         cases.push_back(CaseParameter("volatile",                               "Volatile"));
5063         cases.push_back(CaseParameter("aligned",                                "Aligned 4"));
5064         cases.push_back(CaseParameter("nontemporal",                    "Nontemporal"));
5065         cases.push_back(CaseParameter("aligned_nontemporal",    "Aligned|Nontemporal 4"));
5066         cases.push_back(CaseParameter("aligned_volatile",               "Volatile|Aligned 4"));
5067
5068         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5069
5070         for (size_t ndx = 0; ndx < numElements; ++ndx)
5071                 outputFloats[ndx] = inputFloats[ndx] + inputFloats[ndx];
5072
5073         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5074         {
5075                 map<string, string>             specializations;
5076                 ComputeShaderSpec               spec;
5077
5078                 specializations["ACCESS"] = cases[caseNdx].param;
5079                 spec.assembly = shaderTemplate.specialize(specializations);
5080                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5081                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5082                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5083
5084                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5085         }
5086
5087         return group.release();
5088 }
5089
5090 // Checks that we can get undefined values for various types, without exercising a computation with it.
5091 tcu::TestCaseGroup* createOpUndefGroup (tcu::TestContext& testCtx)
5092 {
5093         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opundef", "Tests the OpUndef instruction"));
5094         vector<CaseParameter>                   cases;
5095         de::Random                                              rnd                             (deStringHash(group->getName()));
5096         const int                                               numElements             = 100;
5097         vector<float>                                   positiveFloats  (numElements, 0);
5098         vector<float>                                   negativeFloats  (numElements, 0);
5099         const StringTemplate                    shaderTemplate  (
5100                 string(getComputeAsmShaderPreamble()) +
5101
5102                 "OpSource GLSL 430\n"
5103                 "OpName %main           \"main\"\n"
5104                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5105
5106                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5107
5108                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
5109                 "%uvec2     = OpTypeVector %u32 2\n"
5110                 "%fvec4     = OpTypeVector %f32 4\n"
5111                 "%fmat33    = OpTypeMatrix %fvec3 3\n"
5112                 "%image     = OpTypeImage %f32 2D 0 0 0 1 Unknown\n"
5113                 "%sampler   = OpTypeSampler\n"
5114                 "%simage    = OpTypeSampledImage %image\n"
5115                 "%const100  = OpConstant %u32 100\n"
5116                 "%uarr100   = OpTypeArray %i32 %const100\n"
5117                 "%struct    = OpTypeStruct %f32 %i32 %u32\n"
5118                 "%pointer   = OpTypePointer Function %i32\n"
5119                 + string(getComputeAsmInputOutputBuffer()) +
5120
5121                 "%id        = OpVariable %uvec3ptr Input\n"
5122                 "%zero      = OpConstant %i32 0\n"
5123
5124                 "%main      = OpFunction %void None %voidf\n"
5125                 "%label     = OpLabel\n"
5126
5127                 "%undef     = OpUndef ${TYPE}\n"
5128
5129                 "%idval     = OpLoad %uvec3 %id\n"
5130                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5131
5132                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5133                 "%inval     = OpLoad %f32 %inloc\n"
5134                 "%neg       = OpFNegate %f32 %inval\n"
5135                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5136                 "             OpStore %outloc %neg\n"
5137                 "             OpReturn\n"
5138                 "             OpFunctionEnd\n");
5139
5140         cases.push_back(CaseParameter("bool",                   "%bool"));
5141         cases.push_back(CaseParameter("sint32",                 "%i32"));
5142         cases.push_back(CaseParameter("uint32",                 "%u32"));
5143         cases.push_back(CaseParameter("float32",                "%f32"));
5144         cases.push_back(CaseParameter("vec4float32",    "%fvec4"));
5145         cases.push_back(CaseParameter("vec2uint32",             "%uvec2"));
5146         cases.push_back(CaseParameter("matrix",                 "%fmat33"));
5147         cases.push_back(CaseParameter("image",                  "%image"));
5148         cases.push_back(CaseParameter("sampler",                "%sampler"));
5149         cases.push_back(CaseParameter("sampledimage",   "%simage"));
5150         cases.push_back(CaseParameter("array",                  "%uarr100"));
5151         cases.push_back(CaseParameter("runtimearray",   "%f32arr"));
5152         cases.push_back(CaseParameter("struct",                 "%struct"));
5153         cases.push_back(CaseParameter("pointer",                "%pointer"));
5154
5155         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
5156
5157         for (size_t ndx = 0; ndx < numElements; ++ndx)
5158                 negativeFloats[ndx] = -positiveFloats[ndx];
5159
5160         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5161         {
5162                 map<string, string>             specializations;
5163                 ComputeShaderSpec               spec;
5164
5165                 specializations["TYPE"] = cases[caseNdx].param;
5166                 spec.assembly = shaderTemplate.specialize(specializations);
5167                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
5168                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
5169                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5170
5171                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5172         }
5173
5174                 return group.release();
5175 }
5176
5177 } // anonymous
5178
5179 tcu::TestCaseGroup* createOpSourceTests (tcu::TestContext& testCtx)
5180 {
5181         struct NameCodePair { string name, code; };
5182         RGBA                                                    defaultColors[4];
5183         de::MovePtr<tcu::TestCaseGroup> opSourceTests                   (new tcu::TestCaseGroup(testCtx, "opsource", "OpSource instruction"));
5184         const std::string                               opsourceGLSLWithFile    = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile ";
5185         map<string, string>                             fragments                               = passthruFragments();
5186         const NameCodePair                              tests[]                                 =
5187         {
5188                 {"unknown", "OpSource Unknown 321"},
5189                 {"essl", "OpSource ESSL 310"},
5190                 {"glsl", "OpSource GLSL 450"},
5191                 {"opencl_cpp", "OpSource OpenCL_CPP 120"},
5192                 {"opencl_c", "OpSource OpenCL_C 120"},
5193                 {"multiple", "OpSource GLSL 450\nOpSource GLSL 450"},
5194                 {"file", opsourceGLSLWithFile},
5195                 {"source", opsourceGLSLWithFile + "\"void main(){}\""},
5196                 // Longest possible source string: SPIR-V limits instructions to 65535
5197                 // words, of which the first 4 are opsourceGLSLWithFile; the rest will
5198                 // contain 65530 UTF8 characters (one word each) plus one last word
5199                 // containing 3 ASCII characters and \0.
5200                 {"longsource", opsourceGLSLWithFile + '"' + makeLongUTF8String(65530) + "ccc" + '"'}
5201         };
5202
5203         getDefaultColors(defaultColors);
5204         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
5205         {
5206                 fragments["debug"] = tests[testNdx].code;
5207                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
5208         }
5209
5210         return opSourceTests.release();
5211 }
5212
5213 tcu::TestCaseGroup* createOpSourceContinuedTests (tcu::TestContext& testCtx)
5214 {
5215         struct NameCodePair { string name, code; };
5216         RGBA                                                            defaultColors[4];
5217         de::MovePtr<tcu::TestCaseGroup>         opSourceTests           (new tcu::TestCaseGroup(testCtx, "opsourcecontinued", "OpSourceContinued instruction"));
5218         map<string, string>                                     fragments                       = passthruFragments();
5219         const std::string                                       opsource                        = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile \"void main(){}\"\n";
5220         const NameCodePair                                      tests[]                         =
5221         {
5222                 {"empty", opsource + "OpSourceContinued \"\""},
5223                 {"short", opsource + "OpSourceContinued \"abcde\""},
5224                 {"multiple", opsource + "OpSourceContinued \"abcde\"\nOpSourceContinued \"fghij\""},
5225                 // Longest possible source string: SPIR-V limits instructions to 65535
5226                 // words, of which the first one is OpSourceContinued/length; the rest
5227                 // will contain 65533 UTF8 characters (one word each) plus one last word
5228                 // containing 3 ASCII characters and \0.
5229                 {"long", opsource + "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\""}
5230         };
5231
5232         getDefaultColors(defaultColors);
5233         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
5234         {
5235                 fragments["debug"] = tests[testNdx].code;
5236                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
5237         }
5238
5239         return opSourceTests.release();
5240 }
5241
5242 tcu::TestCaseGroup* createOpNoLineTests(tcu::TestContext& testCtx)
5243 {
5244         RGBA                                                             defaultColors[4];
5245         de::MovePtr<tcu::TestCaseGroup>          opLineTests             (new tcu::TestCaseGroup(testCtx, "opnoline", "OpNoLine instruction"));
5246         map<string, string>                                      fragments;
5247         getDefaultColors(defaultColors);
5248         fragments["debug"]                      =
5249                 "%name = OpString \"name\"\n";
5250
5251         fragments["pre_main"]   =
5252                 "OpNoLine\n"
5253                 "OpNoLine\n"
5254                 "OpLine %name 1 1\n"
5255                 "OpNoLine\n"
5256                 "OpLine %name 1 1\n"
5257                 "OpLine %name 1 1\n"
5258                 "%second_function = OpFunction %v4f32 None %v4f32_function\n"
5259                 "OpNoLine\n"
5260                 "OpLine %name 1 1\n"
5261                 "OpNoLine\n"
5262                 "OpLine %name 1 1\n"
5263                 "OpLine %name 1 1\n"
5264                 "%second_param1 = OpFunctionParameter %v4f32\n"
5265                 "OpNoLine\n"
5266                 "OpNoLine\n"
5267                 "%label_secondfunction = OpLabel\n"
5268                 "OpNoLine\n"
5269                 "OpReturnValue %second_param1\n"
5270                 "OpFunctionEnd\n"
5271                 "OpNoLine\n"
5272                 "OpNoLine\n";
5273
5274         fragments["testfun"]            =
5275                 // A %test_code function that returns its argument unchanged.
5276                 "OpNoLine\n"
5277                 "OpNoLine\n"
5278                 "OpLine %name 1 1\n"
5279                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
5280                 "OpNoLine\n"
5281                 "%param1 = OpFunctionParameter %v4f32\n"
5282                 "OpNoLine\n"
5283                 "OpNoLine\n"
5284                 "%label_testfun = OpLabel\n"
5285                 "OpNoLine\n"
5286                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
5287                 "OpReturnValue %val1\n"
5288                 "OpFunctionEnd\n"
5289                 "OpLine %name 1 1\n"
5290                 "OpNoLine\n";
5291
5292         createTestsForAllStages("opnoline", defaultColors, defaultColors, fragments, opLineTests.get());
5293
5294         return opLineTests.release();
5295 }
5296
5297
5298 tcu::TestCaseGroup* createOpLineTests(tcu::TestContext& testCtx)
5299 {
5300         RGBA                                                                                                    defaultColors[4];
5301         de::MovePtr<tcu::TestCaseGroup>                                                 opLineTests                     (new tcu::TestCaseGroup(testCtx, "opline", "OpLine instruction"));
5302         map<string, string>                                                                             fragments;
5303         std::vector<std::pair<std::string, std::string> >               problemStrings;
5304
5305         problemStrings.push_back(std::make_pair<std::string, std::string>("empty_name", ""));
5306         problemStrings.push_back(std::make_pair<std::string, std::string>("short_name", "short_name"));
5307         problemStrings.push_back(std::make_pair<std::string, std::string>("long_name", makeLongUTF8String(65530) + "ccc"));
5308         getDefaultColors(defaultColors);
5309
5310         fragments["debug"]                      =
5311                 "%other_name = OpString \"other_name\"\n";
5312
5313         fragments["pre_main"]   =
5314                 "OpLine %file_name 32 0\n"
5315                 "OpLine %file_name 32 32\n"
5316                 "OpLine %file_name 32 40\n"
5317                 "OpLine %other_name 32 40\n"
5318                 "OpLine %other_name 0 100\n"
5319                 "OpLine %other_name 0 4294967295\n"
5320                 "OpLine %other_name 4294967295 0\n"
5321                 "OpLine %other_name 32 40\n"
5322                 "OpLine %file_name 0 0\n"
5323                 "%second_function = OpFunction %v4f32 None %v4f32_function\n"
5324                 "OpLine %file_name 1 0\n"
5325                 "%second_param1 = OpFunctionParameter %v4f32\n"
5326                 "OpLine %file_name 1 3\n"
5327                 "OpLine %file_name 1 2\n"
5328                 "%label_secondfunction = OpLabel\n"
5329                 "OpLine %file_name 0 2\n"
5330                 "OpReturnValue %second_param1\n"
5331                 "OpFunctionEnd\n"
5332                 "OpLine %file_name 0 2\n"
5333                 "OpLine %file_name 0 2\n";
5334
5335         fragments["testfun"]            =
5336                 // A %test_code function that returns its argument unchanged.
5337                 "OpLine %file_name 1 0\n"
5338                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
5339                 "OpLine %file_name 16 330\n"
5340                 "%param1 = OpFunctionParameter %v4f32\n"
5341                 "OpLine %file_name 14 442\n"
5342                 "%label_testfun = OpLabel\n"
5343                 "OpLine %file_name 11 1024\n"
5344                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
5345                 "OpLine %file_name 2 97\n"
5346                 "OpReturnValue %val1\n"
5347                 "OpFunctionEnd\n"
5348                 "OpLine %file_name 5 32\n";
5349
5350         for (size_t i = 0; i < problemStrings.size(); ++i)
5351         {
5352                 map<string, string> testFragments = fragments;
5353                 testFragments["debug"] += "%file_name = OpString \"" + problemStrings[i].second + "\"\n";
5354                 createTestsForAllStages(string("opline") + "_" + problemStrings[i].first, defaultColors, defaultColors, testFragments, opLineTests.get());
5355         }
5356
5357         return opLineTests.release();
5358 }
5359
5360 tcu::TestCaseGroup* createOpConstantNullTests(tcu::TestContext& testCtx)
5361 {
5362         de::MovePtr<tcu::TestCaseGroup> opConstantNullTests             (new tcu::TestCaseGroup(testCtx, "opconstantnull", "OpConstantNull instruction"));
5363         RGBA                                                    colors[4];
5364
5365
5366         const char                                              functionStart[] =
5367                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
5368                 "%param1 = OpFunctionParameter %v4f32\n"
5369                 "%lbl    = OpLabel\n";
5370
5371         const char                                              functionEnd[]   =
5372                 "OpReturnValue %transformed_param\n"
5373                 "OpFunctionEnd\n";
5374
5375         struct NameConstantsCode
5376         {
5377                 string name;
5378                 string constants;
5379                 string code;
5380         };
5381
5382         NameConstantsCode tests[] =
5383         {
5384                 {
5385                         "vec4",
5386                         "%cnull = OpConstantNull %v4f32\n",
5387                         "%transformed_param = OpFAdd %v4f32 %param1 %cnull\n"
5388                 },
5389                 {
5390                         "float",
5391                         "%cnull = OpConstantNull %f32\n",
5392                         "%vp = OpVariable %fp_v4f32 Function\n"
5393                         "%v  = OpLoad %v4f32 %vp\n"
5394                         "%v0 = OpVectorInsertDynamic %v4f32 %v %cnull %c_i32_0\n"
5395                         "%v1 = OpVectorInsertDynamic %v4f32 %v0 %cnull %c_i32_1\n"
5396                         "%v2 = OpVectorInsertDynamic %v4f32 %v1 %cnull %c_i32_2\n"
5397                         "%v3 = OpVectorInsertDynamic %v4f32 %v2 %cnull %c_i32_3\n"
5398                         "%transformed_param = OpFAdd %v4f32 %param1 %v3\n"
5399                 },
5400                 {
5401                         "bool",
5402                         "%cnull             = OpConstantNull %bool\n",
5403                         "%v                 = OpVariable %fp_v4f32 Function\n"
5404                         "                     OpStore %v %param1\n"
5405                         "                     OpSelectionMerge %false_label None\n"
5406                         "                     OpBranchConditional %cnull %true_label %false_label\n"
5407                         "%true_label        = OpLabel\n"
5408                         "                     OpStore %v %c_v4f32_0_5_0_5_0_5_0_5\n"
5409                         "                     OpBranch %false_label\n"
5410                         "%false_label       = OpLabel\n"
5411                         "%transformed_param = OpLoad %v4f32 %v\n"
5412                 },
5413                 {
5414                         "i32",
5415                         "%cnull             = OpConstantNull %i32\n",
5416                         "%v                 = OpVariable %fp_v4f32 Function %c_v4f32_0_5_0_5_0_5_0_5\n"
5417                         "%b                 = OpIEqual %bool %cnull %c_i32_0\n"
5418                         "                     OpSelectionMerge %false_label None\n"
5419                         "                     OpBranchConditional %b %true_label %false_label\n"
5420                         "%true_label        = OpLabel\n"
5421                         "                     OpStore %v %param1\n"
5422                         "                     OpBranch %false_label\n"
5423                         "%false_label       = OpLabel\n"
5424                         "%transformed_param = OpLoad %v4f32 %v\n"
5425                 },
5426                 {
5427                         "struct",
5428                         "%stype             = OpTypeStruct %f32 %v4f32\n"
5429                         "%fp_stype          = OpTypePointer Function %stype\n"
5430                         "%cnull             = OpConstantNull %stype\n",
5431                         "%v                 = OpVariable %fp_stype Function %cnull\n"
5432                         "%f                 = OpAccessChain %fp_v4f32 %v %c_i32_1\n"
5433                         "%f_val             = OpLoad %v4f32 %f\n"
5434                         "%transformed_param = OpFAdd %v4f32 %param1 %f_val\n"
5435                 },
5436                 {
5437                         "array",
5438                         "%a4_v4f32          = OpTypeArray %v4f32 %c_u32_4\n"
5439                         "%fp_a4_v4f32       = OpTypePointer Function %a4_v4f32\n"
5440                         "%cnull             = OpConstantNull %a4_v4f32\n",
5441                         "%v                 = OpVariable %fp_a4_v4f32 Function %cnull\n"
5442                         "%f                 = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
5443                         "%f1                = OpAccessChain %fp_v4f32 %v %c_u32_1\n"
5444                         "%f2                = OpAccessChain %fp_v4f32 %v %c_u32_2\n"
5445                         "%f3                = OpAccessChain %fp_v4f32 %v %c_u32_3\n"
5446                         "%f_val             = OpLoad %v4f32 %f\n"
5447                         "%f1_val            = OpLoad %v4f32 %f1\n"
5448                         "%f2_val            = OpLoad %v4f32 %f2\n"
5449                         "%f3_val            = OpLoad %v4f32 %f3\n"
5450                         "%t0                = OpFAdd %v4f32 %param1 %f_val\n"
5451                         "%t1                = OpFAdd %v4f32 %t0 %f1_val\n"
5452                         "%t2                = OpFAdd %v4f32 %t1 %f2_val\n"
5453                         "%transformed_param = OpFAdd %v4f32 %t2 %f3_val\n"
5454                 },
5455                 {
5456                         "matrix",
5457                         "%mat4x4_f32        = OpTypeMatrix %v4f32 4\n"
5458                         "%cnull             = OpConstantNull %mat4x4_f32\n",
5459                         // Our null matrix * any vector should result in a zero vector.
5460                         "%v                 = OpVectorTimesMatrix %v4f32 %param1 %cnull\n"
5461                         "%transformed_param = OpFAdd %v4f32 %param1 %v\n"
5462                 }
5463         };
5464
5465         getHalfColorsFullAlpha(colors);
5466
5467         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
5468         {
5469                 map<string, string> fragments;
5470                 fragments["pre_main"] = tests[testNdx].constants;
5471                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
5472                 createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, opConstantNullTests.get());
5473         }
5474         return opConstantNullTests.release();
5475 }
5476 tcu::TestCaseGroup* createOpConstantCompositeTests(tcu::TestContext& testCtx)
5477 {
5478         de::MovePtr<tcu::TestCaseGroup> opConstantCompositeTests                (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "OpConstantComposite instruction"));
5479         RGBA                                                    inputColors[4];
5480         RGBA                                                    outputColors[4];
5481
5482
5483         const char                                              functionStart[]  =
5484                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
5485                 "%param1 = OpFunctionParameter %v4f32\n"
5486                 "%lbl    = OpLabel\n";
5487
5488         const char                                              functionEnd[]           =
5489                 "OpReturnValue %transformed_param\n"
5490                 "OpFunctionEnd\n";
5491
5492         struct NameConstantsCode
5493         {
5494                 string name;
5495                 string constants;
5496                 string code;
5497         };
5498
5499         NameConstantsCode tests[] =
5500         {
5501                 {
5502                         "vec4",
5503
5504                         "%cval              = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0\n",
5505                         "%transformed_param = OpFAdd %v4f32 %param1 %cval\n"
5506                 },
5507                 {
5508                         "struct",
5509
5510                         "%stype             = OpTypeStruct %v4f32 %f32\n"
5511                         "%fp_stype          = OpTypePointer Function %stype\n"
5512                         "%f32_n_1           = OpConstant %f32 -1.0\n"
5513                         "%f32_1_5           = OpConstant %f32 !0x3fc00000\n" // +1.5
5514                         "%cvec              = OpConstantComposite %v4f32 %f32_1_5 %f32_1_5 %f32_1_5 %c_f32_1\n"
5515                         "%cval              = OpConstantComposite %stype %cvec %f32_n_1\n",
5516
5517                         "%v                 = OpVariable %fp_stype Function %cval\n"
5518                         "%vec_ptr           = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
5519                         "%f32_ptr           = OpAccessChain %fp_f32 %v %c_u32_1\n"
5520                         "%vec_val           = OpLoad %v4f32 %vec_ptr\n"
5521                         "%f32_val           = OpLoad %f32 %f32_ptr\n"
5522                         "%tmp1              = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_1 %f32_val\n" // vec4(-1)
5523                         "%tmp2              = OpFAdd %v4f32 %tmp1 %param1\n" // param1 + vec4(-1)
5524                         "%transformed_param = OpFAdd %v4f32 %tmp2 %vec_val\n" // param1 + vec4(-1) + vec4(1.5, 1.5, 1.5, 1.0)
5525                 },
5526                 {
5527                         // [1|0|0|0.5] [x] = x + 0.5
5528                         // [0|1|0|0.5] [y] = y + 0.5
5529                         // [0|0|1|0.5] [z] = z + 0.5
5530                         // [0|0|0|1  ] [1] = 1
5531                         "matrix",
5532
5533                         "%mat4x4_f32          = OpTypeMatrix %v4f32 4\n"
5534                     "%v4f32_1_0_0_0       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_0 %c_f32_0 %c_f32_0\n"
5535                     "%v4f32_0_1_0_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_1 %c_f32_0 %c_f32_0\n"
5536                     "%v4f32_0_0_1_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_1 %c_f32_0\n"
5537                     "%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"
5538                         "%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",
5539
5540                         "%transformed_param   = OpMatrixTimesVector %v4f32 %cval %param1\n"
5541                 },
5542                 {
5543                         "array",
5544
5545                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
5546                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
5547                         "%f32_n_1             = OpConstant %f32 -1.0\n"
5548                         "%f32_1_5             = OpConstant %f32 !0x3fc00000\n" // +1.5
5549                         "%carr                = OpConstantComposite %a4f32 %c_f32_0 %f32_n_1 %f32_1_5 %c_f32_0\n",
5550
5551                         "%v                   = OpVariable %fp_a4f32 Function %carr\n"
5552                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_0\n"
5553                         "%f1                  = OpAccessChain %fp_f32 %v %c_u32_1\n"
5554                         "%f2                  = OpAccessChain %fp_f32 %v %c_u32_2\n"
5555                         "%f3                  = OpAccessChain %fp_f32 %v %c_u32_3\n"
5556                         "%f_val               = OpLoad %f32 %f\n"
5557                         "%f1_val              = OpLoad %f32 %f1\n"
5558                         "%f2_val              = OpLoad %f32 %f2\n"
5559                         "%f3_val              = OpLoad %f32 %f3\n"
5560                         "%ftot1               = OpFAdd %f32 %f_val %f1_val\n"
5561                         "%ftot2               = OpFAdd %f32 %ftot1 %f2_val\n"
5562                         "%ftot3               = OpFAdd %f32 %ftot2 %f3_val\n"  // 0 - 1 + 1.5 + 0
5563                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %ftot3\n"
5564                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
5565                 },
5566                 {
5567                         //
5568                         // [
5569                         //   {
5570                         //      0.0,
5571                         //      [ 1.0, 1.0, 1.0, 1.0]
5572                         //   },
5573                         //   {
5574                         //      1.0,
5575                         //      [ 0.0, 0.5, 0.0, 0.0]
5576                         //   }, //     ^^^
5577                         //   {
5578                         //      0.0,
5579                         //      [ 1.0, 1.0, 1.0, 1.0]
5580                         //   }
5581                         // ]
5582                         "array_of_struct_of_array",
5583
5584                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
5585                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
5586                         "%stype               = OpTypeStruct %f32 %a4f32\n"
5587                         "%a3stype             = OpTypeArray %stype %c_u32_3\n"
5588                         "%fp_a3stype          = OpTypePointer Function %a3stype\n"
5589                         "%ca4f32_0            = OpConstantComposite %a4f32 %c_f32_0 %c_f32_0_5 %c_f32_0 %c_f32_0\n"
5590                         "%ca4f32_1            = OpConstantComposite %a4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
5591                         "%cstype1             = OpConstantComposite %stype %c_f32_0 %ca4f32_1\n"
5592                         "%cstype2             = OpConstantComposite %stype %c_f32_1 %ca4f32_0\n"
5593                         "%carr                = OpConstantComposite %a3stype %cstype1 %cstype2 %cstype1",
5594
5595                         "%v                   = OpVariable %fp_a3stype Function %carr\n"
5596                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_1 %c_u32_1 %c_u32_1\n"
5597                         "%f_l                 = OpLoad %f32 %f\n"
5598                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %f_l\n"
5599                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
5600                 }
5601         };
5602
5603         getHalfColorsFullAlpha(inputColors);
5604         outputColors[0] = RGBA(255, 255, 255, 255);
5605         outputColors[1] = RGBA(255, 127, 127, 255);
5606         outputColors[2] = RGBA(127, 255, 127, 255);
5607         outputColors[3] = RGBA(127, 127, 255, 255);
5608
5609         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
5610         {
5611                 map<string, string> fragments;
5612                 fragments["pre_main"] = tests[testNdx].constants;
5613                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
5614                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, opConstantCompositeTests.get());
5615         }
5616         return opConstantCompositeTests.release();
5617 }
5618
5619 tcu::TestCaseGroup* createSelectionBlockOrderTests(tcu::TestContext& testCtx)
5620 {
5621         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "selection_block_order", "Out-of-order blocks for selection"));
5622         RGBA                                                    inputColors[4];
5623         RGBA                                                    outputColors[4];
5624         map<string, string>                             fragments;
5625
5626         // vec4 test_code(vec4 param) {
5627         //   vec4 result = param;
5628         //   for (int i = 0; i < 4; ++i) {
5629         //     if (i == 0) result[i] = 0.;
5630         //     else        result[i] = 1. - result[i];
5631         //   }
5632         //   return result;
5633         // }
5634         const char                                              function[]                      =
5635                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
5636                 "%param1    = OpFunctionParameter %v4f32\n"
5637                 "%lbl       = OpLabel\n"
5638                 "%iptr      = OpVariable %fp_i32 Function\n"
5639                 "%result    = OpVariable %fp_v4f32 Function\n"
5640                 "             OpStore %iptr %c_i32_0\n"
5641                 "             OpStore %result %param1\n"
5642                 "             OpBranch %loop\n"
5643
5644                 // Loop entry block.
5645                 "%loop      = OpLabel\n"
5646                 "%ival      = OpLoad %i32 %iptr\n"
5647                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
5648                 "             OpLoopMerge %exit %if_entry None\n"
5649                 "             OpBranchConditional %lt_4 %if_entry %exit\n"
5650
5651                 // Merge block for loop.
5652                 "%exit      = OpLabel\n"
5653                 "%ret       = OpLoad %v4f32 %result\n"
5654                 "             OpReturnValue %ret\n"
5655
5656                 // If-statement entry block.
5657                 "%if_entry  = OpLabel\n"
5658                 "%loc       = OpAccessChain %fp_f32 %result %ival\n"
5659                 "%eq_0      = OpIEqual %bool %ival %c_i32_0\n"
5660                 "             OpSelectionMerge %if_exit None\n"
5661                 "             OpBranchConditional %eq_0 %if_true %if_false\n"
5662
5663                 // False branch for if-statement.
5664                 "%if_false  = OpLabel\n"
5665                 "%val       = OpLoad %f32 %loc\n"
5666                 "%sub       = OpFSub %f32 %c_f32_1 %val\n"
5667                 "             OpStore %loc %sub\n"
5668                 "             OpBranch %if_exit\n"
5669
5670                 // Merge block for if-statement.
5671                 "%if_exit   = OpLabel\n"
5672                 "%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
5673                 "             OpStore %iptr %ival_next\n"
5674                 "             OpBranch %loop\n"
5675
5676                 // True branch for if-statement.
5677                 "%if_true   = OpLabel\n"
5678                 "             OpStore %loc %c_f32_0\n"
5679                 "             OpBranch %if_exit\n"
5680
5681                 "             OpFunctionEnd\n";
5682
5683         fragments["testfun"]    = function;
5684
5685         inputColors[0]                  = RGBA(127, 127, 127, 0);
5686         inputColors[1]                  = RGBA(127, 0,   0,   0);
5687         inputColors[2]                  = RGBA(0,   127, 0,   0);
5688         inputColors[3]                  = RGBA(0,   0,   127, 0);
5689
5690         outputColors[0]                 = RGBA(0, 128, 128, 255);
5691         outputColors[1]                 = RGBA(0, 255, 255, 255);
5692         outputColors[2]                 = RGBA(0, 128, 255, 255);
5693         outputColors[3]                 = RGBA(0, 255, 128, 255);
5694
5695         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
5696
5697         return group.release();
5698 }
5699
5700 tcu::TestCaseGroup* createSwitchBlockOrderTests(tcu::TestContext& testCtx)
5701 {
5702         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "switch_block_order", "Out-of-order blocks for switch"));
5703         RGBA                                                    inputColors[4];
5704         RGBA                                                    outputColors[4];
5705         map<string, string>                             fragments;
5706
5707         const char                                              typesAndConstants[]     =
5708                 "%c_f32_p2  = OpConstant %f32 0.2\n"
5709                 "%c_f32_p4  = OpConstant %f32 0.4\n"
5710                 "%c_f32_p6  = OpConstant %f32 0.6\n"
5711                 "%c_f32_p8  = OpConstant %f32 0.8\n";
5712
5713         // vec4 test_code(vec4 param) {
5714         //   vec4 result = param;
5715         //   for (int i = 0; i < 4; ++i) {
5716         //     switch (i) {
5717         //       case 0: result[i] += .2; break;
5718         //       case 1: result[i] += .6; break;
5719         //       case 2: result[i] += .4; break;
5720         //       case 3: result[i] += .8; break;
5721         //       default: break; // unreachable
5722         //     }
5723         //   }
5724         //   return result;
5725         // }
5726         const char                                              function[]                      =
5727                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
5728                 "%param1    = OpFunctionParameter %v4f32\n"
5729                 "%lbl       = OpLabel\n"
5730                 "%iptr      = OpVariable %fp_i32 Function\n"
5731                 "%result    = OpVariable %fp_v4f32 Function\n"
5732                 "             OpStore %iptr %c_i32_0\n"
5733                 "             OpStore %result %param1\n"
5734                 "             OpBranch %loop\n"
5735
5736                 // Loop entry block.
5737                 "%loop      = OpLabel\n"
5738                 "%ival      = OpLoad %i32 %iptr\n"
5739                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
5740                 "             OpLoopMerge %exit %switch_exit None\n"
5741                 "             OpBranchConditional %lt_4 %switch_entry %exit\n"
5742
5743                 // Merge block for loop.
5744                 "%exit      = OpLabel\n"
5745                 "%ret       = OpLoad %v4f32 %result\n"
5746                 "             OpReturnValue %ret\n"
5747
5748                 // Switch-statement entry block.
5749                 "%switch_entry   = OpLabel\n"
5750                 "%loc            = OpAccessChain %fp_f32 %result %ival\n"
5751                 "%val            = OpLoad %f32 %loc\n"
5752                 "                  OpSelectionMerge %switch_exit None\n"
5753                 "                  OpSwitch %ival %switch_default 0 %case0 1 %case1 2 %case2 3 %case3\n"
5754
5755                 "%case2          = OpLabel\n"
5756                 "%addp4          = OpFAdd %f32 %val %c_f32_p4\n"
5757                 "                  OpStore %loc %addp4\n"
5758                 "                  OpBranch %switch_exit\n"
5759
5760                 "%switch_default = OpLabel\n"
5761                 "                  OpUnreachable\n"
5762
5763                 "%case3          = OpLabel\n"
5764                 "%addp8          = OpFAdd %f32 %val %c_f32_p8\n"
5765                 "                  OpStore %loc %addp8\n"
5766                 "                  OpBranch %switch_exit\n"
5767
5768                 "%case0          = OpLabel\n"
5769                 "%addp2          = OpFAdd %f32 %val %c_f32_p2\n"
5770                 "                  OpStore %loc %addp2\n"
5771                 "                  OpBranch %switch_exit\n"
5772
5773                 // Merge block for switch-statement.
5774                 "%switch_exit    = OpLabel\n"
5775                 "%ival_next      = OpIAdd %i32 %ival %c_i32_1\n"
5776                 "                  OpStore %iptr %ival_next\n"
5777                 "                  OpBranch %loop\n"
5778
5779                 "%case1          = OpLabel\n"
5780                 "%addp6          = OpFAdd %f32 %val %c_f32_p6\n"
5781                 "                  OpStore %loc %addp6\n"
5782                 "                  OpBranch %switch_exit\n"
5783
5784                 "                  OpFunctionEnd\n";
5785
5786         fragments["pre_main"]   = typesAndConstants;
5787         fragments["testfun"]    = function;
5788
5789         inputColors[0]                  = RGBA(127, 27,  127, 51);
5790         inputColors[1]                  = RGBA(127, 0,   0,   51);
5791         inputColors[2]                  = RGBA(0,   27,  0,   51);
5792         inputColors[3]                  = RGBA(0,   0,   127, 51);
5793
5794         outputColors[0]                 = RGBA(178, 180, 229, 255);
5795         outputColors[1]                 = RGBA(178, 153, 102, 255);
5796         outputColors[2]                 = RGBA(51,  180, 102, 255);
5797         outputColors[3]                 = RGBA(51,  153, 229, 255);
5798
5799         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
5800
5801         return group.release();
5802 }
5803
5804 tcu::TestCaseGroup* createDecorationGroupTests(tcu::TestContext& testCtx)
5805 {
5806         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "decoration_group", "Decoration group tests"));
5807         RGBA                                                    inputColors[4];
5808         RGBA                                                    outputColors[4];
5809         map<string, string>                             fragments;
5810
5811         const char                                              decorations[]           =
5812                 "OpDecorate %array_group         ArrayStride 4\n"
5813                 "OpDecorate %struct_member_group Offset 0\n"
5814                 "%array_group         = OpDecorationGroup\n"
5815                 "%struct_member_group = OpDecorationGroup\n"
5816
5817                 "OpDecorate %group1 RelaxedPrecision\n"
5818                 "OpDecorate %group3 RelaxedPrecision\n"
5819                 "OpDecorate %group3 Invariant\n"
5820                 "OpDecorate %group3 Restrict\n"
5821                 "%group0 = OpDecorationGroup\n"
5822                 "%group1 = OpDecorationGroup\n"
5823                 "%group3 = OpDecorationGroup\n";
5824
5825         const char                                              typesAndConstants[]     =
5826                 "%a3f32     = OpTypeArray %f32 %c_u32_3\n"
5827                 "%struct1   = OpTypeStruct %a3f32\n"
5828                 "%struct2   = OpTypeStruct %a3f32\n"
5829                 "%fp_struct1 = OpTypePointer Function %struct1\n"
5830                 "%fp_struct2 = OpTypePointer Function %struct2\n"
5831                 "%c_f32_2    = OpConstant %f32 2.\n"
5832                 "%c_f32_n2   = OpConstant %f32 -2.\n"
5833
5834                 "%c_a3f32_1 = OpConstantComposite %a3f32 %c_f32_1 %c_f32_2 %c_f32_1\n"
5835                 "%c_a3f32_2 = OpConstantComposite %a3f32 %c_f32_n1 %c_f32_n2 %c_f32_n1\n"
5836                 "%c_struct1 = OpConstantComposite %struct1 %c_a3f32_1\n"
5837                 "%c_struct2 = OpConstantComposite %struct2 %c_a3f32_2\n";
5838
5839         const char                                              function[]                      =
5840                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
5841                 "%param     = OpFunctionParameter %v4f32\n"
5842                 "%entry     = OpLabel\n"
5843                 "%result    = OpVariable %fp_v4f32 Function\n"
5844                 "%v_struct1 = OpVariable %fp_struct1 Function\n"
5845                 "%v_struct2 = OpVariable %fp_struct2 Function\n"
5846                 "             OpStore %result %param\n"
5847                 "             OpStore %v_struct1 %c_struct1\n"
5848                 "             OpStore %v_struct2 %c_struct2\n"
5849                 "%ptr1      = OpAccessChain %fp_f32 %v_struct1 %c_i32_0 %c_i32_2\n"
5850                 "%val1      = OpLoad %f32 %ptr1\n"
5851                 "%ptr2      = OpAccessChain %fp_f32 %v_struct2 %c_i32_0 %c_i32_2\n"
5852                 "%val2      = OpLoad %f32 %ptr2\n"
5853                 "%addvalues = OpFAdd %f32 %val1 %val2\n"
5854                 "%ptr       = OpAccessChain %fp_f32 %result %c_i32_1\n"
5855                 "%val       = OpLoad %f32 %ptr\n"
5856                 "%addresult = OpFAdd %f32 %addvalues %val\n"
5857                 "             OpStore %ptr %addresult\n"
5858                 "%ret       = OpLoad %v4f32 %result\n"
5859                 "             OpReturnValue %ret\n"
5860                 "             OpFunctionEnd\n";
5861
5862         struct CaseNameDecoration
5863         {
5864                 string name;
5865                 string decoration;
5866         };
5867
5868         CaseNameDecoration tests[] =
5869         {
5870                 {
5871                         "same_decoration_group_on_multiple_types",
5872                         "OpGroupMemberDecorate %struct_member_group %struct1 0 %struct2 0\n"
5873                 },
5874                 {
5875                         "empty_decoration_group",
5876                         "OpGroupDecorate %group0      %a3f32\n"
5877                         "OpGroupDecorate %group0      %result\n"
5878                 },
5879                 {
5880                         "one_element_decoration_group",
5881                         "OpGroupDecorate %array_group %a3f32\n"
5882                 },
5883                 {
5884                         "multiple_elements_decoration_group",
5885                         "OpGroupDecorate %group3      %v_struct1\n"
5886                 },
5887                 {
5888                         "multiple_decoration_groups_on_same_variable",
5889                         "OpGroupDecorate %group0      %v_struct2\n"
5890                         "OpGroupDecorate %group1      %v_struct2\n"
5891                         "OpGroupDecorate %group3      %v_struct2\n"
5892                 },
5893                 {
5894                         "same_decoration_group_multiple_times",
5895                         "OpGroupDecorate %group1      %addvalues\n"
5896                         "OpGroupDecorate %group1      %addvalues\n"
5897                         "OpGroupDecorate %group1      %addvalues\n"
5898                 },
5899
5900         };
5901
5902         getHalfColorsFullAlpha(inputColors);
5903         getHalfColorsFullAlpha(outputColors);
5904
5905         for (size_t idx = 0; idx < (sizeof(tests) / sizeof(tests[0])); ++idx)
5906         {
5907                 fragments["decoration"] = decorations + tests[idx].decoration;
5908                 fragments["pre_main"]   = typesAndConstants;
5909                 fragments["testfun"]    = function;
5910
5911                 createTestsForAllStages(tests[idx].name, inputColors, outputColors, fragments, group.get());
5912         }
5913
5914         return group.release();
5915 }
5916
5917 struct SpecConstantTwoIntGraphicsCase
5918 {
5919         const char*             caseName;
5920         const char*             scDefinition0;
5921         const char*             scDefinition1;
5922         const char*             scResultType;
5923         const char*             scOperation;
5924         deInt32                 scActualValue0;
5925         deInt32                 scActualValue1;
5926         const char*             resultOperation;
5927         RGBA                    expectedColors[4];
5928
5929                                         SpecConstantTwoIntGraphicsCase (const char* name,
5930                                                                                         const char* definition0,
5931                                                                                         const char* definition1,
5932                                                                                         const char* resultType,
5933                                                                                         const char* operation,
5934                                                                                         deInt32         value0,
5935                                                                                         deInt32         value1,
5936                                                                                         const char* resultOp,
5937                                                                                         const RGBA      (&output)[4])
5938                                                 : caseName                      (name)
5939                                                 , scDefinition0         (definition0)
5940                                                 , scDefinition1         (definition1)
5941                                                 , scResultType          (resultType)
5942                                                 , scOperation           (operation)
5943                                                 , scActualValue0        (value0)
5944                                                 , scActualValue1        (value1)
5945                                                 , resultOperation       (resultOp)
5946         {
5947                 expectedColors[0] = output[0];
5948                 expectedColors[1] = output[1];
5949                 expectedColors[2] = output[2];
5950                 expectedColors[3] = output[3];
5951         }
5952 };
5953
5954 tcu::TestCaseGroup* createSpecConstantTests (tcu::TestContext& testCtx)
5955 {
5956         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
5957         vector<SpecConstantTwoIntGraphicsCase>  cases;
5958         RGBA                                                    inputColors[4];
5959         RGBA                                                    outputColors0[4];
5960         RGBA                                                    outputColors1[4];
5961         RGBA                                                    outputColors2[4];
5962
5963         const char      decorations1[]                  =
5964                 "OpDecorate %sc_0  SpecId 0\n"
5965                 "OpDecorate %sc_1  SpecId 1\n";
5966
5967         const char      typesAndConstants1[]    =
5968                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
5969                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
5970                 "%sc_op     = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n";
5971
5972         const char      function1[]                             =
5973                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
5974                 "%param     = OpFunctionParameter %v4f32\n"
5975                 "%label     = OpLabel\n"
5976                 "%result    = OpVariable %fp_v4f32 Function\n"
5977                 "             OpStore %result %param\n"
5978                 "%gen       = ${GEN_RESULT}\n"
5979                 "%index     = OpIAdd %i32 %gen %c_i32_1\n"
5980                 "%loc       = OpAccessChain %fp_f32 %result %index\n"
5981                 "%val       = OpLoad %f32 %loc\n"
5982                 "%add       = OpFAdd %f32 %val %c_f32_0_5\n"
5983                 "             OpStore %loc %add\n"
5984                 "%ret       = OpLoad %v4f32 %result\n"
5985                 "             OpReturnValue %ret\n"
5986                 "             OpFunctionEnd\n";
5987
5988         inputColors[0] = RGBA(127, 127, 127, 255);
5989         inputColors[1] = RGBA(127, 0,   0,   255);
5990         inputColors[2] = RGBA(0,   127, 0,   255);
5991         inputColors[3] = RGBA(0,   0,   127, 255);
5992
5993         // Derived from inputColors[x] by adding 128 to inputColors[x][0].
5994         outputColors0[0] = RGBA(255, 127, 127, 255);
5995         outputColors0[1] = RGBA(255, 0,   0,   255);
5996         outputColors0[2] = RGBA(128, 127, 0,   255);
5997         outputColors0[3] = RGBA(128, 0,   127, 255);
5998
5999         // Derived from inputColors[x] by adding 128 to inputColors[x][1].
6000         outputColors1[0] = RGBA(127, 255, 127, 255);
6001         outputColors1[1] = RGBA(127, 128, 0,   255);
6002         outputColors1[2] = RGBA(0,   255, 0,   255);
6003         outputColors1[3] = RGBA(0,   128, 127, 255);
6004
6005         // Derived from inputColors[x] by adding 128 to inputColors[x][2].
6006         outputColors2[0] = RGBA(127, 127, 255, 255);
6007         outputColors2[1] = RGBA(127, 0,   128, 255);
6008         outputColors2[2] = RGBA(0,   127, 128, 255);
6009         outputColors2[3] = RGBA(0,   0,   255, 255);
6010
6011         const char addZeroToSc[]                = "OpIAdd %i32 %c_i32_0 %sc_op";
6012         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_op %c_i32_1 %c_i32_0";
6013         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_op %c_i32_0 %c_i32_1";
6014
6015         cases.push_back(SpecConstantTwoIntGraphicsCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                             19,             -20,    addZeroToSc,            outputColors0));
6016         cases.push_back(SpecConstantTwoIntGraphicsCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                             19,             20,             addZeroToSc,            outputColors0));
6017         cases.push_back(SpecConstantTwoIntGraphicsCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                             -1,             -1,             addZeroToSc,            outputColors2));
6018         cases.push_back(SpecConstantTwoIntGraphicsCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                             -126,   126,    addZeroToSc,            outputColors0));
6019         cases.push_back(SpecConstantTwoIntGraphicsCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                             126,    126,    addZeroToSc,            outputColors2));
6020         cases.push_back(SpecConstantTwoIntGraphicsCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
6021         cases.push_back(SpecConstantTwoIntGraphicsCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
6022         cases.push_back(SpecConstantTwoIntGraphicsCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                             1001,   500,    addZeroToSc,            outputColors2));
6023         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                             0x33,   0x0d,   addZeroToSc,            outputColors2));
6024         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                             0,              1,              addZeroToSc,            outputColors2));
6025         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                             0x2e,   0x2f,   addZeroToSc,            outputColors2));
6026         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                             2,              1,              addZeroToSc,            outputColors2));
6027         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                             -4,             2,              addZeroToSc,            outputColors0));
6028         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                             1,              0,              addZeroToSc,            outputColors2));
6029         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                             -20,    -10,    selectTrueUsingSc,      outputColors2));
6030         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                             10,             20,             selectTrueUsingSc,      outputColors2));
6031         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
6032         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                             10,             5,              selectTrueUsingSc,      outputColors2));
6033         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                             -10,    -10,    selectTrueUsingSc,      outputColors2));
6034         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                             50,             100,    selectTrueUsingSc,      outputColors2));
6035         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
6036         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                             10,             10,             selectTrueUsingSc,      outputColors2));
6037         cases.push_back(SpecConstantTwoIntGraphicsCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                             42,             24,             selectFalseUsingSc,     outputColors2));
6038         cases.push_back(SpecConstantTwoIntGraphicsCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
6039         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
6040         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
6041         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
6042         cases.push_back(SpecConstantTwoIntGraphicsCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                                   -1,             0,              addZeroToSc,            outputColors2));
6043         cases.push_back(SpecConstantTwoIntGraphicsCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                                   -2,             0,              addZeroToSc,            outputColors2));
6044         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                                   1,              0,              selectFalseUsingSc,     outputColors2));
6045         cases.push_back(SpecConstantTwoIntGraphicsCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %c_i32_0",    1,              1,              addZeroToSc,            outputColors2));
6046         // OpSConvert, OpFConvert: these two instructions involve ints/floats of different bitwidths.
6047         // \todo[2015-12-1 antiagainst] OpQuantizeToF16
6048
6049         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
6050         {
6051                 map<string, string>     specializations;
6052                 map<string, string>     fragments;
6053                 vector<deInt32>         specConstants;
6054
6055                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
6056                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
6057                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
6058                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
6059                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
6060
6061                 fragments["decoration"]                         = tcu::StringTemplate(decorations1).specialize(specializations);
6062                 fragments["pre_main"]                           = tcu::StringTemplate(typesAndConstants1).specialize(specializations);
6063                 fragments["testfun"]                            = tcu::StringTemplate(function1).specialize(specializations);
6064
6065                 specConstants.push_back(cases[caseNdx].scActualValue0);
6066                 specConstants.push_back(cases[caseNdx].scActualValue1);
6067
6068                 createTestsForAllStages(cases[caseNdx].caseName, inputColors, cases[caseNdx].expectedColors, fragments, specConstants, group.get());
6069         }
6070
6071         const char      decorations2[]                  =
6072                 "OpDecorate %sc_0  SpecId 0\n"
6073                 "OpDecorate %sc_1  SpecId 1\n"
6074                 "OpDecorate %sc_2  SpecId 2\n";
6075
6076         const char      typesAndConstants2[]    =
6077                 "%v3i32       = OpTypeVector %i32 3\n"
6078                 "%vec3_0      = OpConstantComposite %v3i32 %c_i32_0 %c_i32_0 %c_i32_0\n"
6079                 "%vec3_undef  = OpUndef %v3i32\n"
6080
6081                 "%sc_0        = OpSpecConstant %i32 0\n"
6082                 "%sc_1        = OpSpecConstant %i32 0\n"
6083                 "%sc_2        = OpSpecConstant %i32 0\n"
6084                 "%sc_vec3_0   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_0        %vec3_0      0\n"                                                 // (sc_0, 0,    0)
6085                 "%sc_vec3_1   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_1        %vec3_0      1\n"                                                 // (0,    sc_1, 0)
6086                 "%sc_vec3_2   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_2        %vec3_0      2\n"                                                 // (0,    0,    sc_2)
6087                 "%sc_vec3_0_s = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_0   %vec3_undef  0          0xFFFFFFFF 2\n"   // (sc_0, ???,  0)
6088                 "%sc_vec3_1_s = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_1   %vec3_undef  0xFFFFFFFF 1          0\n"   // (???,  sc_1, 0)
6089                 "%sc_vec3_2_s = OpSpecConstantOp %v3i32 VectorShuffle    %vec3_undef  %sc_vec3_2   5          0xFFFFFFFF 5\n"   // (sc_2, ???,  sc_2)
6090                 "%sc_vec3_01  = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_0_s %sc_vec3_1_s 1 0 4\n"                                             // (0,    sc_0, sc_1)
6091                 "%sc_vec3_012 = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_01  %sc_vec3_2_s 5 1 2\n"                                             // (sc_2, sc_0, sc_1)
6092                 "%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              0\n"                                                 // sc_2
6093                 "%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              1\n"                                                 // sc_0
6094                 "%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              2\n"                                                 // sc_1
6095                 "%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"                                                              // (sc_2 - sc_0)
6096                 "%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n";                                                             // (sc_2 - sc_0) * sc_1
6097
6098         const char      function2[]                             =
6099                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6100                 "%param     = OpFunctionParameter %v4f32\n"
6101                 "%label     = OpLabel\n"
6102                 "%result    = OpVariable %fp_v4f32 Function\n"
6103                 "             OpStore %result %param\n"
6104                 "%loc       = OpAccessChain %fp_f32 %result %sc_final\n"
6105                 "%val       = OpLoad %f32 %loc\n"
6106                 "%add       = OpFAdd %f32 %val %c_f32_0_5\n"
6107                 "             OpStore %loc %add\n"
6108                 "%ret       = OpLoad %v4f32 %result\n"
6109                 "             OpReturnValue %ret\n"
6110                 "             OpFunctionEnd\n";
6111
6112         map<string, string>     fragments;
6113         vector<deInt32>         specConstants;
6114
6115         fragments["decoration"] = decorations2;
6116         fragments["pre_main"]   = typesAndConstants2;
6117         fragments["testfun"]    = function2;
6118
6119         specConstants.push_back(56789);
6120         specConstants.push_back(-2);
6121         specConstants.push_back(56788);
6122
6123         createTestsForAllStages("vector_related", inputColors, outputColors2, fragments, specConstants, group.get());
6124
6125         return group.release();
6126 }
6127
6128 tcu::TestCaseGroup* createOpPhiTests(tcu::TestContext& testCtx)
6129 {
6130         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
6131         RGBA                                                    inputColors[4];
6132         RGBA                                                    outputColors1[4];
6133         RGBA                                                    outputColors2[4];
6134         RGBA                                                    outputColors3[4];
6135         map<string, string>                             fragments1;
6136         map<string, string>                             fragments2;
6137         map<string, string>                             fragments3;
6138
6139         const char      typesAndConstants1[]    =
6140                 "%c_f32_p2  = OpConstant %f32 0.2\n"
6141                 "%c_f32_p4  = OpConstant %f32 0.4\n"
6142                 "%c_f32_p5  = OpConstant %f32 0.5\n"
6143                 "%c_f32_p8  = OpConstant %f32 0.8\n";
6144
6145         // vec4 test_code(vec4 param) {
6146         //   vec4 result = param;
6147         //   for (int i = 0; i < 4; ++i) {
6148         //     float operand;
6149         //     switch (i) {
6150         //       case 0: operand = .2; break;
6151         //       case 1: operand = .5; break;
6152         //       case 2: operand = .4; break;
6153         //       case 3: operand = .0; break;
6154         //       default: break; // unreachable
6155         //     }
6156         //     result[i] += operand;
6157         //   }
6158         //   return result;
6159         // }
6160         const char      function1[]                             =
6161                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6162                 "%param1    = OpFunctionParameter %v4f32\n"
6163                 "%lbl       = OpLabel\n"
6164                 "%iptr      = OpVariable %fp_i32 Function\n"
6165                 "%result    = OpVariable %fp_v4f32 Function\n"
6166                 "             OpStore %iptr %c_i32_0\n"
6167                 "             OpStore %result %param1\n"
6168                 "             OpBranch %loop\n"
6169
6170                 "%loop      = OpLabel\n"
6171                 "%ival      = OpLoad %i32 %iptr\n"
6172                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6173                 "             OpLoopMerge %exit %phi None\n"
6174                 "             OpBranchConditional %lt_4 %entry %exit\n"
6175
6176                 "%entry     = OpLabel\n"
6177                 "%loc       = OpAccessChain %fp_f32 %result %ival\n"
6178                 "%val       = OpLoad %f32 %loc\n"
6179                 "             OpSelectionMerge %phi None\n"
6180                 "             OpSwitch %ival %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
6181
6182                 "%case0     = OpLabel\n"
6183                 "             OpBranch %phi\n"
6184                 "%case1     = OpLabel\n"
6185                 "             OpBranch %phi\n"
6186                 "%case2     = OpLabel\n"
6187                 "             OpBranch %phi\n"
6188                 "%case3     = OpLabel\n"
6189                 "             OpBranch %phi\n"
6190
6191                 "%default   = OpLabel\n"
6192                 "             OpUnreachable\n"
6193
6194                 "%phi       = OpLabel\n"
6195                 "%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
6196                 "%add       = OpFAdd %f32 %val %operand\n"
6197                 "             OpStore %loc %add\n"
6198                 "%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
6199                 "             OpStore %iptr %ival_next\n"
6200                 "             OpBranch %loop\n"
6201
6202                 "%exit      = OpLabel\n"
6203                 "%ret       = OpLoad %v4f32 %result\n"
6204                 "             OpReturnValue %ret\n"
6205
6206                 "             OpFunctionEnd\n";
6207
6208         fragments1["pre_main"]  = typesAndConstants1;
6209         fragments1["testfun"]   = function1;
6210
6211         getHalfColorsFullAlpha(inputColors);
6212
6213         outputColors1[0]                = RGBA(178, 255, 229, 255);
6214         outputColors1[1]                = RGBA(178, 127, 102, 255);
6215         outputColors1[2]                = RGBA(51,  255, 102, 255);
6216         outputColors1[3]                = RGBA(51,  127, 229, 255);
6217
6218         createTestsForAllStages("out_of_order", inputColors, outputColors1, fragments1, group.get());
6219
6220         const char      typesAndConstants2[]    =
6221                 "%c_f32_p2  = OpConstant %f32 0.2\n";
6222
6223         // Add .4 to the second element of the given parameter.
6224         const char      function2[]                             =
6225                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6226                 "%param     = OpFunctionParameter %v4f32\n"
6227                 "%entry     = OpLabel\n"
6228                 "%result    = OpVariable %fp_v4f32 Function\n"
6229                 "             OpStore %result %param\n"
6230                 "%loc       = OpAccessChain %fp_f32 %result %c_i32_1\n"
6231                 "%val       = OpLoad %f32 %loc\n"
6232                 "             OpBranch %phi\n"
6233
6234                 "%phi        = OpLabel\n"
6235                 "%step       = OpPhi %i32 %c_i32_0  %entry %step_next  %phi\n"
6236                 "%accum      = OpPhi %f32 %val      %entry %accum_next %phi\n"
6237                 "%step_next  = OpIAdd %i32 %step  %c_i32_1\n"
6238                 "%accum_next = OpFAdd %f32 %accum %c_f32_p2\n"
6239                 "%still_loop = OpSLessThan %bool %step %c_i32_2\n"
6240                 "              OpLoopMerge %exit %phi None\n"
6241                 "              OpBranchConditional %still_loop %phi %exit\n"
6242
6243                 "%exit       = OpLabel\n"
6244                 "              OpStore %loc %accum\n"
6245                 "%ret        = OpLoad %v4f32 %result\n"
6246                 "              OpReturnValue %ret\n"
6247
6248                 "              OpFunctionEnd\n";
6249
6250         fragments2["pre_main"]  = typesAndConstants2;
6251         fragments2["testfun"]   = function2;
6252
6253         outputColors2[0]                        = RGBA(127, 229, 127, 255);
6254         outputColors2[1]                        = RGBA(127, 102, 0,   255);
6255         outputColors2[2]                        = RGBA(0,   229, 0,   255);
6256         outputColors2[3]                        = RGBA(0,   102, 127, 255);
6257
6258         createTestsForAllStages("induction", inputColors, outputColors2, fragments2, group.get());
6259
6260         const char      typesAndConstants3[]    =
6261                 "%true      = OpConstantTrue %bool\n"
6262                 "%false     = OpConstantFalse %bool\n"
6263                 "%c_f32_p2  = OpConstant %f32 0.2\n";
6264
6265         // Swap the second and the third element of the given parameter.
6266         const char      function3[]                             =
6267                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6268                 "%param     = OpFunctionParameter %v4f32\n"
6269                 "%entry     = OpLabel\n"
6270                 "%result    = OpVariable %fp_v4f32 Function\n"
6271                 "             OpStore %result %param\n"
6272                 "%a_loc     = OpAccessChain %fp_f32 %result %c_i32_1\n"
6273                 "%a_init    = OpLoad %f32 %a_loc\n"
6274                 "%b_loc     = OpAccessChain %fp_f32 %result %c_i32_2\n"
6275                 "%b_init    = OpLoad %f32 %b_loc\n"
6276                 "             OpBranch %phi\n"
6277
6278                 "%phi        = OpLabel\n"
6279                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
6280                 "%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
6281                 "%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
6282                 "              OpLoopMerge %exit %phi None\n"
6283                 "              OpBranchConditional %still_loop %phi %exit\n"
6284
6285                 "%exit       = OpLabel\n"
6286                 "              OpStore %a_loc %a_next\n"
6287                 "              OpStore %b_loc %b_next\n"
6288                 "%ret        = OpLoad %v4f32 %result\n"
6289                 "              OpReturnValue %ret\n"
6290
6291                 "              OpFunctionEnd\n";
6292
6293         fragments3["pre_main"]  = typesAndConstants3;
6294         fragments3["testfun"]   = function3;
6295
6296         outputColors3[0]                        = RGBA(127, 127, 127, 255);
6297         outputColors3[1]                        = RGBA(127, 0,   0,   255);
6298         outputColors3[2]                        = RGBA(0,   0,   127, 255);
6299         outputColors3[3]                        = RGBA(0,   127, 0,   255);
6300
6301         createTestsForAllStages("swap", inputColors, outputColors3, fragments3, group.get());
6302
6303         return group.release();
6304 }
6305
6306 tcu::TestCaseGroup* createNoContractionTests(tcu::TestContext& testCtx)
6307 {
6308         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
6309         RGBA                                                    inputColors[4];
6310         RGBA                                                    outputColors[4];
6311
6312         // With NoContraction, (1 + 2^-23) * (1 - 2^-23) - 1 should be conducted as a multiplication and an addition separately.
6313         // For the multiplication, the result is 1 - 2^-46, which is out of the precision range for 32-bit float. (32-bit float
6314         // only have 23-bit fraction.) So it will be rounded to 1. Or 0x1.fffffc. Then the final result is 0 or -0x1p-24.
6315         // On the contrary, the result will be 2^-46, which is a normalized number perfectly representable as 32-bit float.
6316         const char                                              constantsAndTypes[]      =
6317                 "%c_vec4_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_0 %c_f32_1\n"
6318                 "%c_vec4_1       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
6319                 "%c_f32_1pl2_23  = OpConstant %f32 0x1.000002p+0\n" // 1 + 2^-23
6320                 "%c_f32_1mi2_23  = OpConstant %f32 0x1.fffffcp-1\n" // 1 - 2^-23
6321                 "%c_f32_n1pn24   = OpConstant %f32 -0x1p-24\n";
6322
6323         const char                                              function[]       =
6324                 "%test_code      = OpFunction %v4f32 None %v4f32_function\n"
6325                 "%param          = OpFunctionParameter %v4f32\n"
6326                 "%label          = OpLabel\n"
6327                 "%var1           = OpVariable %fp_f32 Function %c_f32_1pl2_23\n"
6328                 "%var2           = OpVariable %fp_f32 Function\n"
6329                 "%red            = OpCompositeExtract %f32 %param 0\n"
6330                 "%plus_red       = OpFAdd %f32 %c_f32_1mi2_23 %red\n"
6331                 "                  OpStore %var2 %plus_red\n"
6332                 "%val1           = OpLoad %f32 %var1\n"
6333                 "%val2           = OpLoad %f32 %var2\n"
6334                 "%mul            = OpFMul %f32 %val1 %val2\n"
6335                 "%add            = OpFAdd %f32 %mul %c_f32_n1\n"
6336                 "%is0            = OpFOrdEqual %bool %add %c_f32_0\n"
6337                 "%isn1n24         = OpFOrdEqual %bool %add %c_f32_n1pn24\n"
6338                 "%success        = OpLogicalOr %bool %is0 %isn1n24\n"
6339                 "%v4success      = OpCompositeConstruct %v4bool %success %success %success %success\n"
6340                 "%ret            = OpSelect %v4f32 %v4success %c_vec4_0 %c_vec4_1\n"
6341                 "                  OpReturnValue %ret\n"
6342                 "                  OpFunctionEnd\n";
6343
6344         struct CaseNameDecoration
6345         {
6346                 string name;
6347                 string decoration;
6348         };
6349
6350
6351         CaseNameDecoration tests[] = {
6352                 {"multiplication",      "OpDecorate %mul NoContraction"},
6353                 {"addition",            "OpDecorate %add NoContraction"},
6354                 {"both",                        "OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"},
6355         };
6356
6357         getHalfColorsFullAlpha(inputColors);
6358
6359         for (deUint8 idx = 0; idx < 4; ++idx)
6360         {
6361                 inputColors[idx].setRed(0);
6362                 outputColors[idx] = RGBA(0, 0, 0, 255);
6363         }
6364
6365         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(CaseNameDecoration); ++testNdx)
6366         {
6367                 map<string, string> fragments;
6368
6369                 fragments["decoration"] = tests[testNdx].decoration;
6370                 fragments["pre_main"] = constantsAndTypes;
6371                 fragments["testfun"] = function;
6372
6373                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, group.get());
6374         }
6375
6376         return group.release();
6377 }
6378
6379 tcu::TestCaseGroup* createMemoryAccessTests(tcu::TestContext& testCtx)
6380 {
6381         de::MovePtr<tcu::TestCaseGroup> memoryAccessTests (new tcu::TestCaseGroup(testCtx, "opmemoryaccess", "Memory Semantics"));
6382         RGBA                                                    colors[4];
6383
6384         const char                                              constantsAndTypes[]      =
6385                 "%c_a2f32_1         = OpConstantComposite %a2f32 %c_f32_1 %c_f32_1\n"
6386                 "%fp_a2f32          = OpTypePointer Function %a2f32\n"
6387                 "%stype             = OpTypeStruct  %v4f32 %a2f32 %f32\n"
6388                 "%fp_stype          = OpTypePointer Function %stype\n";
6389
6390         const char                                              function[]       =
6391                 "%test_code         = OpFunction %v4f32 None %v4f32_function\n"
6392                 "%param1            = OpFunctionParameter %v4f32\n"
6393                 "%lbl               = OpLabel\n"
6394                 "%v1                = OpVariable %fp_v4f32 Function\n"
6395                 "%v2                = OpVariable %fp_a2f32 Function\n"
6396                 "%v3                = OpVariable %fp_f32 Function\n"
6397                 "%v                 = OpVariable %fp_stype Function\n"
6398                 "%vv                = OpVariable %fp_stype Function\n"
6399                 "%vvv               = OpVariable %fp_f32 Function\n"
6400
6401                 "                     OpStore %v1 %c_v4f32_1_1_1_1\n"
6402                 "                     OpStore %v2 %c_a2f32_1\n"
6403                 "                     OpStore %v3 %c_f32_1\n"
6404
6405                 "%p_v4f32          = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
6406                 "%p_a2f32          = OpAccessChain %fp_a2f32 %v %c_u32_1\n"
6407                 "%p_f32            = OpAccessChain %fp_f32 %v %c_u32_2\n"
6408                 "%v1_v             = OpLoad %v4f32 %v1 ${access_type}\n"
6409                 "%v2_v             = OpLoad %a2f32 %v2 ${access_type}\n"
6410                 "%v3_v             = OpLoad %f32 %v3 ${access_type}\n"
6411
6412                 "                    OpStore %p_v4f32 %v1_v ${access_type}\n"
6413                 "                    OpStore %p_a2f32 %v2_v ${access_type}\n"
6414                 "                    OpStore %p_f32 %v3_v ${access_type}\n"
6415
6416                 "                    OpCopyMemory %vv %v ${access_type}\n"
6417                 "                    OpCopyMemory %vvv %p_f32 ${access_type}\n"
6418
6419                 "%p_f32_2          = OpAccessChain %fp_f32 %vv %c_u32_2\n"
6420                 "%v_f32_2          = OpLoad %f32 %p_f32_2\n"
6421                 "%v_f32_3          = OpLoad %f32 %vvv\n"
6422
6423                 "%ret1             = OpVectorTimesScalar %v4f32 %param1 %v_f32_2\n"
6424                 "%ret2             = OpVectorTimesScalar %v4f32 %ret1 %v_f32_3\n"
6425                 "                    OpReturnValue %ret2\n"
6426                 "                    OpFunctionEnd\n";
6427
6428         struct NameMemoryAccess
6429         {
6430                 string name;
6431                 string accessType;
6432         };
6433
6434
6435         NameMemoryAccess tests[] =
6436         {
6437                 { "none", "" },
6438                 { "volatile", "Volatile" },
6439                 { "aligned",  "Aligned 1" },
6440                 { "volatile_aligned",  "Volatile|Aligned 1" },
6441                 { "nontemporal_aligned",  "Nontemporal|Aligned 1" },
6442                 { "volatile_nontemporal",  "Volatile|Nontemporal" },
6443                 { "volatile_nontermporal_aligned",  "Volatile|Nontemporal|Aligned 1" },
6444         };
6445
6446         getHalfColorsFullAlpha(colors);
6447
6448         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameMemoryAccess); ++testNdx)
6449         {
6450                 map<string, string> fragments;
6451                 map<string, string> memoryAccess;
6452                 memoryAccess["access_type"] = tests[testNdx].accessType;
6453
6454                 fragments["pre_main"] = constantsAndTypes;
6455                 fragments["testfun"] = tcu::StringTemplate(function).specialize(memoryAccess);
6456                 createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, memoryAccessTests.get());
6457         }
6458         return memoryAccessTests.release();
6459 }
6460 tcu::TestCaseGroup* createOpUndefTests(tcu::TestContext& testCtx)
6461 {
6462         de::MovePtr<tcu::TestCaseGroup>         opUndefTests             (new tcu::TestCaseGroup(testCtx, "opundef", "Test OpUndef"));
6463         RGBA                                                            defaultColors[4];
6464         map<string, string>                                     fragments;
6465         getDefaultColors(defaultColors);
6466
6467         // First, simple cases that don't do anything with the OpUndef result.
6468         struct NameCodePair { string name, decl, type; };
6469         const NameCodePair tests[] =
6470         {
6471                 {"bool", "", "%bool"},
6472                 {"vec2uint32", "", "%v2u32"},
6473                 {"image", "%type = OpTypeImage %f32 2D 0 0 0 1 Unknown", "%type"},
6474                 {"sampler", "%type = OpTypeSampler", "%type"},
6475                 {"sampledimage", "%img = OpTypeImage %f32 2D 0 0 0 1 Unknown\n" "%type = OpTypeSampledImage %img", "%type"},
6476                 {"pointer", "", "%fp_i32"},
6477                 {"runtimearray", "%type = OpTypeRuntimeArray %f32", "%type"},
6478                 {"array", "%c_u32_100 = OpConstant %u32 100\n" "%type = OpTypeArray %i32 %c_u32_100", "%type"},
6479                 {"struct", "%type = OpTypeStruct %f32 %i32 %u32", "%type"}};
6480         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
6481         {
6482                 fragments["undef_type"] = tests[testNdx].type;
6483                 fragments["testfun"] = StringTemplate(
6484                         "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6485                         "%param1 = OpFunctionParameter %v4f32\n"
6486                         "%label_testfun = OpLabel\n"
6487                         "%undef = OpUndef ${undef_type}\n"
6488                         "OpReturnValue %param1\n"
6489                         "OpFunctionEnd\n").specialize(fragments);
6490                 fragments["pre_main"] = tests[testNdx].decl;
6491                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opUndefTests.get());
6492         }
6493         fragments.clear();
6494
6495         fragments["testfun"] =
6496                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6497                 "%param1 = OpFunctionParameter %v4f32\n"
6498                 "%label_testfun = OpLabel\n"
6499                 "%undef = OpUndef %f32\n"
6500                 "%zero = OpFMul %f32 %undef %c_f32_0\n"
6501                 "%is_nan = OpIsNan %bool %zero\n" //OpUndef may result in NaN which may turn %zero into Nan.
6502                 "%actually_zero = OpSelect %f32 %is_nan %c_f32_0 %zero\n"
6503                 "%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
6504                 "%b = OpFAdd %f32 %a %actually_zero\n"
6505                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %b %c_i32_0\n"
6506                 "OpReturnValue %ret\n"
6507                 "OpFunctionEnd\n";
6508
6509         createTestsForAllStages("float32", defaultColors, defaultColors, fragments, opUndefTests.get());
6510
6511         fragments["testfun"] =
6512                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6513                 "%param1 = OpFunctionParameter %v4f32\n"
6514                 "%label_testfun = OpLabel\n"
6515                 "%undef = OpUndef %i32\n"
6516                 "%zero = OpIMul %i32 %undef %c_i32_0\n"
6517                 "%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
6518                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
6519                 "OpReturnValue %ret\n"
6520                 "OpFunctionEnd\n";
6521
6522         createTestsForAllStages("sint32", defaultColors, defaultColors, fragments, opUndefTests.get());
6523
6524         fragments["testfun"] =
6525                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6526                 "%param1 = OpFunctionParameter %v4f32\n"
6527                 "%label_testfun = OpLabel\n"
6528                 "%undef = OpUndef %u32\n"
6529                 "%zero = OpIMul %u32 %undef %c_i32_0\n"
6530                 "%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
6531                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
6532                 "OpReturnValue %ret\n"
6533                 "OpFunctionEnd\n";
6534
6535         createTestsForAllStages("uint32", defaultColors, defaultColors, fragments, opUndefTests.get());
6536
6537         fragments["testfun"] =
6538                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6539                 "%param1 = OpFunctionParameter %v4f32\n"
6540                 "%label_testfun = OpLabel\n"
6541                 "%undef = OpUndef %v4f32\n"
6542                 "%vzero = OpVectorTimesScalar %v4f32 %undef %c_f32_0\n"
6543                 "%zero_0 = OpVectorExtractDynamic %f32 %vzero %c_i32_0\n"
6544                 "%zero_1 = OpVectorExtractDynamic %f32 %vzero %c_i32_1\n"
6545                 "%zero_2 = OpVectorExtractDynamic %f32 %vzero %c_i32_2\n"
6546                 "%zero_3 = OpVectorExtractDynamic %f32 %vzero %c_i32_3\n"
6547                 "%is_nan_0 = OpIsNan %bool %zero_0\n"
6548                 "%is_nan_1 = OpIsNan %bool %zero_1\n"
6549                 "%is_nan_2 = OpIsNan %bool %zero_2\n"
6550                 "%is_nan_3 = OpIsNan %bool %zero_3\n"
6551                 "%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
6552                 "%actually_zero_1 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_1\n"
6553                 "%actually_zero_2 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_2\n"
6554                 "%actually_zero_3 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_3\n"
6555                 "%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
6556                 "%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
6557                 "%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
6558                 "%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
6559                 "%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
6560                 "%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
6561                 "%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
6562                 "%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
6563                 "%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
6564                 "%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
6565                 "%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
6566                 "%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
6567                 "OpReturnValue %ret\n"
6568                 "OpFunctionEnd\n";
6569
6570         createTestsForAllStages("vec4float32", defaultColors, defaultColors, fragments, opUndefTests.get());
6571
6572         fragments["pre_main"] =
6573                 "%m2x2f32 = OpTypeMatrix %v2f32 2\n";
6574         fragments["testfun"] =
6575                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6576                 "%param1 = OpFunctionParameter %v4f32\n"
6577                 "%label_testfun = OpLabel\n"
6578                 "%undef = OpUndef %m2x2f32\n"
6579                 "%mzero = OpMatrixTimesScalar %m2x2f32 %undef %c_f32_0\n"
6580                 "%zero_0 = OpCompositeExtract %f32 %mzero 0 0\n"
6581                 "%zero_1 = OpCompositeExtract %f32 %mzero 0 1\n"
6582                 "%zero_2 = OpCompositeExtract %f32 %mzero 1 0\n"
6583                 "%zero_3 = OpCompositeExtract %f32 %mzero 1 1\n"
6584                 "%is_nan_0 = OpIsNan %bool %zero_0\n"
6585                 "%is_nan_1 = OpIsNan %bool %zero_1\n"
6586                 "%is_nan_2 = OpIsNan %bool %zero_2\n"
6587                 "%is_nan_3 = OpIsNan %bool %zero_3\n"
6588                 "%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
6589                 "%actually_zero_1 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_1\n"
6590                 "%actually_zero_2 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_2\n"
6591                 "%actually_zero_3 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_3\n"
6592                 "%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
6593                 "%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
6594                 "%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
6595                 "%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
6596                 "%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
6597                 "%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
6598                 "%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
6599                 "%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
6600                 "%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
6601                 "%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
6602                 "%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
6603                 "%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
6604                 "OpReturnValue %ret\n"
6605                 "OpFunctionEnd\n";
6606
6607         createTestsForAllStages("matrix", defaultColors, defaultColors, fragments, opUndefTests.get());
6608
6609         return opUndefTests.release();
6610 }
6611
6612 void createOpQuantizeSingleOptionTests(tcu::TestCaseGroup* testCtx)
6613 {
6614         const RGBA              inputColors[4]          =
6615         {
6616                 RGBA(0,         0,              0,              255),
6617                 RGBA(0,         0,              255,    255),
6618                 RGBA(0,         255,    0,              255),
6619                 RGBA(0,         255,    255,    255)
6620         };
6621
6622         const RGBA              expectedColors[4]       =
6623         {
6624                 RGBA(255,        0,              0,              255),
6625                 RGBA(255,        0,              0,              255),
6626                 RGBA(255,        0,              0,              255),
6627                 RGBA(255,        0,              0,              255)
6628         };
6629
6630         const struct SingleFP16Possibility
6631         {
6632                 const char* name;
6633                 const char* constant;  // Value to assign to %test_constant.
6634                 float           valueAsFloat;
6635                 const char* condition; // Must assign to %cond an expression that evaluates to true after %c = OpQuantizeToF16(%test_constant + 0).
6636         }                               tests[]                         =
6637         {
6638                 {
6639                         "negative",
6640                         "-0x1.3p1\n",
6641                         -constructNormalizedFloat(1, 0x300000),
6642                         "%cond = OpFOrdEqual %bool %c %test_constant\n"
6643                 }, // -19
6644                 {
6645                         "positive",
6646                         "0x1.0p7\n",
6647                         constructNormalizedFloat(7, 0x000000),
6648                         "%cond = OpFOrdEqual %bool %c %test_constant\n"
6649                 },  // +128
6650                 // SPIR-V requires that OpQuantizeToF16 flushes
6651                 // any numbers that would end up denormalized in F16 to zero.
6652                 {
6653                         "denorm",
6654                         "0x0.0006p-126\n",
6655                         std::ldexp(1.5f, -140),
6656                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
6657                 },  // denorm
6658                 {
6659                         "negative_denorm",
6660                         "-0x0.0006p-126\n",
6661                         -std::ldexp(1.5f, -140),
6662                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
6663                 }, // -denorm
6664                 {
6665                         "too_small",
6666                         "0x1.0p-16\n",
6667                         std::ldexp(1.0f, -16),
6668                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
6669                 },     // too small positive
6670                 {
6671                         "negative_too_small",
6672                         "-0x1.0p-32\n",
6673                         -std::ldexp(1.0f, -32),
6674                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
6675                 },      // too small negative
6676                 {
6677                         "negative_inf",
6678                         "-0x1.0p128\n",
6679                         -std::ldexp(1.0f, 128),
6680
6681                         "%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
6682                         "%inf = OpIsInf %bool %c\n"
6683                         "%cond = OpLogicalAnd %bool %gz %inf\n"
6684                 },     // -inf to -inf
6685                 {
6686                         "inf",
6687                         "0x1.0p128\n",
6688                         std::ldexp(1.0f, 128),
6689
6690                         "%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
6691                         "%inf = OpIsInf %bool %c\n"
6692                         "%cond = OpLogicalAnd %bool %gz %inf\n"
6693                 },     // +inf to +inf
6694                 {
6695                         "round_to_negative_inf",
6696                         "-0x1.0p32\n",
6697                         -std::ldexp(1.0f, 32),
6698
6699                         "%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
6700                         "%inf = OpIsInf %bool %c\n"
6701                         "%cond = OpLogicalAnd %bool %gz %inf\n"
6702                 },     // round to -inf
6703                 {
6704                         "round_to_inf",
6705                         "0x1.0p16\n",
6706                         std::ldexp(1.0f, 16),
6707
6708                         "%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
6709                         "%inf = OpIsInf %bool %c\n"
6710                         "%cond = OpLogicalAnd %bool %gz %inf\n"
6711                 },     // round to +inf
6712                 {
6713                         "nan",
6714                         "0x1.1p128\n",
6715                         std::numeric_limits<float>::quiet_NaN(),
6716
6717                         // Test for any NaN value, as NaNs are not preserved
6718                         "%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
6719                         "%cond = OpIsNan %bool %direct_quant\n"
6720                 }, // nan
6721                 {
6722                         "negative_nan",
6723                         "-0x1.0001p128\n",
6724                         std::numeric_limits<float>::quiet_NaN(),
6725
6726                         // Test for any NaN value, as NaNs are not preserved
6727                         "%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
6728                         "%cond = OpIsNan %bool %direct_quant\n"
6729                 } // -nan
6730         };
6731         const char*             constants                       =
6732                 "%test_constant = OpConstant %f32 ";  // The value will be test.constant.
6733
6734         StringTemplate  function                        (
6735                 "%test_code     = OpFunction %v4f32 None %v4f32_function\n"
6736                 "%param1        = OpFunctionParameter %v4f32\n"
6737                 "%label_testfun = OpLabel\n"
6738                 "%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
6739                 "%b             = OpFAdd %f32 %test_constant %a\n"
6740                 "%c             = OpQuantizeToF16 %f32 %b\n"
6741                 "${condition}\n"
6742                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
6743                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
6744                 "                 OpReturnValue %retval\n"
6745                 "OpFunctionEnd\n"
6746         );
6747
6748         const char*             specDecorations         = "OpDecorate %test_constant SpecId 0\n";
6749         const char*             specConstants           =
6750                         "%test_constant = OpSpecConstant %f32 0.\n"
6751                         "%c             = OpSpecConstantOp %f32 QuantizeToF16 %test_constant\n";
6752
6753         StringTemplate  specConstantFunction(
6754                 "%test_code     = OpFunction %v4f32 None %v4f32_function\n"
6755                 "%param1        = OpFunctionParameter %v4f32\n"
6756                 "%label_testfun = OpLabel\n"
6757                 "${condition}\n"
6758                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
6759                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
6760                 "                 OpReturnValue %retval\n"
6761                 "OpFunctionEnd\n"
6762         );
6763
6764         for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
6765         {
6766                 map<string, string>                                                             codeSpecialization;
6767                 map<string, string>                                                             fragments;
6768                 codeSpecialization["condition"]                                 = tests[idx].condition;
6769                 fragments["testfun"]                                                    = function.specialize(codeSpecialization);
6770                 fragments["pre_main"]                                                   = string(constants) + tests[idx].constant + "\n";
6771                 createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
6772         }
6773
6774         for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
6775         {
6776                 map<string, string>                                                             codeSpecialization;
6777                 map<string, string>                                                             fragments;
6778                 vector<deInt32>                                                                 passConstants;
6779                 deInt32                                                                                 specConstant;
6780
6781                 codeSpecialization["condition"]                                 = tests[idx].condition;
6782                 fragments["testfun"]                                                    = specConstantFunction.specialize(codeSpecialization);
6783                 fragments["decoration"]                                                 = specDecorations;
6784                 fragments["pre_main"]                                                   = specConstants;
6785
6786                 memcpy(&specConstant, &tests[idx].valueAsFloat, sizeof(float));
6787                 passConstants.push_back(specConstant);
6788
6789                 createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
6790         }
6791 }
6792
6793 void createOpQuantizeTwoPossibilityTests(tcu::TestCaseGroup* testCtx)
6794 {
6795         RGBA inputColors[4] =  {
6796                 RGBA(0,         0,              0,              255),
6797                 RGBA(0,         0,              255,    255),
6798                 RGBA(0,         255,    0,              255),
6799                 RGBA(0,         255,    255,    255)
6800         };
6801
6802         RGBA expectedColors[4] =
6803         {
6804                 RGBA(255,        0,              0,              255),
6805                 RGBA(255,        0,              0,              255),
6806                 RGBA(255,        0,              0,              255),
6807                 RGBA(255,        0,              0,              255)
6808         };
6809
6810         struct DualFP16Possibility
6811         {
6812                 const char* name;
6813                 const char* input;
6814                 float           inputAsFloat;
6815                 const char* possibleOutput1;
6816                 const char* possibleOutput2;
6817         } tests[] = {
6818                 {
6819                         "positive_round_up_or_round_down",
6820                         "0x1.3003p8",
6821                         constructNormalizedFloat(8, 0x300300),
6822                         "0x1.304p8",
6823                         "0x1.3p8"
6824                 },
6825                 {
6826                         "negative_round_up_or_round_down",
6827                         "-0x1.6008p-7",
6828                         -constructNormalizedFloat(-7, 0x600800),
6829                         "-0x1.6p-7",
6830                         "-0x1.604p-7"
6831                 },
6832                 {
6833                         "carry_bit",
6834                         "0x1.01ep2",
6835                         constructNormalizedFloat(2, 0x01e000),
6836                         "0x1.01cp2",
6837                         "0x1.02p2"
6838                 },
6839                 {
6840                         "carry_to_exponent",
6841                         "0x1.ffep1",
6842                         constructNormalizedFloat(1, 0xffe000),
6843                         "0x1.ffcp1",
6844                         "0x1.0p2"
6845                 },
6846         };
6847         StringTemplate constants (
6848                 "%input_const = OpConstant %f32 ${input}\n"
6849                 "%possible_solution1 = OpConstant %f32 ${output1}\n"
6850                 "%possible_solution2 = OpConstant %f32 ${output2}\n"
6851                 );
6852
6853         StringTemplate specConstants (
6854                 "%input_const = OpSpecConstant %f32 0.\n"
6855                 "%possible_solution1 = OpConstant %f32 ${output1}\n"
6856                 "%possible_solution2 = OpConstant %f32 ${output2}\n"
6857         );
6858
6859         const char* specDecorations = "OpDecorate %input_const  SpecId 0\n";
6860
6861         const char* function  =
6862                 "%test_code     = OpFunction %v4f32 None %v4f32_function\n"
6863                 "%param1        = OpFunctionParameter %v4f32\n"
6864                 "%label_testfun = OpLabel\n"
6865                 "%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
6866                 // For the purposes of this test we assume that 0.f will always get
6867                 // faithfully passed through the pipeline stages.
6868                 "%b             = OpFAdd %f32 %input_const %a\n"
6869                 "%c             = OpQuantizeToF16 %f32 %b\n"
6870                 "%eq_1          = OpFOrdEqual %bool %c %possible_solution1\n"
6871                 "%eq_2          = OpFOrdEqual %bool %c %possible_solution2\n"
6872                 "%cond          = OpLogicalOr %bool %eq_1 %eq_2\n"
6873                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
6874                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1"
6875                 "                 OpReturnValue %retval\n"
6876                 "OpFunctionEnd\n";
6877
6878         for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
6879                 map<string, string>                                                                     fragments;
6880                 map<string, string>                                                                     constantSpecialization;
6881
6882                 constantSpecialization["input"]                                         = tests[idx].input;
6883                 constantSpecialization["output1"]                                       = tests[idx].possibleOutput1;
6884                 constantSpecialization["output2"]                                       = tests[idx].possibleOutput2;
6885                 fragments["testfun"]                                                            = function;
6886                 fragments["pre_main"]                                                           = constants.specialize(constantSpecialization);
6887                 createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
6888         }
6889
6890         for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
6891                 map<string, string>                                                                     fragments;
6892                 map<string, string>                                                                     constantSpecialization;
6893                 vector<deInt32>                                                                         passConstants;
6894                 deInt32                                                                                         specConstant;
6895
6896                 constantSpecialization["output1"]                                       = tests[idx].possibleOutput1;
6897                 constantSpecialization["output2"]                                       = tests[idx].possibleOutput2;
6898                 fragments["testfun"]                                                            = function;
6899                 fragments["decoration"]                                                         = specDecorations;
6900                 fragments["pre_main"]                                                           = specConstants.specialize(constantSpecialization);
6901
6902                 memcpy(&specConstant, &tests[idx].inputAsFloat, sizeof(float));
6903                 passConstants.push_back(specConstant);
6904
6905                 createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
6906         }
6907 }
6908
6909 tcu::TestCaseGroup* createOpQuantizeTests(tcu::TestContext& testCtx)
6910 {
6911         de::MovePtr<tcu::TestCaseGroup> opQuantizeTests (new tcu::TestCaseGroup(testCtx, "opquantize", "Test OpQuantizeToF16"));
6912         createOpQuantizeSingleOptionTests(opQuantizeTests.get());
6913         createOpQuantizeTwoPossibilityTests(opQuantizeTests.get());
6914         return opQuantizeTests.release();
6915 }
6916
6917 struct ShaderPermutation
6918 {
6919         deUint8 vertexPermutation;
6920         deUint8 geometryPermutation;
6921         deUint8 tesscPermutation;
6922         deUint8 tessePermutation;
6923         deUint8 fragmentPermutation;
6924 };
6925
6926 ShaderPermutation getShaderPermutation(deUint8 inputValue)
6927 {
6928         ShaderPermutation       permutation =
6929         {
6930                 static_cast<deUint8>(inputValue & 0x10? 1u: 0u),
6931                 static_cast<deUint8>(inputValue & 0x08? 1u: 0u),
6932                 static_cast<deUint8>(inputValue & 0x04? 1u: 0u),
6933                 static_cast<deUint8>(inputValue & 0x02? 1u: 0u),
6934                 static_cast<deUint8>(inputValue & 0x01? 1u: 0u)
6935         };
6936         return permutation;
6937 }
6938
6939 tcu::TestCaseGroup* createModuleTests(tcu::TestContext& testCtx)
6940 {
6941         RGBA                                                            defaultColors[4];
6942         RGBA                                                            invertedColors[4];
6943         de::MovePtr<tcu::TestCaseGroup>         moduleTests                     (new tcu::TestCaseGroup(testCtx, "module", "Multiple entry points into shaders"));
6944
6945         const ShaderElement                                     combinedPipeline[]      =
6946         {
6947                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
6948                 ShaderElement("module", "main", VK_SHADER_STAGE_GEOMETRY_BIT),
6949                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
6950                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
6951                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
6952         };
6953
6954         getDefaultColors(defaultColors);
6955         getInvertedDefaultColors(invertedColors);
6956         addFunctionCaseWithPrograms<InstanceContext>(
6957                         moduleTests.get(), "same_module", "", createCombinedModule, runAndVerifyDefaultPipeline,
6958                         createInstanceContext(combinedPipeline, map<string, string>()));
6959
6960         const char* numbers[] =
6961         {
6962                 "1", "2"
6963         };
6964
6965         for (deInt8 idx = 0; idx < 32; ++idx)
6966         {
6967                 ShaderPermutation                       permutation             = getShaderPermutation(idx);
6968                 string                                          name                    = string("vert") + numbers[permutation.vertexPermutation] + "_geom" + numbers[permutation.geometryPermutation] + "_tessc" + numbers[permutation.tesscPermutation] + "_tesse" + numbers[permutation.tessePermutation] + "_frag" + numbers[permutation.fragmentPermutation];
6969                 const ShaderElement                     pipeline[]              =
6970                 {
6971                         ShaderElement("vert",   string("vert") +        numbers[permutation.vertexPermutation],         VK_SHADER_STAGE_VERTEX_BIT),
6972                         ShaderElement("geom",   string("geom") +        numbers[permutation.geometryPermutation],       VK_SHADER_STAGE_GEOMETRY_BIT),
6973                         ShaderElement("tessc",  string("tessc") +       numbers[permutation.tesscPermutation],          VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
6974                         ShaderElement("tesse",  string("tesse") +       numbers[permutation.tessePermutation],          VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
6975                         ShaderElement("frag",   string("frag") +        numbers[permutation.fragmentPermutation],       VK_SHADER_STAGE_FRAGMENT_BIT)
6976                 };
6977
6978                 // If there are an even number of swaps, then it should be no-op.
6979                 // If there are an odd number, the color should be flipped.
6980                 if ((permutation.vertexPermutation + permutation.geometryPermutation + permutation.tesscPermutation + permutation.tessePermutation + permutation.fragmentPermutation) % 2 == 0)
6981                 {
6982                         addFunctionCaseWithPrograms<InstanceContext>(
6983                                         moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline,
6984                                         createInstanceContext(pipeline, defaultColors, defaultColors, map<string, string>()));
6985                 }
6986                 else
6987                 {
6988                         addFunctionCaseWithPrograms<InstanceContext>(
6989                                         moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline,
6990                                         createInstanceContext(pipeline, defaultColors, invertedColors, map<string, string>()));
6991                 }
6992         }
6993         return moduleTests.release();
6994 }
6995
6996 tcu::TestCaseGroup* createLoopTests(tcu::TestContext& testCtx)
6997 {
6998         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "loop", "Looping control flow"));
6999         RGBA defaultColors[4];
7000         getDefaultColors(defaultColors);
7001         map<string, string> fragments;
7002         fragments["pre_main"] =
7003                 "%c_f32_5 = OpConstant %f32 5.\n";
7004
7005         // A loop with a single block. The Continue Target is the loop block
7006         // itself. In SPIR-V terms, the "loop construct" contains no blocks at all
7007         // -- the "continue construct" forms the entire loop.
7008         fragments["testfun"] =
7009                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7010                 "%param1 = OpFunctionParameter %v4f32\n"
7011
7012                 "%entry = OpLabel\n"
7013                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7014                 "OpBranch %loop\n"
7015
7016                 ";adds and subtracts 1.0 to %val in alternate iterations\n"
7017                 "%loop = OpLabel\n"
7018                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
7019                 "%delta = OpPhi %f32 %c_f32_1 %entry %minus_delta %loop\n"
7020                 "%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
7021                 "%val = OpFAdd %f32 %val1 %delta\n"
7022                 "%minus_delta = OpFSub %f32 %c_f32_0 %delta\n"
7023                 "%count__ = OpISub %i32 %count %c_i32_1\n"
7024                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
7025                 "OpLoopMerge %exit %loop None\n"
7026                 "OpBranchConditional %again %loop %exit\n"
7027
7028                 "%exit = OpLabel\n"
7029                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
7030                 "OpReturnValue %result\n"
7031
7032                 "OpFunctionEnd\n";
7033
7034         createTestsForAllStages("single_block", defaultColors, defaultColors, fragments, testGroup.get());
7035
7036         // Body comprised of multiple basic blocks.
7037         const StringTemplate multiBlock(
7038                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7039                 "%param1 = OpFunctionParameter %v4f32\n"
7040
7041                 "%entry = OpLabel\n"
7042                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7043                 "OpBranch %loop\n"
7044
7045                 ";adds and subtracts 1.0 to %val in alternate iterations\n"
7046                 "%loop = OpLabel\n"
7047                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %gather\n"
7048                 "%delta = OpPhi %f32 %c_f32_1 %entry %delta_next %gather\n"
7049                 "%val1 = OpPhi %f32 %val0 %entry %val %gather\n"
7050                 // There are several possibilities for the Continue Target below.  Each
7051                 // will be specialized into a separate test case.
7052                 "OpLoopMerge %exit ${continue_target} None\n"
7053                 "OpBranch %if\n"
7054
7055                 "%if = OpLabel\n"
7056                 ";delta_next = (delta > 0) ? -1 : 1;\n"
7057                 "%gt0 = OpFOrdGreaterThan %bool %delta %c_f32_0\n"
7058                 "OpSelectionMerge %gather DontFlatten\n"
7059                 "OpBranchConditional %gt0 %even %odd ;tells us if %count is even or odd\n"
7060
7061                 "%odd = OpLabel\n"
7062                 "OpBranch %gather\n"
7063
7064                 "%even = OpLabel\n"
7065                 "OpBranch %gather\n"
7066
7067                 "%gather = OpLabel\n"
7068                 "%delta_next = OpPhi %f32 %c_f32_n1 %even %c_f32_1 %odd\n"
7069                 "%val = OpFAdd %f32 %val1 %delta\n"
7070                 "%count__ = OpISub %i32 %count %c_i32_1\n"
7071                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
7072                 "OpBranchConditional %again %loop %exit\n"
7073
7074                 "%exit = OpLabel\n"
7075                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
7076                 "OpReturnValue %result\n"
7077
7078                 "OpFunctionEnd\n");
7079
7080         map<string, string> continue_target;
7081
7082         // The Continue Target is the loop block itself.
7083         continue_target["continue_target"] = "%loop";
7084         fragments["testfun"] = multiBlock.specialize(continue_target);
7085         createTestsForAllStages("multi_block_continue_construct", defaultColors, defaultColors, fragments, testGroup.get());
7086
7087         // The Continue Target is at the end of the loop.
7088         continue_target["continue_target"] = "%gather";
7089         fragments["testfun"] = multiBlock.specialize(continue_target);
7090         createTestsForAllStages("multi_block_loop_construct", defaultColors, defaultColors, fragments, testGroup.get());
7091
7092         // A loop with continue statement.
7093         fragments["testfun"] =
7094                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7095                 "%param1 = OpFunctionParameter %v4f32\n"
7096
7097                 "%entry = OpLabel\n"
7098                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7099                 "OpBranch %loop\n"
7100
7101                 ";adds 4, 3, and 1 to %val0 (skips 2)\n"
7102                 "%loop = OpLabel\n"
7103                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
7104                 "%val1 = OpPhi %f32 %val0 %entry %val %continue\n"
7105                 "OpLoopMerge %exit %continue None\n"
7106                 "OpBranch %if\n"
7107
7108                 "%if = OpLabel\n"
7109                 ";skip if %count==2\n"
7110                 "%eq2 = OpIEqual %bool %count %c_i32_2\n"
7111                 "OpSelectionMerge %continue DontFlatten\n"
7112                 "OpBranchConditional %eq2 %continue %body\n"
7113
7114                 "%body = OpLabel\n"
7115                 "%fcount = OpConvertSToF %f32 %count\n"
7116                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
7117                 "OpBranch %continue\n"
7118
7119                 "%continue = OpLabel\n"
7120                 "%val = OpPhi %f32 %val2 %body %val1 %if\n"
7121                 "%count__ = OpISub %i32 %count %c_i32_1\n"
7122                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
7123                 "OpBranchConditional %again %loop %exit\n"
7124
7125                 "%exit = OpLabel\n"
7126                 "%same = OpFSub %f32 %val %c_f32_8\n"
7127                 "%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
7128                 "OpReturnValue %result\n"
7129                 "OpFunctionEnd\n";
7130         createTestsForAllStages("continue", defaultColors, defaultColors, fragments, testGroup.get());
7131
7132         // A loop with break.
7133         fragments["testfun"] =
7134                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7135                 "%param1 = OpFunctionParameter %v4f32\n"
7136
7137                 "%entry = OpLabel\n"
7138                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
7139                 "%dot = OpDot %f32 %param1 %param1\n"
7140                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
7141                 "%zero = OpConvertFToU %u32 %div\n"
7142                 "%two = OpIAdd %i32 %zero %c_i32_2\n"
7143                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7144                 "OpBranch %loop\n"
7145
7146                 ";adds 4 and 3 to %val0 (exits early)\n"
7147                 "%loop = OpLabel\n"
7148                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
7149                 "%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
7150                 "OpLoopMerge %exit %continue None\n"
7151                 "OpBranch %if\n"
7152
7153                 "%if = OpLabel\n"
7154                 ";end loop if %count==%two\n"
7155                 "%above2 = OpSGreaterThan %bool %count %two\n"
7156                 "OpSelectionMerge %continue DontFlatten\n"
7157                 "OpBranchConditional %above2 %body %exit\n"
7158
7159                 "%body = OpLabel\n"
7160                 "%fcount = OpConvertSToF %f32 %count\n"
7161                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
7162                 "OpBranch %continue\n"
7163
7164                 "%continue = OpLabel\n"
7165                 "%count__ = OpISub %i32 %count %c_i32_1\n"
7166                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
7167                 "OpBranchConditional %again %loop %exit\n"
7168
7169                 "%exit = OpLabel\n"
7170                 "%val_post = OpPhi %f32 %val2 %continue %val1 %if\n"
7171                 "%same = OpFSub %f32 %val_post %c_f32_7\n"
7172                 "%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
7173                 "OpReturnValue %result\n"
7174                 "OpFunctionEnd\n";
7175         createTestsForAllStages("break", defaultColors, defaultColors, fragments, testGroup.get());
7176
7177         // A loop with return.
7178         fragments["testfun"] =
7179                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7180                 "%param1 = OpFunctionParameter %v4f32\n"
7181
7182                 "%entry = OpLabel\n"
7183                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
7184                 "%dot = OpDot %f32 %param1 %param1\n"
7185                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
7186                 "%zero = OpConvertFToU %u32 %div\n"
7187                 "%two = OpIAdd %i32 %zero %c_i32_2\n"
7188                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7189                 "OpBranch %loop\n"
7190
7191                 ";returns early without modifying %param1\n"
7192                 "%loop = OpLabel\n"
7193                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
7194                 "%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
7195                 "OpLoopMerge %exit %continue None\n"
7196                 "OpBranch %if\n"
7197
7198                 "%if = OpLabel\n"
7199                 ";return if %count==%two\n"
7200                 "%above2 = OpSGreaterThan %bool %count %two\n"
7201                 "OpSelectionMerge %continue DontFlatten\n"
7202                 "OpBranchConditional %above2 %body %early_exit\n"
7203
7204                 "%early_exit = OpLabel\n"
7205                 "OpReturnValue %param1\n"
7206
7207                 "%body = OpLabel\n"
7208                 "%fcount = OpConvertSToF %f32 %count\n"
7209                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
7210                 "OpBranch %continue\n"
7211
7212                 "%continue = OpLabel\n"
7213                 "%count__ = OpISub %i32 %count %c_i32_1\n"
7214                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
7215                 "OpBranchConditional %again %loop %exit\n"
7216
7217                 "%exit = OpLabel\n"
7218                 ";should never get here, so return an incorrect result\n"
7219                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val2 %c_i32_0\n"
7220                 "OpReturnValue %result\n"
7221                 "OpFunctionEnd\n";
7222         createTestsForAllStages("return", defaultColors, defaultColors, fragments, testGroup.get());
7223
7224         return testGroup.release();
7225 }
7226
7227 // A collection of tests putting OpControlBarrier in places GLSL forbids but SPIR-V allows.
7228 tcu::TestCaseGroup* createBarrierTests(tcu::TestContext& testCtx)
7229 {
7230         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "barrier", "OpControlBarrier"));
7231         map<string, string> fragments;
7232
7233         // A barrier inside a function body.
7234         fragments["pre_main"] =
7235                 "%Workgroup = OpConstant %i32 2\n"
7236                 "%SequentiallyConsistent = OpConstant %i32 0x10\n";
7237         fragments["testfun"] =
7238                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7239                 "%param1 = OpFunctionParameter %v4f32\n"
7240                 "%label_testfun = OpLabel\n"
7241                 "OpControlBarrier %Workgroup %Workgroup %SequentiallyConsistent\n"
7242                 "OpReturnValue %param1\n"
7243                 "OpFunctionEnd\n";
7244         addTessCtrlTest(testGroup.get(), "in_function", fragments);
7245
7246         // Common setup code for the following tests.
7247         fragments["pre_main"] =
7248                 "%Workgroup = OpConstant %i32 2\n"
7249                 "%SequentiallyConsistent = OpConstant %i32 0x10\n"
7250                 "%c_f32_5 = OpConstant %f32 5.\n";
7251         const string setupPercentZero =  // Begins %test_code function with code that sets %zero to 0u but cannot be optimized away.
7252                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7253                 "%param1 = OpFunctionParameter %v4f32\n"
7254                 "%entry = OpLabel\n"
7255                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
7256                 "%dot = OpDot %f32 %param1 %param1\n"
7257                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
7258                 "%zero = OpConvertFToU %u32 %div\n";
7259
7260         // Barriers inside OpSwitch branches.
7261         fragments["testfun"] =
7262                 setupPercentZero +
7263                 "OpSelectionMerge %switch_exit None\n"
7264                 "OpSwitch %zero %switch_default 0 %case0 1 %case1 ;should always go to %case0\n"
7265
7266                 "%case1 = OpLabel\n"
7267                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
7268                 "OpControlBarrier %Workgroup %Workgroup %SequentiallyConsistent\n"
7269                 "%wrong_branch_alert1 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
7270                 "OpBranch %switch_exit\n"
7271
7272                 "%switch_default = OpLabel\n"
7273                 "%wrong_branch_alert2 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
7274                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
7275                 "OpControlBarrier %Workgroup %Workgroup %SequentiallyConsistent\n"
7276                 "OpBranch %switch_exit\n"
7277
7278                 "%case0 = OpLabel\n"
7279                 "OpControlBarrier %Workgroup %Workgroup %SequentiallyConsistent\n"
7280                 "OpBranch %switch_exit\n"
7281
7282                 "%switch_exit = OpLabel\n"
7283                 "%ret = OpPhi %v4f32 %param1 %case0 %wrong_branch_alert1 %case1 %wrong_branch_alert2 %switch_default\n"
7284                 "OpReturnValue %ret\n"
7285                 "OpFunctionEnd\n";
7286         addTessCtrlTest(testGroup.get(), "in_switch", fragments);
7287
7288         // Barriers inside if-then-else.
7289         fragments["testfun"] =
7290                 setupPercentZero +
7291                 "%eq0 = OpIEqual %bool %zero %c_u32_0\n"
7292                 "OpSelectionMerge %exit DontFlatten\n"
7293                 "OpBranchConditional %eq0 %then %else\n"
7294
7295                 "%else = OpLabel\n"
7296                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
7297                 "OpControlBarrier %Workgroup %Workgroup %SequentiallyConsistent\n"
7298                 "%wrong_branch_alert = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
7299                 "OpBranch %exit\n"
7300
7301                 "%then = OpLabel\n"
7302                 "OpControlBarrier %Workgroup %Workgroup %SequentiallyConsistent\n"
7303                 "OpBranch %exit\n"
7304
7305                 "%exit = OpLabel\n"
7306                 "%ret = OpPhi %v4f32 %param1 %then %wrong_branch_alert %else\n"
7307                 "OpReturnValue %ret\n"
7308                 "OpFunctionEnd\n";
7309         addTessCtrlTest(testGroup.get(), "in_if", fragments);
7310
7311         // A barrier after control-flow reconvergence, tempting the compiler to attempt something like this:
7312         // http://lists.llvm.org/pipermail/llvm-dev/2009-October/026317.html.
7313         fragments["testfun"] =
7314                 setupPercentZero +
7315                 "%thread_id = OpLoad %i32 %BP_gl_InvocationID\n"
7316                 "%thread0 = OpIEqual %bool %thread_id %c_i32_0\n"
7317                 "OpSelectionMerge %exit DontFlatten\n"
7318                 "OpBranchConditional %thread0 %then %else\n"
7319
7320                 "%else = OpLabel\n"
7321                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7322                 "OpBranch %exit\n"
7323
7324                 "%then = OpLabel\n"
7325                 "%val1 = OpVectorExtractDynamic %f32 %param1 %zero\n"
7326                 "OpBranch %exit\n"
7327
7328                 "%exit = OpLabel\n"
7329                 "%val = OpPhi %f32 %val0 %else %val1 %then\n"
7330                 "OpControlBarrier %Workgroup %Workgroup %SequentiallyConsistent\n"
7331                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %val %zero\n"
7332                 "OpReturnValue %ret\n"
7333                 "OpFunctionEnd\n";
7334         addTessCtrlTest(testGroup.get(), "after_divergent_if", fragments);
7335
7336         // A barrier inside a loop.
7337         fragments["pre_main"] =
7338                 "%Workgroup = OpConstant %i32 2\n"
7339                 "%SequentiallyConsistent = OpConstant %i32 0x10\n"
7340                 "%c_f32_10 = OpConstant %f32 10.\n";
7341         fragments["testfun"] =
7342                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7343                 "%param1 = OpFunctionParameter %v4f32\n"
7344                 "%entry = OpLabel\n"
7345                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7346                 "OpBranch %loop\n"
7347
7348                 ";adds 4, 3, 2, and 1 to %val0\n"
7349                 "%loop = OpLabel\n"
7350                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
7351                 "%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
7352                 "OpControlBarrier %Workgroup %Workgroup %SequentiallyConsistent\n"
7353                 "%fcount = OpConvertSToF %f32 %count\n"
7354                 "%val = OpFAdd %f32 %val1 %fcount\n"
7355                 "%count__ = OpISub %i32 %count %c_i32_1\n"
7356                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
7357                 "OpLoopMerge %exit %loop None\n"
7358                 "OpBranchConditional %again %loop %exit\n"
7359
7360                 "%exit = OpLabel\n"
7361                 "%same = OpFSub %f32 %val %c_f32_10\n"
7362                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
7363                 "OpReturnValue %ret\n"
7364                 "OpFunctionEnd\n";
7365         addTessCtrlTest(testGroup.get(), "in_loop", fragments);
7366
7367         return testGroup.release();
7368 }
7369
7370 // Test for the OpFRem instruction.
7371 tcu::TestCaseGroup* createFRemTests(tcu::TestContext& testCtx)
7372 {
7373         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "frem", "OpFRem"));
7374         map<string, string>                                     fragments;
7375         RGBA                                                            inputColors[4];
7376         RGBA                                                            outputColors[4];
7377
7378         fragments["pre_main"]                            =
7379                 "%c_f32_3 = OpConstant %f32 3.0\n"
7380                 "%c_f32_n3 = OpConstant %f32 -3.0\n"
7381                 "%c_f32_4 = OpConstant %f32 4.0\n"
7382                 "%c_f32_p75 = OpConstant %f32 0.75\n"
7383                 "%c_v4f32_p75_p75_p75_p75 = OpConstantComposite %v4f32 %c_f32_p75 %c_f32_p75 %c_f32_p75 %c_f32_p75 \n"
7384                 "%c_v4f32_4_4_4_4 = OpConstantComposite %v4f32 %c_f32_4 %c_f32_4 %c_f32_4 %c_f32_4\n"
7385                 "%c_v4f32_3_n3_3_n3 = OpConstantComposite %v4f32 %c_f32_3 %c_f32_n3 %c_f32_3 %c_f32_n3\n";
7386
7387         // The test does the following.
7388         // vec4 result = (param1 * 8.0) - 4.0;
7389         // return (frem(result.x,3) + 0.75, frem(result.y, -3) + 0.75, 0, 1)
7390         fragments["testfun"]                             =
7391                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7392                 "%param1 = OpFunctionParameter %v4f32\n"
7393                 "%label_testfun = OpLabel\n"
7394                 "%v_times_8 = OpVectorTimesScalar %v4f32 %param1 %c_f32_8\n"
7395                 "%minus_4 = OpFSub %v4f32 %v_times_8 %c_v4f32_4_4_4_4\n"
7396                 "%frem = OpFRem %v4f32 %minus_4 %c_v4f32_3_n3_3_n3\n"
7397                 "%added = OpFAdd %v4f32 %frem %c_v4f32_p75_p75_p75_p75\n"
7398                 "%xyz_1 = OpVectorInsertDynamic %v4f32 %added %c_f32_1 %c_i32_3\n"
7399                 "%xy_0_1 = OpVectorInsertDynamic %v4f32 %xyz_1 %c_f32_0 %c_i32_2\n"
7400                 "OpReturnValue %xy_0_1\n"
7401                 "OpFunctionEnd\n";
7402
7403
7404         inputColors[0]          = RGBA(16,      16,             0, 255);
7405         inputColors[1]          = RGBA(232, 232,        0, 255);
7406         inputColors[2]          = RGBA(232, 16,         0, 255);
7407         inputColors[3]          = RGBA(16,      232,    0, 255);
7408
7409         outputColors[0]         = RGBA(64,      64,             0, 255);
7410         outputColors[1]         = RGBA(255, 255,        0, 255);
7411         outputColors[2]         = RGBA(255, 64,         0, 255);
7412         outputColors[3]         = RGBA(64,      255,    0, 255);
7413
7414         createTestsForAllStages("frem", inputColors, outputColors, fragments, testGroup.get());
7415         return testGroup.release();
7416 }
7417
7418 // Test for the OpSRem instruction.
7419 tcu::TestCaseGroup* createOpSRemGraphicsTests(tcu::TestContext& testCtx, qpTestResult negFailResult)
7420 {
7421         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "srem", "OpSRem"));
7422         map<string, string>                                     fragments;
7423
7424         fragments["pre_main"]                            =
7425                 "%c_f32_255 = OpConstant %f32 255.0\n"
7426                 "%c_i32_128 = OpConstant %i32 128\n"
7427                 "%c_i32_255 = OpConstant %i32 255\n"
7428                 "%c_v4f32_255 = OpConstantComposite %v4f32 %c_f32_255 %c_f32_255 %c_f32_255 %c_f32_255 \n"
7429                 "%c_v4f32_0_5 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 \n"
7430                 "%c_v4i32_128 = OpConstantComposite %v4i32 %c_i32_128 %c_i32_128 %c_i32_128 %c_i32_128 \n";
7431
7432         // The test does the following.
7433         // ivec4 ints = int(param1 * 255.0 + 0.5) - 128;
7434         // ivec4 result = ivec4(srem(ints.x, ints.y), srem(ints.y, ints.z), srem(ints.z, ints.x), 255);
7435         // return float(result + 128) / 255.0;
7436         fragments["testfun"]                             =
7437                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7438                 "%param1 = OpFunctionParameter %v4f32\n"
7439                 "%label_testfun = OpLabel\n"
7440                 "%div255 = OpFMul %v4f32 %param1 %c_v4f32_255\n"
7441                 "%add0_5 = OpFAdd %v4f32 %div255 %c_v4f32_0_5\n"
7442                 "%uints_in = OpConvertFToS %v4i32 %add0_5\n"
7443                 "%ints_in = OpISub %v4i32 %uints_in %c_v4i32_128\n"
7444                 "%x_in = OpCompositeExtract %i32 %ints_in 0\n"
7445                 "%y_in = OpCompositeExtract %i32 %ints_in 1\n"
7446                 "%z_in = OpCompositeExtract %i32 %ints_in 2\n"
7447                 "%x_out = OpSRem %i32 %x_in %y_in\n"
7448                 "%y_out = OpSRem %i32 %y_in %z_in\n"
7449                 "%z_out = OpSRem %i32 %z_in %x_in\n"
7450                 "%ints_out = OpCompositeConstruct %v4i32 %x_out %y_out %z_out %c_i32_255\n"
7451                 "%ints_offset = OpIAdd %v4i32 %ints_out %c_v4i32_128\n"
7452                 "%f_ints_offset = OpConvertSToF %v4f32 %ints_offset\n"
7453                 "%float_out = OpFDiv %v4f32 %f_ints_offset %c_v4f32_255\n"
7454                 "OpReturnValue %float_out\n"
7455                 "OpFunctionEnd\n";
7456
7457         const struct CaseParams
7458         {
7459                 const char*             name;
7460                 const char*             failMessageTemplate;    // customized status message
7461                 qpTestResult    failResult;                             // override status on failure
7462                 int                             operands[4][3];                 // four (x, y, z) vectors of operands
7463                 int                             results[4][3];                  // four (x, y, z) vectors of results
7464         } cases[] =
7465         {
7466                 {
7467                         "positive",
7468                         "${reason}",
7469                         QP_TEST_RESULT_FAIL,
7470                         { { 5, 12, 17 }, { 5, 5, 7 }, { 75, 8, 81 }, { 25, 60, 100 } },                 // operands
7471                         { { 5, 12,  2 }, { 0, 5, 2 }, {  3, 8,  6 }, { 25, 60,   0 } },                 // results
7472                 },
7473                 {
7474                         "all",
7475                         "Inconsistent results, but within specification: ${reason}",
7476                         negFailResult,                                                                                                                  // negative operands, not required by the spec
7477                         { { 5, 12, -17 }, { -5, -5, 7 }, { 75, 8, -81 }, { 25, -60, 100 } },    // operands
7478                         { { 5, 12,  -2 }, {  0, -5, 2 }, {  3, 8,  -6 }, { 25, -60,   0 } },    // results
7479                 },
7480         };
7481         // If either operand is negative the result is undefined. Some implementations may still return correct values.
7482
7483         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
7484         {
7485                 const CaseParams&       params                  = cases[caseNdx];
7486                 RGBA                            inputColors[4];
7487                 RGBA                            outputColors[4];
7488
7489                 for (int i = 0; i < 4; ++i)
7490                 {
7491                         inputColors [i] = RGBA(params.operands[i][0] + 128, params.operands[i][1] + 128, params.operands[i][2] + 128, 255);
7492                         outputColors[i] = RGBA(params.results [i][0] + 128, params.results [i][1] + 128, params.results [i][2] + 128, 255);
7493                 }
7494
7495                 createTestsForAllStages(params.name, inputColors, outputColors, fragments, testGroup.get(), params.failResult, params.failMessageTemplate);
7496         }
7497
7498         return testGroup.release();
7499 }
7500
7501 // Test for the OpSMod instruction.
7502 tcu::TestCaseGroup* createOpSModGraphicsTests(tcu::TestContext& testCtx, qpTestResult negFailResult)
7503 {
7504         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "smod", "OpSMod"));
7505         map<string, string>                                     fragments;
7506
7507         fragments["pre_main"]                            =
7508                 "%c_f32_255 = OpConstant %f32 255.0\n"
7509                 "%c_i32_128 = OpConstant %i32 128\n"
7510                 "%c_i32_255 = OpConstant %i32 255\n"
7511                 "%c_v4f32_255 = OpConstantComposite %v4f32 %c_f32_255 %c_f32_255 %c_f32_255 %c_f32_255 \n"
7512                 "%c_v4f32_0_5 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 \n"
7513                 "%c_v4i32_128 = OpConstantComposite %v4i32 %c_i32_128 %c_i32_128 %c_i32_128 %c_i32_128 \n";
7514
7515         // The test does the following.
7516         // ivec4 ints = int(param1 * 255.0 + 0.5) - 128;
7517         // ivec4 result = ivec4(smod(ints.x, ints.y), smod(ints.y, ints.z), smod(ints.z, ints.x), 255);
7518         // return float(result + 128) / 255.0;
7519         fragments["testfun"]                             =
7520                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7521                 "%param1 = OpFunctionParameter %v4f32\n"
7522                 "%label_testfun = OpLabel\n"
7523                 "%div255 = OpFMul %v4f32 %param1 %c_v4f32_255\n"
7524                 "%add0_5 = OpFAdd %v4f32 %div255 %c_v4f32_0_5\n"
7525                 "%uints_in = OpConvertFToS %v4i32 %add0_5\n"
7526                 "%ints_in = OpISub %v4i32 %uints_in %c_v4i32_128\n"
7527                 "%x_in = OpCompositeExtract %i32 %ints_in 0\n"
7528                 "%y_in = OpCompositeExtract %i32 %ints_in 1\n"
7529                 "%z_in = OpCompositeExtract %i32 %ints_in 2\n"
7530                 "%x_out = OpSMod %i32 %x_in %y_in\n"
7531                 "%y_out = OpSMod %i32 %y_in %z_in\n"
7532                 "%z_out = OpSMod %i32 %z_in %x_in\n"
7533                 "%ints_out = OpCompositeConstruct %v4i32 %x_out %y_out %z_out %c_i32_255\n"
7534                 "%ints_offset = OpIAdd %v4i32 %ints_out %c_v4i32_128\n"
7535                 "%f_ints_offset = OpConvertSToF %v4f32 %ints_offset\n"
7536                 "%float_out = OpFDiv %v4f32 %f_ints_offset %c_v4f32_255\n"
7537                 "OpReturnValue %float_out\n"
7538                 "OpFunctionEnd\n";
7539
7540         const struct CaseParams
7541         {
7542                 const char*             name;
7543                 const char*             failMessageTemplate;    // customized status message
7544                 qpTestResult    failResult;                             // override status on failure
7545                 int                             operands[4][3];                 // four (x, y, z) vectors of operands
7546                 int                             results[4][3];                  // four (x, y, z) vectors of results
7547         } cases[] =
7548         {
7549                 {
7550                         "positive",
7551                         "${reason}",
7552                         QP_TEST_RESULT_FAIL,
7553                         { { 5, 12, 17 }, { 5, 5, 7 }, { 75, 8, 81 }, { 25, 60, 100 } },                         // operands
7554                         { { 5, 12,  2 }, { 0, 5, 2 }, {  3, 8,  6 }, { 25, 60,   0 } },                         // results
7555                 },
7556                 {
7557                         "all",
7558                         "Inconsistent results, but within specification: ${reason}",
7559                         negFailResult,                                                                                                                          // negative operands, not required by the spec
7560                         { { 5, 12, -17 }, { -5, -5,  7 }, { 75,   8, -81 }, {  25, -60, 100 } },        // operands
7561                         { { 5, -5,   3 }, {  0,  2, -3 }, {  3, -73,  69 }, { -35,  40,   0 } },        // results
7562                 },
7563         };
7564         // If either operand is negative the result is undefined. Some implementations may still return correct values.
7565
7566         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
7567         {
7568                 const CaseParams&       params                  = cases[caseNdx];
7569                 RGBA                            inputColors[4];
7570                 RGBA                            outputColors[4];
7571
7572                 for (int i = 0; i < 4; ++i)
7573                 {
7574                         inputColors [i] = RGBA(params.operands[i][0] + 128, params.operands[i][1] + 128, params.operands[i][2] + 128, 255);
7575                         outputColors[i] = RGBA(params.results [i][0] + 128, params.results [i][1] + 128, params.results [i][2] + 128, 255);
7576                 }
7577
7578                 createTestsForAllStages(params.name, inputColors, outputColors, fragments, testGroup.get(), params.failResult, params.failMessageTemplate);
7579         }
7580
7581         return testGroup.release();
7582 }
7583
7584 enum IntegerType
7585 {
7586         INTEGER_TYPE_SIGNED_16,
7587         INTEGER_TYPE_SIGNED_32,
7588         INTEGER_TYPE_SIGNED_64,
7589
7590         INTEGER_TYPE_UNSIGNED_16,
7591         INTEGER_TYPE_UNSIGNED_32,
7592         INTEGER_TYPE_UNSIGNED_64,
7593 };
7594
7595 const string getBitWidthStr (IntegerType type)
7596 {
7597         switch (type)
7598         {
7599                 case INTEGER_TYPE_SIGNED_16:
7600                 case INTEGER_TYPE_UNSIGNED_16:  return "16";
7601
7602                 case INTEGER_TYPE_SIGNED_32:
7603                 case INTEGER_TYPE_UNSIGNED_32:  return "32";
7604
7605                 case INTEGER_TYPE_SIGNED_64:
7606                 case INTEGER_TYPE_UNSIGNED_64:  return "64";
7607
7608                 default:                                                DE_ASSERT(false);
7609                                                                                 return "";
7610         }
7611 }
7612
7613 const string getByteWidthStr (IntegerType type)
7614 {
7615         switch (type)
7616         {
7617                 case INTEGER_TYPE_SIGNED_16:
7618                 case INTEGER_TYPE_UNSIGNED_16:  return "2";
7619
7620                 case INTEGER_TYPE_SIGNED_32:
7621                 case INTEGER_TYPE_UNSIGNED_32:  return "4";
7622
7623                 case INTEGER_TYPE_SIGNED_64:
7624                 case INTEGER_TYPE_UNSIGNED_64:  return "8";
7625
7626                 default:                                                DE_ASSERT(false);
7627                                                                                 return "";
7628         }
7629 }
7630
7631 bool isSigned (IntegerType type)
7632 {
7633         return (type <= INTEGER_TYPE_SIGNED_64);
7634 }
7635
7636 const string getTypeName (IntegerType type)
7637 {
7638         string prefix = isSigned(type) ? "" : "u";
7639         return prefix + "int" + getBitWidthStr(type);
7640 }
7641
7642 const string getTestName (IntegerType from, IntegerType to)
7643 {
7644         return getTypeName(from) + "_to_" + getTypeName(to);
7645 }
7646
7647 const string getAsmTypeDeclaration (IntegerType type)
7648 {
7649         string sign = isSigned(type) ? " 1" : " 0";
7650         return "OpTypeInt " + getBitWidthStr(type) + sign;
7651 }
7652
7653 const string getAsmTypeName (IntegerType type)
7654 {
7655         const string prefix = isSigned(type) ? "%i" : "%u";
7656         return prefix + getBitWidthStr(type);
7657 }
7658
7659 template<typename T>
7660 BufferSp getSpecializedBuffer (deInt64 number)
7661 {
7662         return BufferSp(new Buffer<T>(vector<T>(1, (T)number)));
7663 }
7664
7665 BufferSp getBuffer (IntegerType type, deInt64 number)
7666 {
7667         switch (type)
7668         {
7669                 case INTEGER_TYPE_SIGNED_16:    return getSpecializedBuffer<deInt16>(number);
7670                 case INTEGER_TYPE_SIGNED_32:    return getSpecializedBuffer<deInt32>(number);
7671                 case INTEGER_TYPE_SIGNED_64:    return getSpecializedBuffer<deInt64>(number);
7672
7673                 case INTEGER_TYPE_UNSIGNED_16:  return getSpecializedBuffer<deUint16>(number);
7674                 case INTEGER_TYPE_UNSIGNED_32:  return getSpecializedBuffer<deUint32>(number);
7675                 case INTEGER_TYPE_UNSIGNED_64:  return getSpecializedBuffer<deUint64>(number);
7676
7677                 default:                                                DE_ASSERT(false);
7678                                                                                 return BufferSp(new Buffer<deInt32>(vector<deInt32>(1, 0)));
7679         }
7680 }
7681
7682 bool usesInt16 (IntegerType from, IntegerType to)
7683 {
7684         return (from == INTEGER_TYPE_SIGNED_16 || from == INTEGER_TYPE_UNSIGNED_16
7685                         || to == INTEGER_TYPE_SIGNED_16 || to == INTEGER_TYPE_UNSIGNED_16);
7686 }
7687
7688 bool usesInt64 (IntegerType from, IntegerType to)
7689 {
7690         return (from == INTEGER_TYPE_SIGNED_64 || from == INTEGER_TYPE_UNSIGNED_64
7691                         || to == INTEGER_TYPE_SIGNED_64 || to == INTEGER_TYPE_UNSIGNED_64);
7692 }
7693
7694 ComputeTestFeatures getConversionUsedFeatures (IntegerType from, IntegerType to)
7695 {
7696         if (usesInt16(from, to))
7697         {
7698                 if (usesInt64(from, to))
7699                 {
7700                         return COMPUTE_TEST_USES_INT16_INT64;
7701                 }
7702                 else
7703                 {
7704                         return COMPUTE_TEST_USES_INT16;
7705                 }
7706         }
7707         else
7708         {
7709                 return COMPUTE_TEST_USES_INT64;
7710         }
7711 }
7712
7713 struct ConvertCase
7714 {
7715         ConvertCase (IntegerType from, IntegerType to, deInt64 number)
7716         : m_fromType            (from)
7717         , m_toType                      (to)
7718         , m_features            (getConversionUsedFeatures(from, to))
7719         , m_name                        (getTestName(from, to))
7720         , m_inputBuffer         (getBuffer(from, number))
7721         , m_outputBuffer        (getBuffer(to, number))
7722         {
7723                 m_asmTypes["inputType"]         = getAsmTypeName(from);
7724                 m_asmTypes["outputType"]        = getAsmTypeName(to);
7725
7726                 if (m_features == COMPUTE_TEST_USES_INT16)
7727                 {
7728                         m_asmTypes["int_capabilities"] = "OpCapability Int16\n";
7729                         m_asmTypes["int_additional_decl"] = "%i16        = OpTypeInt 16 1\n%u16        = OpTypeInt 16 0\n";
7730                 }
7731                 else if (m_features == COMPUTE_TEST_USES_INT64)
7732                 {
7733                         m_asmTypes["int_capabilities"] = "OpCapability Int64\n";
7734                         m_asmTypes["int_additional_decl"] = "%i64        = OpTypeInt 64 1\n%u64        = OpTypeInt 64 0\n";
7735                 }
7736                 else if (m_features == COMPUTE_TEST_USES_INT16_INT64)
7737                 {
7738                         m_asmTypes["int_capabilities"] = string("OpCapability Int16\n") +
7739                                                                                                         "OpCapability Int64\n";
7740                         m_asmTypes["int_additional_decl"] =     "%i16        = OpTypeInt 16 1\n%u16        = OpTypeInt 16 0\n"
7741                                                                 "%i64        = OpTypeInt 64 1\n%u64        = OpTypeInt 64 0\n";
7742                 }
7743                 else
7744                 {
7745                         DE_ASSERT(false);
7746                 }
7747         }
7748
7749         IntegerType                             m_fromType;
7750         IntegerType                             m_toType;
7751         ComputeTestFeatures             m_features;
7752         string                                  m_name;
7753         map<string, string>             m_asmTypes;
7754         BufferSp                                m_inputBuffer;
7755         BufferSp                                m_outputBuffer;
7756 };
7757
7758 const string getConvertCaseShaderStr (const string& instruction, const ConvertCase& convertCase)
7759 {
7760         map<string, string> params = convertCase.m_asmTypes;
7761
7762         params["instruction"] = instruction;
7763
7764         params["inDecorator"] = getByteWidthStr(convertCase.m_fromType);
7765         params["outDecorator"] = getByteWidthStr(convertCase.m_toType);
7766
7767         const StringTemplate shader (
7768                 "OpCapability Shader\n"
7769                 "${int_capabilities}"
7770                 "OpMemoryModel Logical GLSL450\n"
7771                 "OpEntryPoint GLCompute %main \"main\" %id\n"
7772                 "OpExecutionMode %main LocalSize 1 1 1\n"
7773                 "OpSource GLSL 430\n"
7774                 "OpName %main           \"main\"\n"
7775                 "OpName %id             \"gl_GlobalInvocationID\"\n"
7776                 // Decorators
7777                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
7778                 "OpDecorate %indata DescriptorSet 0\n"
7779                 "OpDecorate %indata Binding 0\n"
7780                 "OpDecorate %outdata DescriptorSet 0\n"
7781                 "OpDecorate %outdata Binding 1\n"
7782                 "OpDecorate %in_arr ArrayStride ${inDecorator}\n"
7783                 "OpDecorate %out_arr ArrayStride ${outDecorator}\n"
7784                 "OpDecorate %in_buf BufferBlock\n"
7785                 "OpDecorate %out_buf BufferBlock\n"
7786                 "OpMemberDecorate %in_buf 0 Offset 0\n"
7787                 "OpMemberDecorate %out_buf 0 Offset 0\n"
7788                 // Base types
7789                 "%void       = OpTypeVoid\n"
7790                 "%voidf      = OpTypeFunction %void\n"
7791                 "%u32        = OpTypeInt 32 0\n"
7792                 "%i32        = OpTypeInt 32 1\n"
7793                 "${int_additional_decl}"
7794                 "%uvec3      = OpTypeVector %u32 3\n"
7795                 "%uvec3ptr   = OpTypePointer Input %uvec3\n"
7796                 // Derived types
7797                 "%in_ptr     = OpTypePointer Uniform ${inputType}\n"
7798                 "%out_ptr    = OpTypePointer Uniform ${outputType}\n"
7799                 "%in_arr     = OpTypeRuntimeArray ${inputType}\n"
7800                 "%out_arr    = OpTypeRuntimeArray ${outputType}\n"
7801                 "%in_buf     = OpTypeStruct %in_arr\n"
7802                 "%out_buf    = OpTypeStruct %out_arr\n"
7803                 "%in_bufptr  = OpTypePointer Uniform %in_buf\n"
7804                 "%out_bufptr = OpTypePointer Uniform %out_buf\n"
7805                 "%indata     = OpVariable %in_bufptr Uniform\n"
7806                 "%outdata    = OpVariable %out_bufptr Uniform\n"
7807                 "%inputptr   = OpTypePointer Input ${inputType}\n"
7808                 "%id         = OpVariable %uvec3ptr Input\n"
7809                 // Constants
7810                 "%zero       = OpConstant %i32 0\n"
7811                 // Main function
7812                 "%main       = OpFunction %void None %voidf\n"
7813                 "%label      = OpLabel\n"
7814                 "%idval      = OpLoad %uvec3 %id\n"
7815                 "%x          = OpCompositeExtract %u32 %idval 0\n"
7816                 "%inloc      = OpAccessChain %in_ptr %indata %zero %x\n"
7817                 "%outloc     = OpAccessChain %out_ptr %outdata %zero %x\n"
7818                 "%inval      = OpLoad ${inputType} %inloc\n"
7819                 "%conv       = ${instruction} ${outputType} %inval\n"
7820                 "              OpStore %outloc %conv\n"
7821                 "              OpReturn\n"
7822                 "              OpFunctionEnd\n"
7823         );
7824
7825         return shader.specialize(params);
7826 }
7827
7828 void createSConvertCases (vector<ConvertCase>& testCases)
7829 {
7830         // Convert int to int
7831         testCases.push_back(ConvertCase(INTEGER_TYPE_SIGNED_16, INTEGER_TYPE_SIGNED_32,         14669));
7832         testCases.push_back(ConvertCase(INTEGER_TYPE_SIGNED_16, INTEGER_TYPE_SIGNED_64,         3341));
7833
7834         testCases.push_back(ConvertCase(INTEGER_TYPE_SIGNED_32, INTEGER_TYPE_SIGNED_64,         973610259));
7835
7836         // Convert int to unsigned int
7837         testCases.push_back(ConvertCase(INTEGER_TYPE_SIGNED_16, INTEGER_TYPE_UNSIGNED_32,       9288));
7838         testCases.push_back(ConvertCase(INTEGER_TYPE_SIGNED_16, INTEGER_TYPE_UNSIGNED_64,       15460));
7839
7840         testCases.push_back(ConvertCase(INTEGER_TYPE_SIGNED_32, INTEGER_TYPE_UNSIGNED_64,       346213461));
7841 }
7842
7843 //  Test for the OpSConvert instruction.
7844 tcu::TestCaseGroup* createSConvertTests (tcu::TestContext& testCtx)
7845 {
7846         const string instruction                                ("OpSConvert");
7847         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "sconvert", "OpSConvert"));
7848         vector<ConvertCase>                             testCases;
7849         createSConvertCases(testCases);
7850
7851         for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
7852         {
7853                 ComputeShaderSpec       spec;
7854
7855                 spec.assembly = getConvertCaseShaderStr(instruction, *test);
7856                 spec.inputs.push_back(test->m_inputBuffer);
7857                 spec.outputs.push_back(test->m_outputBuffer);
7858                 spec.numWorkGroups = IVec3(1, 1, 1);
7859
7860                 group->addChild(new SpvAsmComputeShaderCase(testCtx, test->m_name.c_str(), "Convert integers with OpSConvert.", spec, test->m_features));
7861         }
7862
7863         return group.release();
7864 }
7865
7866 void createUConvertCases (vector<ConvertCase>& testCases)
7867 {
7868         // Convert unsigned int to unsigned int
7869         testCases.push_back(ConvertCase(INTEGER_TYPE_UNSIGNED_16,       INTEGER_TYPE_UNSIGNED_32,       60653));
7870         testCases.push_back(ConvertCase(INTEGER_TYPE_UNSIGNED_16,       INTEGER_TYPE_UNSIGNED_64,       17991));
7871
7872         testCases.push_back(ConvertCase(INTEGER_TYPE_UNSIGNED_32,       INTEGER_TYPE_UNSIGNED_64,       904256275));
7873
7874         // Convert unsigned int to int
7875         testCases.push_back(ConvertCase(INTEGER_TYPE_UNSIGNED_16,       INTEGER_TYPE_SIGNED_32,         38002));
7876         testCases.push_back(ConvertCase(INTEGER_TYPE_UNSIGNED_16,       INTEGER_TYPE_SIGNED_64,         64921));
7877
7878         testCases.push_back(ConvertCase(INTEGER_TYPE_UNSIGNED_32,       INTEGER_TYPE_SIGNED_64,         4294956295ll));
7879 }
7880
7881 //  Test for the OpUConvert instruction.
7882 tcu::TestCaseGroup* createUConvertTests (tcu::TestContext& testCtx)
7883 {
7884         const string instruction                                ("OpUConvert");
7885         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "uconvert", "OpUConvert"));
7886         vector<ConvertCase>                             testCases;
7887         createUConvertCases(testCases);
7888
7889         for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
7890         {
7891                 ComputeShaderSpec       spec;
7892
7893                 spec.assembly = getConvertCaseShaderStr(instruction, *test);
7894                 spec.inputs.push_back(test->m_inputBuffer);
7895                 spec.outputs.push_back(test->m_outputBuffer);
7896                 spec.numWorkGroups = IVec3(1, 1, 1);
7897
7898                 group->addChild(new SpvAsmComputeShaderCase(testCtx, test->m_name.c_str(), "Convert integers with OpUConvert.", spec, test->m_features));
7899         }
7900         return group.release();
7901 }
7902
7903 const string getNumberTypeName (const NumberType type)
7904 {
7905         if (type == NUMBERTYPE_INT32)
7906         {
7907                 return "int";
7908         }
7909         else if (type == NUMBERTYPE_UINT32)
7910         {
7911                 return "uint";
7912         }
7913         else if (type == NUMBERTYPE_FLOAT32)
7914         {
7915                 return "float";
7916         }
7917         else
7918         {
7919                 DE_ASSERT(false);
7920                 return "";
7921         }
7922 }
7923
7924 deInt32 getInt(de::Random& rnd)
7925 {
7926         return rnd.getInt(std::numeric_limits<int>::min(), std::numeric_limits<int>::max());
7927 }
7928
7929 const string repeatString (const string& str, int times)
7930 {
7931         string filler;
7932         for (int i = 0; i < times; ++i)
7933         {
7934                 filler += str;
7935         }
7936         return filler;
7937 }
7938
7939 const string getRandomConstantString (const NumberType type, de::Random& rnd)
7940 {
7941         if (type == NUMBERTYPE_INT32)
7942         {
7943                 return numberToString<deInt32>(getInt(rnd));
7944         }
7945         else if (type == NUMBERTYPE_UINT32)
7946         {
7947                 return numberToString<deUint32>(rnd.getUint32());
7948         }
7949         else if (type == NUMBERTYPE_FLOAT32)
7950         {
7951                 return numberToString<float>(rnd.getFloat());
7952         }
7953         else
7954         {
7955                 DE_ASSERT(false);
7956                 return "";
7957         }
7958 }
7959
7960 void createVectorCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
7961 {
7962         map<string, string> params;
7963
7964         // Vec2 to Vec4
7965         for (int width = 2; width <= 4; ++width)
7966         {
7967                 const string randomConst = numberToString(getInt(rnd));
7968                 const string widthStr = numberToString(width);
7969                 const string composite_type = "${customType}vec" + widthStr;
7970                 const int index = rnd.getInt(0, width-1);
7971
7972                 params["type"]                  = "vec";
7973                 params["name"]                  = params["type"] + "_" + widthStr;
7974                 params["compositeDecl"]         = composite_type + " = OpTypeVector ${customType} " + widthStr +"\n";
7975                 params["compositeType"]         = composite_type;
7976                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
7977                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct " + composite_type + repeatString(" %filler", width) + "\n";
7978                 params["indexes"]               = numberToString(index);
7979                 testCases.push_back(params);
7980         }
7981 }
7982
7983 void createArrayCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
7984 {
7985         const int limit = 10;
7986         map<string, string> params;
7987
7988         for (int width = 2; width <= limit; ++width)
7989         {
7990                 string randomConst = numberToString(getInt(rnd));
7991                 string widthStr = numberToString(width);
7992                 int index = rnd.getInt(0, width-1);
7993
7994                 params["type"]                  = "array";
7995                 params["name"]                  = params["type"] + "_" + widthStr;
7996                 params["compositeDecl"]         = string("%arraywidth = OpConstant %u32 " + widthStr + "\n")
7997                                                                                         +        "%composite = OpTypeArray ${customType} %arraywidth\n";
7998                 params["compositeType"]         = "%composite";
7999                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
8000                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
8001                 params["indexes"]               = numberToString(index);
8002                 testCases.push_back(params);
8003         }
8004 }
8005
8006 void createStructCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
8007 {
8008         const int limit = 10;
8009         map<string, string> params;
8010
8011         for (int width = 2; width <= limit; ++width)
8012         {
8013                 string randomConst = numberToString(getInt(rnd));
8014                 int index = rnd.getInt(0, width-1);
8015
8016                 params["type"]                  = "struct";
8017                 params["name"]                  = params["type"] + "_" + numberToString(width);
8018                 params["compositeDecl"]         = "%composite = OpTypeStruct" + repeatString(" ${customType}", width) + "\n";
8019                 params["compositeType"]         = "%composite";
8020                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
8021                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
8022                 params["indexes"]               = numberToString(index);
8023                 testCases.push_back(params);
8024         }
8025 }
8026
8027 void createMatrixCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
8028 {
8029         map<string, string> params;
8030
8031         // Vec2 to Vec4
8032         for (int width = 2; width <= 4; ++width)
8033         {
8034                 string widthStr = numberToString(width);
8035
8036                 for (int column = 2 ; column <= 4; ++column)
8037                 {
8038                         int index_0 = rnd.getInt(0, column-1);
8039                         int index_1 = rnd.getInt(0, width-1);
8040                         string columnStr = numberToString(column);
8041
8042                         params["type"]          = "matrix";
8043                         params["name"]          = params["type"] + "_" + widthStr + "x" + columnStr;
8044                         params["compositeDecl"] = string("%vectype   = OpTypeVector ${customType} " + widthStr + "\n")
8045                                                                                                 +        "%composite = OpTypeMatrix %vectype " + columnStr + "\n";
8046                         params["compositeType"] = "%composite";
8047
8048                         params["filler"]        = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n"
8049                                                                                                 +        "%fillerVec = OpConstantComposite %vectype" + repeatString(" %filler", width) + "\n";
8050
8051                         params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %fillerVec", column) + "\n";
8052                         params["indexes"]       = numberToString(index_0) + " " + numberToString(index_1);
8053                         testCases.push_back(params);
8054                 }
8055         }
8056 }
8057
8058 void createCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
8059 {
8060         createVectorCompositeCases(testCases, rnd, type);
8061         createArrayCompositeCases(testCases, rnd, type);
8062         createStructCompositeCases(testCases, rnd, type);
8063         // Matrix only supports float types
8064         if (type == NUMBERTYPE_FLOAT32)
8065         {
8066                 createMatrixCompositeCases(testCases, rnd, type);
8067         }
8068 }
8069
8070 const string getAssemblyTypeDeclaration (const NumberType type)
8071 {
8072         switch (type)
8073         {
8074                 case NUMBERTYPE_INT32:          return "OpTypeInt 32 1";
8075                 case NUMBERTYPE_UINT32:         return "OpTypeInt 32 0";
8076                 case NUMBERTYPE_FLOAT32:        return "OpTypeFloat 32";
8077                 default:                        DE_ASSERT(false); return "";
8078         }
8079 }
8080
8081 const string getAssemblyTypeName (const NumberType type)
8082 {
8083         switch (type)
8084         {
8085                 case NUMBERTYPE_INT32:          return "%i32";
8086                 case NUMBERTYPE_UINT32:         return "%u32";
8087                 case NUMBERTYPE_FLOAT32:        return "%f32";
8088                 default:                        DE_ASSERT(false); return "";
8089         }
8090 }
8091
8092 const string specializeCompositeInsertShaderTemplate (const NumberType type, const map<string, string>& params)
8093 {
8094         map<string, string>     parameters(params);
8095
8096         const string customType = getAssemblyTypeName(type);
8097         map<string, string> substCustomType;
8098         substCustomType["customType"] = customType;
8099         parameters["compositeDecl"] = StringTemplate(parameters.at("compositeDecl")).specialize(substCustomType);
8100         parameters["compositeType"] = StringTemplate(parameters.at("compositeType")).specialize(substCustomType);
8101         parameters["compositeConstruct"] = StringTemplate(parameters.at("compositeConstruct")).specialize(substCustomType);
8102         parameters["filler"] = StringTemplate(parameters.at("filler")).specialize(substCustomType);
8103         parameters["customType"] = customType;
8104         parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
8105
8106         if (parameters.at("compositeType") != "%u32vec3")
8107         {
8108                 parameters["u32vec3Decl"] = "%u32vec3   = OpTypeVector %u32 3\n";
8109         }
8110
8111         return StringTemplate(
8112                 "OpCapability Shader\n"
8113                 "OpCapability Matrix\n"
8114                 "OpMemoryModel Logical GLSL450\n"
8115                 "OpEntryPoint GLCompute %main \"main\" %id\n"
8116                 "OpExecutionMode %main LocalSize 1 1 1\n"
8117
8118                 "OpSource GLSL 430\n"
8119                 "OpName %main           \"main\"\n"
8120                 "OpName %id             \"gl_GlobalInvocationID\"\n"
8121
8122                 // Decorators
8123                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
8124                 "OpDecorate %buf BufferBlock\n"
8125                 "OpDecorate %indata DescriptorSet 0\n"
8126                 "OpDecorate %indata Binding 0\n"
8127                 "OpDecorate %outdata DescriptorSet 0\n"
8128                 "OpDecorate %outdata Binding 1\n"
8129                 "OpDecorate %customarr ArrayStride 4\n"
8130                 "${compositeDecorator}"
8131                 "OpMemberDecorate %buf 0 Offset 0\n"
8132
8133                 // General types
8134                 "%void      = OpTypeVoid\n"
8135                 "%voidf     = OpTypeFunction %void\n"
8136                 "%u32       = OpTypeInt 32 0\n"
8137                 "%i32       = OpTypeInt 32 1\n"
8138                 "%f32       = OpTypeFloat 32\n"
8139
8140                 // Composite declaration
8141                 "${compositeDecl}"
8142
8143                 // Constants
8144                 "${filler}"
8145
8146                 "${u32vec3Decl:opt}"
8147                 "%uvec3ptr  = OpTypePointer Input %u32vec3\n"
8148
8149                 // Inherited from custom
8150                 "%customptr = OpTypePointer Uniform ${customType}\n"
8151                 "%customarr = OpTypeRuntimeArray ${customType}\n"
8152                 "%buf       = OpTypeStruct %customarr\n"
8153                 "%bufptr    = OpTypePointer Uniform %buf\n"
8154
8155                 "%indata    = OpVariable %bufptr Uniform\n"
8156                 "%outdata   = OpVariable %bufptr Uniform\n"
8157
8158                 "%id        = OpVariable %uvec3ptr Input\n"
8159                 "%zero      = OpConstant %i32 0\n"
8160
8161                 "%main      = OpFunction %void None %voidf\n"
8162                 "%label     = OpLabel\n"
8163                 "%idval     = OpLoad %u32vec3 %id\n"
8164                 "%x         = OpCompositeExtract %u32 %idval 0\n"
8165
8166                 "%inloc     = OpAccessChain %customptr %indata %zero %x\n"
8167                 "%outloc    = OpAccessChain %customptr %outdata %zero %x\n"
8168                 // Read the input value
8169                 "%inval     = OpLoad ${customType} %inloc\n"
8170                 // Create the composite and fill it
8171                 "${compositeConstruct}"
8172                 // Insert the input value to a place
8173                 "%instance2 = OpCompositeInsert ${compositeType} %inval %instance ${indexes}\n"
8174                 // Read back the value from the position
8175                 "%out_val   = OpCompositeExtract ${customType} %instance2 ${indexes}\n"
8176                 // Store it in the output position
8177                 "             OpStore %outloc %out_val\n"
8178                 "             OpReturn\n"
8179                 "             OpFunctionEnd\n"
8180         ).specialize(parameters);
8181 }
8182
8183 template<typename T>
8184 BufferSp createCompositeBuffer(T number)
8185 {
8186         return BufferSp(new Buffer<T>(vector<T>(1, number)));
8187 }
8188
8189 tcu::TestCaseGroup* createOpCompositeInsertGroup (tcu::TestContext& testCtx)
8190 {
8191         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "opcompositeinsert", "Test the OpCompositeInsert instruction"));
8192         de::Random                                              rnd             (deStringHash(group->getName()));
8193
8194         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
8195         {
8196                 NumberType                                              numberType              = NumberType(type);
8197                 const string                                    typeName                = getNumberTypeName(numberType);
8198                 const string                                    description             = "Test the OpCompositeInsert instruction with " + typeName + "s";
8199                 de::MovePtr<tcu::TestCaseGroup> subGroup                (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
8200                 vector<map<string, string> >    testCases;
8201
8202                 createCompositeCases(testCases, rnd, numberType);
8203
8204                 for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
8205                 {
8206                         ComputeShaderSpec       spec;
8207
8208                         spec.assembly = specializeCompositeInsertShaderTemplate(numberType, *test);
8209
8210                         switch (numberType)
8211                         {
8212                                 case NUMBERTYPE_INT32:
8213                                 {
8214                                         deInt32 number = getInt(rnd);
8215                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
8216                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
8217                                         break;
8218                                 }
8219                                 case NUMBERTYPE_UINT32:
8220                                 {
8221                                         deUint32 number = rnd.getUint32();
8222                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
8223                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
8224                                         break;
8225                                 }
8226                                 case NUMBERTYPE_FLOAT32:
8227                                 {
8228                                         float number = rnd.getFloat();
8229                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
8230                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
8231                                         break;
8232                                 }
8233                                 default:
8234                                         DE_ASSERT(false);
8235                         }
8236
8237                         spec.numWorkGroups = IVec3(1, 1, 1);
8238                         subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpCompositeInsert test", spec));
8239                 }
8240                 group->addChild(subGroup.release());
8241         }
8242         return group.release();
8243 }
8244
8245 struct AssemblyStructInfo
8246 {
8247         AssemblyStructInfo (const deUint32 comp, const deUint32 idx)
8248         : components    (comp)
8249         , index                 (idx)
8250         {}
8251
8252         deUint32 components;
8253         deUint32 index;
8254 };
8255
8256 const string specializeInBoundsShaderTemplate (const NumberType type, const AssemblyStructInfo& structInfo, const map<string, string>& params)
8257 {
8258         // Create the full index string
8259         string                          fullIndex       = numberToString(structInfo.index) + " " + params.at("indexes");
8260         // Convert it to list of indexes
8261         vector<string>          indexes         = de::splitString(fullIndex, ' ');
8262
8263         map<string, string>     parameters      (params);
8264         parameters["structType"]        = repeatString(" ${compositeType}", structInfo.components);
8265         parameters["structConstruct"]   = repeatString(" %instance", structInfo.components);
8266         parameters["insertIndexes"]     = fullIndex;
8267
8268         // In matrix cases the last two index is the CompositeExtract indexes
8269         const deUint32 extractIndexes = (parameters["type"] == "matrix") ? 2 : 1;
8270
8271         // Construct the extractIndex
8272         for (vector<string>::const_iterator index = indexes.end() - extractIndexes; index != indexes.end(); ++index)
8273         {
8274                 parameters["extractIndexes"] += " " + *index;
8275         }
8276
8277         // Remove the last 1 or 2 element depends on matrix case or not
8278         indexes.erase(indexes.end() - extractIndexes, indexes.end());
8279
8280         deUint32 id = 0;
8281         // Generate AccessChain index expressions (except for the last one, because we use ptr to the composite)
8282         for (vector<string>::const_iterator index = indexes.begin(); index != indexes.end(); ++index)
8283         {
8284                 string indexId = "%index_" + numberToString(id++);
8285                 parameters["accessChainConstDeclaration"] += indexId + "   = OpConstant %u32 " + *index + "\n";
8286                 parameters["accessChainIndexes"] += " " + indexId;
8287         }
8288
8289         parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
8290
8291         const string customType = getAssemblyTypeName(type);
8292         map<string, string> substCustomType;
8293         substCustomType["customType"] = customType;
8294         parameters["compositeDecl"] = StringTemplate(parameters.at("compositeDecl")).specialize(substCustomType);
8295         parameters["compositeType"] = StringTemplate(parameters.at("compositeType")).specialize(substCustomType);
8296         parameters["compositeConstruct"] = StringTemplate(parameters.at("compositeConstruct")).specialize(substCustomType);
8297         parameters["filler"] = StringTemplate(parameters.at("filler")).specialize(substCustomType);
8298         parameters["customType"] = customType;
8299
8300         const string compositeType = parameters.at("compositeType");
8301         map<string, string> substCompositeType;
8302         substCompositeType["compositeType"] = compositeType;
8303         parameters["structType"] = StringTemplate(parameters.at("structType")).specialize(substCompositeType);
8304         if (compositeType != "%u32vec3")
8305         {
8306                 parameters["u32vec3Decl"] = "%u32vec3   = OpTypeVector %u32 3\n";
8307         }
8308
8309         return StringTemplate(
8310                 "OpCapability Shader\n"
8311                 "OpCapability Matrix\n"
8312                 "OpMemoryModel Logical GLSL450\n"
8313                 "OpEntryPoint GLCompute %main \"main\" %id\n"
8314                 "OpExecutionMode %main LocalSize 1 1 1\n"
8315
8316                 "OpSource GLSL 430\n"
8317                 "OpName %main           \"main\"\n"
8318                 "OpName %id             \"gl_GlobalInvocationID\"\n"
8319                 // Decorators
8320                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
8321                 "OpDecorate %buf BufferBlock\n"
8322                 "OpDecorate %indata DescriptorSet 0\n"
8323                 "OpDecorate %indata Binding 0\n"
8324                 "OpDecorate %outdata DescriptorSet 0\n"
8325                 "OpDecorate %outdata Binding 1\n"
8326                 "OpDecorate %customarr ArrayStride 4\n"
8327                 "${compositeDecorator}"
8328                 "OpMemberDecorate %buf 0 Offset 0\n"
8329                 // General types
8330                 "%void      = OpTypeVoid\n"
8331                 "%voidf     = OpTypeFunction %void\n"
8332                 "%i32       = OpTypeInt 32 1\n"
8333                 "%u32       = OpTypeInt 32 0\n"
8334                 "%f32       = OpTypeFloat 32\n"
8335                 // Custom types
8336                 "${compositeDecl}"
8337                 // %u32vec3 if not already declared in ${compositeDecl}
8338                 "${u32vec3Decl:opt}"
8339                 "%uvec3ptr  = OpTypePointer Input %u32vec3\n"
8340                 // Inherited from composite
8341                 "%composite_p = OpTypePointer Function ${compositeType}\n"
8342                 "%struct_t  = OpTypeStruct${structType}\n"
8343                 "%struct_p  = OpTypePointer Function %struct_t\n"
8344                 // Constants
8345                 "${filler}"
8346                 "${accessChainConstDeclaration}"
8347                 // Inherited from custom
8348                 "%customptr = OpTypePointer Uniform ${customType}\n"
8349                 "%customarr = OpTypeRuntimeArray ${customType}\n"
8350                 "%buf       = OpTypeStruct %customarr\n"
8351                 "%bufptr    = OpTypePointer Uniform %buf\n"
8352                 "%indata    = OpVariable %bufptr Uniform\n"
8353                 "%outdata   = OpVariable %bufptr Uniform\n"
8354
8355                 "%id        = OpVariable %uvec3ptr Input\n"
8356                 "%zero      = OpConstant %u32 0\n"
8357                 "%main      = OpFunction %void None %voidf\n"
8358                 "%label     = OpLabel\n"
8359                 "%struct_v  = OpVariable %struct_p Function\n"
8360                 "%idval     = OpLoad %u32vec3 %id\n"
8361                 "%x         = OpCompositeExtract %u32 %idval 0\n"
8362                 // Create the input/output type
8363                 "%inloc     = OpInBoundsAccessChain %customptr %indata %zero %x\n"
8364                 "%outloc    = OpInBoundsAccessChain %customptr %outdata %zero %x\n"
8365                 // Read the input value
8366                 "%inval     = OpLoad ${customType} %inloc\n"
8367                 // Create the composite and fill it
8368                 "${compositeConstruct}"
8369                 // Create the struct and fill it with the composite
8370                 "%struct    = OpCompositeConstruct %struct_t${structConstruct}\n"
8371                 // Insert the value
8372                 "%comp_obj  = OpCompositeInsert %struct_t %inval %struct ${insertIndexes}\n"
8373                 // Store the object
8374                 "             OpStore %struct_v %comp_obj\n"
8375                 // Get deepest possible composite pointer
8376                 "%inner_ptr = OpInBoundsAccessChain %composite_p %struct_v${accessChainIndexes}\n"
8377                 "%read_obj  = OpLoad ${compositeType} %inner_ptr\n"
8378                 // Read back the stored value
8379                 "%read_val  = OpCompositeExtract ${customType} %read_obj${extractIndexes}\n"
8380                 "             OpStore %outloc %read_val\n"
8381                 "             OpReturn\n"
8382                 "             OpFunctionEnd\n"
8383         ).specialize(parameters);
8384 }
8385
8386 tcu::TestCaseGroup* createOpInBoundsAccessChainGroup (tcu::TestContext& testCtx)
8387 {
8388         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opinboundsaccesschain", "Test the OpInBoundsAccessChain instruction"));
8389         de::Random                                              rnd                             (deStringHash(group->getName()));
8390
8391         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
8392         {
8393                 NumberType                                              numberType      = NumberType(type);
8394                 const string                                    typeName        = getNumberTypeName(numberType);
8395                 const string                                    description     = "Test the OpInBoundsAccessChain instruction with " + typeName + "s";
8396                 de::MovePtr<tcu::TestCaseGroup> subGroup        (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
8397
8398                 vector<map<string, string> >    testCases;
8399                 createCompositeCases(testCases, rnd, numberType);
8400
8401                 for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
8402                 {
8403                         ComputeShaderSpec       spec;
8404
8405                         // Number of components inside of a struct
8406                         deUint32 structComponents = rnd.getInt(2, 8);
8407                         // Component index value
8408                         deUint32 structIndex = rnd.getInt(0, structComponents - 1);
8409                         AssemblyStructInfo structInfo(structComponents, structIndex);
8410
8411                         spec.assembly = specializeInBoundsShaderTemplate(numberType, structInfo, *test);
8412
8413                         switch (numberType)
8414                         {
8415                                 case NUMBERTYPE_INT32:
8416                                 {
8417                                         deInt32 number = getInt(rnd);
8418                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
8419                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
8420                                         break;
8421                                 }
8422                                 case NUMBERTYPE_UINT32:
8423                                 {
8424                                         deUint32 number = rnd.getUint32();
8425                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
8426                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
8427                                         break;
8428                                 }
8429                                 case NUMBERTYPE_FLOAT32:
8430                                 {
8431                                         float number = rnd.getFloat();
8432                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
8433                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
8434                                         break;
8435                                 }
8436                                 default:
8437                                         DE_ASSERT(false);
8438                         }
8439                         spec.numWorkGroups = IVec3(1, 1, 1);
8440                         subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpInBoundsAccessChain test", spec));
8441                 }
8442                 group->addChild(subGroup.release());
8443         }
8444         return group.release();
8445 }
8446
8447 // If the params missing, uninitialized case
8448 const string specializeDefaultOutputShaderTemplate (const NumberType type, const map<string, string>& params = map<string, string>())
8449 {
8450         map<string, string> parameters(params);
8451
8452         parameters["customType"]        = getAssemblyTypeName(type);
8453
8454         // Declare the const value, and use it in the initializer
8455         if (params.find("constValue") != params.end())
8456         {
8457                 parameters["variableInitializer"]       = " %const";
8458         }
8459         // Uninitialized case
8460         else
8461         {
8462                 parameters["commentDecl"]       = ";";
8463         }
8464
8465         return StringTemplate(
8466                 "OpCapability Shader\n"
8467                 "OpMemoryModel Logical GLSL450\n"
8468                 "OpEntryPoint GLCompute %main \"main\" %id\n"
8469                 "OpExecutionMode %main LocalSize 1 1 1\n"
8470                 "OpSource GLSL 430\n"
8471                 "OpName %main           \"main\"\n"
8472                 "OpName %id             \"gl_GlobalInvocationID\"\n"
8473                 // Decorators
8474                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
8475                 "OpDecorate %indata DescriptorSet 0\n"
8476                 "OpDecorate %indata Binding 0\n"
8477                 "OpDecorate %outdata DescriptorSet 0\n"
8478                 "OpDecorate %outdata Binding 1\n"
8479                 "OpDecorate %in_arr ArrayStride 4\n"
8480                 "OpDecorate %in_buf BufferBlock\n"
8481                 "OpMemberDecorate %in_buf 0 Offset 0\n"
8482                 // Base types
8483                 "%void       = OpTypeVoid\n"
8484                 "%voidf      = OpTypeFunction %void\n"
8485                 "%u32        = OpTypeInt 32 0\n"
8486                 "%i32        = OpTypeInt 32 1\n"
8487                 "%f32        = OpTypeFloat 32\n"
8488                 "%uvec3      = OpTypeVector %u32 3\n"
8489                 "%uvec3ptr   = OpTypePointer Input %uvec3\n"
8490                 "${commentDecl:opt}%const      = OpConstant ${customType} ${constValue:opt}\n"
8491                 // Derived types
8492                 "%in_ptr     = OpTypePointer Uniform ${customType}\n"
8493                 "%in_arr     = OpTypeRuntimeArray ${customType}\n"
8494                 "%in_buf     = OpTypeStruct %in_arr\n"
8495                 "%in_bufptr  = OpTypePointer Uniform %in_buf\n"
8496                 "%indata     = OpVariable %in_bufptr Uniform\n"
8497                 "%outdata    = OpVariable %in_bufptr Uniform\n"
8498                 "%id         = OpVariable %uvec3ptr Input\n"
8499                 "%var_ptr    = OpTypePointer Function ${customType}\n"
8500                 // Constants
8501                 "%zero       = OpConstant %i32 0\n"
8502                 // Main function
8503                 "%main       = OpFunction %void None %voidf\n"
8504                 "%label      = OpLabel\n"
8505                 "%out_var    = OpVariable %var_ptr Function${variableInitializer:opt}\n"
8506                 "%idval      = OpLoad %uvec3 %id\n"
8507                 "%x          = OpCompositeExtract %u32 %idval 0\n"
8508                 "%inloc      = OpAccessChain %in_ptr %indata %zero %x\n"
8509                 "%outloc     = OpAccessChain %in_ptr %outdata %zero %x\n"
8510
8511                 "%outval     = OpLoad ${customType} %out_var\n"
8512                 "              OpStore %outloc %outval\n"
8513                 "              OpReturn\n"
8514                 "              OpFunctionEnd\n"
8515         ).specialize(parameters);
8516 }
8517
8518 bool compareFloats (const std::vector<BufferSp>&, const vector<AllocationSp>& outputAllocs, const std::vector<BufferSp>& expectedOutputs, TestLog& log)
8519 {
8520         DE_ASSERT(outputAllocs.size() != 0);
8521         DE_ASSERT(outputAllocs.size() == expectedOutputs.size());
8522
8523         // Use custom epsilon because of the float->string conversion
8524         const float     epsilon = 0.00001f;
8525
8526         for (size_t outputNdx = 0; outputNdx < outputAllocs.size(); ++outputNdx)
8527         {
8528                 vector<deUint8> expectedBytes;
8529                 float                   expected;
8530                 float                   actual;
8531
8532                 expectedOutputs[outputNdx]->getBytes(expectedBytes);
8533                 memcpy(&expected, &expectedBytes.front(), expectedBytes.size());
8534                 memcpy(&actual, outputAllocs[outputNdx]->getHostPtr(), expectedBytes.size());
8535
8536                 // Test with epsilon
8537                 if (fabs(expected - actual) > epsilon)
8538                 {
8539                         log << TestLog::Message << "Error: The actual and expected values not matching."
8540                                 << " Expected: " << expected << " Actual: " << actual << " Epsilon: " << epsilon << TestLog::EndMessage;
8541                         return false;
8542                 }
8543         }
8544         return true;
8545 }
8546
8547 // Checks if the driver crash with uninitialized cases
8548 bool passthruVerify (const std::vector<BufferSp>&, const vector<AllocationSp>& outputAllocs, const std::vector<BufferSp>& expectedOutputs, TestLog&)
8549 {
8550         DE_ASSERT(outputAllocs.size() != 0);
8551         DE_ASSERT(outputAllocs.size() == expectedOutputs.size());
8552
8553         // Copy and discard the result.
8554         for (size_t outputNdx = 0; outputNdx < outputAllocs.size(); ++outputNdx)
8555         {
8556                 vector<deUint8> expectedBytes;
8557                 expectedOutputs[outputNdx]->getBytes(expectedBytes);
8558
8559                 const size_t    width                   = expectedBytes.size();
8560                 vector<char>    data                    (width);
8561
8562                 memcpy(&data[0], outputAllocs[outputNdx]->getHostPtr(), width);
8563         }
8564         return true;
8565 }
8566
8567 tcu::TestCaseGroup* createShaderDefaultOutputGroup (tcu::TestContext& testCtx)
8568 {
8569         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "shader_default_output", "Test shader default output."));
8570         de::Random                                              rnd             (deStringHash(group->getName()));
8571
8572         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
8573         {
8574                 NumberType                                              numberType      = NumberType(type);
8575                 const string                                    typeName        = getNumberTypeName(numberType);
8576                 const string                                    description     = "Test the OpVariable initializer with " + typeName + ".";
8577                 de::MovePtr<tcu::TestCaseGroup> subGroup        (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
8578
8579                 // 2 similar subcases (initialized and uninitialized)
8580                 for (int subCase = 0; subCase < 2; ++subCase)
8581                 {
8582                         ComputeShaderSpec spec;
8583                         spec.numWorkGroups = IVec3(1, 1, 1);
8584
8585                         map<string, string>                             params;
8586
8587                         switch (numberType)
8588                         {
8589                                 case NUMBERTYPE_INT32:
8590                                 {
8591                                         deInt32 number = getInt(rnd);
8592                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
8593                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
8594                                         params["constValue"] = numberToString(number);
8595                                         break;
8596                                 }
8597                                 case NUMBERTYPE_UINT32:
8598                                 {
8599                                         deUint32 number = rnd.getUint32();
8600                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
8601                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
8602                                         params["constValue"] = numberToString(number);
8603                                         break;
8604                                 }
8605                                 case NUMBERTYPE_FLOAT32:
8606                                 {
8607                                         float number = rnd.getFloat();
8608                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
8609                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
8610                                         spec.verifyIO = &compareFloats;
8611                                         params["constValue"] = numberToString(number);
8612                                         break;
8613                                 }
8614                                 default:
8615                                         DE_ASSERT(false);
8616                         }
8617
8618                         // Initialized subcase
8619                         if (!subCase)
8620                         {
8621                                 spec.assembly = specializeDefaultOutputShaderTemplate(numberType, params);
8622                                 subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "initialized", "OpVariable initializer tests.", spec));
8623                         }
8624                         // Uninitialized subcase
8625                         else
8626                         {
8627                                 spec.assembly = specializeDefaultOutputShaderTemplate(numberType);
8628                                 spec.verifyIO = &passthruVerify;
8629                                 subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "uninitialized", "OpVariable initializer tests.", spec));
8630                         }
8631                 }
8632                 group->addChild(subGroup.release());
8633         }
8634         return group.release();
8635 }
8636
8637 tcu::TestCaseGroup* createOpNopTests (tcu::TestContext& testCtx)
8638 {
8639         de::MovePtr<tcu::TestCaseGroup> testGroup (new tcu::TestCaseGroup(testCtx, "opnop", "Test OpNop"));
8640         RGBA                                                    defaultColors[4];
8641         map<string, string>                             opNopFragments;
8642
8643         getDefaultColors(defaultColors);
8644
8645         opNopFragments["testfun"]               =
8646                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
8647                 "%param1 = OpFunctionParameter %v4f32\n"
8648                 "%label_testfun = OpLabel\n"
8649                 "OpNop\n"
8650                 "OpNop\n"
8651                 "OpNop\n"
8652                 "OpNop\n"
8653                 "OpNop\n"
8654                 "OpNop\n"
8655                 "OpNop\n"
8656                 "OpNop\n"
8657                 "%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8658                 "%b = OpFAdd %f32 %a %a\n"
8659                 "OpNop\n"
8660                 "%c = OpFSub %f32 %b %a\n"
8661                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
8662                 "OpNop\n"
8663                 "OpNop\n"
8664                 "OpReturnValue %ret\n"
8665                 "OpFunctionEnd\n";
8666
8667         createTestsForAllStages("opnop", defaultColors, defaultColors, opNopFragments, testGroup.get());
8668
8669         return testGroup.release();
8670 }
8671
8672 tcu::TestCaseGroup* createInstructionTests (tcu::TestContext& testCtx)
8673 {
8674         de::MovePtr<tcu::TestCaseGroup> instructionTests        (new tcu::TestCaseGroup(testCtx, "instruction", "Instructions with special opcodes/operands"));
8675         de::MovePtr<tcu::TestCaseGroup> computeTests            (new tcu::TestCaseGroup(testCtx, "compute", "Compute Instructions with special opcodes/operands"));
8676         de::MovePtr<tcu::TestCaseGroup> graphicsTests           (new tcu::TestCaseGroup(testCtx, "graphics", "Graphics Instructions with special opcodes/operands"));
8677
8678         computeTests->addChild(createLocalSizeGroup(testCtx));
8679         computeTests->addChild(createOpNopGroup(testCtx));
8680         computeTests->addChild(createOpFUnordGroup(testCtx));
8681         computeTests->addChild(createOpAtomicGroup(testCtx, false));
8682         computeTests->addChild(createOpAtomicGroup(testCtx, true)); // Using new StorageBuffer decoration
8683         computeTests->addChild(createOpLineGroup(testCtx));
8684         computeTests->addChild(createOpNoLineGroup(testCtx));
8685         computeTests->addChild(createOpConstantNullGroup(testCtx));
8686         computeTests->addChild(createOpConstantCompositeGroup(testCtx));
8687         computeTests->addChild(createOpConstantUsageGroup(testCtx));
8688         computeTests->addChild(createSpecConstantGroup(testCtx));
8689         computeTests->addChild(createOpSourceGroup(testCtx));
8690         computeTests->addChild(createOpSourceExtensionGroup(testCtx));
8691         computeTests->addChild(createDecorationGroupGroup(testCtx));
8692         computeTests->addChild(createOpPhiGroup(testCtx));
8693         computeTests->addChild(createLoopControlGroup(testCtx));
8694         computeTests->addChild(createFunctionControlGroup(testCtx));
8695         computeTests->addChild(createSelectionControlGroup(testCtx));
8696         computeTests->addChild(createBlockOrderGroup(testCtx));
8697         computeTests->addChild(createMultipleShaderGroup(testCtx));
8698         computeTests->addChild(createMemoryAccessGroup(testCtx));
8699         computeTests->addChild(createOpCopyMemoryGroup(testCtx));
8700         computeTests->addChild(createOpCopyObjectGroup(testCtx));
8701         computeTests->addChild(createNoContractionGroup(testCtx));
8702         computeTests->addChild(createOpUndefGroup(testCtx));
8703         computeTests->addChild(createOpUnreachableGroup(testCtx));
8704         computeTests ->addChild(createOpQuantizeToF16Group(testCtx));
8705         computeTests ->addChild(createOpFRemGroup(testCtx));
8706         computeTests->addChild(createOpSRemComputeGroup(testCtx, QP_TEST_RESULT_PASS));
8707         computeTests->addChild(createOpSRemComputeGroup64(testCtx, QP_TEST_RESULT_PASS));
8708         computeTests->addChild(createOpSModComputeGroup(testCtx, QP_TEST_RESULT_PASS));
8709         computeTests->addChild(createOpSModComputeGroup64(testCtx, QP_TEST_RESULT_PASS));
8710         computeTests->addChild(createSConvertTests(testCtx));
8711         computeTests->addChild(createUConvertTests(testCtx));
8712         computeTests->addChild(createOpCompositeInsertGroup(testCtx));
8713         computeTests->addChild(createOpInBoundsAccessChainGroup(testCtx));
8714         computeTests->addChild(createShaderDefaultOutputGroup(testCtx));
8715         computeTests->addChild(createOpNMinGroup(testCtx));
8716         computeTests->addChild(createOpNMaxGroup(testCtx));
8717         computeTests->addChild(createOpNClampGroup(testCtx));
8718         {
8719                 de::MovePtr<tcu::TestCaseGroup> computeAndroidTests     (new tcu::TestCaseGroup(testCtx, "android", "Android CTS Tests"));
8720
8721                 computeAndroidTests->addChild(createOpSRemComputeGroup(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
8722                 computeAndroidTests->addChild(createOpSModComputeGroup(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
8723
8724                 computeTests->addChild(computeAndroidTests.release());
8725         }
8726
8727         computeTests->addChild(create16BitStorageComputeGroup(testCtx));
8728         computeTests->addChild(createUboMatrixPaddingComputeGroup(testCtx));
8729         computeTests->addChild(createConditionalBranchComputeGroup(testCtx));
8730         computeTests->addChild(createIndexingComputeGroup(testCtx));
8731         computeTests->addChild(createVariablePointersComputeGroup(testCtx));
8732         computeTests->addChild(createImageSamplerComputeGroup(testCtx));
8733         graphicsTests->addChild(createOpNopTests(testCtx));
8734         graphicsTests->addChild(createOpSourceTests(testCtx));
8735         graphicsTests->addChild(createOpSourceContinuedTests(testCtx));
8736         graphicsTests->addChild(createOpLineTests(testCtx));
8737         graphicsTests->addChild(createOpNoLineTests(testCtx));
8738         graphicsTests->addChild(createOpConstantNullTests(testCtx));
8739         graphicsTests->addChild(createOpConstantCompositeTests(testCtx));
8740         graphicsTests->addChild(createMemoryAccessTests(testCtx));
8741         graphicsTests->addChild(createOpUndefTests(testCtx));
8742         graphicsTests->addChild(createSelectionBlockOrderTests(testCtx));
8743         graphicsTests->addChild(createModuleTests(testCtx));
8744         graphicsTests->addChild(createSwitchBlockOrderTests(testCtx));
8745         graphicsTests->addChild(createOpPhiTests(testCtx));
8746         graphicsTests->addChild(createNoContractionTests(testCtx));
8747         graphicsTests->addChild(createOpQuantizeTests(testCtx));
8748         graphicsTests->addChild(createLoopTests(testCtx));
8749         graphicsTests->addChild(createSpecConstantTests(testCtx));
8750         graphicsTests->addChild(createSpecConstantOpQuantizeToF16Group(testCtx));
8751         graphicsTests->addChild(createBarrierTests(testCtx));
8752         graphicsTests->addChild(createDecorationGroupTests(testCtx));
8753         graphicsTests->addChild(createFRemTests(testCtx));
8754         graphicsTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
8755         graphicsTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
8756
8757         {
8758                 de::MovePtr<tcu::TestCaseGroup> graphicsAndroidTests    (new tcu::TestCaseGroup(testCtx, "android", "Android CTS Tests"));
8759
8760                 graphicsAndroidTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
8761                 graphicsAndroidTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
8762
8763                 graphicsTests->addChild(graphicsAndroidTests.release());
8764         }
8765
8766         graphicsTests->addChild(create16BitStorageGraphicsGroup(testCtx));
8767         graphicsTests->addChild(createUboMatrixPaddingGraphicsGroup(testCtx));
8768         graphicsTests->addChild(createConditionalBranchGraphicsGroup(testCtx));
8769         graphicsTests->addChild(createIndexingGraphicsGroup(testCtx));
8770         graphicsTests->addChild(createVariablePointersGraphicsGroup(testCtx));
8771         graphicsTests->addChild(createImageSamplerGraphicsGroup(testCtx));
8772
8773         instructionTests->addChild(computeTests.release());
8774         instructionTests->addChild(graphicsTests.release());
8775
8776         return instructionTests.release();
8777 }
8778
8779 } // SpirVAssembly
8780 } // vkt