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