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