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