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