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