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