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