• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*-------------------------------------------------------------------------
2  * Vulkan Conformance Tests
3  * ------------------------
4  *
5  * Copyright (c) 2015 Google Inc.
6  * Copyright (c) 2016 The Khronos Group Inc.
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  *//*!
21  * \file
22  * \brief SPIR-V Assembly Tests for Instructions (special opcode/operand)
23  *//*--------------------------------------------------------------------*/
24 
25 #include "vktSpvAsmInstructionTests.hpp"
26 
27 #include "tcuCommandLine.hpp"
28 #include "tcuFormatUtil.hpp"
29 #include "tcuFloat.hpp"
30 #include "tcuFloatFormat.hpp"
31 #include "tcuRGBA.hpp"
32 #include "tcuStringTemplate.hpp"
33 #include "tcuTestLog.hpp"
34 #include "tcuVectorUtil.hpp"
35 #include "tcuInterval.hpp"
36 
37 #include "vkDefs.hpp"
38 #include "vkDeviceUtil.hpp"
39 #include "vkMemUtil.hpp"
40 #include "vkPlatform.hpp"
41 #include "vkPrograms.hpp"
42 #include "vkQueryUtil.hpp"
43 #include "vkRef.hpp"
44 #include "vkRefUtil.hpp"
45 #include "vkStrUtil.hpp"
46 #include "vkTypeUtil.hpp"
47 
48 #include "deStringUtil.hpp"
49 #include "deUniquePtr.hpp"
50 #include "deMath.h"
51 #include "tcuStringTemplate.hpp"
52 
53 #include "vktSpvAsmCrossStageInterfaceTests.hpp"
54 #include "vktSpvAsm8bitStorageTests.hpp"
55 #include "vktSpvAsm16bitStorageTests.hpp"
56 #include "vktSpvAsmUboMatrixPaddingTests.hpp"
57 #include "vktSpvAsmConditionalBranchTests.hpp"
58 #include "vktSpvAsmIndexingTests.hpp"
59 #include "vktSpvAsmImageSamplerTests.hpp"
60 #include "vktSpvAsmComputeShaderCase.hpp"
61 #include "vktSpvAsmComputeShaderTestUtil.hpp"
62 #include "vktSpvAsmFloatControlsTests.hpp"
63 #include "vktSpvAsmGraphicsShaderTestUtil.hpp"
64 #include "vktSpvAsmVariablePointersTests.hpp"
65 #include "vktSpvAsmVariableInitTests.hpp"
66 #include "vktSpvAsmPointerParameterTests.hpp"
67 #include "vktSpvAsmSpirvVersionTests.hpp"
68 #include "vktTestCaseUtil.hpp"
69 #include "vktSpvAsmLoopDepLenTests.hpp"
70 #include "vktSpvAsmLoopDepInfTests.hpp"
71 #include "vktSpvAsmCompositeInsertTests.hpp"
72 #include "vktSpvAsmVaryingNameTests.hpp"
73 #include "vktSpvAsmWorkgroupMemoryTests.hpp"
74 
75 #include <cmath>
76 #include <limits>
77 #include <map>
78 #include <string>
79 #include <sstream>
80 #include <utility>
81 #include <stack>
82 
83 namespace vkt
84 {
85 namespace SpirVAssembly
86 {
87 
88 namespace
89 {
90 
91 using namespace vk;
92 using std::map;
93 using std::string;
94 using std::vector;
95 using tcu::IVec3;
96 using tcu::IVec4;
97 using tcu::RGBA;
98 using tcu::TestLog;
99 using tcu::TestStatus;
100 using tcu::Vec4;
101 using de::UniquePtr;
102 using tcu::StringTemplate;
103 using tcu::Vec4;
104 
105 const bool TEST_WITH_NAN	= true;
106 const bool TEST_WITHOUT_NAN	= false;
107 
108 template<typename T>
fillRandomScalars(de::Random & rnd,T minValue,T maxValue,void * dst,int numValues,int offset=0)109 static void fillRandomScalars (de::Random& rnd, T minValue, T maxValue, void* dst, int numValues, int offset = 0)
110 {
111 	T* const typedPtr = (T*)dst;
112 	for (int ndx = 0; ndx < numValues; ndx++)
113 		typedPtr[offset + ndx] = randomScalar<T>(rnd, minValue, maxValue);
114 }
115 
116 // Filter is a function that returns true if a value should pass, false otherwise.
117 template<typename T, typename FilterT>
fillRandomScalars(de::Random & rnd,T minValue,T maxValue,void * dst,int numValues,FilterT filter,int offset=0)118 static void fillRandomScalars (de::Random& rnd, T minValue, T maxValue, void* dst, int numValues, FilterT filter, int offset = 0)
119 {
120 	T* const typedPtr = (T*)dst;
121 	T value;
122 	for (int ndx = 0; ndx < numValues; ndx++)
123 	{
124 		do
125 			value = randomScalar<T>(rnd, minValue, maxValue);
126 		while (!filter(value));
127 
128 		typedPtr[offset + ndx] = value;
129 	}
130 }
131 
132 // Gets a 64-bit integer with a more logarithmic distribution
randomInt64LogDistributed(de::Random & rnd)133 deInt64 randomInt64LogDistributed (de::Random& rnd)
134 {
135 	deInt64 val = rnd.getUint64();
136 	val &= (1ull << rnd.getInt(1, 63)) - 1;
137 	if (rnd.getBool())
138 		val = -val;
139 	return val;
140 }
141 
fillRandomInt64sLogDistributed(de::Random & rnd,vector<deInt64> & dst,int numValues)142 static void fillRandomInt64sLogDistributed (de::Random& rnd, vector<deInt64>& dst, int numValues)
143 {
144 	for (int ndx = 0; ndx < numValues; ndx++)
145 		dst[ndx] = randomInt64LogDistributed(rnd);
146 }
147 
148 template<typename FilterT>
fillRandomInt64sLogDistributed(de::Random & rnd,vector<deInt64> & dst,int numValues,FilterT filter)149 static void fillRandomInt64sLogDistributed (de::Random& rnd, vector<deInt64>& dst, int numValues, FilterT filter)
150 {
151 	for (int ndx = 0; ndx < numValues; ndx++)
152 	{
153 		deInt64 value;
154 		do {
155 			value = randomInt64LogDistributed(rnd);
156 		} while (!filter(value));
157 		dst[ndx] = value;
158 	}
159 }
160 
filterNonNegative(const deInt64 value)161 inline bool filterNonNegative (const deInt64 value)
162 {
163 	return value >= 0;
164 }
165 
filterPositive(const deInt64 value)166 inline bool filterPositive (const deInt64 value)
167 {
168 	return value > 0;
169 }
170 
filterNotZero(const deInt64 value)171 inline bool filterNotZero (const deInt64 value)
172 {
173 	return value != 0;
174 }
175 
floorAll(vector<float> & values)176 static void floorAll (vector<float>& values)
177 {
178 	for (size_t i = 0; i < values.size(); i++)
179 		values[i] = deFloatFloor(values[i]);
180 }
181 
floorAll(vector<Vec4> & values)182 static void floorAll (vector<Vec4>& values)
183 {
184 	for (size_t i = 0; i < values.size(); i++)
185 		values[i] = floor(values[i]);
186 }
187 
188 struct CaseParameter
189 {
190 	const char*		name;
191 	string			param;
192 
CaseParametervkt::SpirVAssembly::__anon68fe7dee0111::CaseParameter193 	CaseParameter	(const char* case_, const string& param_) : name(case_), param(param_) {}
194 };
195 
196 // Assembly code used for testing LocalSize, OpNop, OpConstant{Null|Composite}, Op[No]Line, OpSource[Continued], OpSourceExtension, OpUndef is based on GLSL source code:
197 //
198 // #version 430
199 //
200 // layout(std140, set = 0, binding = 0) readonly buffer Input {
201 //   float elements[];
202 // } input_data;
203 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
204 //   float elements[];
205 // } output_data;
206 //
207 // layout (local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
208 //
209 // void main() {
210 //   uint x = gl_GlobalInvocationID.x;
211 //   output_data.elements[x] = -input_data.elements[x];
212 // }
213 
getAsmForLocalSizeTest(bool useLiteralLocalSize,bool useSpecConstantWorkgroupSize,IVec3 workGroupSize,deUint32 ndx)214 static string getAsmForLocalSizeTest(bool useLiteralLocalSize, bool useSpecConstantWorkgroupSize, IVec3 workGroupSize, deUint32 ndx)
215 {
216 	std::ostringstream out;
217 	out << getComputeAsmShaderPreambleWithoutLocalSize();
218 
219 	if (useLiteralLocalSize)
220 	{
221 		out << "OpExecutionMode %main LocalSize "
222 			<< workGroupSize.x() << " " << workGroupSize.y() << " " << workGroupSize.z() << "\n";
223 	}
224 
225 	out << "OpSource GLSL 430\n"
226 		"OpName %main           \"main\"\n"
227 		"OpName %id             \"gl_GlobalInvocationID\"\n"
228 		"OpDecorate %id BuiltIn GlobalInvocationId\n";
229 
230 	if (useSpecConstantWorkgroupSize)
231 	{
232 		out << "OpDecorate %spec_0 SpecId 100\n"
233 			<< "OpDecorate %spec_1 SpecId 101\n"
234 			<< "OpDecorate %spec_2 SpecId 102\n"
235 			<< "OpDecorate %gl_WorkGroupSize BuiltIn WorkgroupSize\n";
236 	}
237 
238 	out << getComputeAsmInputOutputBufferTraits()
239 		<< getComputeAsmCommonTypes()
240 		<< getComputeAsmInputOutputBuffer()
241 		<< "%id        = OpVariable %uvec3ptr Input\n"
242 		<< "%zero      = OpConstant %i32 0 \n";
243 
244 	if (useSpecConstantWorkgroupSize)
245 	{
246 		out	<< "%spec_0   = OpSpecConstant %u32 "<< workGroupSize.x() << "\n"
247 			<< "%spec_1   = OpSpecConstant %u32 "<< workGroupSize.y() << "\n"
248 			<< "%spec_2   = OpSpecConstant %u32 "<< workGroupSize.z() << "\n"
249 			<< "%gl_WorkGroupSize = OpSpecConstantComposite %uvec3 %spec_0 %spec_1 %spec_2\n";
250 	}
251 
252 	out << "%main      = OpFunction %void None %voidf\n"
253 		<< "%label     = OpLabel\n"
254 		<< "%idval     = OpLoad %uvec3 %id\n"
255 		<< "%ndx         = OpCompositeExtract %u32 %idval " << ndx << "\n"
256 
257 			"%inloc     = OpAccessChain %f32ptr %indata %zero %ndx\n"
258 			"%inval     = OpLoad %f32 %inloc\n"
259 			"%neg       = OpFNegate %f32 %inval\n"
260 			"%outloc    = OpAccessChain %f32ptr %outdata %zero %ndx\n"
261 			"             OpStore %outloc %neg\n"
262 			"             OpReturn\n"
263 			"             OpFunctionEnd\n";
264 	return out.str();
265 }
266 
createLocalSizeGroup(tcu::TestContext & testCtx)267 tcu::TestCaseGroup* createLocalSizeGroup (tcu::TestContext& testCtx)
268 {
269 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "localsize", ""));
270 	ComputeShaderSpec				spec;
271 	de::Random						rnd				(deStringHash(group->getName()));
272 	const deUint32					numElements		= 64u;
273 	vector<float>					positiveFloats	(numElements, 0);
274 	vector<float>					negativeFloats	(numElements, 0);
275 
276 	fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
277 
278 	for (size_t ndx = 0; ndx < numElements; ++ndx)
279 		negativeFloats[ndx] = -positiveFloats[ndx];
280 
281 	spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
282 	spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
283 
284 	spec.numWorkGroups = IVec3(numElements, 1, 1);
285 
286 	spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, 1, 1), 0u);
287 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize", "", spec));
288 
289 	spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, 1, 1), 0u);
290 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize", "", spec));
291 
292 	spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, 1, 1), 0u);
293 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize", "", spec));
294 
295 	spec.numWorkGroups = IVec3(1, 1, 1);
296 
297 	spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(numElements, 1, 1), 0u);
298 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_x", "", spec));
299 
300 	spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(numElements, 1, 1), 0u);
301 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_x", "", spec));
302 
303 	spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(numElements, 1, 1), 0u);
304 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_x", "", spec));
305 
306 	spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, numElements, 1), 1u);
307 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_y", "", spec));
308 
309 	spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, numElements, 1), 1u);
310 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_y", "", spec));
311 
312 	spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, numElements, 1), 1u);
313 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_y", "", spec));
314 
315 	spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, 1, numElements), 2u);
316 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_z", "", spec));
317 
318 	spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, 1, numElements), 2u);
319 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_z", "", spec));
320 
321 	spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, 1, numElements), 2u);
322 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_z", "", spec));
323 
324 	return group.release();
325 }
326 
createOpNopGroup(tcu::TestContext & testCtx)327 tcu::TestCaseGroup* createOpNopGroup (tcu::TestContext& testCtx)
328 {
329 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "opnop", "Test the OpNop instruction"));
330 	ComputeShaderSpec				spec;
331 	de::Random						rnd				(deStringHash(group->getName()));
332 	const int						numElements		= 100;
333 	vector<float>					positiveFloats	(numElements, 0);
334 	vector<float>					negativeFloats	(numElements, 0);
335 
336 	fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
337 
338 	for (size_t ndx = 0; ndx < numElements; ++ndx)
339 		negativeFloats[ndx] = -positiveFloats[ndx];
340 
341 	spec.assembly =
342 		string(getComputeAsmShaderPreamble()) +
343 
344 		"OpSource GLSL 430\n"
345 		"OpName %main           \"main\"\n"
346 		"OpName %id             \"gl_GlobalInvocationID\"\n"
347 
348 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
349 
350 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes())
351 
352 		+ string(getComputeAsmInputOutputBuffer()) +
353 
354 		"%id        = OpVariable %uvec3ptr Input\n"
355 		"%zero      = OpConstant %i32 0\n"
356 
357 		"%main      = OpFunction %void None %voidf\n"
358 		"%label     = OpLabel\n"
359 		"%idval     = OpLoad %uvec3 %id\n"
360 		"%x         = OpCompositeExtract %u32 %idval 0\n"
361 
362 		"             OpNop\n" // Inside a function body
363 
364 		"%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
365 		"%inval     = OpLoad %f32 %inloc\n"
366 		"%neg       = OpFNegate %f32 %inval\n"
367 		"%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
368 		"             OpStore %outloc %neg\n"
369 		"             OpReturn\n"
370 		"             OpFunctionEnd\n";
371 	spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
372 	spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
373 	spec.numWorkGroups = IVec3(numElements, 1, 1);
374 
375 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpNop appearing at different places", spec));
376 
377 	return group.release();
378 }
379 
380 template<bool nanSupported>
compareFUnord(const std::vector<Resource> & inputs,const vector<AllocationSp> & outputAllocs,const std::vector<Resource> & expectedOutputs,TestLog & log)381 bool compareFUnord (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
382 {
383 	if (outputAllocs.size() != 1)
384 		return false;
385 
386 	vector<deUint8>	input1Bytes;
387 	vector<deUint8>	input2Bytes;
388 	vector<deUint8>	expectedBytes;
389 
390 	inputs[0].getBytes(input1Bytes);
391 	inputs[1].getBytes(input2Bytes);
392 	expectedOutputs[0].getBytes(expectedBytes);
393 
394 	const deInt32* const	expectedOutputAsInt		= reinterpret_cast<const deInt32*>(&expectedBytes.front());
395 	const deInt32* const	outputAsInt				= static_cast<const deInt32*>(outputAllocs[0]->getHostPtr());
396 	const float* const		input1AsFloat			= reinterpret_cast<const float*>(&input1Bytes.front());
397 	const float* const		input2AsFloat			= reinterpret_cast<const float*>(&input2Bytes.front());
398 	bool returnValue								= true;
399 
400 	for (size_t idx = 0; idx < expectedBytes.size() / sizeof(deInt32); ++idx)
401 	{
402 		if (!nanSupported && (tcu::Float32(input1AsFloat[idx]).isNaN() || tcu::Float32(input2AsFloat[idx]).isNaN()))
403 			continue;
404 
405 		if (outputAsInt[idx] != expectedOutputAsInt[idx])
406 		{
407 			log << TestLog::Message << "ERROR: Sub-case failed. inputs: " << input1AsFloat[idx] << "," << input2AsFloat[idx] << " output: " << outputAsInt[idx]<< " expected output: " << expectedOutputAsInt[idx] << TestLog::EndMessage;
408 			returnValue = false;
409 		}
410 	}
411 	return returnValue;
412 }
413 
414 typedef VkBool32 (*compareFuncType) (float, float);
415 
416 struct OpFUnordCase
417 {
418 	const char*		name;
419 	const char*		opCode;
420 	compareFuncType	compareFunc;
421 
OpFUnordCasevkt::SpirVAssembly::__anon68fe7dee0111::OpFUnordCase422 					OpFUnordCase			(const char* _name, const char* _opCode, compareFuncType _compareFunc)
423 						: name				(_name)
424 						, opCode			(_opCode)
425 						, compareFunc		(_compareFunc) {}
426 };
427 
428 #define ADD_OPFUNORD_CASE(NAME, OPCODE, OPERATOR) \
429 do { \
430 	struct compare_##NAME { static VkBool32 compare(float x, float y) { return (x OPERATOR y) ? VK_TRUE : VK_FALSE; } }; \
431 	cases.push_back(OpFUnordCase(#NAME, OPCODE, compare_##NAME::compare)); \
432 } while (deGetFalse())
433 
createOpFUnordGroup(tcu::TestContext & testCtx,const bool nanSupported)434 tcu::TestCaseGroup* createOpFUnordGroup (tcu::TestContext& testCtx, const bool nanSupported)
435 {
436 	const string					nan				= nanSupported ? "_nan" : "";
437 	const string					groupName		= "opfunord" + nan;
438 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Test the OpFUnord* opcodes"));
439 	de::Random						rnd				(deStringHash(group->getName()));
440 	const int						numElements		= 100;
441 	vector<OpFUnordCase>			cases;
442 	string							extensions		= nanSupported ? "OpExtension \"SPV_KHR_float_controls\"\n" : "";
443 	string							capabilities	= nanSupported ? "OpCapability SignedZeroInfNanPreserve\n" : "";
444 	string                          exeModes        = nanSupported ? "OpExecutionMode %main SignedZeroInfNanPreserve 32\n" : "";
445 	const StringTemplate			shaderTemplate	(
446 		string(getComputeAsmShaderPreamble(capabilities, extensions, exeModes)) +
447 		"OpSource GLSL 430\n"
448 		"OpName %main           \"main\"\n"
449 		"OpName %id             \"gl_GlobalInvocationID\"\n"
450 
451 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
452 
453 		"OpDecorate %buf BufferBlock\n"
454 		"OpDecorate %buf2 BufferBlock\n"
455 		"OpDecorate %indata1 DescriptorSet 0\n"
456 		"OpDecorate %indata1 Binding 0\n"
457 		"OpDecorate %indata2 DescriptorSet 0\n"
458 		"OpDecorate %indata2 Binding 1\n"
459 		"OpDecorate %outdata DescriptorSet 0\n"
460 		"OpDecorate %outdata Binding 2\n"
461 		"OpDecorate %f32arr ArrayStride 4\n"
462 		"OpDecorate %i32arr ArrayStride 4\n"
463 		"OpMemberDecorate %buf 0 Offset 0\n"
464 		"OpMemberDecorate %buf2 0 Offset 0\n"
465 
466 		+ string(getComputeAsmCommonTypes()) +
467 
468 		"%buf        = OpTypeStruct %f32arr\n"
469 		"%bufptr     = OpTypePointer Uniform %buf\n"
470 		"%indata1    = OpVariable %bufptr Uniform\n"
471 		"%indata2    = OpVariable %bufptr Uniform\n"
472 
473 		"%buf2       = OpTypeStruct %i32arr\n"
474 		"%buf2ptr    = OpTypePointer Uniform %buf2\n"
475 		"%outdata    = OpVariable %buf2ptr Uniform\n"
476 
477 		"%id        = OpVariable %uvec3ptr Input\n"
478 		"%zero      = OpConstant %i32 0\n"
479 		"%consti1   = OpConstant %i32 1\n"
480 		"%constf1   = OpConstant %f32 1.0\n"
481 
482 		"%main      = OpFunction %void None %voidf\n"
483 		"%label     = OpLabel\n"
484 		"%idval     = OpLoad %uvec3 %id\n"
485 		"%x         = OpCompositeExtract %u32 %idval 0\n"
486 
487 		"%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
488 		"%inval1    = OpLoad %f32 %inloc1\n"
489 		"%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
490 		"%inval2    = OpLoad %f32 %inloc2\n"
491 		"%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
492 
493 		"%result    = ${OPCODE} %bool %inval1 %inval2\n"
494 		"%int_res   = OpSelect %i32 %result %consti1 %zero\n"
495 		"             OpStore %outloc %int_res\n"
496 
497 		"             OpReturn\n"
498 		"             OpFunctionEnd\n");
499 
500 	ADD_OPFUNORD_CASE(equal, "OpFUnordEqual", ==);
501 	ADD_OPFUNORD_CASE(less, "OpFUnordLessThan", <);
502 	ADD_OPFUNORD_CASE(lessequal, "OpFUnordLessThanEqual", <=);
503 	ADD_OPFUNORD_CASE(greater, "OpFUnordGreaterThan", >);
504 	ADD_OPFUNORD_CASE(greaterequal, "OpFUnordGreaterThanEqual", >=);
505 	ADD_OPFUNORD_CASE(notequal, "OpFUnordNotEqual", !=);
506 
507 	for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
508 	{
509 		map<string, string>			specializations;
510 		ComputeShaderSpec			spec;
511 		const float					NaN				= std::numeric_limits<float>::quiet_NaN();
512 		vector<float>				inputFloats1	(numElements, 0);
513 		vector<float>				inputFloats2	(numElements, 0);
514 		vector<deInt32>				expectedInts	(numElements, 0);
515 
516 		specializations["OPCODE"]	= cases[caseNdx].opCode;
517 		spec.assembly				= shaderTemplate.specialize(specializations);
518 
519 		fillRandomScalars(rnd, 1.f, 100.f, &inputFloats1[0], numElements);
520 		for (size_t ndx = 0; ndx < numElements; ++ndx)
521 		{
522 			switch (ndx % 6)
523 			{
524 				case 0:		inputFloats2[ndx] = inputFloats1[ndx] + 1.0f; break;
525 				case 1:		inputFloats2[ndx] = inputFloats1[ndx] - 1.0f; break;
526 				case 2:		inputFloats2[ndx] = inputFloats1[ndx]; break;
527 				case 3:		inputFloats2[ndx] = NaN; break;
528 				case 4:		inputFloats2[ndx] = inputFloats1[ndx];	inputFloats1[ndx] = NaN; break;
529 				case 5:		inputFloats2[ndx] = NaN;				inputFloats1[ndx] = NaN; break;
530 			}
531 			expectedInts[ndx] = tcu::Float32(inputFloats1[ndx]).isNaN() || tcu::Float32(inputFloats2[ndx]).isNaN() || cases[caseNdx].compareFunc(inputFloats1[ndx], inputFloats2[ndx]);
532 		}
533 
534 		spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
535 		spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
536 		spec.outputs.push_back(BufferSp(new Int32Buffer(expectedInts)));
537 		spec.numWorkGroups = IVec3(numElements, 1, 1);
538 		spec.verifyIO = nanSupported ? &compareFUnord<true> : &compareFUnord<false>;
539 		if (nanSupported)
540 		{
541 			spec.extensions.push_back("VK_KHR_shader_float_controls");
542 			spec.requestedVulkanFeatures.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat32 = DE_TRUE;
543 		}
544 		group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
545 	}
546 
547 	return group.release();
548 }
549 
550 struct OpAtomicCase
551 {
552 	const char*		name;
553 	const char*		assembly;
554 	const char*		retValAssembly;
555 	OpAtomicType	opAtomic;
556 	deInt32			numOutputElements;
557 
OpAtomicCasevkt::SpirVAssembly::__anon68fe7dee0111::OpAtomicCase558 					OpAtomicCase(const char* _name, const char* _assembly, const char* _retValAssembly, OpAtomicType _opAtomic, deInt32 _numOutputElements)
559 						: name				(_name)
560 						, assembly			(_assembly)
561 						, retValAssembly	(_retValAssembly)
562 						, opAtomic			(_opAtomic)
563 						, numOutputElements	(_numOutputElements) {}
564 };
565 
createOpAtomicGroup(tcu::TestContext & testCtx,bool useStorageBuffer,int numElements=65535,bool verifyReturnValues=false)566 tcu::TestCaseGroup* createOpAtomicGroup (tcu::TestContext& testCtx, bool useStorageBuffer, int numElements = 65535, bool verifyReturnValues = false)
567 {
568 	std::string						groupName			("opatomic");
569 	if (useStorageBuffer)
570 		groupName += "_storage_buffer";
571 	if (verifyReturnValues)
572 		groupName += "_return_values";
573 	de::MovePtr<tcu::TestCaseGroup>	group				(new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Test the OpAtomic* opcodes"));
574 	vector<OpAtomicCase>			cases;
575 
576 	const StringTemplate			shaderTemplate	(
577 
578 		string("OpCapability Shader\n") +
579 		(useStorageBuffer ? "OpExtension \"SPV_KHR_storage_buffer_storage_class\"\n" : "") +
580 		"OpMemoryModel Logical GLSL450\n"
581 		"OpEntryPoint GLCompute %main \"main\" %id\n"
582 		"OpExecutionMode %main LocalSize 1 1 1\n" +
583 
584 		"OpSource GLSL 430\n"
585 		"OpName %main           \"main\"\n"
586 		"OpName %id             \"gl_GlobalInvocationID\"\n"
587 
588 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
589 
590 		"OpDecorate %buf ${BLOCK_DECORATION}\n"
591 		"OpDecorate %indata DescriptorSet 0\n"
592 		"OpDecorate %indata Binding 0\n"
593 		"OpDecorate %i32arr ArrayStride 4\n"
594 		"OpMemberDecorate %buf 0 Offset 0\n"
595 
596 		"OpDecorate %sumbuf ${BLOCK_DECORATION}\n"
597 		"OpDecorate %sum DescriptorSet 0\n"
598 		"OpDecorate %sum Binding 1\n"
599 		"OpMemberDecorate %sumbuf 0 Coherent\n"
600 		"OpMemberDecorate %sumbuf 0 Offset 0\n"
601 
602 		"${RETVAL_BUF_DECORATE}"
603 
604 		+ getComputeAsmCommonTypes("${BLOCK_POINTER_TYPE}") +
605 
606 		"%buf       = OpTypeStruct %i32arr\n"
607 		"%bufptr    = OpTypePointer ${BLOCK_POINTER_TYPE} %buf\n"
608 		"%indata    = OpVariable %bufptr ${BLOCK_POINTER_TYPE}\n"
609 
610 		"%sumbuf    = OpTypeStruct %i32arr\n"
611 		"%sumbufptr = OpTypePointer ${BLOCK_POINTER_TYPE} %sumbuf\n"
612 		"%sum       = OpVariable %sumbufptr ${BLOCK_POINTER_TYPE}\n"
613 
614 		"${RETVAL_BUF_DECL}"
615 
616 		"%id        = OpVariable %uvec3ptr Input\n"
617 		"%minusone  = OpConstant %i32 -1\n"
618 		"%zero      = OpConstant %i32 0\n"
619 		"%one       = OpConstant %u32 1\n"
620 		"%two       = OpConstant %i32 2\n"
621 
622 		"%main      = OpFunction %void None %voidf\n"
623 		"%label     = OpLabel\n"
624 		"%idval     = OpLoad %uvec3 %id\n"
625 		"%x         = OpCompositeExtract %u32 %idval 0\n"
626 
627 		"%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
628 		"%inval     = OpLoad %i32 %inloc\n"
629 
630 		"%outloc    = OpAccessChain %i32ptr %sum %zero ${INDEX}\n"
631 		"${INSTRUCTION}"
632 		"${RETVAL_ASSEMBLY}"
633 
634 		"             OpReturn\n"
635 		"             OpFunctionEnd\n");
636 
637 	#define ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, NUM_OUTPUT_ELEMENTS) \
638 	do { \
639 		DE_ASSERT((NUM_OUTPUT_ELEMENTS) == 1 || (NUM_OUTPUT_ELEMENTS) == numElements); \
640 		cases.push_back(OpAtomicCase(#NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, NUM_OUTPUT_ELEMENTS)); \
641 	} while (deGetFalse())
642 	#define ADD_OPATOMIC_CASE_1(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, 1)
643 	#define ADD_OPATOMIC_CASE_N(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, numElements)
644 
645 	ADD_OPATOMIC_CASE_1(iadd,	"%retv      = OpAtomicIAdd %i32 %outloc %one %zero %inval\n",
646 								"             OpStore %retloc %retv\n", OPATOMIC_IADD );
647 	ADD_OPATOMIC_CASE_1(isub,	"%retv      = OpAtomicISub %i32 %outloc %one %zero %inval\n",
648 								"             OpStore %retloc %retv\n", OPATOMIC_ISUB );
649 	ADD_OPATOMIC_CASE_1(iinc,	"%retv      = OpAtomicIIncrement %i32 %outloc %one %zero\n",
650 								"             OpStore %retloc %retv\n", OPATOMIC_IINC );
651 	ADD_OPATOMIC_CASE_1(idec,	"%retv      = OpAtomicIDecrement %i32 %outloc %one %zero\n",
652 								"             OpStore %retloc %retv\n", OPATOMIC_IDEC );
653 	if (!verifyReturnValues)
654 	{
655 		ADD_OPATOMIC_CASE_N(load,	"%inval2    = OpAtomicLoad %i32 %inloc %one %zero\n"
656 									"             OpStore %outloc %inval2\n", "", OPATOMIC_LOAD );
657 		ADD_OPATOMIC_CASE_N(store,	"             OpAtomicStore %outloc %one %zero %inval\n", "", OPATOMIC_STORE );
658 	}
659 
660 	ADD_OPATOMIC_CASE_N(compex, "%even      = OpSMod %i32 %inval %two\n"
661 								"             OpStore %outloc %even\n"
662 								"%retv      = OpAtomicCompareExchange %i32 %outloc %one %zero %zero %minusone %zero\n",
663 								"			  OpStore %retloc %retv\n", OPATOMIC_COMPEX );
664 
665 
666 	#undef ADD_OPATOMIC_CASE
667 	#undef ADD_OPATOMIC_CASE_1
668 	#undef ADD_OPATOMIC_CASE_N
669 
670 	for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
671 	{
672 		map<string, string>			specializations;
673 		ComputeShaderSpec			spec;
674 		vector<deInt32>				inputInts		(numElements, 0);
675 		vector<deInt32>				expected		(cases[caseNdx].numOutputElements, -1);
676 
677 		specializations["INDEX"]				= (cases[caseNdx].numOutputElements == 1) ? "%zero" : "%x";
678 		specializations["INSTRUCTION"]			= cases[caseNdx].assembly;
679 		specializations["BLOCK_DECORATION"]		= useStorageBuffer ? "Block" : "BufferBlock";
680 		specializations["BLOCK_POINTER_TYPE"]	= useStorageBuffer ? "StorageBuffer" : "Uniform";
681 
682 		if (verifyReturnValues)
683 		{
684 			const StringTemplate blockDecoration	(
685 				"\n"
686 				"OpDecorate %retbuf ${BLOCK_DECORATION}\n"
687 				"OpDecorate %ret DescriptorSet 0\n"
688 				"OpDecorate %ret Binding 2\n"
689 				"OpMemberDecorate %retbuf 0 Offset 0\n\n");
690 
691 			const StringTemplate blockDeclaration	(
692 				"\n"
693 				"%retbuf    = OpTypeStruct %i32arr\n"
694 				"%retbufptr = OpTypePointer ${BLOCK_POINTER_TYPE} %retbuf\n"
695 				"%ret       = OpVariable %retbufptr ${BLOCK_POINTER_TYPE}\n\n");
696 
697 			specializations["RETVAL_ASSEMBLY"] =
698 				"%retloc    = OpAccessChain %i32ptr %ret %zero %x\n"
699 				+ std::string(cases[caseNdx].retValAssembly);
700 
701 			specializations["RETVAL_BUF_DECORATE"]	= blockDecoration.specialize(specializations);
702 			specializations["RETVAL_BUF_DECL"]		= blockDeclaration.specialize(specializations);
703 		}
704 		else
705 		{
706 			specializations["RETVAL_ASSEMBLY"]		= "";
707 			specializations["RETVAL_BUF_DECORATE"]	= "";
708 			specializations["RETVAL_BUF_DECL"]		= "";
709 		}
710 
711 		spec.assembly							= shaderTemplate.specialize(specializations);
712 
713 		if (useStorageBuffer)
714 			spec.extensions.push_back("VK_KHR_storage_buffer_storage_class");
715 
716 		spec.inputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_INPUT)));
717 		spec.outputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_EXPECTED)));
718 		if (verifyReturnValues)
719 			spec.outputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_ATOMIC_RET)));
720 		spec.numWorkGroups = IVec3(numElements, 1, 1);
721 
722 		if (verifyReturnValues)
723 		{
724 			switch (cases[caseNdx].opAtomic)
725 			{
726 				case OPATOMIC_IADD:
727 					spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IADD>;
728 					break;
729 				case OPATOMIC_ISUB:
730 					spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_ISUB>;
731 					break;
732 				case OPATOMIC_IINC:
733 					spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IINC>;
734 					break;
735 				case OPATOMIC_IDEC:
736 					spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IDEC>;
737 					break;
738 				case OPATOMIC_COMPEX:
739 					spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_COMPEX>;
740 					break;
741 				default:
742 					DE_FATAL("Unsupported OpAtomic type for return value verification");
743 			}
744 		}
745 		group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
746 	}
747 
748 	return group.release();
749 }
750 
createOpLineGroup(tcu::TestContext & testCtx)751 tcu::TestCaseGroup* createOpLineGroup (tcu::TestContext& testCtx)
752 {
753 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "opline", "Test the OpLine instruction"));
754 	ComputeShaderSpec				spec;
755 	de::Random						rnd				(deStringHash(group->getName()));
756 	const int						numElements		= 100;
757 	vector<float>					positiveFloats	(numElements, 0);
758 	vector<float>					negativeFloats	(numElements, 0);
759 
760 	fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
761 
762 	for (size_t ndx = 0; ndx < numElements; ++ndx)
763 		negativeFloats[ndx] = -positiveFloats[ndx];
764 
765 	spec.assembly =
766 		string(getComputeAsmShaderPreamble()) +
767 
768 		"%fname1 = OpString \"negateInputs.comp\"\n"
769 		"%fname2 = OpString \"negateInputs\"\n"
770 
771 		"OpSource GLSL 430\n"
772 		"OpName %main           \"main\"\n"
773 		"OpName %id             \"gl_GlobalInvocationID\"\n"
774 
775 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
776 
777 		+ string(getComputeAsmInputOutputBufferTraits()) +
778 
779 		"OpLine %fname1 0 0\n" // At the earliest possible position
780 
781 		+ string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
782 
783 		"OpLine %fname1 0 1\n" // Multiple OpLines in sequence
784 		"OpLine %fname2 1 0\n" // Different filenames
785 		"OpLine %fname1 1000 100000\n"
786 
787 		"%id        = OpVariable %uvec3ptr Input\n"
788 		"%zero      = OpConstant %i32 0\n"
789 
790 		"OpLine %fname1 1 1\n" // Before a function
791 
792 		"%main      = OpFunction %void None %voidf\n"
793 		"%label     = OpLabel\n"
794 
795 		"OpLine %fname1 1 1\n" // In a function
796 
797 		"%idval     = OpLoad %uvec3 %id\n"
798 		"%x         = OpCompositeExtract %u32 %idval 0\n"
799 		"%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
800 		"%inval     = OpLoad %f32 %inloc\n"
801 		"%neg       = OpFNegate %f32 %inval\n"
802 		"%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
803 		"             OpStore %outloc %neg\n"
804 		"             OpReturn\n"
805 		"             OpFunctionEnd\n";
806 	spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
807 	spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
808 	spec.numWorkGroups = IVec3(numElements, 1, 1);
809 
810 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpLine appearing at different places", spec));
811 
812 	return group.release();
813 }
814 
veryfiBinaryShader(const ProgramBinary & binary)815 bool veryfiBinaryShader (const ProgramBinary& binary)
816 {
817 	const size_t	paternCount			= 3u;
818 	bool paternsCheck[paternCount]		=
819 	{
820 		false, false, false
821 	};
822 	const string patersns[paternCount]	=
823 	{
824 		"VULKAN CTS",
825 		"Negative values",
826 		"Date: 2017/09/21"
827 	};
828 	size_t			paternNdx		= 0u;
829 
830 	for (size_t ndx = 0u; ndx < binary.getSize(); ++ndx)
831 	{
832 		if (false == paternsCheck[paternNdx] &&
833 			patersns[paternNdx][0] == static_cast<char>(binary.getBinary()[ndx]) &&
834 			deMemoryEqual((const char*)&binary.getBinary()[ndx], &patersns[paternNdx][0], patersns[paternNdx].length()))
835 		{
836 			paternsCheck[paternNdx]= true;
837 			paternNdx++;
838 			if (paternNdx == paternCount)
839 				break;
840 		}
841 	}
842 
843 	for (size_t ndx = 0u; ndx < paternCount; ++ndx)
844 	{
845 		if (!paternsCheck[ndx])
846 			return false;
847 	}
848 
849 	return true;
850 }
851 
createOpModuleProcessedGroup(tcu::TestContext & testCtx)852 tcu::TestCaseGroup* createOpModuleProcessedGroup (tcu::TestContext& testCtx)
853 {
854 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "opmoduleprocessed", "Test the OpModuleProcessed instruction"));
855 	ComputeShaderSpec				spec;
856 	de::Random						rnd				(deStringHash(group->getName()));
857 	const int						numElements		= 10;
858 	vector<float>					positiveFloats	(numElements, 0);
859 	vector<float>					negativeFloats	(numElements, 0);
860 
861 	fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
862 
863 	for (size_t ndx = 0; ndx < numElements; ++ndx)
864 		negativeFloats[ndx] = -positiveFloats[ndx];
865 
866 	spec.assembly =
867 		string(getComputeAsmShaderPreamble()) +
868 		"%fname = OpString \"negateInputs.comp\"\n"
869 
870 		"OpSource GLSL 430\n"
871 		"OpName %main           \"main\"\n"
872 		"OpName %id             \"gl_GlobalInvocationID\"\n"
873 		"OpModuleProcessed \"VULKAN CTS\"\n"					//OpModuleProcessed;
874 		"OpModuleProcessed \"Negative values\"\n"
875 		"OpModuleProcessed \"Date: 2017/09/21\"\n"
876 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
877 
878 		+ string(getComputeAsmInputOutputBufferTraits())
879 
880 		+ string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
881 
882 		"OpLine %fname 0 1\n"
883 
884 		"OpLine %fname 1000 1\n"
885 
886 		"%id        = OpVariable %uvec3ptr Input\n"
887 		"%zero      = OpConstant %i32 0\n"
888 		"%main      = OpFunction %void None %voidf\n"
889 
890 		"%label     = OpLabel\n"
891 		"%idval     = OpLoad %uvec3 %id\n"
892 		"%x         = OpCompositeExtract %u32 %idval 0\n"
893 
894 		"%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
895 		"%inval     = OpLoad %f32 %inloc\n"
896 		"%neg       = OpFNegate %f32 %inval\n"
897 		"%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
898 		"             OpStore %outloc %neg\n"
899 		"             OpReturn\n"
900 		"             OpFunctionEnd\n";
901 	spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
902 	spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
903 	spec.numWorkGroups = IVec3(numElements, 1, 1);
904 	spec.verifyBinary = veryfiBinaryShader;
905 	spec.spirvVersion = SPIRV_VERSION_1_3;
906 
907 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpModuleProcessed Tests", spec));
908 
909 	return group.release();
910 }
911 
createOpNoLineGroup(tcu::TestContext & testCtx)912 tcu::TestCaseGroup* createOpNoLineGroup (tcu::TestContext& testCtx)
913 {
914 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "opnoline", "Test the OpNoLine instruction"));
915 	ComputeShaderSpec				spec;
916 	de::Random						rnd				(deStringHash(group->getName()));
917 	const int						numElements		= 100;
918 	vector<float>					positiveFloats	(numElements, 0);
919 	vector<float>					negativeFloats	(numElements, 0);
920 
921 	fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
922 
923 	for (size_t ndx = 0; ndx < numElements; ++ndx)
924 		negativeFloats[ndx] = -positiveFloats[ndx];
925 
926 	spec.assembly =
927 		string(getComputeAsmShaderPreamble()) +
928 
929 		"%fname = OpString \"negateInputs.comp\"\n"
930 
931 		"OpSource GLSL 430\n"
932 		"OpName %main           \"main\"\n"
933 		"OpName %id             \"gl_GlobalInvocationID\"\n"
934 
935 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
936 
937 		+ string(getComputeAsmInputOutputBufferTraits()) +
938 
939 		"OpNoLine\n" // At the earliest possible position, without preceding OpLine
940 
941 		+ string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
942 
943 		"OpLine %fname 0 1\n"
944 		"OpNoLine\n" // Immediately following a preceding OpLine
945 
946 		"OpLine %fname 1000 1\n"
947 
948 		"%id        = OpVariable %uvec3ptr Input\n"
949 		"%zero      = OpConstant %i32 0\n"
950 
951 		"OpNoLine\n" // Contents after the previous OpLine
952 
953 		"%main      = OpFunction %void None %voidf\n"
954 		"%label     = OpLabel\n"
955 		"%idval     = OpLoad %uvec3 %id\n"
956 		"%x         = OpCompositeExtract %u32 %idval 0\n"
957 
958 		"OpNoLine\n" // Multiple OpNoLine
959 		"OpNoLine\n"
960 		"OpNoLine\n"
961 
962 		"%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
963 		"%inval     = OpLoad %f32 %inloc\n"
964 		"%neg       = OpFNegate %f32 %inval\n"
965 		"%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
966 		"             OpStore %outloc %neg\n"
967 		"             OpReturn\n"
968 		"             OpFunctionEnd\n";
969 	spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
970 	spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
971 	spec.numWorkGroups = IVec3(numElements, 1, 1);
972 
973 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpNoLine appearing at different places", spec));
974 
975 	return group.release();
976 }
977 
978 // Compare instruction for the contraction compute case.
979 // Returns true if the output is what is expected from the test case.
compareNoContractCase(const std::vector<Resource> &,const vector<AllocationSp> & outputAllocs,const std::vector<Resource> & expectedOutputs,TestLog &)980 bool compareNoContractCase(const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
981 {
982 	if (outputAllocs.size() != 1)
983 		return false;
984 
985 	// Only size is needed because we are not comparing the exact values.
986 	size_t byteSize = expectedOutputs[0].getByteSize();
987 
988 	const float*	outputAsFloat	= static_cast<const float*>(outputAllocs[0]->getHostPtr());
989 
990 	for(size_t i = 0; i < byteSize / sizeof(float); ++i) {
991 		if (outputAsFloat[i] != 0.f &&
992 			outputAsFloat[i] != -ldexp(1, -24)) {
993 			return false;
994 		}
995 	}
996 
997 	return true;
998 }
999 
createNoContractionGroup(tcu::TestContext & testCtx)1000 tcu::TestCaseGroup* createNoContractionGroup (tcu::TestContext& testCtx)
1001 {
1002 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
1003 	vector<CaseParameter>			cases;
1004 	const int						numElements		= 100;
1005 	vector<float>					inputFloats1	(numElements, 0);
1006 	vector<float>					inputFloats2	(numElements, 0);
1007 	vector<float>					outputFloats	(numElements, 0);
1008 	const StringTemplate			shaderTemplate	(
1009 		string(getComputeAsmShaderPreamble()) +
1010 
1011 		"OpName %main           \"main\"\n"
1012 		"OpName %id             \"gl_GlobalInvocationID\"\n"
1013 
1014 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
1015 
1016 		"${DECORATION}\n"
1017 
1018 		"OpDecorate %buf BufferBlock\n"
1019 		"OpDecorate %indata1 DescriptorSet 0\n"
1020 		"OpDecorate %indata1 Binding 0\n"
1021 		"OpDecorate %indata2 DescriptorSet 0\n"
1022 		"OpDecorate %indata2 Binding 1\n"
1023 		"OpDecorate %outdata DescriptorSet 0\n"
1024 		"OpDecorate %outdata Binding 2\n"
1025 		"OpDecorate %f32arr ArrayStride 4\n"
1026 		"OpMemberDecorate %buf 0 Offset 0\n"
1027 
1028 		+ string(getComputeAsmCommonTypes()) +
1029 
1030 		"%buf        = OpTypeStruct %f32arr\n"
1031 		"%bufptr     = OpTypePointer Uniform %buf\n"
1032 		"%indata1    = OpVariable %bufptr Uniform\n"
1033 		"%indata2    = OpVariable %bufptr Uniform\n"
1034 		"%outdata    = OpVariable %bufptr Uniform\n"
1035 
1036 		"%id         = OpVariable %uvec3ptr Input\n"
1037 		"%zero       = OpConstant %i32 0\n"
1038 		"%c_f_m1     = OpConstant %f32 -1.\n"
1039 
1040 		"%main       = OpFunction %void None %voidf\n"
1041 		"%label      = OpLabel\n"
1042 		"%idval      = OpLoad %uvec3 %id\n"
1043 		"%x          = OpCompositeExtract %u32 %idval 0\n"
1044 		"%inloc1     = OpAccessChain %f32ptr %indata1 %zero %x\n"
1045 		"%inval1     = OpLoad %f32 %inloc1\n"
1046 		"%inloc2     = OpAccessChain %f32ptr %indata2 %zero %x\n"
1047 		"%inval2     = OpLoad %f32 %inloc2\n"
1048 		"%mul        = OpFMul %f32 %inval1 %inval2\n"
1049 		"%add        = OpFAdd %f32 %mul %c_f_m1\n"
1050 		"%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
1051 		"              OpStore %outloc %add\n"
1052 		"              OpReturn\n"
1053 		"              OpFunctionEnd\n");
1054 
1055 	cases.push_back(CaseParameter("multiplication",	"OpDecorate %mul NoContraction"));
1056 	cases.push_back(CaseParameter("addition",		"OpDecorate %add NoContraction"));
1057 	cases.push_back(CaseParameter("both",			"OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"));
1058 
1059 	for (size_t ndx = 0; ndx < numElements; ++ndx)
1060 	{
1061 		inputFloats1[ndx]	= 1.f + std::ldexp(1.f, -23); // 1 + 2^-23.
1062 		inputFloats2[ndx]	= 1.f - std::ldexp(1.f, -23); // 1 - 2^-23.
1063 		// Result for (1 + 2^-23) * (1 - 2^-23) - 1. With NoContraction, the multiplication will be
1064 		// conducted separately and the result is rounded to 1, or 0x1.fffffcp-1
1065 		// So the final result will be 0.f or 0x1p-24.
1066 		// If the operation is combined into a precise fused multiply-add, then the result would be
1067 		// 2^-46 (0xa8800000).
1068 		outputFloats[ndx]	= 0.f;
1069 	}
1070 
1071 	for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
1072 	{
1073 		map<string, string>		specializations;
1074 		ComputeShaderSpec		spec;
1075 
1076 		specializations["DECORATION"] = cases[caseNdx].param;
1077 		spec.assembly = shaderTemplate.specialize(specializations);
1078 		spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1079 		spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1080 		spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1081 		spec.numWorkGroups = IVec3(numElements, 1, 1);
1082 		// Check against the two possible answers based on rounding mode.
1083 		spec.verifyIO = &compareNoContractCase;
1084 
1085 		group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
1086 	}
1087 	return group.release();
1088 }
1089 
compareFRem(const std::vector<Resource> &,const vector<AllocationSp> & outputAllocs,const std::vector<Resource> & expectedOutputs,TestLog &)1090 bool compareFRem(const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1091 {
1092 	if (outputAllocs.size() != 1)
1093 		return false;
1094 
1095 	vector<deUint8>	expectedBytes;
1096 	expectedOutputs[0].getBytes(expectedBytes);
1097 
1098 	const float*	expectedOutputAsFloat	= reinterpret_cast<const float*>(&expectedBytes.front());
1099 	const float*	outputAsFloat			= static_cast<const float*>(outputAllocs[0]->getHostPtr());
1100 
1101 	for (size_t idx = 0; idx < expectedBytes.size() / sizeof(float); ++idx)
1102 	{
1103 		const float f0 = expectedOutputAsFloat[idx];
1104 		const float f1 = outputAsFloat[idx];
1105 		// \todo relative error needs to be fairly high because FRem may be implemented as
1106 		// (roughly) frac(a/b)*b, so LSB errors can be magnified. But this should be fine for now.
1107 		if (deFloatAbs((f1 - f0) / f0) > 0.02)
1108 			return false;
1109 	}
1110 
1111 	return true;
1112 }
1113 
createOpFRemGroup(tcu::TestContext & testCtx)1114 tcu::TestCaseGroup* createOpFRemGroup (tcu::TestContext& testCtx)
1115 {
1116 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "opfrem", "Test the OpFRem instruction"));
1117 	ComputeShaderSpec				spec;
1118 	de::Random						rnd				(deStringHash(group->getName()));
1119 	const int						numElements		= 200;
1120 	vector<float>					inputFloats1	(numElements, 0);
1121 	vector<float>					inputFloats2	(numElements, 0);
1122 	vector<float>					outputFloats	(numElements, 0);
1123 
1124 	fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1125 	fillRandomScalars(rnd, -100.f, 100.f, &inputFloats2[0], numElements);
1126 
1127 	for (size_t ndx = 0; ndx < numElements; ++ndx)
1128 	{
1129 		// Guard against divisors near zero.
1130 		if (std::fabs(inputFloats2[ndx]) < 1e-3)
1131 			inputFloats2[ndx] = 8.f;
1132 
1133 		// The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1134 		outputFloats[ndx] = std::fmod(inputFloats1[ndx], inputFloats2[ndx]);
1135 	}
1136 
1137 	spec.assembly =
1138 		string(getComputeAsmShaderPreamble()) +
1139 
1140 		"OpName %main           \"main\"\n"
1141 		"OpName %id             \"gl_GlobalInvocationID\"\n"
1142 
1143 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
1144 
1145 		"OpDecorate %buf BufferBlock\n"
1146 		"OpDecorate %indata1 DescriptorSet 0\n"
1147 		"OpDecorate %indata1 Binding 0\n"
1148 		"OpDecorate %indata2 DescriptorSet 0\n"
1149 		"OpDecorate %indata2 Binding 1\n"
1150 		"OpDecorate %outdata DescriptorSet 0\n"
1151 		"OpDecorate %outdata Binding 2\n"
1152 		"OpDecorate %f32arr ArrayStride 4\n"
1153 		"OpMemberDecorate %buf 0 Offset 0\n"
1154 
1155 		+ string(getComputeAsmCommonTypes()) +
1156 
1157 		"%buf        = OpTypeStruct %f32arr\n"
1158 		"%bufptr     = OpTypePointer Uniform %buf\n"
1159 		"%indata1    = OpVariable %bufptr Uniform\n"
1160 		"%indata2    = OpVariable %bufptr Uniform\n"
1161 		"%outdata    = OpVariable %bufptr Uniform\n"
1162 
1163 		"%id        = OpVariable %uvec3ptr Input\n"
1164 		"%zero      = OpConstant %i32 0\n"
1165 
1166 		"%main      = OpFunction %void None %voidf\n"
1167 		"%label     = OpLabel\n"
1168 		"%idval     = OpLoad %uvec3 %id\n"
1169 		"%x         = OpCompositeExtract %u32 %idval 0\n"
1170 		"%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1171 		"%inval1    = OpLoad %f32 %inloc1\n"
1172 		"%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1173 		"%inval2    = OpLoad %f32 %inloc2\n"
1174 		"%rem       = OpFRem %f32 %inval1 %inval2\n"
1175 		"%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1176 		"             OpStore %outloc %rem\n"
1177 		"             OpReturn\n"
1178 		"             OpFunctionEnd\n";
1179 
1180 	spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1181 	spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1182 	spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1183 	spec.numWorkGroups = IVec3(numElements, 1, 1);
1184 	spec.verifyIO = &compareFRem;
1185 
1186 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1187 
1188 	return group.release();
1189 }
1190 
compareNMin(const std::vector<Resource> &,const vector<AllocationSp> & outputAllocs,const std::vector<Resource> & expectedOutputs,TestLog &)1191 bool compareNMin (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1192 {
1193 	if (outputAllocs.size() != 1)
1194 		return false;
1195 
1196 	const BufferSp&			expectedOutput			(expectedOutputs[0].getBuffer());
1197 	std::vector<deUint8>	data;
1198 	expectedOutput->getBytes(data);
1199 
1200 	const float* const		expectedOutputAsFloat	= reinterpret_cast<const float*>(&data.front());
1201 	const float* const		outputAsFloat			= static_cast<const float*>(outputAllocs[0]->getHostPtr());
1202 
1203 	for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float); ++idx)
1204 	{
1205 		const float f0 = expectedOutputAsFloat[idx];
1206 		const float f1 = outputAsFloat[idx];
1207 
1208 		// For NMin, we accept NaN as output if both inputs were NaN.
1209 		// Otherwise the NaN is the wrong choise, as on architectures that
1210 		// do not handle NaN, those are huge values.
1211 		if (!(tcu::Float32(f1).isNaN() && tcu::Float32(f0).isNaN()) && deFloatAbs(f1 - f0) > 0.00001f)
1212 			return false;
1213 	}
1214 
1215 	return true;
1216 }
1217 
createOpNMinGroup(tcu::TestContext & testCtx)1218 tcu::TestCaseGroup* createOpNMinGroup (tcu::TestContext& testCtx)
1219 {
1220 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "opnmin", "Test the OpNMin instruction"));
1221 	ComputeShaderSpec				spec;
1222 	de::Random						rnd				(deStringHash(group->getName()));
1223 	const int						numElements		= 200;
1224 	vector<float>					inputFloats1	(numElements, 0);
1225 	vector<float>					inputFloats2	(numElements, 0);
1226 	vector<float>					outputFloats	(numElements, 0);
1227 
1228 	fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1229 	fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1230 
1231 	// Make the first case a full-NAN case.
1232 	inputFloats1[0] = TCU_NAN;
1233 	inputFloats2[0] = TCU_NAN;
1234 
1235 	for (size_t ndx = 0; ndx < numElements; ++ndx)
1236 	{
1237 		// By default, pick the smallest
1238 		outputFloats[ndx] = std::min(inputFloats1[ndx], inputFloats2[ndx]);
1239 
1240 		// Make half of the cases NaN cases
1241 		if ((ndx & 1) == 0)
1242 		{
1243 			// Alternate between the NaN operand
1244 			if ((ndx & 2) == 0)
1245 			{
1246 				outputFloats[ndx] = inputFloats2[ndx];
1247 				inputFloats1[ndx] = TCU_NAN;
1248 			}
1249 			else
1250 			{
1251 				outputFloats[ndx] = inputFloats1[ndx];
1252 				inputFloats2[ndx] = TCU_NAN;
1253 			}
1254 		}
1255 	}
1256 
1257 	spec.assembly =
1258 		"OpCapability Shader\n"
1259 		"%std450	= OpExtInstImport \"GLSL.std.450\"\n"
1260 		"OpMemoryModel Logical GLSL450\n"
1261 		"OpEntryPoint GLCompute %main \"main\" %id\n"
1262 		"OpExecutionMode %main LocalSize 1 1 1\n"
1263 
1264 		"OpName %main           \"main\"\n"
1265 		"OpName %id             \"gl_GlobalInvocationID\"\n"
1266 
1267 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
1268 
1269 		"OpDecorate %buf BufferBlock\n"
1270 		"OpDecorate %indata1 DescriptorSet 0\n"
1271 		"OpDecorate %indata1 Binding 0\n"
1272 		"OpDecorate %indata2 DescriptorSet 0\n"
1273 		"OpDecorate %indata2 Binding 1\n"
1274 		"OpDecorate %outdata DescriptorSet 0\n"
1275 		"OpDecorate %outdata Binding 2\n"
1276 		"OpDecorate %f32arr ArrayStride 4\n"
1277 		"OpMemberDecorate %buf 0 Offset 0\n"
1278 
1279 		+ string(getComputeAsmCommonTypes()) +
1280 
1281 		"%buf        = OpTypeStruct %f32arr\n"
1282 		"%bufptr     = OpTypePointer Uniform %buf\n"
1283 		"%indata1    = OpVariable %bufptr Uniform\n"
1284 		"%indata2    = OpVariable %bufptr Uniform\n"
1285 		"%outdata    = OpVariable %bufptr Uniform\n"
1286 
1287 		"%id        = OpVariable %uvec3ptr Input\n"
1288 		"%zero      = OpConstant %i32 0\n"
1289 
1290 		"%main      = OpFunction %void None %voidf\n"
1291 		"%label     = OpLabel\n"
1292 		"%idval     = OpLoad %uvec3 %id\n"
1293 		"%x         = OpCompositeExtract %u32 %idval 0\n"
1294 		"%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1295 		"%inval1    = OpLoad %f32 %inloc1\n"
1296 		"%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1297 		"%inval2    = OpLoad %f32 %inloc2\n"
1298 		"%rem       = OpExtInst %f32 %std450 NMin %inval1 %inval2\n"
1299 		"%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1300 		"             OpStore %outloc %rem\n"
1301 		"             OpReturn\n"
1302 		"             OpFunctionEnd\n";
1303 
1304 	spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1305 	spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1306 	spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1307 	spec.numWorkGroups = IVec3(numElements, 1, 1);
1308 	spec.verifyIO = &compareNMin;
1309 
1310 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1311 
1312 	return group.release();
1313 }
1314 
compareNMax(const std::vector<Resource> &,const vector<AllocationSp> & outputAllocs,const std::vector<Resource> & expectedOutputs,TestLog &)1315 bool compareNMax (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1316 {
1317 	if (outputAllocs.size() != 1)
1318 		return false;
1319 
1320 	const BufferSp&			expectedOutput			= expectedOutputs[0].getBuffer();
1321 	std::vector<deUint8>	data;
1322 	expectedOutput->getBytes(data);
1323 
1324 	const float* const		expectedOutputAsFloat	= reinterpret_cast<const float*>(&data.front());
1325 	const float* const		outputAsFloat			= static_cast<const float*>(outputAllocs[0]->getHostPtr());
1326 
1327 	for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float); ++idx)
1328 	{
1329 		const float f0 = expectedOutputAsFloat[idx];
1330 		const float f1 = outputAsFloat[idx];
1331 
1332 		// For NMax, NaN is considered acceptable result, since in
1333 		// architectures that do not handle NaNs, those are huge values.
1334 		if (!tcu::Float32(f1).isNaN() && deFloatAbs(f1 - f0) > 0.00001f)
1335 			return false;
1336 	}
1337 
1338 	return true;
1339 }
1340 
createOpNMaxGroup(tcu::TestContext & testCtx)1341 tcu::TestCaseGroup* createOpNMaxGroup (tcu::TestContext& testCtx)
1342 {
1343 	de::MovePtr<tcu::TestCaseGroup>	group(new tcu::TestCaseGroup(testCtx, "opnmax", "Test the OpNMax instruction"));
1344 	ComputeShaderSpec				spec;
1345 	de::Random						rnd				(deStringHash(group->getName()));
1346 	const int						numElements		= 200;
1347 	vector<float>					inputFloats1	(numElements, 0);
1348 	vector<float>					inputFloats2	(numElements, 0);
1349 	vector<float>					outputFloats	(numElements, 0);
1350 
1351 	fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1352 	fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1353 
1354 	// Make the first case a full-NAN case.
1355 	inputFloats1[0] = TCU_NAN;
1356 	inputFloats2[0] = TCU_NAN;
1357 
1358 	for (size_t ndx = 0; ndx < numElements; ++ndx)
1359 	{
1360 		// By default, pick the biggest
1361 		outputFloats[ndx] = std::max(inputFloats1[ndx], inputFloats2[ndx]);
1362 
1363 		// Make half of the cases NaN cases
1364 		if ((ndx & 1) == 0)
1365 		{
1366 			// Alternate between the NaN operand
1367 			if ((ndx & 2) == 0)
1368 			{
1369 				outputFloats[ndx] = inputFloats2[ndx];
1370 				inputFloats1[ndx] = TCU_NAN;
1371 			}
1372 			else
1373 			{
1374 				outputFloats[ndx] = inputFloats1[ndx];
1375 				inputFloats2[ndx] = TCU_NAN;
1376 			}
1377 		}
1378 	}
1379 
1380 	spec.assembly =
1381 		"OpCapability Shader\n"
1382 		"%std450	= OpExtInstImport \"GLSL.std.450\"\n"
1383 		"OpMemoryModel Logical GLSL450\n"
1384 		"OpEntryPoint GLCompute %main \"main\" %id\n"
1385 		"OpExecutionMode %main LocalSize 1 1 1\n"
1386 
1387 		"OpName %main           \"main\"\n"
1388 		"OpName %id             \"gl_GlobalInvocationID\"\n"
1389 
1390 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
1391 
1392 		"OpDecorate %buf BufferBlock\n"
1393 		"OpDecorate %indata1 DescriptorSet 0\n"
1394 		"OpDecorate %indata1 Binding 0\n"
1395 		"OpDecorate %indata2 DescriptorSet 0\n"
1396 		"OpDecorate %indata2 Binding 1\n"
1397 		"OpDecorate %outdata DescriptorSet 0\n"
1398 		"OpDecorate %outdata Binding 2\n"
1399 		"OpDecorate %f32arr ArrayStride 4\n"
1400 		"OpMemberDecorate %buf 0 Offset 0\n"
1401 
1402 		+ string(getComputeAsmCommonTypes()) +
1403 
1404 		"%buf        = OpTypeStruct %f32arr\n"
1405 		"%bufptr     = OpTypePointer Uniform %buf\n"
1406 		"%indata1    = OpVariable %bufptr Uniform\n"
1407 		"%indata2    = OpVariable %bufptr Uniform\n"
1408 		"%outdata    = OpVariable %bufptr Uniform\n"
1409 
1410 		"%id        = OpVariable %uvec3ptr Input\n"
1411 		"%zero      = OpConstant %i32 0\n"
1412 
1413 		"%main      = OpFunction %void None %voidf\n"
1414 		"%label     = OpLabel\n"
1415 		"%idval     = OpLoad %uvec3 %id\n"
1416 		"%x         = OpCompositeExtract %u32 %idval 0\n"
1417 		"%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1418 		"%inval1    = OpLoad %f32 %inloc1\n"
1419 		"%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1420 		"%inval2    = OpLoad %f32 %inloc2\n"
1421 		"%rem       = OpExtInst %f32 %std450 NMax %inval1 %inval2\n"
1422 		"%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1423 		"             OpStore %outloc %rem\n"
1424 		"             OpReturn\n"
1425 		"             OpFunctionEnd\n";
1426 
1427 	spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1428 	spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1429 	spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1430 	spec.numWorkGroups = IVec3(numElements, 1, 1);
1431 	spec.verifyIO = &compareNMax;
1432 
1433 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1434 
1435 	return group.release();
1436 }
1437 
compareNClamp(const std::vector<Resource> &,const vector<AllocationSp> & outputAllocs,const std::vector<Resource> & expectedOutputs,TestLog &)1438 bool compareNClamp (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1439 {
1440 	if (outputAllocs.size() != 1)
1441 		return false;
1442 
1443 	const BufferSp&			expectedOutput			= expectedOutputs[0].getBuffer();
1444 	std::vector<deUint8>	data;
1445 	expectedOutput->getBytes(data);
1446 
1447 	const float* const		expectedOutputAsFloat	= reinterpret_cast<const float*>(&data.front());
1448 	const float* const		outputAsFloat			= static_cast<const float*>(outputAllocs[0]->getHostPtr());
1449 
1450 	for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float) / 2; ++idx)
1451 	{
1452 		const float e0 = expectedOutputAsFloat[idx * 2];
1453 		const float e1 = expectedOutputAsFloat[idx * 2 + 1];
1454 		const float res = outputAsFloat[idx];
1455 
1456 		// For NClamp, we have two possible outcomes based on
1457 		// whether NaNs are handled or not.
1458 		// If either min or max value is NaN, the result is undefined,
1459 		// so this test doesn't stress those. If the clamped value is
1460 		// NaN, and NaNs are handled, the result is min; if NaNs are not
1461 		// handled, they are big values that result in max.
1462 		// If all three parameters are NaN, the result should be NaN.
1463 		if (!((tcu::Float32(e0).isNaN() && tcu::Float32(res).isNaN()) ||
1464 			 (deFloatAbs(e0 - res) < 0.00001f) ||
1465 			 (deFloatAbs(e1 - res) < 0.00001f)))
1466 			return false;
1467 	}
1468 
1469 	return true;
1470 }
1471 
createOpNClampGroup(tcu::TestContext & testCtx)1472 tcu::TestCaseGroup* createOpNClampGroup (tcu::TestContext& testCtx)
1473 {
1474 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "opnclamp", "Test the OpNClamp instruction"));
1475 	ComputeShaderSpec				spec;
1476 	de::Random						rnd				(deStringHash(group->getName()));
1477 	const int						numElements		= 200;
1478 	vector<float>					inputFloats1	(numElements, 0);
1479 	vector<float>					inputFloats2	(numElements, 0);
1480 	vector<float>					inputFloats3	(numElements, 0);
1481 	vector<float>					outputFloats	(numElements * 2, 0);
1482 
1483 	fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1484 	fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1485 	fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats3[0], numElements);
1486 
1487 	for (size_t ndx = 0; ndx < numElements; ++ndx)
1488 	{
1489 		// Results are only defined if max value is bigger than min value.
1490 		if (inputFloats2[ndx] > inputFloats3[ndx])
1491 		{
1492 			float t = inputFloats2[ndx];
1493 			inputFloats2[ndx] = inputFloats3[ndx];
1494 			inputFloats3[ndx] = t;
1495 		}
1496 
1497 		// By default, do the clamp, setting both possible answers
1498 		float defaultRes = std::min(std::max(inputFloats1[ndx], inputFloats2[ndx]), inputFloats3[ndx]);
1499 
1500 		float maxResA = std::max(inputFloats1[ndx], inputFloats2[ndx]);
1501 		float maxResB = maxResA;
1502 
1503 		// Alternate between the NaN cases
1504 		if (ndx & 1)
1505 		{
1506 			inputFloats1[ndx] = TCU_NAN;
1507 			// If NaN is handled, the result should be same as the clamp minimum.
1508 			// If NaN is not handled, the result should clamp to the clamp maximum.
1509 			maxResA = inputFloats2[ndx];
1510 			maxResB = inputFloats3[ndx];
1511 		}
1512 		else
1513 		{
1514 			// Not a NaN case - only one legal result.
1515 			maxResA = defaultRes;
1516 			maxResB = defaultRes;
1517 		}
1518 
1519 		outputFloats[ndx * 2] = maxResA;
1520 		outputFloats[ndx * 2 + 1] = maxResB;
1521 	}
1522 
1523 	// Make the first case a full-NAN case.
1524 	inputFloats1[0] = TCU_NAN;
1525 	inputFloats2[0] = TCU_NAN;
1526 	inputFloats3[0] = TCU_NAN;
1527 	outputFloats[0] = TCU_NAN;
1528 	outputFloats[1] = TCU_NAN;
1529 
1530 	spec.assembly =
1531 		"OpCapability Shader\n"
1532 		"%std450	= OpExtInstImport \"GLSL.std.450\"\n"
1533 		"OpMemoryModel Logical GLSL450\n"
1534 		"OpEntryPoint GLCompute %main \"main\" %id\n"
1535 		"OpExecutionMode %main LocalSize 1 1 1\n"
1536 
1537 		"OpName %main           \"main\"\n"
1538 		"OpName %id             \"gl_GlobalInvocationID\"\n"
1539 
1540 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
1541 
1542 		"OpDecorate %buf BufferBlock\n"
1543 		"OpDecorate %indata1 DescriptorSet 0\n"
1544 		"OpDecorate %indata1 Binding 0\n"
1545 		"OpDecorate %indata2 DescriptorSet 0\n"
1546 		"OpDecorate %indata2 Binding 1\n"
1547 		"OpDecorate %indata3 DescriptorSet 0\n"
1548 		"OpDecorate %indata3 Binding 2\n"
1549 		"OpDecorate %outdata DescriptorSet 0\n"
1550 		"OpDecorate %outdata Binding 3\n"
1551 		"OpDecorate %f32arr ArrayStride 4\n"
1552 		"OpMemberDecorate %buf 0 Offset 0\n"
1553 
1554 		+ string(getComputeAsmCommonTypes()) +
1555 
1556 		"%buf        = OpTypeStruct %f32arr\n"
1557 		"%bufptr     = OpTypePointer Uniform %buf\n"
1558 		"%indata1    = OpVariable %bufptr Uniform\n"
1559 		"%indata2    = OpVariable %bufptr Uniform\n"
1560 		"%indata3    = OpVariable %bufptr Uniform\n"
1561 		"%outdata    = OpVariable %bufptr Uniform\n"
1562 
1563 		"%id        = OpVariable %uvec3ptr Input\n"
1564 		"%zero      = OpConstant %i32 0\n"
1565 
1566 		"%main      = OpFunction %void None %voidf\n"
1567 		"%label     = OpLabel\n"
1568 		"%idval     = OpLoad %uvec3 %id\n"
1569 		"%x         = OpCompositeExtract %u32 %idval 0\n"
1570 		"%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1571 		"%inval1    = OpLoad %f32 %inloc1\n"
1572 		"%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1573 		"%inval2    = OpLoad %f32 %inloc2\n"
1574 		"%inloc3    = OpAccessChain %f32ptr %indata3 %zero %x\n"
1575 		"%inval3    = OpLoad %f32 %inloc3\n"
1576 		"%rem       = OpExtInst %f32 %std450 NClamp %inval1 %inval2 %inval3\n"
1577 		"%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1578 		"             OpStore %outloc %rem\n"
1579 		"             OpReturn\n"
1580 		"             OpFunctionEnd\n";
1581 
1582 	spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1583 	spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1584 	spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
1585 	spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1586 	spec.numWorkGroups = IVec3(numElements, 1, 1);
1587 	spec.verifyIO = &compareNClamp;
1588 
1589 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1590 
1591 	return group.release();
1592 }
1593 
createOpSRemComputeGroup(tcu::TestContext & testCtx,qpTestResult negFailResult)1594 tcu::TestCaseGroup* createOpSRemComputeGroup (tcu::TestContext& testCtx, qpTestResult negFailResult)
1595 {
1596 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "opsrem", "Test the OpSRem instruction"));
1597 	de::Random						rnd				(deStringHash(group->getName()));
1598 	const int						numElements		= 200;
1599 
1600 	const struct CaseParams
1601 	{
1602 		const char*		name;
1603 		const char*		failMessage;		// customized status message
1604 		qpTestResult	failResult;			// override status on failure
1605 		int				op1Min, op1Max;		// operand ranges
1606 		int				op2Min, op2Max;
1607 	} cases[] =
1608 	{
1609 		{ "positive",	"Output doesn't match with expected",				QP_TEST_RESULT_FAIL,	0,		65536,	0,		100 },
1610 		{ "all",		"Inconsistent results, but within specification",	negFailResult,			-65536,	65536,	-100,	100 },	// see below
1611 	};
1612 	// If either operand is negative the result is undefined. Some implementations may still return correct values.
1613 
1614 	for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1615 	{
1616 		const CaseParams&	params		= cases[caseNdx];
1617 		ComputeShaderSpec	spec;
1618 		vector<deInt32>		inputInts1	(numElements, 0);
1619 		vector<deInt32>		inputInts2	(numElements, 0);
1620 		vector<deInt32>		outputInts	(numElements, 0);
1621 
1622 		fillRandomScalars(rnd, params.op1Min, params.op1Max, &inputInts1[0], numElements);
1623 		fillRandomScalars(rnd, params.op2Min, params.op2Max, &inputInts2[0], numElements, filterNotZero);
1624 
1625 		for (int ndx = 0; ndx < numElements; ++ndx)
1626 		{
1627 			// The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1628 			outputInts[ndx] = inputInts1[ndx] % inputInts2[ndx];
1629 		}
1630 
1631 		spec.assembly =
1632 			string(getComputeAsmShaderPreamble()) +
1633 
1634 			"OpName %main           \"main\"\n"
1635 			"OpName %id             \"gl_GlobalInvocationID\"\n"
1636 
1637 			"OpDecorate %id BuiltIn GlobalInvocationId\n"
1638 
1639 			"OpDecorate %buf BufferBlock\n"
1640 			"OpDecorate %indata1 DescriptorSet 0\n"
1641 			"OpDecorate %indata1 Binding 0\n"
1642 			"OpDecorate %indata2 DescriptorSet 0\n"
1643 			"OpDecorate %indata2 Binding 1\n"
1644 			"OpDecorate %outdata DescriptorSet 0\n"
1645 			"OpDecorate %outdata Binding 2\n"
1646 			"OpDecorate %i32arr ArrayStride 4\n"
1647 			"OpMemberDecorate %buf 0 Offset 0\n"
1648 
1649 			+ string(getComputeAsmCommonTypes()) +
1650 
1651 			"%buf        = OpTypeStruct %i32arr\n"
1652 			"%bufptr     = OpTypePointer Uniform %buf\n"
1653 			"%indata1    = OpVariable %bufptr Uniform\n"
1654 			"%indata2    = OpVariable %bufptr Uniform\n"
1655 			"%outdata    = OpVariable %bufptr Uniform\n"
1656 
1657 			"%id        = OpVariable %uvec3ptr Input\n"
1658 			"%zero      = OpConstant %i32 0\n"
1659 
1660 			"%main      = OpFunction %void None %voidf\n"
1661 			"%label     = OpLabel\n"
1662 			"%idval     = OpLoad %uvec3 %id\n"
1663 			"%x         = OpCompositeExtract %u32 %idval 0\n"
1664 			"%inloc1    = OpAccessChain %i32ptr %indata1 %zero %x\n"
1665 			"%inval1    = OpLoad %i32 %inloc1\n"
1666 			"%inloc2    = OpAccessChain %i32ptr %indata2 %zero %x\n"
1667 			"%inval2    = OpLoad %i32 %inloc2\n"
1668 			"%rem       = OpSRem %i32 %inval1 %inval2\n"
1669 			"%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
1670 			"             OpStore %outloc %rem\n"
1671 			"             OpReturn\n"
1672 			"             OpFunctionEnd\n";
1673 
1674 		spec.inputs.push_back	(BufferSp(new Int32Buffer(inputInts1)));
1675 		spec.inputs.push_back	(BufferSp(new Int32Buffer(inputInts2)));
1676 		spec.outputs.push_back	(BufferSp(new Int32Buffer(outputInts)));
1677 		spec.numWorkGroups		= IVec3(numElements, 1, 1);
1678 		spec.failResult			= params.failResult;
1679 		spec.failMessage		= params.failMessage;
1680 
1681 		group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1682 	}
1683 
1684 	return group.release();
1685 }
1686 
createOpSRemComputeGroup64(tcu::TestContext & testCtx,qpTestResult negFailResult)1687 tcu::TestCaseGroup* createOpSRemComputeGroup64 (tcu::TestContext& testCtx, qpTestResult negFailResult)
1688 {
1689 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "opsrem64", "Test the 64-bit OpSRem instruction"));
1690 	de::Random						rnd				(deStringHash(group->getName()));
1691 	const int						numElements		= 200;
1692 
1693 	const struct CaseParams
1694 	{
1695 		const char*		name;
1696 		const char*		failMessage;		// customized status message
1697 		qpTestResult	failResult;			// override status on failure
1698 		bool			positive;
1699 	} cases[] =
1700 	{
1701 		{ "positive",	"Output doesn't match with expected",				QP_TEST_RESULT_FAIL,	true },
1702 		{ "all",		"Inconsistent results, but within specification",	negFailResult,			false },	// see below
1703 	};
1704 	// If either operand is negative the result is undefined. Some implementations may still return correct values.
1705 
1706 	for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1707 	{
1708 		const CaseParams&	params		= cases[caseNdx];
1709 		ComputeShaderSpec	spec;
1710 		vector<deInt64>		inputInts1	(numElements, 0);
1711 		vector<deInt64>		inputInts2	(numElements, 0);
1712 		vector<deInt64>		outputInts	(numElements, 0);
1713 
1714 		if (params.positive)
1715 		{
1716 			fillRandomInt64sLogDistributed(rnd, inputInts1, numElements, filterNonNegative);
1717 			fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterPositive);
1718 		}
1719 		else
1720 		{
1721 			fillRandomInt64sLogDistributed(rnd, inputInts1, numElements);
1722 			fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterNotZero);
1723 		}
1724 
1725 		for (int ndx = 0; ndx < numElements; ++ndx)
1726 		{
1727 			// The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1728 			outputInts[ndx] = inputInts1[ndx] % inputInts2[ndx];
1729 		}
1730 
1731 		spec.assembly =
1732 			"OpCapability Int64\n"
1733 
1734 			+ string(getComputeAsmShaderPreamble()) +
1735 
1736 			"OpName %main           \"main\"\n"
1737 			"OpName %id             \"gl_GlobalInvocationID\"\n"
1738 
1739 			"OpDecorate %id BuiltIn GlobalInvocationId\n"
1740 
1741 			"OpDecorate %buf BufferBlock\n"
1742 			"OpDecorate %indata1 DescriptorSet 0\n"
1743 			"OpDecorate %indata1 Binding 0\n"
1744 			"OpDecorate %indata2 DescriptorSet 0\n"
1745 			"OpDecorate %indata2 Binding 1\n"
1746 			"OpDecorate %outdata DescriptorSet 0\n"
1747 			"OpDecorate %outdata Binding 2\n"
1748 			"OpDecorate %i64arr ArrayStride 8\n"
1749 			"OpMemberDecorate %buf 0 Offset 0\n"
1750 
1751 			+ string(getComputeAsmCommonTypes())
1752 			+ string(getComputeAsmCommonInt64Types()) +
1753 
1754 			"%buf        = OpTypeStruct %i64arr\n"
1755 			"%bufptr     = OpTypePointer Uniform %buf\n"
1756 			"%indata1    = OpVariable %bufptr Uniform\n"
1757 			"%indata2    = OpVariable %bufptr Uniform\n"
1758 			"%outdata    = OpVariable %bufptr Uniform\n"
1759 
1760 			"%id        = OpVariable %uvec3ptr Input\n"
1761 			"%zero      = OpConstant %i64 0\n"
1762 
1763 			"%main      = OpFunction %void None %voidf\n"
1764 			"%label     = OpLabel\n"
1765 			"%idval     = OpLoad %uvec3 %id\n"
1766 			"%x         = OpCompositeExtract %u32 %idval 0\n"
1767 			"%inloc1    = OpAccessChain %i64ptr %indata1 %zero %x\n"
1768 			"%inval1    = OpLoad %i64 %inloc1\n"
1769 			"%inloc2    = OpAccessChain %i64ptr %indata2 %zero %x\n"
1770 			"%inval2    = OpLoad %i64 %inloc2\n"
1771 			"%rem       = OpSRem %i64 %inval1 %inval2\n"
1772 			"%outloc    = OpAccessChain %i64ptr %outdata %zero %x\n"
1773 			"             OpStore %outloc %rem\n"
1774 			"             OpReturn\n"
1775 			"             OpFunctionEnd\n";
1776 
1777 		spec.inputs.push_back	(BufferSp(new Int64Buffer(inputInts1)));
1778 		spec.inputs.push_back	(BufferSp(new Int64Buffer(inputInts2)));
1779 		spec.outputs.push_back	(BufferSp(new Int64Buffer(outputInts)));
1780 		spec.numWorkGroups		= IVec3(numElements, 1, 1);
1781 		spec.failResult			= params.failResult;
1782 		spec.failMessage		= params.failMessage;
1783 
1784 		spec.requestedVulkanFeatures.coreFeatures.shaderInt64 = VK_TRUE;
1785 
1786 		group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1787 	}
1788 
1789 	return group.release();
1790 }
1791 
createOpSModComputeGroup(tcu::TestContext & testCtx,qpTestResult negFailResult)1792 tcu::TestCaseGroup* createOpSModComputeGroup (tcu::TestContext& testCtx, qpTestResult negFailResult)
1793 {
1794 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "opsmod", "Test the OpSMod instruction"));
1795 	de::Random						rnd				(deStringHash(group->getName()));
1796 	const int						numElements		= 200;
1797 
1798 	const struct CaseParams
1799 	{
1800 		const char*		name;
1801 		const char*		failMessage;		// customized status message
1802 		qpTestResult	failResult;			// override status on failure
1803 		int				op1Min, op1Max;		// operand ranges
1804 		int				op2Min, op2Max;
1805 	} cases[] =
1806 	{
1807 		{ "positive",	"Output doesn't match with expected",				QP_TEST_RESULT_FAIL,	0,		65536,	0,		100 },
1808 		{ "all",		"Inconsistent results, but within specification",	negFailResult,			-65536,	65536,	-100,	100 },	// see below
1809 	};
1810 	// If either operand is negative the result is undefined. Some implementations may still return correct values.
1811 
1812 	for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1813 	{
1814 		const CaseParams&	params		= cases[caseNdx];
1815 
1816 		ComputeShaderSpec	spec;
1817 		vector<deInt32>		inputInts1	(numElements, 0);
1818 		vector<deInt32>		inputInts2	(numElements, 0);
1819 		vector<deInt32>		outputInts	(numElements, 0);
1820 
1821 		fillRandomScalars(rnd, params.op1Min, params.op1Max, &inputInts1[0], numElements);
1822 		fillRandomScalars(rnd, params.op2Min, params.op2Max, &inputInts2[0], numElements, filterNotZero);
1823 
1824 		for (int ndx = 0; ndx < numElements; ++ndx)
1825 		{
1826 			deInt32 rem = inputInts1[ndx] % inputInts2[ndx];
1827 			if (rem == 0)
1828 			{
1829 				outputInts[ndx] = 0;
1830 			}
1831 			else if ((inputInts1[ndx] >= 0) == (inputInts2[ndx] >= 0))
1832 			{
1833 				// They have the same sign
1834 				outputInts[ndx] = rem;
1835 			}
1836 			else
1837 			{
1838 				// They have opposite sign.  The remainder operation takes the
1839 				// sign inputInts1[ndx] but OpSMod is supposed to take ths sign
1840 				// of inputInts2[ndx].  Adding inputInts2[ndx] will ensure that
1841 				// the result has the correct sign and that it is still
1842 				// congruent to inputInts1[ndx] modulo inputInts2[ndx]
1843 				//
1844 				// See also http://mathforum.org/library/drmath/view/52343.html
1845 				outputInts[ndx] = rem + inputInts2[ndx];
1846 			}
1847 		}
1848 
1849 		spec.assembly =
1850 			string(getComputeAsmShaderPreamble()) +
1851 
1852 			"OpName %main           \"main\"\n"
1853 			"OpName %id             \"gl_GlobalInvocationID\"\n"
1854 
1855 			"OpDecorate %id BuiltIn GlobalInvocationId\n"
1856 
1857 			"OpDecorate %buf BufferBlock\n"
1858 			"OpDecorate %indata1 DescriptorSet 0\n"
1859 			"OpDecorate %indata1 Binding 0\n"
1860 			"OpDecorate %indata2 DescriptorSet 0\n"
1861 			"OpDecorate %indata2 Binding 1\n"
1862 			"OpDecorate %outdata DescriptorSet 0\n"
1863 			"OpDecorate %outdata Binding 2\n"
1864 			"OpDecorate %i32arr ArrayStride 4\n"
1865 			"OpMemberDecorate %buf 0 Offset 0\n"
1866 
1867 			+ string(getComputeAsmCommonTypes()) +
1868 
1869 			"%buf        = OpTypeStruct %i32arr\n"
1870 			"%bufptr     = OpTypePointer Uniform %buf\n"
1871 			"%indata1    = OpVariable %bufptr Uniform\n"
1872 			"%indata2    = OpVariable %bufptr Uniform\n"
1873 			"%outdata    = OpVariable %bufptr Uniform\n"
1874 
1875 			"%id        = OpVariable %uvec3ptr Input\n"
1876 			"%zero      = OpConstant %i32 0\n"
1877 
1878 			"%main      = OpFunction %void None %voidf\n"
1879 			"%label     = OpLabel\n"
1880 			"%idval     = OpLoad %uvec3 %id\n"
1881 			"%x         = OpCompositeExtract %u32 %idval 0\n"
1882 			"%inloc1    = OpAccessChain %i32ptr %indata1 %zero %x\n"
1883 			"%inval1    = OpLoad %i32 %inloc1\n"
1884 			"%inloc2    = OpAccessChain %i32ptr %indata2 %zero %x\n"
1885 			"%inval2    = OpLoad %i32 %inloc2\n"
1886 			"%rem       = OpSMod %i32 %inval1 %inval2\n"
1887 			"%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
1888 			"             OpStore %outloc %rem\n"
1889 			"             OpReturn\n"
1890 			"             OpFunctionEnd\n";
1891 
1892 		spec.inputs.push_back	(BufferSp(new Int32Buffer(inputInts1)));
1893 		spec.inputs.push_back	(BufferSp(new Int32Buffer(inputInts2)));
1894 		spec.outputs.push_back	(BufferSp(new Int32Buffer(outputInts)));
1895 		spec.numWorkGroups		= IVec3(numElements, 1, 1);
1896 		spec.failResult			= params.failResult;
1897 		spec.failMessage		= params.failMessage;
1898 
1899 		group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1900 	}
1901 
1902 	return group.release();
1903 }
1904 
createOpSModComputeGroup64(tcu::TestContext & testCtx,qpTestResult negFailResult)1905 tcu::TestCaseGroup* createOpSModComputeGroup64 (tcu::TestContext& testCtx, qpTestResult negFailResult)
1906 {
1907 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "opsmod64", "Test the OpSMod instruction"));
1908 	de::Random						rnd				(deStringHash(group->getName()));
1909 	const int						numElements		= 200;
1910 
1911 	const struct CaseParams
1912 	{
1913 		const char*		name;
1914 		const char*		failMessage;		// customized status message
1915 		qpTestResult	failResult;			// override status on failure
1916 		bool			positive;
1917 	} cases[] =
1918 	{
1919 		{ "positive",	"Output doesn't match with expected",				QP_TEST_RESULT_FAIL,	true },
1920 		{ "all",		"Inconsistent results, but within specification",	negFailResult,			false },	// see below
1921 	};
1922 	// If either operand is negative the result is undefined. Some implementations may still return correct values.
1923 
1924 	for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1925 	{
1926 		const CaseParams&	params		= cases[caseNdx];
1927 
1928 		ComputeShaderSpec	spec;
1929 		vector<deInt64>		inputInts1	(numElements, 0);
1930 		vector<deInt64>		inputInts2	(numElements, 0);
1931 		vector<deInt64>		outputInts	(numElements, 0);
1932 
1933 
1934 		if (params.positive)
1935 		{
1936 			fillRandomInt64sLogDistributed(rnd, inputInts1, numElements, filterNonNegative);
1937 			fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterPositive);
1938 		}
1939 		else
1940 		{
1941 			fillRandomInt64sLogDistributed(rnd, inputInts1, numElements);
1942 			fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterNotZero);
1943 		}
1944 
1945 		for (int ndx = 0; ndx < numElements; ++ndx)
1946 		{
1947 			deInt64 rem = inputInts1[ndx] % inputInts2[ndx];
1948 			if (rem == 0)
1949 			{
1950 				outputInts[ndx] = 0;
1951 			}
1952 			else if ((inputInts1[ndx] >= 0) == (inputInts2[ndx] >= 0))
1953 			{
1954 				// They have the same sign
1955 				outputInts[ndx] = rem;
1956 			}
1957 			else
1958 			{
1959 				// They have opposite sign.  The remainder operation takes the
1960 				// sign inputInts1[ndx] but OpSMod is supposed to take ths sign
1961 				// of inputInts2[ndx].  Adding inputInts2[ndx] will ensure that
1962 				// the result has the correct sign and that it is still
1963 				// congruent to inputInts1[ndx] modulo inputInts2[ndx]
1964 				//
1965 				// See also http://mathforum.org/library/drmath/view/52343.html
1966 				outputInts[ndx] = rem + inputInts2[ndx];
1967 			}
1968 		}
1969 
1970 		spec.assembly =
1971 			"OpCapability Int64\n"
1972 
1973 			+ string(getComputeAsmShaderPreamble()) +
1974 
1975 			"OpName %main           \"main\"\n"
1976 			"OpName %id             \"gl_GlobalInvocationID\"\n"
1977 
1978 			"OpDecorate %id BuiltIn GlobalInvocationId\n"
1979 
1980 			"OpDecorate %buf BufferBlock\n"
1981 			"OpDecorate %indata1 DescriptorSet 0\n"
1982 			"OpDecorate %indata1 Binding 0\n"
1983 			"OpDecorate %indata2 DescriptorSet 0\n"
1984 			"OpDecorate %indata2 Binding 1\n"
1985 			"OpDecorate %outdata DescriptorSet 0\n"
1986 			"OpDecorate %outdata Binding 2\n"
1987 			"OpDecorate %i64arr ArrayStride 8\n"
1988 			"OpMemberDecorate %buf 0 Offset 0\n"
1989 
1990 			+ string(getComputeAsmCommonTypes())
1991 			+ string(getComputeAsmCommonInt64Types()) +
1992 
1993 			"%buf        = OpTypeStruct %i64arr\n"
1994 			"%bufptr     = OpTypePointer Uniform %buf\n"
1995 			"%indata1    = OpVariable %bufptr Uniform\n"
1996 			"%indata2    = OpVariable %bufptr Uniform\n"
1997 			"%outdata    = OpVariable %bufptr Uniform\n"
1998 
1999 			"%id        = OpVariable %uvec3ptr Input\n"
2000 			"%zero      = OpConstant %i64 0\n"
2001 
2002 			"%main      = OpFunction %void None %voidf\n"
2003 			"%label     = OpLabel\n"
2004 			"%idval     = OpLoad %uvec3 %id\n"
2005 			"%x         = OpCompositeExtract %u32 %idval 0\n"
2006 			"%inloc1    = OpAccessChain %i64ptr %indata1 %zero %x\n"
2007 			"%inval1    = OpLoad %i64 %inloc1\n"
2008 			"%inloc2    = OpAccessChain %i64ptr %indata2 %zero %x\n"
2009 			"%inval2    = OpLoad %i64 %inloc2\n"
2010 			"%rem       = OpSMod %i64 %inval1 %inval2\n"
2011 			"%outloc    = OpAccessChain %i64ptr %outdata %zero %x\n"
2012 			"             OpStore %outloc %rem\n"
2013 			"             OpReturn\n"
2014 			"             OpFunctionEnd\n";
2015 
2016 		spec.inputs.push_back	(BufferSp(new Int64Buffer(inputInts1)));
2017 		spec.inputs.push_back	(BufferSp(new Int64Buffer(inputInts2)));
2018 		spec.outputs.push_back	(BufferSp(new Int64Buffer(outputInts)));
2019 		spec.numWorkGroups		= IVec3(numElements, 1, 1);
2020 		spec.failResult			= params.failResult;
2021 		spec.failMessage		= params.failMessage;
2022 
2023 		spec.requestedVulkanFeatures.coreFeatures.shaderInt64 = VK_TRUE;
2024 
2025 		group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
2026 	}
2027 
2028 	return group.release();
2029 }
2030 
2031 // Copy contents in the input buffer to the output buffer.
createOpCopyMemoryGroup(tcu::TestContext & testCtx)2032 tcu::TestCaseGroup* createOpCopyMemoryGroup (tcu::TestContext& testCtx)
2033 {
2034 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "opcopymemory", "Test the OpCopyMemory instruction"));
2035 	de::Random						rnd				(deStringHash(group->getName()));
2036 	const int						numElements		= 100;
2037 
2038 	// 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.
2039 	ComputeShaderSpec				spec1;
2040 	vector<Vec4>					inputFloats1	(numElements);
2041 	vector<Vec4>					outputFloats1	(numElements);
2042 
2043 	fillRandomScalars(rnd, -200.f, 200.f, &inputFloats1[0], numElements * 4);
2044 
2045 	// CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2046 	floorAll(inputFloats1);
2047 
2048 	for (size_t ndx = 0; ndx < numElements; ++ndx)
2049 		outputFloats1[ndx] = inputFloats1[ndx] + Vec4(0.f, 0.5f, 1.5f, 2.5f);
2050 
2051 	spec1.assembly =
2052 		string(getComputeAsmShaderPreamble()) +
2053 
2054 		"OpName %main           \"main\"\n"
2055 		"OpName %id             \"gl_GlobalInvocationID\"\n"
2056 
2057 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
2058 		"OpDecorate %vec4arr ArrayStride 16\n"
2059 
2060 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2061 
2062 		"%vec4       = OpTypeVector %f32 4\n"
2063 		"%vec4ptr_u  = OpTypePointer Uniform %vec4\n"
2064 		"%vec4ptr_f  = OpTypePointer Function %vec4\n"
2065 		"%vec4arr    = OpTypeRuntimeArray %vec4\n"
2066 		"%buf        = OpTypeStruct %vec4arr\n"
2067 		"%bufptr     = OpTypePointer Uniform %buf\n"
2068 		"%indata     = OpVariable %bufptr Uniform\n"
2069 		"%outdata    = OpVariable %bufptr Uniform\n"
2070 
2071 		"%id         = OpVariable %uvec3ptr Input\n"
2072 		"%zero       = OpConstant %i32 0\n"
2073 		"%c_f_0      = OpConstant %f32 0.\n"
2074 		"%c_f_0_5    = OpConstant %f32 0.5\n"
2075 		"%c_f_1_5    = OpConstant %f32 1.5\n"
2076 		"%c_f_2_5    = OpConstant %f32 2.5\n"
2077 		"%c_vec4     = OpConstantComposite %vec4 %c_f_0 %c_f_0_5 %c_f_1_5 %c_f_2_5\n"
2078 
2079 		"%main       = OpFunction %void None %voidf\n"
2080 		"%label      = OpLabel\n"
2081 		"%v_vec4     = OpVariable %vec4ptr_f Function\n"
2082 		"%idval      = OpLoad %uvec3 %id\n"
2083 		"%x          = OpCompositeExtract %u32 %idval 0\n"
2084 		"%inloc      = OpAccessChain %vec4ptr_u %indata %zero %x\n"
2085 		"%outloc     = OpAccessChain %vec4ptr_u %outdata %zero %x\n"
2086 		"              OpCopyMemory %v_vec4 %inloc\n"
2087 		"%v_vec4_val = OpLoad %vec4 %v_vec4\n"
2088 		"%add        = OpFAdd %vec4 %v_vec4_val %c_vec4\n"
2089 		"              OpStore %outloc %add\n"
2090 		"              OpReturn\n"
2091 		"              OpFunctionEnd\n";
2092 
2093 	spec1.inputs.push_back(BufferSp(new Vec4Buffer(inputFloats1)));
2094 	spec1.outputs.push_back(BufferSp(new Vec4Buffer(outputFloats1)));
2095 	spec1.numWorkGroups = IVec3(numElements, 1, 1);
2096 
2097 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector", "OpCopyMemory elements of vector type", spec1));
2098 
2099 	// The following case copies a float[100] variable from the input buffer to the output buffer.
2100 	ComputeShaderSpec				spec2;
2101 	vector<float>					inputFloats2	(numElements);
2102 	vector<float>					outputFloats2	(numElements);
2103 
2104 	fillRandomScalars(rnd, -200.f, 200.f, &inputFloats2[0], numElements);
2105 
2106 	for (size_t ndx = 0; ndx < numElements; ++ndx)
2107 		outputFloats2[ndx] = inputFloats2[ndx];
2108 
2109 	spec2.assembly =
2110 		string(getComputeAsmShaderPreamble()) +
2111 
2112 		"OpName %main           \"main\"\n"
2113 		"OpName %id             \"gl_GlobalInvocationID\"\n"
2114 
2115 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
2116 		"OpDecorate %f32arr100 ArrayStride 4\n"
2117 
2118 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2119 
2120 		"%hundred        = OpConstant %u32 100\n"
2121 		"%f32arr100      = OpTypeArray %f32 %hundred\n"
2122 		"%f32arr100ptr_f = OpTypePointer Function %f32arr100\n"
2123 		"%f32arr100ptr_u = OpTypePointer Uniform %f32arr100\n"
2124 		"%buf            = OpTypeStruct %f32arr100\n"
2125 		"%bufptr         = OpTypePointer Uniform %buf\n"
2126 		"%indata         = OpVariable %bufptr Uniform\n"
2127 		"%outdata        = OpVariable %bufptr Uniform\n"
2128 
2129 		"%id             = OpVariable %uvec3ptr Input\n"
2130 		"%zero           = OpConstant %i32 0\n"
2131 
2132 		"%main           = OpFunction %void None %voidf\n"
2133 		"%label          = OpLabel\n"
2134 		"%var            = OpVariable %f32arr100ptr_f Function\n"
2135 		"%inarr          = OpAccessChain %f32arr100ptr_u %indata %zero\n"
2136 		"%outarr         = OpAccessChain %f32arr100ptr_u %outdata %zero\n"
2137 		"                  OpCopyMemory %var %inarr\n"
2138 		"                  OpCopyMemory %outarr %var\n"
2139 		"                  OpReturn\n"
2140 		"                  OpFunctionEnd\n";
2141 
2142 	spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
2143 	spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
2144 	spec2.numWorkGroups = IVec3(1, 1, 1);
2145 
2146 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "array", "OpCopyMemory elements of array type", spec2));
2147 
2148 	// The following case copies a struct{vec4, vec4, vec4, vec4} variable from the input buffer to the output buffer.
2149 	ComputeShaderSpec				spec3;
2150 	vector<float>					inputFloats3	(16);
2151 	vector<float>					outputFloats3	(16);
2152 
2153 	fillRandomScalars(rnd, -200.f, 200.f, &inputFloats3[0], 16);
2154 
2155 	for (size_t ndx = 0; ndx < 16; ++ndx)
2156 		outputFloats3[ndx] = inputFloats3[ndx];
2157 
2158 	spec3.assembly =
2159 		string(getComputeAsmShaderPreamble()) +
2160 
2161 		"OpName %main           \"main\"\n"
2162 		"OpName %id             \"gl_GlobalInvocationID\"\n"
2163 
2164 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
2165 		//"OpMemberDecorate %buf 0 Offset 0\n"  - exists in getComputeAsmInputOutputBufferTraits
2166 		"OpMemberDecorate %buf 1 Offset 16\n"
2167 		"OpMemberDecorate %buf 2 Offset 32\n"
2168 		"OpMemberDecorate %buf 3 Offset 48\n"
2169 
2170 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2171 
2172 		"%vec4      = OpTypeVector %f32 4\n"
2173 		"%buf       = OpTypeStruct %vec4 %vec4 %vec4 %vec4\n"
2174 		"%bufptr    = OpTypePointer Uniform %buf\n"
2175 		"%indata    = OpVariable %bufptr Uniform\n"
2176 		"%outdata   = OpVariable %bufptr Uniform\n"
2177 		"%vec4stptr = OpTypePointer Function %buf\n"
2178 
2179 		"%id        = OpVariable %uvec3ptr Input\n"
2180 		"%zero      = OpConstant %i32 0\n"
2181 
2182 		"%main      = OpFunction %void None %voidf\n"
2183 		"%label     = OpLabel\n"
2184 		"%var       = OpVariable %vec4stptr Function\n"
2185 		"             OpCopyMemory %var %indata\n"
2186 		"             OpCopyMemory %outdata %var\n"
2187 		"             OpReturn\n"
2188 		"             OpFunctionEnd\n";
2189 
2190 	spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
2191 	spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
2192 	spec3.numWorkGroups = IVec3(1, 1, 1);
2193 
2194 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "struct", "OpCopyMemory elements of struct type", spec3));
2195 
2196 	// The following case negates multiple float variables from the input buffer and stores the results to the output buffer.
2197 	ComputeShaderSpec				spec4;
2198 	vector<float>					inputFloats4	(numElements);
2199 	vector<float>					outputFloats4	(numElements);
2200 
2201 	fillRandomScalars(rnd, -200.f, 200.f, &inputFloats4[0], numElements);
2202 
2203 	for (size_t ndx = 0; ndx < numElements; ++ndx)
2204 		outputFloats4[ndx] = -inputFloats4[ndx];
2205 
2206 	spec4.assembly =
2207 		string(getComputeAsmShaderPreamble()) +
2208 
2209 		"OpName %main           \"main\"\n"
2210 		"OpName %id             \"gl_GlobalInvocationID\"\n"
2211 
2212 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
2213 
2214 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2215 
2216 		"%f32ptr_f  = OpTypePointer Function %f32\n"
2217 		"%id        = OpVariable %uvec3ptr Input\n"
2218 		"%zero      = OpConstant %i32 0\n"
2219 
2220 		"%main      = OpFunction %void None %voidf\n"
2221 		"%label     = OpLabel\n"
2222 		"%var       = OpVariable %f32ptr_f Function\n"
2223 		"%idval     = OpLoad %uvec3 %id\n"
2224 		"%x         = OpCompositeExtract %u32 %idval 0\n"
2225 		"%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
2226 		"%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
2227 		"             OpCopyMemory %var %inloc\n"
2228 		"%val       = OpLoad %f32 %var\n"
2229 		"%neg       = OpFNegate %f32 %val\n"
2230 		"             OpStore %outloc %neg\n"
2231 		"             OpReturn\n"
2232 		"             OpFunctionEnd\n";
2233 
2234 	spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
2235 	spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
2236 	spec4.numWorkGroups = IVec3(numElements, 1, 1);
2237 
2238 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "float", "OpCopyMemory elements of float type", spec4));
2239 
2240 	return group.release();
2241 }
2242 
createOpCopyObjectGroup(tcu::TestContext & testCtx)2243 tcu::TestCaseGroup* createOpCopyObjectGroup (tcu::TestContext& testCtx)
2244 {
2245 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "opcopyobject", "Test the OpCopyObject instruction"));
2246 	ComputeShaderSpec				spec;
2247 	de::Random						rnd				(deStringHash(group->getName()));
2248 	const int						numElements		= 100;
2249 	vector<float>					inputFloats		(numElements, 0);
2250 	vector<float>					outputFloats	(numElements, 0);
2251 
2252 	fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
2253 
2254 	// CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2255 	floorAll(inputFloats);
2256 
2257 	for (size_t ndx = 0; ndx < numElements; ++ndx)
2258 		outputFloats[ndx] = inputFloats[ndx] + 7.5f;
2259 
2260 	spec.assembly =
2261 		string(getComputeAsmShaderPreamble()) +
2262 
2263 		"OpName %main           \"main\"\n"
2264 		"OpName %id             \"gl_GlobalInvocationID\"\n"
2265 
2266 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
2267 
2268 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2269 
2270 		"%fmat     = OpTypeMatrix %fvec3 3\n"
2271 		"%three    = OpConstant %u32 3\n"
2272 		"%farr     = OpTypeArray %f32 %three\n"
2273 		"%fst      = OpTypeStruct %f32 %f32\n"
2274 
2275 		+ string(getComputeAsmInputOutputBuffer()) +
2276 
2277 		"%id            = OpVariable %uvec3ptr Input\n"
2278 		"%zero          = OpConstant %i32 0\n"
2279 		"%c_f           = OpConstant %f32 1.5\n"
2280 		"%c_fvec3       = OpConstantComposite %fvec3 %c_f %c_f %c_f\n"
2281 		"%c_fmat        = OpConstantComposite %fmat %c_fvec3 %c_fvec3 %c_fvec3\n"
2282 		"%c_farr        = OpConstantComposite %farr %c_f %c_f %c_f\n"
2283 		"%c_fst         = OpConstantComposite %fst %c_f %c_f\n"
2284 
2285 		"%main          = OpFunction %void None %voidf\n"
2286 		"%label         = OpLabel\n"
2287 		"%c_f_copy      = OpCopyObject %f32   %c_f\n"
2288 		"%c_fvec3_copy  = OpCopyObject %fvec3 %c_fvec3\n"
2289 		"%c_fmat_copy   = OpCopyObject %fmat  %c_fmat\n"
2290 		"%c_farr_copy   = OpCopyObject %farr  %c_farr\n"
2291 		"%c_fst_copy    = OpCopyObject %fst   %c_fst\n"
2292 		"%fvec3_elem    = OpCompositeExtract %f32 %c_fvec3_copy 0\n"
2293 		"%fmat_elem     = OpCompositeExtract %f32 %c_fmat_copy 1 2\n"
2294 		"%farr_elem     = OpCompositeExtract %f32 %c_farr_copy 2\n"
2295 		"%fst_elem      = OpCompositeExtract %f32 %c_fst_copy 1\n"
2296 		// Add up. 1.5 * 5 = 7.5.
2297 		"%add1          = OpFAdd %f32 %c_f_copy %fvec3_elem\n"
2298 		"%add2          = OpFAdd %f32 %add1     %fmat_elem\n"
2299 		"%add3          = OpFAdd %f32 %add2     %farr_elem\n"
2300 		"%add4          = OpFAdd %f32 %add3     %fst_elem\n"
2301 
2302 		"%idval         = OpLoad %uvec3 %id\n"
2303 		"%x             = OpCompositeExtract %u32 %idval 0\n"
2304 		"%inloc         = OpAccessChain %f32ptr %indata %zero %x\n"
2305 		"%outloc        = OpAccessChain %f32ptr %outdata %zero %x\n"
2306 		"%inval         = OpLoad %f32 %inloc\n"
2307 		"%add           = OpFAdd %f32 %add4 %inval\n"
2308 		"                 OpStore %outloc %add\n"
2309 		"                 OpReturn\n"
2310 		"                 OpFunctionEnd\n";
2311 	spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2312 	spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2313 	spec.numWorkGroups = IVec3(numElements, 1, 1);
2314 
2315 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "OpCopyObject on different types", spec));
2316 
2317 	return group.release();
2318 }
2319 // Assembly code used for testing OpUnreachable is based on GLSL source code:
2320 //
2321 // #version 430
2322 //
2323 // layout(std140, set = 0, binding = 0) readonly buffer Input {
2324 //   float elements[];
2325 // } input_data;
2326 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
2327 //   float elements[];
2328 // } output_data;
2329 //
2330 // void not_called_func() {
2331 //   // place OpUnreachable here
2332 // }
2333 //
2334 // uint modulo4(uint val) {
2335 //   switch (val % uint(4)) {
2336 //     case 0:  return 3;
2337 //     case 1:  return 2;
2338 //     case 2:  return 1;
2339 //     case 3:  return 0;
2340 //     default: return 100; // place OpUnreachable here
2341 //   }
2342 // }
2343 //
2344 // uint const5() {
2345 //   return 5;
2346 //   // place OpUnreachable here
2347 // }
2348 //
2349 // void main() {
2350 //   uint x = gl_GlobalInvocationID.x;
2351 //   if (const5() > modulo4(1000)) {
2352 //     output_data.elements[x] = -input_data.elements[x];
2353 //   } else {
2354 //     // place OpUnreachable here
2355 //     output_data.elements[x] = input_data.elements[x];
2356 //   }
2357 // }
2358 
createOpUnreachableGroup(tcu::TestContext & testCtx)2359 tcu::TestCaseGroup* createOpUnreachableGroup (tcu::TestContext& testCtx)
2360 {
2361 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "opunreachable", "Test the OpUnreachable instruction"));
2362 	ComputeShaderSpec				spec;
2363 	de::Random						rnd				(deStringHash(group->getName()));
2364 	const int						numElements		= 100;
2365 	vector<float>					positiveFloats	(numElements, 0);
2366 	vector<float>					negativeFloats	(numElements, 0);
2367 
2368 	fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
2369 
2370 	for (size_t ndx = 0; ndx < numElements; ++ndx)
2371 		negativeFloats[ndx] = -positiveFloats[ndx];
2372 
2373 	spec.assembly =
2374 		string(getComputeAsmShaderPreamble()) +
2375 
2376 		"OpSource GLSL 430\n"
2377 		"OpName %main            \"main\"\n"
2378 		"OpName %func_not_called_func \"not_called_func(\"\n"
2379 		"OpName %func_modulo4         \"modulo4(u1;\"\n"
2380 		"OpName %func_const5          \"const5(\"\n"
2381 		"OpName %id                   \"gl_GlobalInvocationID\"\n"
2382 
2383 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
2384 
2385 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2386 
2387 		"%u32ptr    = OpTypePointer Function %u32\n"
2388 		"%uintfuint = OpTypeFunction %u32 %u32ptr\n"
2389 		"%unitf     = OpTypeFunction %u32\n"
2390 
2391 		"%id        = OpVariable %uvec3ptr Input\n"
2392 		"%zero      = OpConstant %u32 0\n"
2393 		"%one       = OpConstant %u32 1\n"
2394 		"%two       = OpConstant %u32 2\n"
2395 		"%three     = OpConstant %u32 3\n"
2396 		"%four      = OpConstant %u32 4\n"
2397 		"%five      = OpConstant %u32 5\n"
2398 		"%hundred   = OpConstant %u32 100\n"
2399 		"%thousand  = OpConstant %u32 1000\n"
2400 
2401 		+ string(getComputeAsmInputOutputBuffer()) +
2402 
2403 		// Main()
2404 		"%main   = OpFunction %void None %voidf\n"
2405 		"%main_entry  = OpLabel\n"
2406 		"%v_thousand  = OpVariable %u32ptr Function %thousand\n"
2407 		"%idval       = OpLoad %uvec3 %id\n"
2408 		"%x           = OpCompositeExtract %u32 %idval 0\n"
2409 		"%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
2410 		"%inval       = OpLoad %f32 %inloc\n"
2411 		"%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
2412 		"%ret_const5  = OpFunctionCall %u32 %func_const5\n"
2413 		"%ret_modulo4 = OpFunctionCall %u32 %func_modulo4 %v_thousand\n"
2414 		"%cmp_gt      = OpUGreaterThan %bool %ret_const5 %ret_modulo4\n"
2415 		"               OpSelectionMerge %if_end None\n"
2416 		"               OpBranchConditional %cmp_gt %if_true %if_false\n"
2417 		"%if_true     = OpLabel\n"
2418 		"%negate      = OpFNegate %f32 %inval\n"
2419 		"               OpStore %outloc %negate\n"
2420 		"               OpBranch %if_end\n"
2421 		"%if_false    = OpLabel\n"
2422 		"               OpUnreachable\n" // Unreachable else branch for if statement
2423 		"%if_end      = OpLabel\n"
2424 		"               OpReturn\n"
2425 		"               OpFunctionEnd\n"
2426 
2427 		// not_called_function()
2428 		"%func_not_called_func  = OpFunction %void None %voidf\n"
2429 		"%not_called_func_entry = OpLabel\n"
2430 		"                         OpUnreachable\n" // Unreachable entry block in not called static function
2431 		"                         OpFunctionEnd\n"
2432 
2433 		// modulo4()
2434 		"%func_modulo4  = OpFunction %u32 None %uintfuint\n"
2435 		"%valptr        = OpFunctionParameter %u32ptr\n"
2436 		"%modulo4_entry = OpLabel\n"
2437 		"%val           = OpLoad %u32 %valptr\n"
2438 		"%modulo        = OpUMod %u32 %val %four\n"
2439 		"                 OpSelectionMerge %switch_merge None\n"
2440 		"                 OpSwitch %modulo %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
2441 		"%case0         = OpLabel\n"
2442 		"                 OpReturnValue %three\n"
2443 		"%case1         = OpLabel\n"
2444 		"                 OpReturnValue %two\n"
2445 		"%case2         = OpLabel\n"
2446 		"                 OpReturnValue %one\n"
2447 		"%case3         = OpLabel\n"
2448 		"                 OpReturnValue %zero\n"
2449 		"%default       = OpLabel\n"
2450 		"                 OpUnreachable\n" // Unreachable default case for switch statement
2451 		"%switch_merge  = OpLabel\n"
2452 		"                 OpUnreachable\n" // Unreachable merge block for switch statement
2453 		"                 OpFunctionEnd\n"
2454 
2455 		// const5()
2456 		"%func_const5  = OpFunction %u32 None %unitf\n"
2457 		"%const5_entry = OpLabel\n"
2458 		"                OpReturnValue %five\n"
2459 		"%unreachable  = OpLabel\n"
2460 		"                OpUnreachable\n" // Unreachable block in function
2461 		"                OpFunctionEnd\n";
2462 	spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
2463 	spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
2464 	spec.numWorkGroups = IVec3(numElements, 1, 1);
2465 
2466 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpUnreachable appearing at different places", spec));
2467 
2468 	return group.release();
2469 }
2470 
2471 // Assembly code used for testing decoration group is based on GLSL source code:
2472 //
2473 // #version 430
2474 //
2475 // layout(std140, set = 0, binding = 0) readonly buffer Input0 {
2476 //   float elements[];
2477 // } input_data0;
2478 // layout(std140, set = 0, binding = 1) readonly buffer Input1 {
2479 //   float elements[];
2480 // } input_data1;
2481 // layout(std140, set = 0, binding = 2) readonly buffer Input2 {
2482 //   float elements[];
2483 // } input_data2;
2484 // layout(std140, set = 0, binding = 3) readonly buffer Input3 {
2485 //   float elements[];
2486 // } input_data3;
2487 // layout(std140, set = 0, binding = 4) readonly buffer Input4 {
2488 //   float elements[];
2489 // } input_data4;
2490 // layout(std140, set = 0, binding = 5) writeonly buffer Output {
2491 //   float elements[];
2492 // } output_data;
2493 //
2494 // void main() {
2495 //   uint x = gl_GlobalInvocationID.x;
2496 //   output_data.elements[x] = input_data0.elements[x] + input_data1.elements[x] + input_data2.elements[x] + input_data3.elements[x] + input_data4.elements[x];
2497 // }
createDecorationGroupGroup(tcu::TestContext & testCtx)2498 tcu::TestCaseGroup* createDecorationGroupGroup (tcu::TestContext& testCtx)
2499 {
2500 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "decoration_group", "Test the OpDecorationGroup & OpGroupDecorate instruction"));
2501 	ComputeShaderSpec				spec;
2502 	de::Random						rnd				(deStringHash(group->getName()));
2503 	const int						numElements		= 100;
2504 	vector<float>					inputFloats0	(numElements, 0);
2505 	vector<float>					inputFloats1	(numElements, 0);
2506 	vector<float>					inputFloats2	(numElements, 0);
2507 	vector<float>					inputFloats3	(numElements, 0);
2508 	vector<float>					inputFloats4	(numElements, 0);
2509 	vector<float>					outputFloats	(numElements, 0);
2510 
2511 	fillRandomScalars(rnd, -300.f, 300.f, &inputFloats0[0], numElements);
2512 	fillRandomScalars(rnd, -300.f, 300.f, &inputFloats1[0], numElements);
2513 	fillRandomScalars(rnd, -300.f, 300.f, &inputFloats2[0], numElements);
2514 	fillRandomScalars(rnd, -300.f, 300.f, &inputFloats3[0], numElements);
2515 	fillRandomScalars(rnd, -300.f, 300.f, &inputFloats4[0], numElements);
2516 
2517 	// CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2518 	floorAll(inputFloats0);
2519 	floorAll(inputFloats1);
2520 	floorAll(inputFloats2);
2521 	floorAll(inputFloats3);
2522 	floorAll(inputFloats4);
2523 
2524 	for (size_t ndx = 0; ndx < numElements; ++ndx)
2525 		outputFloats[ndx] = inputFloats0[ndx] + inputFloats1[ndx] + inputFloats2[ndx] + inputFloats3[ndx] + inputFloats4[ndx];
2526 
2527 	spec.assembly =
2528 		string(getComputeAsmShaderPreamble()) +
2529 
2530 		"OpSource GLSL 430\n"
2531 		"OpName %main \"main\"\n"
2532 		"OpName %id \"gl_GlobalInvocationID\"\n"
2533 
2534 		// Not using group decoration on variable.
2535 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
2536 		// Not using group decoration on type.
2537 		"OpDecorate %f32arr ArrayStride 4\n"
2538 
2539 		"OpDecorate %groups BufferBlock\n"
2540 		"OpDecorate %groupm Offset 0\n"
2541 		"%groups = OpDecorationGroup\n"
2542 		"%groupm = OpDecorationGroup\n"
2543 
2544 		// Group decoration on multiple structs.
2545 		"OpGroupDecorate %groups %outbuf %inbuf0 %inbuf1 %inbuf2 %inbuf3 %inbuf4\n"
2546 		// Group decoration on multiple struct members.
2547 		"OpGroupMemberDecorate %groupm %outbuf 0 %inbuf0 0 %inbuf1 0 %inbuf2 0 %inbuf3 0 %inbuf4 0\n"
2548 
2549 		"OpDecorate %group1 DescriptorSet 0\n"
2550 		"OpDecorate %group3 DescriptorSet 0\n"
2551 		"OpDecorate %group3 NonWritable\n"
2552 		"OpDecorate %group3 Restrict\n"
2553 		"%group0 = OpDecorationGroup\n"
2554 		"%group1 = OpDecorationGroup\n"
2555 		"%group3 = OpDecorationGroup\n"
2556 
2557 		// Applying the same decoration group multiple times.
2558 		"OpGroupDecorate %group1 %outdata\n"
2559 		"OpGroupDecorate %group1 %outdata\n"
2560 		"OpGroupDecorate %group1 %outdata\n"
2561 		"OpDecorate %outdata DescriptorSet 0\n"
2562 		"OpDecorate %outdata Binding 5\n"
2563 		// Applying decoration group containing nothing.
2564 		"OpGroupDecorate %group0 %indata0\n"
2565 		"OpDecorate %indata0 DescriptorSet 0\n"
2566 		"OpDecorate %indata0 Binding 0\n"
2567 		// Applying decoration group containing one decoration.
2568 		"OpGroupDecorate %group1 %indata1\n"
2569 		"OpDecorate %indata1 Binding 1\n"
2570 		// Applying decoration group containing multiple decorations.
2571 		"OpGroupDecorate %group3 %indata2 %indata3\n"
2572 		"OpDecorate %indata2 Binding 2\n"
2573 		"OpDecorate %indata3 Binding 3\n"
2574 		// Applying multiple decoration groups (with overlapping).
2575 		"OpGroupDecorate %group0 %indata4\n"
2576 		"OpGroupDecorate %group1 %indata4\n"
2577 		"OpGroupDecorate %group3 %indata4\n"
2578 		"OpDecorate %indata4 Binding 4\n"
2579 
2580 		+ string(getComputeAsmCommonTypes()) +
2581 
2582 		"%id   = OpVariable %uvec3ptr Input\n"
2583 		"%zero = OpConstant %i32 0\n"
2584 
2585 		"%outbuf    = OpTypeStruct %f32arr\n"
2586 		"%outbufptr = OpTypePointer Uniform %outbuf\n"
2587 		"%outdata   = OpVariable %outbufptr Uniform\n"
2588 		"%inbuf0    = OpTypeStruct %f32arr\n"
2589 		"%inbuf0ptr = OpTypePointer Uniform %inbuf0\n"
2590 		"%indata0   = OpVariable %inbuf0ptr Uniform\n"
2591 		"%inbuf1    = OpTypeStruct %f32arr\n"
2592 		"%inbuf1ptr = OpTypePointer Uniform %inbuf1\n"
2593 		"%indata1   = OpVariable %inbuf1ptr Uniform\n"
2594 		"%inbuf2    = OpTypeStruct %f32arr\n"
2595 		"%inbuf2ptr = OpTypePointer Uniform %inbuf2\n"
2596 		"%indata2   = OpVariable %inbuf2ptr Uniform\n"
2597 		"%inbuf3    = OpTypeStruct %f32arr\n"
2598 		"%inbuf3ptr = OpTypePointer Uniform %inbuf3\n"
2599 		"%indata3   = OpVariable %inbuf3ptr Uniform\n"
2600 		"%inbuf4    = OpTypeStruct %f32arr\n"
2601 		"%inbufptr  = OpTypePointer Uniform %inbuf4\n"
2602 		"%indata4   = OpVariable %inbufptr Uniform\n"
2603 
2604 		"%main   = OpFunction %void None %voidf\n"
2605 		"%label  = OpLabel\n"
2606 		"%idval  = OpLoad %uvec3 %id\n"
2607 		"%x      = OpCompositeExtract %u32 %idval 0\n"
2608 		"%inloc0 = OpAccessChain %f32ptr %indata0 %zero %x\n"
2609 		"%inloc1 = OpAccessChain %f32ptr %indata1 %zero %x\n"
2610 		"%inloc2 = OpAccessChain %f32ptr %indata2 %zero %x\n"
2611 		"%inloc3 = OpAccessChain %f32ptr %indata3 %zero %x\n"
2612 		"%inloc4 = OpAccessChain %f32ptr %indata4 %zero %x\n"
2613 		"%outloc = OpAccessChain %f32ptr %outdata %zero %x\n"
2614 		"%inval0 = OpLoad %f32 %inloc0\n"
2615 		"%inval1 = OpLoad %f32 %inloc1\n"
2616 		"%inval2 = OpLoad %f32 %inloc2\n"
2617 		"%inval3 = OpLoad %f32 %inloc3\n"
2618 		"%inval4 = OpLoad %f32 %inloc4\n"
2619 		"%add0   = OpFAdd %f32 %inval0 %inval1\n"
2620 		"%add1   = OpFAdd %f32 %add0 %inval2\n"
2621 		"%add2   = OpFAdd %f32 %add1 %inval3\n"
2622 		"%add    = OpFAdd %f32 %add2 %inval4\n"
2623 		"          OpStore %outloc %add\n"
2624 		"          OpReturn\n"
2625 		"          OpFunctionEnd\n";
2626 	spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats0)));
2627 	spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
2628 	spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
2629 	spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
2630 	spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
2631 	spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2632 	spec.numWorkGroups = IVec3(numElements, 1, 1);
2633 
2634 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "decoration group cases", spec));
2635 
2636 	return group.release();
2637 }
2638 
2639 struct SpecConstantTwoIntCase
2640 {
2641 	const char*		caseName;
2642 	const char*		scDefinition0;
2643 	const char*		scDefinition1;
2644 	const char*		scResultType;
2645 	const char*		scOperation;
2646 	deInt32			scActualValue0;
2647 	deInt32			scActualValue1;
2648 	const char*		resultOperation;
2649 	vector<deInt32>	expectedOutput;
2650 	deInt32			scActualValueLength;
2651 
SpecConstantTwoIntCasevkt::SpirVAssembly::__anon68fe7dee0111::SpecConstantTwoIntCase2652 					SpecConstantTwoIntCase (const char* name,
2653 											const char* definition0,
2654 											const char* definition1,
2655 											const char* resultType,
2656 											const char* operation,
2657 											deInt32 value0,
2658 											deInt32 value1,
2659 											const char* resultOp,
2660 											const vector<deInt32>& output,
2661 											const deInt32	valueLength = sizeof(deInt32))
2662 						: caseName				(name)
2663 						, scDefinition0			(definition0)
2664 						, scDefinition1			(definition1)
2665 						, scResultType			(resultType)
2666 						, scOperation			(operation)
2667 						, scActualValue0		(value0)
2668 						, scActualValue1		(value1)
2669 						, resultOperation		(resultOp)
2670 						, expectedOutput		(output)
2671 						, scActualValueLength	(valueLength)
2672 						{}
2673 };
2674 
createSpecConstantGroup(tcu::TestContext & testCtx)2675 tcu::TestCaseGroup* createSpecConstantGroup (tcu::TestContext& testCtx)
2676 {
2677 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
2678 	vector<SpecConstantTwoIntCase>	cases;
2679 	de::Random						rnd				(deStringHash(group->getName()));
2680 	const int						numElements		= 100;
2681 	const deInt32					p1AsFloat16		= 0x3c00; // +1(fp16) == 0 01111 0000000000 == 0011 1100 0000 0000
2682 	vector<deInt32>					inputInts		(numElements, 0);
2683 	vector<deInt32>					outputInts1		(numElements, 0);
2684 	vector<deInt32>					outputInts2		(numElements, 0);
2685 	vector<deInt32>					outputInts3		(numElements, 0);
2686 	vector<deInt32>					outputInts4		(numElements, 0);
2687 	const StringTemplate			shaderTemplate	(
2688 		"${CAPABILITIES:opt}"
2689 		+ string(getComputeAsmShaderPreamble()) +
2690 
2691 		"OpName %main           \"main\"\n"
2692 		"OpName %id             \"gl_GlobalInvocationID\"\n"
2693 
2694 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
2695 		"OpDecorate %sc_0  SpecId 0\n"
2696 		"OpDecorate %sc_1  SpecId 1\n"
2697 		"OpDecorate %i32arr ArrayStride 4\n"
2698 
2699 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2700 
2701 		"${OPTYPE_DEFINITIONS:opt}"
2702 		"%buf     = OpTypeStruct %i32arr\n"
2703 		"%bufptr  = OpTypePointer Uniform %buf\n"
2704 		"%indata    = OpVariable %bufptr Uniform\n"
2705 		"%outdata   = OpVariable %bufptr Uniform\n"
2706 
2707 		"%id        = OpVariable %uvec3ptr Input\n"
2708 		"%zero      = OpConstant %i32 0\n"
2709 
2710 		"%sc_0      = OpSpecConstant${SC_DEF0}\n"
2711 		"%sc_1      = OpSpecConstant${SC_DEF1}\n"
2712 		"%sc_final  = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n"
2713 
2714 		"%main      = OpFunction %void None %voidf\n"
2715 		"%label     = OpLabel\n"
2716 		"${TYPE_CONVERT:opt}"
2717 		"%idval     = OpLoad %uvec3 %id\n"
2718 		"%x         = OpCompositeExtract %u32 %idval 0\n"
2719 		"%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
2720 		"%inval     = OpLoad %i32 %inloc\n"
2721 		"%final     = ${GEN_RESULT}\n"
2722 		"%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2723 		"             OpStore %outloc %final\n"
2724 		"             OpReturn\n"
2725 		"             OpFunctionEnd\n");
2726 
2727 	fillRandomScalars(rnd, -65536, 65536, &inputInts[0], numElements);
2728 
2729 	for (size_t ndx = 0; ndx < numElements; ++ndx)
2730 	{
2731 		outputInts1[ndx] = inputInts[ndx] + 42;
2732 		outputInts2[ndx] = inputInts[ndx];
2733 		outputInts3[ndx] = inputInts[ndx] - 11200;
2734 		outputInts4[ndx] = inputInts[ndx] + 1;
2735 	}
2736 
2737 	const char addScToInput[]		= "OpIAdd %i32 %inval %sc_final";
2738 	const char addSc32ToInput[]		= "OpIAdd %i32 %inval %sc_final32";
2739 	const char selectTrueUsingSc[]	= "OpSelect %i32 %sc_final %inval %zero";
2740 	const char selectFalseUsingSc[]	= "OpSelect %i32 %sc_final %zero %inval";
2741 
2742 	cases.push_back(SpecConstantTwoIntCase("iadd",					" %i32 0",		" %i32 0",		"%i32",		"IAdd                 %sc_0 %sc_1",			62,		-20,	addScToInput,		outputInts1));
2743 	cases.push_back(SpecConstantTwoIntCase("isub",					" %i32 0",		" %i32 0",		"%i32",		"ISub                 %sc_0 %sc_1",			100,	58,		addScToInput,		outputInts1));
2744 	cases.push_back(SpecConstantTwoIntCase("imul",					" %i32 0",		" %i32 0",		"%i32",		"IMul                 %sc_0 %sc_1",			-2,		-21,	addScToInput,		outputInts1));
2745 	cases.push_back(SpecConstantTwoIntCase("sdiv",					" %i32 0",		" %i32 0",		"%i32",		"SDiv                 %sc_0 %sc_1",			-126,	-3,		addScToInput,		outputInts1));
2746 	cases.push_back(SpecConstantTwoIntCase("udiv",					" %i32 0",		" %i32 0",		"%i32",		"UDiv                 %sc_0 %sc_1",			126,	3,		addScToInput,		outputInts1));
2747 	cases.push_back(SpecConstantTwoIntCase("srem",					" %i32 0",		" %i32 0",		"%i32",		"SRem                 %sc_0 %sc_1",			7,		3,		addScToInput,		outputInts4));
2748 	cases.push_back(SpecConstantTwoIntCase("smod",					" %i32 0",		" %i32 0",		"%i32",		"SMod                 %sc_0 %sc_1",			7,		3,		addScToInput,		outputInts4));
2749 	cases.push_back(SpecConstantTwoIntCase("umod",					" %i32 0",		" %i32 0",		"%i32",		"UMod                 %sc_0 %sc_1",			342,	50,		addScToInput,		outputInts1));
2750 	cases.push_back(SpecConstantTwoIntCase("bitwiseand",			" %i32 0",		" %i32 0",		"%i32",		"BitwiseAnd           %sc_0 %sc_1",			42,		63,		addScToInput,		outputInts1));
2751 	cases.push_back(SpecConstantTwoIntCase("bitwiseor",				" %i32 0",		" %i32 0",		"%i32",		"BitwiseOr            %sc_0 %sc_1",			34,		8,		addScToInput,		outputInts1));
2752 	cases.push_back(SpecConstantTwoIntCase("bitwisexor",			" %i32 0",		" %i32 0",		"%i32",		"BitwiseXor           %sc_0 %sc_1",			18,		56,		addScToInput,		outputInts1));
2753 	cases.push_back(SpecConstantTwoIntCase("shiftrightlogical",		" %i32 0",		" %i32 0",		"%i32",		"ShiftRightLogical    %sc_0 %sc_1",			168,	2,		addScToInput,		outputInts1));
2754 	cases.push_back(SpecConstantTwoIntCase("shiftrightarithmetic",	" %i32 0",		" %i32 0",		"%i32",		"ShiftRightArithmetic %sc_0 %sc_1",			168,	2,		addScToInput,		outputInts1));
2755 	cases.push_back(SpecConstantTwoIntCase("shiftleftlogical",		" %i32 0",		" %i32 0",		"%i32",		"ShiftLeftLogical     %sc_0 %sc_1",			21,		1,		addScToInput,		outputInts1));
2756 	cases.push_back(SpecConstantTwoIntCase("slessthan",				" %i32 0",		" %i32 0",		"%bool",	"SLessThan            %sc_0 %sc_1",			-20,	-10,	selectTrueUsingSc,	outputInts2));
2757 	cases.push_back(SpecConstantTwoIntCase("ulessthan",				" %i32 0",		" %i32 0",		"%bool",	"ULessThan            %sc_0 %sc_1",			10,		20,		selectTrueUsingSc,	outputInts2));
2758 	cases.push_back(SpecConstantTwoIntCase("sgreaterthan",			" %i32 0",		" %i32 0",		"%bool",	"SGreaterThan         %sc_0 %sc_1",			-1000,	50,		selectFalseUsingSc,	outputInts2));
2759 	cases.push_back(SpecConstantTwoIntCase("ugreaterthan",			" %i32 0",		" %i32 0",		"%bool",	"UGreaterThan         %sc_0 %sc_1",			10,		5,		selectTrueUsingSc,	outputInts2));
2760 	cases.push_back(SpecConstantTwoIntCase("slessthanequal",		" %i32 0",		" %i32 0",		"%bool",	"SLessThanEqual       %sc_0 %sc_1",			-10,	-10,	selectTrueUsingSc,	outputInts2));
2761 	cases.push_back(SpecConstantTwoIntCase("ulessthanequal",		" %i32 0",		" %i32 0",		"%bool",	"ULessThanEqual       %sc_0 %sc_1",			50,		100,	selectTrueUsingSc,	outputInts2));
2762 	cases.push_back(SpecConstantTwoIntCase("sgreaterthanequal",		" %i32 0",		" %i32 0",		"%bool",	"SGreaterThanEqual    %sc_0 %sc_1",			-1000,	50,		selectFalseUsingSc,	outputInts2));
2763 	cases.push_back(SpecConstantTwoIntCase("ugreaterthanequal",		" %i32 0",		" %i32 0",		"%bool",	"UGreaterThanEqual    %sc_0 %sc_1",			10,		10,		selectTrueUsingSc,	outputInts2));
2764 	cases.push_back(SpecConstantTwoIntCase("iequal",				" %i32 0",		" %i32 0",		"%bool",	"IEqual               %sc_0 %sc_1",			42,		24,		selectFalseUsingSc,	outputInts2));
2765 	cases.push_back(SpecConstantTwoIntCase("inotequal",				" %i32 0",		" %i32 0",		"%bool",	"INotEqual            %sc_0 %sc_1",			42,		24,		selectTrueUsingSc,	outputInts2));
2766 	cases.push_back(SpecConstantTwoIntCase("logicaland",			"True %bool",	"True %bool",	"%bool",	"LogicalAnd           %sc_0 %sc_1",			0,		1,		selectFalseUsingSc,	outputInts2));
2767 	cases.push_back(SpecConstantTwoIntCase("logicalor",				"False %bool",	"False %bool",	"%bool",	"LogicalOr            %sc_0 %sc_1",			1,		0,		selectTrueUsingSc,	outputInts2));
2768 	cases.push_back(SpecConstantTwoIntCase("logicalequal",			"True %bool",	"True %bool",	"%bool",	"LogicalEqual         %sc_0 %sc_1",			0,		1,		selectFalseUsingSc,	outputInts2));
2769 	cases.push_back(SpecConstantTwoIntCase("logicalnotequal",		"False %bool",	"False %bool",	"%bool",	"LogicalNotEqual      %sc_0 %sc_1",			1,		0,		selectTrueUsingSc,	outputInts2));
2770 	cases.push_back(SpecConstantTwoIntCase("snegate",				" %i32 0",		" %i32 0",		"%i32",		"SNegate              %sc_0",				-42,	0,		addScToInput,		outputInts1));
2771 	cases.push_back(SpecConstantTwoIntCase("not",					" %i32 0",		" %i32 0",		"%i32",		"Not                  %sc_0",				-43,	0,		addScToInput,		outputInts1));
2772 	cases.push_back(SpecConstantTwoIntCase("logicalnot",			"False %bool",	"False %bool",	"%bool",	"LogicalNot           %sc_0",				1,		0,		selectFalseUsingSc,	outputInts2));
2773 	cases.push_back(SpecConstantTwoIntCase("select",				"False %bool",	" %i32 0",		"%i32",		"Select               %sc_0 %sc_1 %zero",	1,		42,		addScToInput,		outputInts1));
2774 	cases.push_back(SpecConstantTwoIntCase("sconvert",				" %i32 0",		" %i32 0",		"%i16",		"SConvert             %sc_0",				-11200,	0,		addSc32ToInput,		outputInts3));
2775 	// -969998336 stored as 32-bit two's complement is the binary representation of -11200 as IEEE-754 Float
2776 	cases.push_back(SpecConstantTwoIntCase("fconvert",				" %f32 0",		" %f32 0",		"%f64",		"FConvert             %sc_0",				-969998336, 0,	addSc32ToInput,		outputInts3));
2777 	cases.push_back(SpecConstantTwoIntCase("fconvert16",			" %f16 0",		" %f16 0",		"%f32",		"FConvert             %sc_0",				p1AsFloat16, 0,	addSc32ToInput,		outputInts4, sizeof(deFloat16)));
2778 
2779 	for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
2780 	{
2781 		map<string, string>		specializations;
2782 		ComputeShaderSpec		spec;
2783 
2784 		specializations["SC_DEF0"]			= cases[caseNdx].scDefinition0;
2785 		specializations["SC_DEF1"]			= cases[caseNdx].scDefinition1;
2786 		specializations["SC_RESULT_TYPE"]	= cases[caseNdx].scResultType;
2787 		specializations["SC_OP"]			= cases[caseNdx].scOperation;
2788 		specializations["GEN_RESULT"]		= cases[caseNdx].resultOperation;
2789 
2790 		// Special SPIR-V code for SConvert-case
2791 		if (strcmp(cases[caseNdx].caseName, "sconvert") == 0)
2792 		{
2793 			spec.requestedVulkanFeatures.coreFeatures.shaderInt16	= VK_TRUE;
2794 			specializations["CAPABILITIES"]							= "OpCapability Int16\n";							// Adds 16-bit integer capability
2795 			specializations["OPTYPE_DEFINITIONS"]					= "%i16 = OpTypeInt 16 1\n";						// Adds 16-bit integer type
2796 			specializations["TYPE_CONVERT"]							= "%sc_final32 = OpSConvert %i32 %sc_final\n";		// Converts 16-bit integer to 32-bit integer
2797 		}
2798 
2799 		// Special SPIR-V code for FConvert-case
2800 		if (strcmp(cases[caseNdx].caseName, "fconvert") == 0)
2801 		{
2802 			spec.requestedVulkanFeatures.coreFeatures.shaderFloat64	= VK_TRUE;
2803 			specializations["CAPABILITIES"]							= "OpCapability Float64\n";							// Adds 64-bit float capability
2804 			specializations["OPTYPE_DEFINITIONS"]					= "%f64 = OpTypeFloat 64\n";						// Adds 64-bit float type
2805 			specializations["TYPE_CONVERT"]							= "%sc_final32 = OpConvertFToS %i32 %sc_final\n";	// Converts 64-bit float to 32-bit integer
2806 		}
2807 
2808 		// Special SPIR-V code for FConvert-case for 16-bit floats
2809 		if (strcmp(cases[caseNdx].caseName, "fconvert16") == 0)
2810 		{
2811 			spec.extensions.push_back("VK_KHR_shader_float16_int8");
2812 			spec.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
2813 			specializations["CAPABILITIES"]			= "OpCapability Float16\n";							// Adds 16-bit float capability
2814 			specializations["OPTYPE_DEFINITIONS"]	= "%f16 = OpTypeFloat 16\n";						// Adds 16-bit float type
2815 			specializations["TYPE_CONVERT"]			= "%sc_final32 = OpConvertFToS %i32 %sc_final\n";	// Converts 16-bit float to 32-bit integer
2816 		}
2817 
2818 		spec.assembly = shaderTemplate.specialize(specializations);
2819 		spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
2820 		spec.outputs.push_back(BufferSp(new Int32Buffer(cases[caseNdx].expectedOutput)));
2821 		spec.numWorkGroups = IVec3(numElements, 1, 1);
2822 		spec.specConstants.append(&cases[caseNdx].scActualValue0, cases[caseNdx].scActualValueLength);
2823 		spec.specConstants.append(&cases[caseNdx].scActualValue1, cases[caseNdx].scActualValueLength);
2824 
2825 		group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].caseName, cases[caseNdx].caseName, spec));
2826 	}
2827 
2828 	ComputeShaderSpec				spec;
2829 
2830 	spec.assembly =
2831 		string(getComputeAsmShaderPreamble()) +
2832 
2833 		"OpName %main           \"main\"\n"
2834 		"OpName %id             \"gl_GlobalInvocationID\"\n"
2835 
2836 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
2837 		"OpDecorate %sc_0  SpecId 0\n"
2838 		"OpDecorate %sc_1  SpecId 1\n"
2839 		"OpDecorate %sc_2  SpecId 2\n"
2840 		"OpDecorate %i32arr ArrayStride 4\n"
2841 
2842 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2843 
2844 		"%ivec3       = OpTypeVector %i32 3\n"
2845 		"%buf         = OpTypeStruct %i32arr\n"
2846 		"%bufptr      = OpTypePointer Uniform %buf\n"
2847 		"%indata      = OpVariable %bufptr Uniform\n"
2848 		"%outdata     = OpVariable %bufptr Uniform\n"
2849 
2850 		"%id          = OpVariable %uvec3ptr Input\n"
2851 		"%zero        = OpConstant %i32 0\n"
2852 		"%ivec3_0     = OpConstantComposite %ivec3 %zero %zero %zero\n"
2853 		"%vec3_undef  = OpUndef %ivec3\n"
2854 
2855 		"%sc_0        = OpSpecConstant %i32 0\n"
2856 		"%sc_1        = OpSpecConstant %i32 0\n"
2857 		"%sc_2        = OpSpecConstant %i32 0\n"
2858 		"%sc_vec3_0   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_0        %ivec3_0     0\n"							// (sc_0, 0, 0)
2859 		"%sc_vec3_1   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_1        %ivec3_0     1\n"							// (0, sc_1, 0)
2860 		"%sc_vec3_2   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_2        %ivec3_0     2\n"							// (0, 0, sc_2)
2861 		"%sc_vec3_0_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0   %vec3_undef  0          0xFFFFFFFF 2\n"	// (sc_0, ???,  0)
2862 		"%sc_vec3_1_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_1   %vec3_undef  0xFFFFFFFF 1          0\n"	// (???,  sc_1, 0)
2863 		"%sc_vec3_2_s = OpSpecConstantOp %ivec3 VectorShuffle    %vec3_undef  %sc_vec3_2   5          0xFFFFFFFF 5\n"	// (sc_2, ???,  sc_2)
2864 		"%sc_vec3_01  = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0_s %sc_vec3_1_s 1 0 4\n"						// (0,    sc_0, sc_1)
2865 		"%sc_vec3_012 = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_01  %sc_vec3_2_s 5 1 2\n"						// (sc_2, sc_0, sc_1)
2866 		"%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              0\n"							// sc_2
2867 		"%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              1\n"							// sc_0
2868 		"%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              2\n"							// sc_1
2869 		"%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"								// (sc_2 - sc_0)
2870 		"%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n"								// (sc_2 - sc_0) * sc_1
2871 
2872 		"%main      = OpFunction %void None %voidf\n"
2873 		"%label     = OpLabel\n"
2874 		"%idval     = OpLoad %uvec3 %id\n"
2875 		"%x         = OpCompositeExtract %u32 %idval 0\n"
2876 		"%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
2877 		"%inval     = OpLoad %i32 %inloc\n"
2878 		"%final     = OpIAdd %i32 %inval %sc_final\n"
2879 		"%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2880 		"             OpStore %outloc %final\n"
2881 		"             OpReturn\n"
2882 		"             OpFunctionEnd\n";
2883 	spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
2884 	spec.outputs.push_back(BufferSp(new Int32Buffer(outputInts3)));
2885 	spec.numWorkGroups = IVec3(numElements, 1, 1);
2886 	spec.specConstants.append<deInt32>(123);
2887 	spec.specConstants.append<deInt32>(56);
2888 	spec.specConstants.append<deInt32>(-77);
2889 
2890 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector_related", "VectorShuffle, CompositeExtract, & CompositeInsert", spec));
2891 
2892 	return group.release();
2893 }
2894 
createOpPhiVartypeTests(de::MovePtr<tcu::TestCaseGroup> & group,tcu::TestContext & testCtx)2895 void createOpPhiVartypeTests (de::MovePtr<tcu::TestCaseGroup>& group, tcu::TestContext& testCtx)
2896 {
2897 	ComputeShaderSpec	specInt;
2898 	ComputeShaderSpec	specFloat;
2899 	ComputeShaderSpec	specFloat16;
2900 	ComputeShaderSpec	specVec3;
2901 	ComputeShaderSpec	specMat4;
2902 	ComputeShaderSpec	specArray;
2903 	ComputeShaderSpec	specStruct;
2904 	de::Random			rnd				(deStringHash(group->getName()));
2905 	const int			numElements		= 100;
2906 	vector<float>		inputFloats		(numElements, 0);
2907 	vector<float>		outputFloats	(numElements, 0);
2908 	vector<deFloat16>	inputFloats16	(numElements, 0);
2909 	vector<deFloat16>	outputFloats16	(numElements, 0);
2910 
2911 	fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
2912 
2913 	// CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2914 	floorAll(inputFloats);
2915 
2916 	for (size_t ndx = 0; ndx < numElements; ++ndx)
2917 	{
2918 		// Just check if the value is positive or not
2919 		outputFloats[ndx] = (inputFloats[ndx] > 0) ? 1.0f : -1.0f;
2920 	}
2921 
2922 	for (size_t ndx = 0; ndx < numElements; ++ndx)
2923 	{
2924 		inputFloats16[ndx] = tcu::Float16(inputFloats[ndx]).bits();
2925 		outputFloats16[ndx] = tcu::Float16(outputFloats[ndx]).bits();
2926 	}
2927 
2928 	// All of the tests are of the form:
2929 	//
2930 	// testtype r
2931 	//
2932 	// if (inputdata > 0)
2933 	//   r = 1
2934 	// else
2935 	//   r = -1
2936 	//
2937 	// return (float)r
2938 
2939 	specFloat.assembly =
2940 		string(getComputeAsmShaderPreamble()) +
2941 
2942 		"OpSource GLSL 430\n"
2943 		"OpName %main \"main\"\n"
2944 		"OpName %id \"gl_GlobalInvocationID\"\n"
2945 
2946 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
2947 
2948 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2949 
2950 		"%id = OpVariable %uvec3ptr Input\n"
2951 		"%zero       = OpConstant %i32 0\n"
2952 		"%float_0    = OpConstant %f32 0.0\n"
2953 		"%float_1    = OpConstant %f32 1.0\n"
2954 		"%float_n1   = OpConstant %f32 -1.0\n"
2955 
2956 		"%main     = OpFunction %void None %voidf\n"
2957 		"%entry    = OpLabel\n"
2958 		"%idval    = OpLoad %uvec3 %id\n"
2959 		"%x        = OpCompositeExtract %u32 %idval 0\n"
2960 		"%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
2961 		"%inval    = OpLoad %f32 %inloc\n"
2962 
2963 		"%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
2964 		"            OpSelectionMerge %cm None\n"
2965 		"            OpBranchConditional %comp %tb %fb\n"
2966 		"%tb       = OpLabel\n"
2967 		"            OpBranch %cm\n"
2968 		"%fb       = OpLabel\n"
2969 		"            OpBranch %cm\n"
2970 		"%cm       = OpLabel\n"
2971 		"%res      = OpPhi %f32 %float_1 %tb %float_n1 %fb\n"
2972 
2973 		"%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
2974 		"            OpStore %outloc %res\n"
2975 		"            OpReturn\n"
2976 
2977 		"            OpFunctionEnd\n";
2978 	specFloat.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2979 	specFloat.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2980 	specFloat.numWorkGroups = IVec3(numElements, 1, 1);
2981 
2982 	specFloat16.assembly =
2983 		"OpCapability Shader\n"
2984 		"OpCapability StorageUniformBufferBlock16\n"
2985 		"OpExtension \"SPV_KHR_16bit_storage\"\n"
2986 		"OpMemoryModel Logical GLSL450\n"
2987 		"OpEntryPoint GLCompute %main \"main\" %id\n"
2988 		"OpExecutionMode %main LocalSize 1 1 1\n"
2989 
2990 		"OpSource GLSL 430\n"
2991 		"OpName %main \"main\"\n"
2992 		"OpName %id \"gl_GlobalInvocationID\"\n"
2993 
2994 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
2995 
2996 		"OpDecorate %buf BufferBlock\n"
2997 		"OpDecorate %indata DescriptorSet 0\n"
2998 		"OpDecorate %indata Binding 0\n"
2999 		"OpDecorate %outdata DescriptorSet 0\n"
3000 		"OpDecorate %outdata Binding 1\n"
3001 		"OpDecorate %f16arr ArrayStride 2\n"
3002 		"OpMemberDecorate %buf 0 Offset 0\n"
3003 
3004 		"%f16      = OpTypeFloat 16\n"
3005 		"%f16ptr   = OpTypePointer Uniform %f16\n"
3006 		"%f16arr   = OpTypeRuntimeArray %f16\n"
3007 
3008 		+ string(getComputeAsmCommonTypes()) +
3009 
3010 		"%buf      = OpTypeStruct %f16arr\n"
3011 		"%bufptr   = OpTypePointer Uniform %buf\n"
3012 		"%indata   = OpVariable %bufptr Uniform\n"
3013 		"%outdata  = OpVariable %bufptr Uniform\n"
3014 
3015 		"%id       = OpVariable %uvec3ptr Input\n"
3016 		"%zero     = OpConstant %i32 0\n"
3017 		"%float_0  = OpConstant %f16 0.0\n"
3018 		"%float_1  = OpConstant %f16 1.0\n"
3019 		"%float_n1 = OpConstant %f16 -1.0\n"
3020 
3021 		"%main     = OpFunction %void None %voidf\n"
3022 		"%entry    = OpLabel\n"
3023 		"%idval    = OpLoad %uvec3 %id\n"
3024 		"%x        = OpCompositeExtract %u32 %idval 0\n"
3025 		"%inloc    = OpAccessChain %f16ptr %indata %zero %x\n"
3026 		"%inval    = OpLoad %f16 %inloc\n"
3027 
3028 		"%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3029 		"            OpSelectionMerge %cm None\n"
3030 		"            OpBranchConditional %comp %tb %fb\n"
3031 		"%tb       = OpLabel\n"
3032 		"            OpBranch %cm\n"
3033 		"%fb       = OpLabel\n"
3034 		"            OpBranch %cm\n"
3035 		"%cm       = OpLabel\n"
3036 		"%res      = OpPhi %f16 %float_1 %tb %float_n1 %fb\n"
3037 
3038 		"%outloc   = OpAccessChain %f16ptr %outdata %zero %x\n"
3039 		"            OpStore %outloc %res\n"
3040 		"            OpReturn\n"
3041 
3042 		"            OpFunctionEnd\n";
3043 	specFloat16.inputs.push_back(BufferSp(new Float16Buffer(inputFloats16)));
3044 	specFloat16.outputs.push_back(BufferSp(new Float16Buffer(outputFloats16)));
3045 	specFloat16.numWorkGroups = IVec3(numElements, 1, 1);
3046 	specFloat16.requestedVulkanFeatures.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
3047 	specFloat16.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
3048 
3049 	specMat4.assembly =
3050 		string(getComputeAsmShaderPreamble()) +
3051 
3052 		"OpSource GLSL 430\n"
3053 		"OpName %main \"main\"\n"
3054 		"OpName %id \"gl_GlobalInvocationID\"\n"
3055 
3056 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
3057 
3058 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3059 
3060 		"%id = OpVariable %uvec3ptr Input\n"
3061 		"%v4f32      = OpTypeVector %f32 4\n"
3062 		"%mat4v4f32  = OpTypeMatrix %v4f32 4\n"
3063 		"%zero       = OpConstant %i32 0\n"
3064 		"%float_0    = OpConstant %f32 0.0\n"
3065 		"%float_1    = OpConstant %f32 1.0\n"
3066 		"%float_n1   = OpConstant %f32 -1.0\n"
3067 		"%m11        = OpConstantComposite %v4f32 %float_1 %float_0 %float_0 %float_0\n"
3068 		"%m12        = OpConstantComposite %v4f32 %float_0 %float_1 %float_0 %float_0\n"
3069 		"%m13        = OpConstantComposite %v4f32 %float_0 %float_0 %float_1 %float_0\n"
3070 		"%m14        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_1\n"
3071 		"%m1         = OpConstantComposite %mat4v4f32 %m11 %m12 %m13 %m14\n"
3072 		"%m21        = OpConstantComposite %v4f32 %float_n1 %float_0 %float_0 %float_0\n"
3073 		"%m22        = OpConstantComposite %v4f32 %float_0 %float_n1 %float_0 %float_0\n"
3074 		"%m23        = OpConstantComposite %v4f32 %float_0 %float_0 %float_n1 %float_0\n"
3075 		"%m24        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_n1\n"
3076 		"%m2         = OpConstantComposite %mat4v4f32 %m21 %m22 %m23 %m24\n"
3077 
3078 		"%main     = OpFunction %void None %voidf\n"
3079 		"%entry    = OpLabel\n"
3080 		"%idval    = OpLoad %uvec3 %id\n"
3081 		"%x        = OpCompositeExtract %u32 %idval 0\n"
3082 		"%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3083 		"%inval    = OpLoad %f32 %inloc\n"
3084 
3085 		"%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3086 		"            OpSelectionMerge %cm None\n"
3087 		"            OpBranchConditional %comp %tb %fb\n"
3088 		"%tb       = OpLabel\n"
3089 		"            OpBranch %cm\n"
3090 		"%fb       = OpLabel\n"
3091 		"            OpBranch %cm\n"
3092 		"%cm       = OpLabel\n"
3093 		"%mres     = OpPhi %mat4v4f32 %m1 %tb %m2 %fb\n"
3094 		"%res      = OpCompositeExtract %f32 %mres 2 2\n"
3095 
3096 		"%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3097 		"            OpStore %outloc %res\n"
3098 		"            OpReturn\n"
3099 
3100 		"            OpFunctionEnd\n";
3101 	specMat4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3102 	specMat4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3103 	specMat4.numWorkGroups = IVec3(numElements, 1, 1);
3104 
3105 	specVec3.assembly =
3106 		string(getComputeAsmShaderPreamble()) +
3107 
3108 		"OpSource GLSL 430\n"
3109 		"OpName %main \"main\"\n"
3110 		"OpName %id \"gl_GlobalInvocationID\"\n"
3111 
3112 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
3113 
3114 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3115 
3116 		"%id = OpVariable %uvec3ptr Input\n"
3117 		"%zero       = OpConstant %i32 0\n"
3118 		"%float_0    = OpConstant %f32 0.0\n"
3119 		"%float_1    = OpConstant %f32 1.0\n"
3120 		"%float_n1   = OpConstant %f32 -1.0\n"
3121 		"%v1         = OpConstantComposite %fvec3 %float_1 %float_1 %float_1\n"
3122 		"%v2         = OpConstantComposite %fvec3 %float_n1 %float_n1 %float_n1\n"
3123 
3124 		"%main     = OpFunction %void None %voidf\n"
3125 		"%entry    = OpLabel\n"
3126 		"%idval    = OpLoad %uvec3 %id\n"
3127 		"%x        = OpCompositeExtract %u32 %idval 0\n"
3128 		"%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3129 		"%inval    = OpLoad %f32 %inloc\n"
3130 
3131 		"%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3132 		"            OpSelectionMerge %cm None\n"
3133 		"            OpBranchConditional %comp %tb %fb\n"
3134 		"%tb       = OpLabel\n"
3135 		"            OpBranch %cm\n"
3136 		"%fb       = OpLabel\n"
3137 		"            OpBranch %cm\n"
3138 		"%cm       = OpLabel\n"
3139 		"%vres     = OpPhi %fvec3 %v1 %tb %v2 %fb\n"
3140 		"%res      = OpCompositeExtract %f32 %vres 2\n"
3141 
3142 		"%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3143 		"            OpStore %outloc %res\n"
3144 		"            OpReturn\n"
3145 
3146 		"            OpFunctionEnd\n";
3147 	specVec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3148 	specVec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3149 	specVec3.numWorkGroups = IVec3(numElements, 1, 1);
3150 
3151 	specInt.assembly =
3152 		string(getComputeAsmShaderPreamble()) +
3153 
3154 		"OpSource GLSL 430\n"
3155 		"OpName %main \"main\"\n"
3156 		"OpName %id \"gl_GlobalInvocationID\"\n"
3157 
3158 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
3159 
3160 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3161 
3162 		"%id = OpVariable %uvec3ptr Input\n"
3163 		"%zero       = OpConstant %i32 0\n"
3164 		"%float_0    = OpConstant %f32 0.0\n"
3165 		"%i1         = OpConstant %i32 1\n"
3166 		"%i2         = OpConstant %i32 -1\n"
3167 
3168 		"%main     = OpFunction %void None %voidf\n"
3169 		"%entry    = OpLabel\n"
3170 		"%idval    = OpLoad %uvec3 %id\n"
3171 		"%x        = OpCompositeExtract %u32 %idval 0\n"
3172 		"%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3173 		"%inval    = OpLoad %f32 %inloc\n"
3174 
3175 		"%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3176 		"            OpSelectionMerge %cm None\n"
3177 		"            OpBranchConditional %comp %tb %fb\n"
3178 		"%tb       = OpLabel\n"
3179 		"            OpBranch %cm\n"
3180 		"%fb       = OpLabel\n"
3181 		"            OpBranch %cm\n"
3182 		"%cm       = OpLabel\n"
3183 		"%ires     = OpPhi %i32 %i1 %tb %i2 %fb\n"
3184 		"%res      = OpConvertSToF %f32 %ires\n"
3185 
3186 		"%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3187 		"            OpStore %outloc %res\n"
3188 		"            OpReturn\n"
3189 
3190 		"            OpFunctionEnd\n";
3191 	specInt.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3192 	specInt.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3193 	specInt.numWorkGroups = IVec3(numElements, 1, 1);
3194 
3195 	specArray.assembly =
3196 		string(getComputeAsmShaderPreamble()) +
3197 
3198 		"OpSource GLSL 430\n"
3199 		"OpName %main \"main\"\n"
3200 		"OpName %id \"gl_GlobalInvocationID\"\n"
3201 
3202 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
3203 
3204 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3205 
3206 		"%id = OpVariable %uvec3ptr Input\n"
3207 		"%zero       = OpConstant %i32 0\n"
3208 		"%u7         = OpConstant %u32 7\n"
3209 		"%float_0    = OpConstant %f32 0.0\n"
3210 		"%float_1    = OpConstant %f32 1.0\n"
3211 		"%float_n1   = OpConstant %f32 -1.0\n"
3212 		"%f32a7      = OpTypeArray %f32 %u7\n"
3213 		"%a1         = OpConstantComposite %f32a7 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1\n"
3214 		"%a2         = OpConstantComposite %f32a7 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1\n"
3215 		"%main     = OpFunction %void None %voidf\n"
3216 		"%entry    = OpLabel\n"
3217 		"%idval    = OpLoad %uvec3 %id\n"
3218 		"%x        = OpCompositeExtract %u32 %idval 0\n"
3219 		"%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3220 		"%inval    = OpLoad %f32 %inloc\n"
3221 
3222 		"%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3223 		"            OpSelectionMerge %cm None\n"
3224 		"            OpBranchConditional %comp %tb %fb\n"
3225 		"%tb       = OpLabel\n"
3226 		"            OpBranch %cm\n"
3227 		"%fb       = OpLabel\n"
3228 		"            OpBranch %cm\n"
3229 		"%cm       = OpLabel\n"
3230 		"%ares     = OpPhi %f32a7 %a1 %tb %a2 %fb\n"
3231 		"%res      = OpCompositeExtract %f32 %ares 5\n"
3232 
3233 		"%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3234 		"            OpStore %outloc %res\n"
3235 		"            OpReturn\n"
3236 
3237 		"            OpFunctionEnd\n";
3238 	specArray.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3239 	specArray.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3240 	specArray.numWorkGroups = IVec3(numElements, 1, 1);
3241 
3242 	specStruct.assembly =
3243 		string(getComputeAsmShaderPreamble()) +
3244 
3245 		"OpSource GLSL 430\n"
3246 		"OpName %main \"main\"\n"
3247 		"OpName %id \"gl_GlobalInvocationID\"\n"
3248 
3249 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
3250 
3251 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3252 
3253 		"%id = OpVariable %uvec3ptr Input\n"
3254 		"%zero       = OpConstant %i32 0\n"
3255 		"%float_0    = OpConstant %f32 0.0\n"
3256 		"%float_1    = OpConstant %f32 1.0\n"
3257 		"%float_n1   = OpConstant %f32 -1.0\n"
3258 
3259 		"%v2f32      = OpTypeVector %f32 2\n"
3260 		"%Data2      = OpTypeStruct %f32 %v2f32\n"
3261 		"%Data       = OpTypeStruct %Data2 %f32\n"
3262 
3263 		"%in1a       = OpConstantComposite %v2f32 %float_1 %float_1\n"
3264 		"%in1b       = OpConstantComposite %Data2 %float_1 %in1a\n"
3265 		"%s1         = OpConstantComposite %Data %in1b %float_1\n"
3266 		"%in2a       = OpConstantComposite %v2f32 %float_n1 %float_n1\n"
3267 		"%in2b       = OpConstantComposite %Data2 %float_n1 %in2a\n"
3268 		"%s2         = OpConstantComposite %Data %in2b %float_n1\n"
3269 
3270 		"%main     = OpFunction %void None %voidf\n"
3271 		"%entry    = OpLabel\n"
3272 		"%idval    = OpLoad %uvec3 %id\n"
3273 		"%x        = OpCompositeExtract %u32 %idval 0\n"
3274 		"%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3275 		"%inval    = OpLoad %f32 %inloc\n"
3276 
3277 		"%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3278 		"            OpSelectionMerge %cm None\n"
3279 		"            OpBranchConditional %comp %tb %fb\n"
3280 		"%tb       = OpLabel\n"
3281 		"            OpBranch %cm\n"
3282 		"%fb       = OpLabel\n"
3283 		"            OpBranch %cm\n"
3284 		"%cm       = OpLabel\n"
3285 		"%sres     = OpPhi %Data %s1 %tb %s2 %fb\n"
3286 		"%res      = OpCompositeExtract %f32 %sres 0 0\n"
3287 
3288 		"%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3289 		"            OpStore %outloc %res\n"
3290 		"            OpReturn\n"
3291 
3292 		"            OpFunctionEnd\n";
3293 	specStruct.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3294 	specStruct.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3295 	specStruct.numWorkGroups = IVec3(numElements, 1, 1);
3296 
3297 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_int", "OpPhi with int variables", specInt));
3298 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_float", "OpPhi with float variables", specFloat));
3299 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_float16", "OpPhi with 16bit float variables", specFloat16));
3300 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_vec3", "OpPhi with vec3 variables", specVec3));
3301 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_mat4", "OpPhi with mat4 variables", specMat4));
3302 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_array", "OpPhi with array variables", specArray));
3303 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_struct", "OpPhi with struct variables", specStruct));
3304 }
3305 
generateConstantDefinitions(int count)3306 string generateConstantDefinitions (int count)
3307 {
3308 	std::ostringstream	r;
3309 	for (int i = 0; i < count; i++)
3310 		r << "%cf" << (i * 10 + 5) << " = OpConstant %f32 " <<(i * 10 + 5) << ".0\n";
3311 	r << "\n";
3312 	return r.str();
3313 }
3314 
generateSwitchCases(int count)3315 string generateSwitchCases (int count)
3316 {
3317 	std::ostringstream	r;
3318 	for (int i = 0; i < count; i++)
3319 		r << " " << i << " %case" << i;
3320 	r << "\n";
3321 	return r.str();
3322 }
3323 
generateSwitchTargets(int count)3324 string generateSwitchTargets (int count)
3325 {
3326 	std::ostringstream	r;
3327 	for (int i = 0; i < count; i++)
3328 		r << "%case" << i << " = OpLabel\n            OpBranch %phi\n";
3329 	r << "\n";
3330 	return r.str();
3331 }
3332 
generateOpPhiParams(int count)3333 string generateOpPhiParams (int count)
3334 {
3335 	std::ostringstream	r;
3336 	for (int i = 0; i < count; i++)
3337 		r << " %cf" << (i * 10 + 5) << " %case" << i;
3338 	r << "\n";
3339 	return r.str();
3340 }
3341 
generateIntWidth(int value)3342 string generateIntWidth (int value)
3343 {
3344 	std::ostringstream	r;
3345 	r << value;
3346 	return r.str();
3347 }
3348 
3349 // Expand input string by injecting "ABC" between the input
3350 // string characters. The acc/add/treshold parameters are used
3351 // to skip some of the injections to make the result less
3352 // uniform (and a lot shorter).
expandOpPhiCase5(const string & s,int & acc,int add,int treshold)3353 string expandOpPhiCase5 (const string& s, int &acc, int add, int treshold)
3354 {
3355 	std::ostringstream	res;
3356 	const char*			p = s.c_str();
3357 
3358 	while (*p)
3359 	{
3360 		res << *p;
3361 		acc += add;
3362 		if (acc > treshold)
3363 		{
3364 			acc -= treshold;
3365 			res << "ABC";
3366 		}
3367 		p++;
3368 	}
3369 	return res.str();
3370 }
3371 
3372 // Calculate expected result based on the code string
calcOpPhiCase5(float val,const string & s)3373 float calcOpPhiCase5 (float val, const string& s)
3374 {
3375 	const char*		p		= s.c_str();
3376 	float			x[8];
3377 	bool			b[8];
3378 	const float		tv[8]	= { 0.5f, 1.5f, 3.5f, 7.5f, 15.5f, 31.5f, 63.5f, 127.5f };
3379 	const float		v		= deFloatAbs(val);
3380 	float			res		= 0;
3381 	int				depth	= -1;
3382 	int				skip	= 0;
3383 
3384 	for (int i = 7; i >= 0; --i)
3385 		x[i] = std::fmod((float)v, (float)(2 << i));
3386 	for (int i = 7; i >= 0; --i)
3387 		b[i] = x[i] > tv[i];
3388 
3389 	while (*p)
3390 	{
3391 		if (*p == 'A')
3392 		{
3393 			depth++;
3394 			if (skip == 0 && b[depth])
3395 			{
3396 				res++;
3397 			}
3398 			else
3399 				skip++;
3400 		}
3401 		if (*p == 'B')
3402 		{
3403 			if (skip)
3404 				skip--;
3405 			if (b[depth] || skip)
3406 				skip++;
3407 		}
3408 		if (*p == 'C')
3409 		{
3410 			depth--;
3411 			if (skip)
3412 				skip--;
3413 		}
3414 		p++;
3415 	}
3416 	return res;
3417 }
3418 
3419 // In the code string, the letters represent the following:
3420 //
3421 // A:
3422 //     if (certain bit is set)
3423 //     {
3424 //       result++;
3425 //
3426 // B:
3427 //     } else {
3428 //
3429 // C:
3430 //     }
3431 //
3432 // examples:
3433 // AABCBC leads to if(){r++;if(){r++;}else{}}else{}
3434 // ABABCC leads to if(){r++;}else{if(){r++;}else{}}
3435 // ABCABC leads to if(){r++;}else{}if(){r++;}else{}
3436 //
3437 // Code generation gets a bit complicated due to the else-branches,
3438 // which do not generate new values. Thus, the generator needs to
3439 // keep track of the previous variable change seen by the else
3440 // branch.
generateOpPhiCase5(const string & s)3441 string generateOpPhiCase5 (const string& s)
3442 {
3443 	std::stack<int>				idStack;
3444 	std::stack<std::string>		value;
3445 	std::stack<std::string>		valueLabel;
3446 	std::stack<std::string>		mergeLeft;
3447 	std::stack<std::string>		mergeRight;
3448 	std::ostringstream			res;
3449 	const char*					p			= s.c_str();
3450 	int							depth		= -1;
3451 	int							currId		= 0;
3452 	int							iter		= 0;
3453 
3454 	idStack.push(-1);
3455 	value.push("%f32_0");
3456 	valueLabel.push("%f32_0 %entry");
3457 
3458 	while (*p)
3459 	{
3460 		if (*p == 'A')
3461 		{
3462 			depth++;
3463 			currId = iter;
3464 			idStack.push(currId);
3465 			res << "\tOpSelectionMerge %m" << currId << " None\n";
3466 			res << "\tOpBranchConditional %b" << depth << " %t" << currId << " %f" << currId << "\n";
3467 			res << "%t" << currId << " = OpLabel\n";
3468 			res << "%rt" << currId << " = OpFAdd %f32 " << value.top() << " %f32_1\n";
3469 			std::ostringstream tag;
3470 			tag << "%rt" << currId;
3471 			value.push(tag.str());
3472 			tag << " %t" << currId;
3473 			valueLabel.push(tag.str());
3474 		}
3475 
3476 		if (*p == 'B')
3477 		{
3478 			mergeLeft.push(valueLabel.top());
3479 			value.pop();
3480 			valueLabel.pop();
3481 			res << "\tOpBranch %m" << currId << "\n";
3482 			res << "%f" << currId << " = OpLabel\n";
3483 			std::ostringstream tag;
3484 			tag << value.top() << " %f" << currId;
3485 			valueLabel.pop();
3486 			valueLabel.push(tag.str());
3487 		}
3488 
3489 		if (*p == 'C')
3490 		{
3491 			mergeRight.push(valueLabel.top());
3492 			res << "\tOpBranch %m" << currId << "\n";
3493 			res << "%m" << currId << " = OpLabel\n";
3494 			if (*(p + 1) == 0)
3495 				res << "%res"; // last result goes to %res
3496 			else
3497 				res << "%rm" << currId;
3498 			res << " = OpPhi %f32  " << mergeLeft.top() << "  " << mergeRight.top() << "\n";
3499 			std::ostringstream tag;
3500 			tag << "%rm" << currId;
3501 			value.pop();
3502 			value.push(tag.str());
3503 			tag << " %m" << currId;
3504 			valueLabel.pop();
3505 			valueLabel.push(tag.str());
3506 			mergeLeft.pop();
3507 			mergeRight.pop();
3508 			depth--;
3509 			idStack.pop();
3510 			currId = idStack.top();
3511 		}
3512 		p++;
3513 		iter++;
3514 	}
3515 	return res.str();
3516 }
3517 
createOpPhiGroup(tcu::TestContext & testCtx)3518 tcu::TestCaseGroup* createOpPhiGroup (tcu::TestContext& testCtx)
3519 {
3520 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
3521 	ComputeShaderSpec				spec1;
3522 	ComputeShaderSpec				spec2;
3523 	ComputeShaderSpec				spec3;
3524 	ComputeShaderSpec				spec4;
3525 	ComputeShaderSpec				spec5;
3526 	de::Random						rnd				(deStringHash(group->getName()));
3527 	const int						numElements		= 100;
3528 	vector<float>					inputFloats		(numElements, 0);
3529 	vector<float>					outputFloats1	(numElements, 0);
3530 	vector<float>					outputFloats2	(numElements, 0);
3531 	vector<float>					outputFloats3	(numElements, 0);
3532 	vector<float>					outputFloats4	(numElements, 0);
3533 	vector<float>					outputFloats5	(numElements, 0);
3534 	std::string						codestring		= "ABC";
3535 	const int						test4Width		= 1024;
3536 
3537 	// Build case 5 code string. Each iteration makes the hierarchy more complicated.
3538 	// 9 iterations with (7, 24) parameters makes the hierarchy 8 deep with about 1500 lines of
3539 	// shader code.
3540 	for (int i = 0, acc = 0; i < 9; i++)
3541 		codestring = expandOpPhiCase5(codestring, acc, 7, 24);
3542 
3543 	fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
3544 
3545 	// CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3546 	floorAll(inputFloats);
3547 
3548 	for (size_t ndx = 0; ndx < numElements; ++ndx)
3549 	{
3550 		switch (ndx % 3)
3551 		{
3552 			case 0:		outputFloats1[ndx] = inputFloats[ndx] + 5.5f;	break;
3553 			case 1:		outputFloats1[ndx] = inputFloats[ndx] + 20.5f;	break;
3554 			case 2:		outputFloats1[ndx] = inputFloats[ndx] + 1.75f;	break;
3555 			default:	break;
3556 		}
3557 		outputFloats2[ndx] = inputFloats[ndx] + 6.5f * 3;
3558 		outputFloats3[ndx] = 8.5f - inputFloats[ndx];
3559 
3560 		int index4 = (int)deFloor(deAbs((float)ndx * inputFloats[ndx]));
3561 		outputFloats4[ndx] = (float)(index4 % test4Width) * 10.0f + 5.0f;
3562 
3563 		outputFloats5[ndx] = calcOpPhiCase5(inputFloats[ndx], codestring);
3564 	}
3565 
3566 	spec1.assembly =
3567 		string(getComputeAsmShaderPreamble()) +
3568 
3569 		"OpSource GLSL 430\n"
3570 		"OpName %main \"main\"\n"
3571 		"OpName %id \"gl_GlobalInvocationID\"\n"
3572 
3573 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
3574 
3575 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3576 
3577 		"%id = OpVariable %uvec3ptr Input\n"
3578 		"%zero       = OpConstant %i32 0\n"
3579 		"%three      = OpConstant %u32 3\n"
3580 		"%constf5p5  = OpConstant %f32 5.5\n"
3581 		"%constf20p5 = OpConstant %f32 20.5\n"
3582 		"%constf1p75 = OpConstant %f32 1.75\n"
3583 		"%constf8p5  = OpConstant %f32 8.5\n"
3584 		"%constf6p5  = OpConstant %f32 6.5\n"
3585 
3586 		"%main     = OpFunction %void None %voidf\n"
3587 		"%entry    = OpLabel\n"
3588 		"%idval    = OpLoad %uvec3 %id\n"
3589 		"%x        = OpCompositeExtract %u32 %idval 0\n"
3590 		"%selector = OpUMod %u32 %x %three\n"
3591 		"            OpSelectionMerge %phi None\n"
3592 		"            OpSwitch %selector %default 0 %case0 1 %case1 2 %case2\n"
3593 
3594 		// Case 1 before OpPhi.
3595 		"%case1    = OpLabel\n"
3596 		"            OpBranch %phi\n"
3597 
3598 		"%default  = OpLabel\n"
3599 		"            OpUnreachable\n"
3600 
3601 		"%phi      = OpLabel\n"
3602 		"%operand  = OpPhi %f32   %constf1p75 %case2   %constf20p5 %case1   %constf5p5 %case0\n" // not in the order of blocks
3603 		"%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3604 		"%inval    = OpLoad %f32 %inloc\n"
3605 		"%add      = OpFAdd %f32 %inval %operand\n"
3606 		"%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3607 		"            OpStore %outloc %add\n"
3608 		"            OpReturn\n"
3609 
3610 		// Case 0 after OpPhi.
3611 		"%case0    = OpLabel\n"
3612 		"            OpBranch %phi\n"
3613 
3614 
3615 		// Case 2 after OpPhi.
3616 		"%case2    = OpLabel\n"
3617 		"            OpBranch %phi\n"
3618 
3619 		"            OpFunctionEnd\n";
3620 	spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3621 	spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
3622 	spec1.numWorkGroups = IVec3(numElements, 1, 1);
3623 
3624 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "block", "out-of-order and unreachable blocks for OpPhi", spec1));
3625 
3626 	spec2.assembly =
3627 		string(getComputeAsmShaderPreamble()) +
3628 
3629 		"OpName %main \"main\"\n"
3630 		"OpName %id \"gl_GlobalInvocationID\"\n"
3631 
3632 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
3633 
3634 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3635 
3636 		"%id         = OpVariable %uvec3ptr Input\n"
3637 		"%zero       = OpConstant %i32 0\n"
3638 		"%one        = OpConstant %i32 1\n"
3639 		"%three      = OpConstant %i32 3\n"
3640 		"%constf6p5  = OpConstant %f32 6.5\n"
3641 
3642 		"%main       = OpFunction %void None %voidf\n"
3643 		"%entry      = OpLabel\n"
3644 		"%idval      = OpLoad %uvec3 %id\n"
3645 		"%x          = OpCompositeExtract %u32 %idval 0\n"
3646 		"%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3647 		"%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3648 		"%inval      = OpLoad %f32 %inloc\n"
3649 		"              OpBranch %phi\n"
3650 
3651 		"%phi        = OpLabel\n"
3652 		"%step       = OpPhi %i32 %zero  %entry %step_next  %phi\n"
3653 		"%accum      = OpPhi %f32 %inval %entry %accum_next %phi\n"
3654 		"%step_next  = OpIAdd %i32 %step %one\n"
3655 		"%accum_next = OpFAdd %f32 %accum %constf6p5\n"
3656 		"%still_loop = OpSLessThan %bool %step %three\n"
3657 		"              OpLoopMerge %exit %phi None\n"
3658 		"              OpBranchConditional %still_loop %phi %exit\n"
3659 
3660 		"%exit       = OpLabel\n"
3661 		"              OpStore %outloc %accum\n"
3662 		"              OpReturn\n"
3663 		"              OpFunctionEnd\n";
3664 	spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3665 	spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
3666 	spec2.numWorkGroups = IVec3(numElements, 1, 1);
3667 
3668 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "induction", "The usual way induction variables are handled in LLVM IR", spec2));
3669 
3670 	spec3.assembly =
3671 		string(getComputeAsmShaderPreamble()) +
3672 
3673 		"OpName %main \"main\"\n"
3674 		"OpName %id \"gl_GlobalInvocationID\"\n"
3675 
3676 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
3677 
3678 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3679 
3680 		"%f32ptr_f   = OpTypePointer Function %f32\n"
3681 		"%id         = OpVariable %uvec3ptr Input\n"
3682 		"%true       = OpConstantTrue %bool\n"
3683 		"%false      = OpConstantFalse %bool\n"
3684 		"%zero       = OpConstant %i32 0\n"
3685 		"%constf8p5  = OpConstant %f32 8.5\n"
3686 
3687 		"%main       = OpFunction %void None %voidf\n"
3688 		"%entry      = OpLabel\n"
3689 		"%b          = OpVariable %f32ptr_f Function %constf8p5\n"
3690 		"%idval      = OpLoad %uvec3 %id\n"
3691 		"%x          = OpCompositeExtract %u32 %idval 0\n"
3692 		"%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3693 		"%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3694 		"%a_init     = OpLoad %f32 %inloc\n"
3695 		"%b_init     = OpLoad %f32 %b\n"
3696 		"              OpBranch %phi\n"
3697 
3698 		"%phi        = OpLabel\n"
3699 		"%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
3700 		"%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
3701 		"%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
3702 		"              OpLoopMerge %exit %phi None\n"
3703 		"              OpBranchConditional %still_loop %phi %exit\n"
3704 
3705 		"%exit       = OpLabel\n"
3706 		"%sub        = OpFSub %f32 %a_next %b_next\n"
3707 		"              OpStore %outloc %sub\n"
3708 		"              OpReturn\n"
3709 		"              OpFunctionEnd\n";
3710 	spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3711 	spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
3712 	spec3.numWorkGroups = IVec3(numElements, 1, 1);
3713 
3714 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "swap", "Swap the values of two variables using OpPhi", spec3));
3715 
3716 	spec4.assembly =
3717 		"OpCapability Shader\n"
3718 		"%ext = OpExtInstImport \"GLSL.std.450\"\n"
3719 		"OpMemoryModel Logical GLSL450\n"
3720 		"OpEntryPoint GLCompute %main \"main\" %id\n"
3721 		"OpExecutionMode %main LocalSize 1 1 1\n"
3722 
3723 		"OpSource GLSL 430\n"
3724 		"OpName %main \"main\"\n"
3725 		"OpName %id \"gl_GlobalInvocationID\"\n"
3726 
3727 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
3728 
3729 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3730 
3731 		"%id       = OpVariable %uvec3ptr Input\n"
3732 		"%zero     = OpConstant %i32 0\n"
3733 		"%cimod    = OpConstant %u32 " + generateIntWidth(test4Width) + "\n"
3734 
3735 		+ generateConstantDefinitions(test4Width) +
3736 
3737 		"%main     = OpFunction %void None %voidf\n"
3738 		"%entry    = OpLabel\n"
3739 		"%idval    = OpLoad %uvec3 %id\n"
3740 		"%x        = OpCompositeExtract %u32 %idval 0\n"
3741 		"%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3742 		"%inval    = OpLoad %f32 %inloc\n"
3743 		"%xf       = OpConvertUToF %f32 %x\n"
3744 		"%xm       = OpFMul %f32 %xf %inval\n"
3745 		"%xa       = OpExtInst %f32 %ext FAbs %xm\n"
3746 		"%xi       = OpConvertFToU %u32 %xa\n"
3747 		"%selector = OpUMod %u32 %xi %cimod\n"
3748 		"            OpSelectionMerge %phi None\n"
3749 		"            OpSwitch %selector %default "
3750 
3751 		+ generateSwitchCases(test4Width) +
3752 
3753 		"%default  = OpLabel\n"
3754 		"            OpUnreachable\n"
3755 
3756 		+ generateSwitchTargets(test4Width) +
3757 
3758 		"%phi      = OpLabel\n"
3759 		"%result   = OpPhi %f32"
3760 
3761 		+ generateOpPhiParams(test4Width) +
3762 
3763 		"%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3764 		"            OpStore %outloc %result\n"
3765 		"            OpReturn\n"
3766 
3767 		"            OpFunctionEnd\n";
3768 	spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3769 	spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
3770 	spec4.numWorkGroups = IVec3(numElements, 1, 1);
3771 
3772 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "wide", "OpPhi with a lot of parameters", spec4));
3773 
3774 	spec5.assembly =
3775 		"OpCapability Shader\n"
3776 		"%ext      = OpExtInstImport \"GLSL.std.450\"\n"
3777 		"OpMemoryModel Logical GLSL450\n"
3778 		"OpEntryPoint GLCompute %main \"main\" %id\n"
3779 		"OpExecutionMode %main LocalSize 1 1 1\n"
3780 		"%code     = OpString \"" + codestring + "\"\n"
3781 
3782 		"OpSource GLSL 430\n"
3783 		"OpName %main \"main\"\n"
3784 		"OpName %id \"gl_GlobalInvocationID\"\n"
3785 
3786 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
3787 
3788 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3789 
3790 		"%id       = OpVariable %uvec3ptr Input\n"
3791 		"%zero     = OpConstant %i32 0\n"
3792 		"%f32_0    = OpConstant %f32 0.0\n"
3793 		"%f32_0_5  = OpConstant %f32 0.5\n"
3794 		"%f32_1    = OpConstant %f32 1.0\n"
3795 		"%f32_1_5  = OpConstant %f32 1.5\n"
3796 		"%f32_2    = OpConstant %f32 2.0\n"
3797 		"%f32_3_5  = OpConstant %f32 3.5\n"
3798 		"%f32_4    = OpConstant %f32 4.0\n"
3799 		"%f32_7_5  = OpConstant %f32 7.5\n"
3800 		"%f32_8    = OpConstant %f32 8.0\n"
3801 		"%f32_15_5 = OpConstant %f32 15.5\n"
3802 		"%f32_16   = OpConstant %f32 16.0\n"
3803 		"%f32_31_5 = OpConstant %f32 31.5\n"
3804 		"%f32_32   = OpConstant %f32 32.0\n"
3805 		"%f32_63_5 = OpConstant %f32 63.5\n"
3806 		"%f32_64   = OpConstant %f32 64.0\n"
3807 		"%f32_127_5 = OpConstant %f32 127.5\n"
3808 		"%f32_128  = OpConstant %f32 128.0\n"
3809 		"%f32_256  = OpConstant %f32 256.0\n"
3810 
3811 		"%main     = OpFunction %void None %voidf\n"
3812 		"%entry    = OpLabel\n"
3813 		"%idval    = OpLoad %uvec3 %id\n"
3814 		"%x        = OpCompositeExtract %u32 %idval 0\n"
3815 		"%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3816 		"%inval    = OpLoad %f32 %inloc\n"
3817 
3818 		"%xabs     = OpExtInst %f32 %ext FAbs %inval\n"
3819 		"%x8       = OpFMod %f32 %xabs %f32_256\n"
3820 		"%x7       = OpFMod %f32 %xabs %f32_128\n"
3821 		"%x6       = OpFMod %f32 %xabs %f32_64\n"
3822 		"%x5       = OpFMod %f32 %xabs %f32_32\n"
3823 		"%x4       = OpFMod %f32 %xabs %f32_16\n"
3824 		"%x3       = OpFMod %f32 %xabs %f32_8\n"
3825 		"%x2       = OpFMod %f32 %xabs %f32_4\n"
3826 		"%x1       = OpFMod %f32 %xabs %f32_2\n"
3827 
3828 		"%b7       = OpFOrdGreaterThanEqual %bool %x8 %f32_127_5\n"
3829 		"%b6       = OpFOrdGreaterThanEqual %bool %x7 %f32_63_5\n"
3830 		"%b5       = OpFOrdGreaterThanEqual %bool %x6 %f32_31_5\n"
3831 		"%b4       = OpFOrdGreaterThanEqual %bool %x5 %f32_15_5\n"
3832 		"%b3       = OpFOrdGreaterThanEqual %bool %x4 %f32_7_5\n"
3833 		"%b2       = OpFOrdGreaterThanEqual %bool %x3 %f32_3_5\n"
3834 		"%b1       = OpFOrdGreaterThanEqual %bool %x2 %f32_1_5\n"
3835 		"%b0       = OpFOrdGreaterThanEqual %bool %x1 %f32_0_5\n"
3836 
3837 		+ generateOpPhiCase5(codestring) +
3838 
3839 		"%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3840 		"            OpStore %outloc %res\n"
3841 		"            OpReturn\n"
3842 
3843 		"            OpFunctionEnd\n";
3844 	spec5.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3845 	spec5.outputs.push_back(BufferSp(new Float32Buffer(outputFloats5)));
3846 	spec5.numWorkGroups = IVec3(numElements, 1, 1);
3847 
3848 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "nested", "Stress OpPhi with a lot of nesting", spec5));
3849 
3850 	createOpPhiVartypeTests(group, testCtx);
3851 
3852 	return group.release();
3853 }
3854 
3855 // Assembly code used for testing block order is based on GLSL source code:
3856 //
3857 // #version 430
3858 //
3859 // layout(std140, set = 0, binding = 0) readonly buffer Input {
3860 //   float elements[];
3861 // } input_data;
3862 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
3863 //   float elements[];
3864 // } output_data;
3865 //
3866 // void main() {
3867 //   uint x = gl_GlobalInvocationID.x;
3868 //   output_data.elements[x] = input_data.elements[x];
3869 //   if (x > uint(50)) {
3870 //     switch (x % uint(3)) {
3871 //       case 0: output_data.elements[x] += 1.5f; break;
3872 //       case 1: output_data.elements[x] += 42.f; break;
3873 //       case 2: output_data.elements[x] -= 27.f; break;
3874 //       default: break;
3875 //     }
3876 //   } else {
3877 //     output_data.elements[x] = -input_data.elements[x];
3878 //   }
3879 // }
createBlockOrderGroup(tcu::TestContext & testCtx)3880 tcu::TestCaseGroup* createBlockOrderGroup (tcu::TestContext& testCtx)
3881 {
3882 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "block_order", "Test block orders"));
3883 	ComputeShaderSpec				spec;
3884 	de::Random						rnd				(deStringHash(group->getName()));
3885 	const int						numElements		= 100;
3886 	vector<float>					inputFloats		(numElements, 0);
3887 	vector<float>					outputFloats	(numElements, 0);
3888 
3889 	fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
3890 
3891 	// CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3892 	floorAll(inputFloats);
3893 
3894 	for (size_t ndx = 0; ndx <= 50; ++ndx)
3895 		outputFloats[ndx] = -inputFloats[ndx];
3896 
3897 	for (size_t ndx = 51; ndx < numElements; ++ndx)
3898 	{
3899 		switch (ndx % 3)
3900 		{
3901 			case 0:		outputFloats[ndx] = inputFloats[ndx] + 1.5f; break;
3902 			case 1:		outputFloats[ndx] = inputFloats[ndx] + 42.f; break;
3903 			case 2:		outputFloats[ndx] = inputFloats[ndx] - 27.f; break;
3904 			default:	break;
3905 		}
3906 	}
3907 
3908 	spec.assembly =
3909 		string(getComputeAsmShaderPreamble()) +
3910 
3911 		"OpSource GLSL 430\n"
3912 		"OpName %main \"main\"\n"
3913 		"OpName %id \"gl_GlobalInvocationID\"\n"
3914 
3915 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
3916 
3917 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
3918 
3919 		"%u32ptr       = OpTypePointer Function %u32\n"
3920 		"%u32ptr_input = OpTypePointer Input %u32\n"
3921 
3922 		+ string(getComputeAsmInputOutputBuffer()) +
3923 
3924 		"%id        = OpVariable %uvec3ptr Input\n"
3925 		"%zero      = OpConstant %i32 0\n"
3926 		"%const3    = OpConstant %u32 3\n"
3927 		"%const50   = OpConstant %u32 50\n"
3928 		"%constf1p5 = OpConstant %f32 1.5\n"
3929 		"%constf27  = OpConstant %f32 27.0\n"
3930 		"%constf42  = OpConstant %f32 42.0\n"
3931 
3932 		"%main = OpFunction %void None %voidf\n"
3933 
3934 		// entry block.
3935 		"%entry    = OpLabel\n"
3936 
3937 		// Create a temporary variable to hold the value of gl_GlobalInvocationID.x.
3938 		"%xvar     = OpVariable %u32ptr Function\n"
3939 		"%xptr     = OpAccessChain %u32ptr_input %id %zero\n"
3940 		"%x        = OpLoad %u32 %xptr\n"
3941 		"            OpStore %xvar %x\n"
3942 
3943 		"%cmp      = OpUGreaterThan %bool %x %const50\n"
3944 		"            OpSelectionMerge %if_merge None\n"
3945 		"            OpBranchConditional %cmp %if_true %if_false\n"
3946 
3947 		// False branch for if-statement: placed in the middle of switch cases and before true branch.
3948 		"%if_false = OpLabel\n"
3949 		"%x_f      = OpLoad %u32 %xvar\n"
3950 		"%inloc_f  = OpAccessChain %f32ptr %indata %zero %x_f\n"
3951 		"%inval_f  = OpLoad %f32 %inloc_f\n"
3952 		"%negate   = OpFNegate %f32 %inval_f\n"
3953 		"%outloc_f = OpAccessChain %f32ptr %outdata %zero %x_f\n"
3954 		"            OpStore %outloc_f %negate\n"
3955 		"            OpBranch %if_merge\n"
3956 
3957 		// Merge block for if-statement: placed in the middle of true and false branch.
3958 		"%if_merge = OpLabel\n"
3959 		"            OpReturn\n"
3960 
3961 		// True branch for if-statement: placed in the middle of swtich cases and after the false branch.
3962 		"%if_true  = OpLabel\n"
3963 		"%xval_t   = OpLoad %u32 %xvar\n"
3964 		"%mod      = OpUMod %u32 %xval_t %const3\n"
3965 		"            OpSelectionMerge %switch_merge None\n"
3966 		"            OpSwitch %mod %default 0 %case0 1 %case1 2 %case2\n"
3967 
3968 		// Merge block for switch-statement: placed before the case
3969 		// bodies.  But it must follow OpSwitch which dominates it.
3970 		"%switch_merge = OpLabel\n"
3971 		"                OpBranch %if_merge\n"
3972 
3973 		// Case 1 for switch-statement: placed before case 0.
3974 		// It must follow the OpSwitch that dominates it.
3975 		"%case1    = OpLabel\n"
3976 		"%x_1      = OpLoad %u32 %xvar\n"
3977 		"%inloc_1  = OpAccessChain %f32ptr %indata %zero %x_1\n"
3978 		"%inval_1  = OpLoad %f32 %inloc_1\n"
3979 		"%addf42   = OpFAdd %f32 %inval_1 %constf42\n"
3980 		"%outloc_1 = OpAccessChain %f32ptr %outdata %zero %x_1\n"
3981 		"            OpStore %outloc_1 %addf42\n"
3982 		"            OpBranch %switch_merge\n"
3983 
3984 		// Case 2 for switch-statement.
3985 		"%case2    = OpLabel\n"
3986 		"%x_2      = OpLoad %u32 %xvar\n"
3987 		"%inloc_2  = OpAccessChain %f32ptr %indata %zero %x_2\n"
3988 		"%inval_2  = OpLoad %f32 %inloc_2\n"
3989 		"%subf27   = OpFSub %f32 %inval_2 %constf27\n"
3990 		"%outloc_2 = OpAccessChain %f32ptr %outdata %zero %x_2\n"
3991 		"            OpStore %outloc_2 %subf27\n"
3992 		"            OpBranch %switch_merge\n"
3993 
3994 		// Default case for switch-statement: placed in the middle of normal cases.
3995 		"%default = OpLabel\n"
3996 		"           OpBranch %switch_merge\n"
3997 
3998 		// Case 0 for switch-statement: out of order.
3999 		"%case0    = OpLabel\n"
4000 		"%x_0      = OpLoad %u32 %xvar\n"
4001 		"%inloc_0  = OpAccessChain %f32ptr %indata %zero %x_0\n"
4002 		"%inval_0  = OpLoad %f32 %inloc_0\n"
4003 		"%addf1p5  = OpFAdd %f32 %inval_0 %constf1p5\n"
4004 		"%outloc_0 = OpAccessChain %f32ptr %outdata %zero %x_0\n"
4005 		"            OpStore %outloc_0 %addf1p5\n"
4006 		"            OpBranch %switch_merge\n"
4007 
4008 		"            OpFunctionEnd\n";
4009 	spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4010 	spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
4011 	spec.numWorkGroups = IVec3(numElements, 1, 1);
4012 
4013 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "various out-of-order blocks", spec));
4014 
4015 	return group.release();
4016 }
4017 
createMultipleShaderGroup(tcu::TestContext & testCtx)4018 tcu::TestCaseGroup* createMultipleShaderGroup (tcu::TestContext& testCtx)
4019 {
4020 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "multiple_shaders", "Test multiple shaders in the same module"));
4021 	ComputeShaderSpec				spec1;
4022 	ComputeShaderSpec				spec2;
4023 	de::Random						rnd				(deStringHash(group->getName()));
4024 	const int						numElements		= 100;
4025 	vector<float>					inputFloats		(numElements, 0);
4026 	vector<float>					outputFloats1	(numElements, 0);
4027 	vector<float>					outputFloats2	(numElements, 0);
4028 	fillRandomScalars(rnd, -500.f, 500.f, &inputFloats[0], numElements);
4029 
4030 	for (size_t ndx = 0; ndx < numElements; ++ndx)
4031 	{
4032 		outputFloats1[ndx] = inputFloats[ndx] + inputFloats[ndx];
4033 		outputFloats2[ndx] = -inputFloats[ndx];
4034 	}
4035 
4036 	const string assembly(
4037 		"OpCapability Shader\n"
4038 		"OpMemoryModel Logical GLSL450\n"
4039 		"OpEntryPoint GLCompute %comp_main1 \"entrypoint1\" %id\n"
4040 		"OpEntryPoint GLCompute %comp_main2 \"entrypoint2\" %id\n"
4041 		// A module cannot have two OpEntryPoint instructions with the same Execution Model and the same Name string.
4042 		"OpEntryPoint Vertex    %vert_main  \"entrypoint2\" %vert_builtins %vertexIndex %instanceIndex\n"
4043 		"OpExecutionMode %comp_main1 LocalSize 1 1 1\n"
4044 		"OpExecutionMode %comp_main2 LocalSize 1 1 1\n"
4045 
4046 		"OpName %comp_main1              \"entrypoint1\"\n"
4047 		"OpName %comp_main2              \"entrypoint2\"\n"
4048 		"OpName %vert_main               \"entrypoint2\"\n"
4049 		"OpName %id                      \"gl_GlobalInvocationID\"\n"
4050 		"OpName %vert_builtin_st         \"gl_PerVertex\"\n"
4051 		"OpName %vertexIndex             \"gl_VertexIndex\"\n"
4052 		"OpName %instanceIndex           \"gl_InstanceIndex\"\n"
4053 		"OpMemberName %vert_builtin_st 0 \"gl_Position\"\n"
4054 		"OpMemberName %vert_builtin_st 1 \"gl_PointSize\"\n"
4055 		"OpMemberName %vert_builtin_st 2 \"gl_ClipDistance\"\n"
4056 
4057 		"OpDecorate %id                      BuiltIn GlobalInvocationId\n"
4058 		"OpDecorate %vertexIndex             BuiltIn VertexIndex\n"
4059 		"OpDecorate %instanceIndex           BuiltIn InstanceIndex\n"
4060 		"OpDecorate %vert_builtin_st         Block\n"
4061 		"OpMemberDecorate %vert_builtin_st 0 BuiltIn Position\n"
4062 		"OpMemberDecorate %vert_builtin_st 1 BuiltIn PointSize\n"
4063 		"OpMemberDecorate %vert_builtin_st 2 BuiltIn ClipDistance\n"
4064 
4065 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4066 
4067 		"%zero       = OpConstant %i32 0\n"
4068 		"%one        = OpConstant %u32 1\n"
4069 		"%c_f32_1    = OpConstant %f32 1\n"
4070 
4071 		"%i32inputptr         = OpTypePointer Input %i32\n"
4072 		"%vec4                = OpTypeVector %f32 4\n"
4073 		"%vec4ptr             = OpTypePointer Output %vec4\n"
4074 		"%f32arr1             = OpTypeArray %f32 %one\n"
4075 		"%vert_builtin_st     = OpTypeStruct %vec4 %f32 %f32arr1\n"
4076 		"%vert_builtin_st_ptr = OpTypePointer Output %vert_builtin_st\n"
4077 		"%vert_builtins       = OpVariable %vert_builtin_st_ptr Output\n"
4078 
4079 		"%id         = OpVariable %uvec3ptr Input\n"
4080 		"%vertexIndex = OpVariable %i32inputptr Input\n"
4081 		"%instanceIndex = OpVariable %i32inputptr Input\n"
4082 		"%c_vec4_1   = OpConstantComposite %vec4 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
4083 
4084 		// gl_Position = vec4(1.);
4085 		"%vert_main  = OpFunction %void None %voidf\n"
4086 		"%vert_entry = OpLabel\n"
4087 		"%position   = OpAccessChain %vec4ptr %vert_builtins %zero\n"
4088 		"              OpStore %position %c_vec4_1\n"
4089 		"              OpReturn\n"
4090 		"              OpFunctionEnd\n"
4091 
4092 		// Double inputs.
4093 		"%comp_main1  = OpFunction %void None %voidf\n"
4094 		"%comp1_entry = OpLabel\n"
4095 		"%idval1      = OpLoad %uvec3 %id\n"
4096 		"%x1          = OpCompositeExtract %u32 %idval1 0\n"
4097 		"%inloc1      = OpAccessChain %f32ptr %indata %zero %x1\n"
4098 		"%inval1      = OpLoad %f32 %inloc1\n"
4099 		"%add         = OpFAdd %f32 %inval1 %inval1\n"
4100 		"%outloc1     = OpAccessChain %f32ptr %outdata %zero %x1\n"
4101 		"               OpStore %outloc1 %add\n"
4102 		"               OpReturn\n"
4103 		"               OpFunctionEnd\n"
4104 
4105 		// Negate inputs.
4106 		"%comp_main2  = OpFunction %void None %voidf\n"
4107 		"%comp2_entry = OpLabel\n"
4108 		"%idval2      = OpLoad %uvec3 %id\n"
4109 		"%x2          = OpCompositeExtract %u32 %idval2 0\n"
4110 		"%inloc2      = OpAccessChain %f32ptr %indata %zero %x2\n"
4111 		"%inval2      = OpLoad %f32 %inloc2\n"
4112 		"%neg         = OpFNegate %f32 %inval2\n"
4113 		"%outloc2     = OpAccessChain %f32ptr %outdata %zero %x2\n"
4114 		"               OpStore %outloc2 %neg\n"
4115 		"               OpReturn\n"
4116 		"               OpFunctionEnd\n");
4117 
4118 	spec1.assembly = assembly;
4119 	spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4120 	spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
4121 	spec1.numWorkGroups = IVec3(numElements, 1, 1);
4122 	spec1.entryPoint = "entrypoint1";
4123 
4124 	spec2.assembly = assembly;
4125 	spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4126 	spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
4127 	spec2.numWorkGroups = IVec3(numElements, 1, 1);
4128 	spec2.entryPoint = "entrypoint2";
4129 
4130 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader1", "multiple shaders in the same module", spec1));
4131 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader2", "multiple shaders in the same module", spec2));
4132 
4133 	return group.release();
4134 }
4135 
makeLongUTF8String(size_t num4ByteChars)4136 inline std::string makeLongUTF8String (size_t num4ByteChars)
4137 {
4138 	// An example of a longest valid UTF-8 character.  Be explicit about the
4139 	// character type because Microsoft compilers can otherwise interpret the
4140 	// character string as being over wide (16-bit) characters. Ideally, we
4141 	// would just use a C++11 UTF-8 string literal, but we want to support older
4142 	// Microsoft compilers.
4143 	const std::basic_string<char> earthAfrica("\xF0\x9F\x8C\x8D");
4144 	std::string longString;
4145 	longString.reserve(num4ByteChars * 4);
4146 	for (size_t count = 0; count < num4ByteChars; count++)
4147 	{
4148 		longString += earthAfrica;
4149 	}
4150 	return longString;
4151 }
4152 
createOpSourceGroup(tcu::TestContext & testCtx)4153 tcu::TestCaseGroup* createOpSourceGroup (tcu::TestContext& testCtx)
4154 {
4155 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "opsource", "Tests the OpSource & OpSourceContinued instruction"));
4156 	vector<CaseParameter>			cases;
4157 	de::Random						rnd				(deStringHash(group->getName()));
4158 	const int						numElements		= 100;
4159 	vector<float>					positiveFloats	(numElements, 0);
4160 	vector<float>					negativeFloats	(numElements, 0);
4161 	const StringTemplate			shaderTemplate	(
4162 		"OpCapability Shader\n"
4163 		"OpMemoryModel Logical GLSL450\n"
4164 
4165 		"OpEntryPoint GLCompute %main \"main\" %id\n"
4166 		"OpExecutionMode %main LocalSize 1 1 1\n"
4167 
4168 		"${SOURCE}\n"
4169 
4170 		"OpName %main           \"main\"\n"
4171 		"OpName %id             \"gl_GlobalInvocationID\"\n"
4172 
4173 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
4174 
4175 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4176 
4177 		"%id        = OpVariable %uvec3ptr Input\n"
4178 		"%zero      = OpConstant %i32 0\n"
4179 
4180 		"%main      = OpFunction %void None %voidf\n"
4181 		"%label     = OpLabel\n"
4182 		"%idval     = OpLoad %uvec3 %id\n"
4183 		"%x         = OpCompositeExtract %u32 %idval 0\n"
4184 		"%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4185 		"%inval     = OpLoad %f32 %inloc\n"
4186 		"%neg       = OpFNegate %f32 %inval\n"
4187 		"%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4188 		"             OpStore %outloc %neg\n"
4189 		"             OpReturn\n"
4190 		"             OpFunctionEnd\n");
4191 
4192 	cases.push_back(CaseParameter("unknown_source",							"OpSource Unknown 0"));
4193 	cases.push_back(CaseParameter("wrong_source",							"OpSource OpenCL_C 210"));
4194 	cases.push_back(CaseParameter("normal_filename",						"%fname = OpString \"filename\"\n"
4195 																			"OpSource GLSL 430 %fname"));
4196 	cases.push_back(CaseParameter("empty_filename",							"%fname = OpString \"\"\n"
4197 																			"OpSource GLSL 430 %fname"));
4198 	cases.push_back(CaseParameter("normal_source_code",						"%fname = OpString \"filename\"\n"
4199 																			"OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\""));
4200 	cases.push_back(CaseParameter("empty_source_code",						"%fname = OpString \"filename\"\n"
4201 																			"OpSource GLSL 430 %fname \"\""));
4202 	cases.push_back(CaseParameter("long_source_code",						"%fname = OpString \"filename\"\n"
4203 																			"OpSource GLSL 430 %fname \"" + makeLongUTF8String(65530) + "ccc\"")); // word count: 65535
4204 	cases.push_back(CaseParameter("utf8_source_code",						"%fname = OpString \"filename\"\n"
4205 																			"OpSource GLSL 430 %fname \"\xE2\x98\x82\xE2\x98\x85\"")); // umbrella & black star symbol
4206 	cases.push_back(CaseParameter("normal_sourcecontinued",					"%fname = OpString \"filename\"\n"
4207 																			"OpSource GLSL 430 %fname \"#version 430\nvo\"\n"
4208 																			"OpSourceContinued \"id main() {}\""));
4209 	cases.push_back(CaseParameter("empty_sourcecontinued",					"%fname = OpString \"filename\"\n"
4210 																			"OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4211 																			"OpSourceContinued \"\""));
4212 	cases.push_back(CaseParameter("long_sourcecontinued",					"%fname = OpString \"filename\"\n"
4213 																			"OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4214 																			"OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\"")); // word count: 65535
4215 	cases.push_back(CaseParameter("utf8_sourcecontinued",					"%fname = OpString \"filename\"\n"
4216 																			"OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4217 																			"OpSourceContinued \"\xE2\x98\x8E\xE2\x9A\x91\"")); // white telephone & black flag symbol
4218 	cases.push_back(CaseParameter("multi_sourcecontinued",					"%fname = OpString \"filename\"\n"
4219 																			"OpSource GLSL 430 %fname \"#version 430\n\"\n"
4220 																			"OpSourceContinued \"void\"\n"
4221 																			"OpSourceContinued \"main()\"\n"
4222 																			"OpSourceContinued \"{}\""));
4223 	cases.push_back(CaseParameter("empty_source_before_sourcecontinued",	"%fname = OpString \"filename\"\n"
4224 																			"OpSource GLSL 430 %fname \"\"\n"
4225 																			"OpSourceContinued \"#version 430\nvoid main() {}\""));
4226 
4227 	fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4228 
4229 	for (size_t ndx = 0; ndx < numElements; ++ndx)
4230 		negativeFloats[ndx] = -positiveFloats[ndx];
4231 
4232 	for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4233 	{
4234 		map<string, string>		specializations;
4235 		ComputeShaderSpec		spec;
4236 
4237 		specializations["SOURCE"] = cases[caseNdx].param;
4238 		spec.assembly = shaderTemplate.specialize(specializations);
4239 		spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4240 		spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4241 		spec.numWorkGroups = IVec3(numElements, 1, 1);
4242 
4243 		group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4244 	}
4245 
4246 	return group.release();
4247 }
4248 
createOpSourceExtensionGroup(tcu::TestContext & testCtx)4249 tcu::TestCaseGroup* createOpSourceExtensionGroup (tcu::TestContext& testCtx)
4250 {
4251 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "opsourceextension", "Tests the OpSource instruction"));
4252 	vector<CaseParameter>			cases;
4253 	de::Random						rnd				(deStringHash(group->getName()));
4254 	const int						numElements		= 100;
4255 	vector<float>					inputFloats		(numElements, 0);
4256 	vector<float>					outputFloats	(numElements, 0);
4257 	const StringTemplate			shaderTemplate	(
4258 		string(getComputeAsmShaderPreamble()) +
4259 
4260 		"OpSourceExtension \"${EXTENSION}\"\n"
4261 
4262 		"OpName %main           \"main\"\n"
4263 		"OpName %id             \"gl_GlobalInvocationID\"\n"
4264 
4265 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
4266 
4267 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4268 
4269 		"%id        = OpVariable %uvec3ptr Input\n"
4270 		"%zero      = OpConstant %i32 0\n"
4271 
4272 		"%main      = OpFunction %void None %voidf\n"
4273 		"%label     = OpLabel\n"
4274 		"%idval     = OpLoad %uvec3 %id\n"
4275 		"%x         = OpCompositeExtract %u32 %idval 0\n"
4276 		"%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4277 		"%inval     = OpLoad %f32 %inloc\n"
4278 		"%neg       = OpFNegate %f32 %inval\n"
4279 		"%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4280 		"             OpStore %outloc %neg\n"
4281 		"             OpReturn\n"
4282 		"             OpFunctionEnd\n");
4283 
4284 	cases.push_back(CaseParameter("empty_extension",	""));
4285 	cases.push_back(CaseParameter("real_extension",		"GL_ARB_texture_rectangle"));
4286 	cases.push_back(CaseParameter("fake_extension",		"GL_ARB_im_the_ultimate_extension"));
4287 	cases.push_back(CaseParameter("utf8_extension",		"GL_ARB_\xE2\x98\x82\xE2\x98\x85"));
4288 	cases.push_back(CaseParameter("long_extension",		makeLongUTF8String(65533) + "ccc")); // word count: 65535
4289 
4290 	fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
4291 
4292 	for (size_t ndx = 0; ndx < numElements; ++ndx)
4293 		outputFloats[ndx] = -inputFloats[ndx];
4294 
4295 	for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4296 	{
4297 		map<string, string>		specializations;
4298 		ComputeShaderSpec		spec;
4299 
4300 		specializations["EXTENSION"] = cases[caseNdx].param;
4301 		spec.assembly = shaderTemplate.specialize(specializations);
4302 		spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4303 		spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
4304 		spec.numWorkGroups = IVec3(numElements, 1, 1);
4305 
4306 		group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4307 	}
4308 
4309 	return group.release();
4310 }
4311 
4312 // Checks that a compute shader can generate a constant null value of various types, without exercising a computation on it.
createOpConstantNullGroup(tcu::TestContext & testCtx)4313 tcu::TestCaseGroup* createOpConstantNullGroup (tcu::TestContext& testCtx)
4314 {
4315 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "opconstantnull", "Tests the OpConstantNull instruction"));
4316 	vector<CaseParameter>			cases;
4317 	de::Random						rnd				(deStringHash(group->getName()));
4318 	const int						numElements		= 100;
4319 	vector<float>					positiveFloats	(numElements, 0);
4320 	vector<float>					negativeFloats	(numElements, 0);
4321 	const StringTemplate			shaderTemplate	(
4322 		string(getComputeAsmShaderPreamble()) +
4323 
4324 		"OpSource GLSL 430\n"
4325 		"OpName %main           \"main\"\n"
4326 		"OpName %id             \"gl_GlobalInvocationID\"\n"
4327 
4328 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
4329 
4330 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4331 		"%uvec2     = OpTypeVector %u32 2\n"
4332 		"%bvec3     = OpTypeVector %bool 3\n"
4333 		"%fvec4     = OpTypeVector %f32 4\n"
4334 		"%fmat33    = OpTypeMatrix %fvec3 3\n"
4335 		"%const100  = OpConstant %u32 100\n"
4336 		"%uarr100   = OpTypeArray %i32 %const100\n"
4337 		"%struct    = OpTypeStruct %f32 %i32 %u32\n"
4338 		"%pointer   = OpTypePointer Function %i32\n"
4339 		+ string(getComputeAsmInputOutputBuffer()) +
4340 
4341 		"%null      = OpConstantNull ${TYPE}\n"
4342 
4343 		"%id        = OpVariable %uvec3ptr Input\n"
4344 		"%zero      = OpConstant %i32 0\n"
4345 
4346 		"%main      = OpFunction %void None %voidf\n"
4347 		"%label     = OpLabel\n"
4348 		"%idval     = OpLoad %uvec3 %id\n"
4349 		"%x         = OpCompositeExtract %u32 %idval 0\n"
4350 		"%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4351 		"%inval     = OpLoad %f32 %inloc\n"
4352 		"%neg       = OpFNegate %f32 %inval\n"
4353 		"%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4354 		"             OpStore %outloc %neg\n"
4355 		"             OpReturn\n"
4356 		"             OpFunctionEnd\n");
4357 
4358 	cases.push_back(CaseParameter("bool",			"%bool"));
4359 	cases.push_back(CaseParameter("sint32",			"%i32"));
4360 	cases.push_back(CaseParameter("uint32",			"%u32"));
4361 	cases.push_back(CaseParameter("float32",		"%f32"));
4362 	cases.push_back(CaseParameter("vec4float32",	"%fvec4"));
4363 	cases.push_back(CaseParameter("vec3bool",		"%bvec3"));
4364 	cases.push_back(CaseParameter("vec2uint32",		"%uvec2"));
4365 	cases.push_back(CaseParameter("matrix",			"%fmat33"));
4366 	cases.push_back(CaseParameter("array",			"%uarr100"));
4367 	cases.push_back(CaseParameter("struct",			"%struct"));
4368 	cases.push_back(CaseParameter("pointer",		"%pointer"));
4369 
4370 	fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4371 
4372 	for (size_t ndx = 0; ndx < numElements; ++ndx)
4373 		negativeFloats[ndx] = -positiveFloats[ndx];
4374 
4375 	for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4376 	{
4377 		map<string, string>		specializations;
4378 		ComputeShaderSpec		spec;
4379 
4380 		specializations["TYPE"] = cases[caseNdx].param;
4381 		spec.assembly = shaderTemplate.specialize(specializations);
4382 		spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4383 		spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4384 		spec.numWorkGroups = IVec3(numElements, 1, 1);
4385 
4386 		group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4387 	}
4388 
4389 	return group.release();
4390 }
4391 
4392 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
createOpConstantCompositeGroup(tcu::TestContext & testCtx)4393 tcu::TestCaseGroup* createOpConstantCompositeGroup (tcu::TestContext& testCtx)
4394 {
4395 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "Tests the OpConstantComposite instruction"));
4396 	vector<CaseParameter>			cases;
4397 	de::Random						rnd				(deStringHash(group->getName()));
4398 	const int						numElements		= 100;
4399 	vector<float>					positiveFloats	(numElements, 0);
4400 	vector<float>					negativeFloats	(numElements, 0);
4401 	const StringTemplate			shaderTemplate	(
4402 		string(getComputeAsmShaderPreamble()) +
4403 
4404 		"OpSource GLSL 430\n"
4405 		"OpName %main           \"main\"\n"
4406 		"OpName %id             \"gl_GlobalInvocationID\"\n"
4407 
4408 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
4409 
4410 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4411 
4412 		"%id        = OpVariable %uvec3ptr Input\n"
4413 		"%zero      = OpConstant %i32 0\n"
4414 
4415 		"${CONSTANT}\n"
4416 
4417 		"%main      = OpFunction %void None %voidf\n"
4418 		"%label     = OpLabel\n"
4419 		"%idval     = OpLoad %uvec3 %id\n"
4420 		"%x         = OpCompositeExtract %u32 %idval 0\n"
4421 		"%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4422 		"%inval     = OpLoad %f32 %inloc\n"
4423 		"%neg       = OpFNegate %f32 %inval\n"
4424 		"%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4425 		"             OpStore %outloc %neg\n"
4426 		"             OpReturn\n"
4427 		"             OpFunctionEnd\n");
4428 
4429 	cases.push_back(CaseParameter("vector",			"%five = OpConstant %u32 5\n"
4430 													"%const = OpConstantComposite %uvec3 %five %zero %five"));
4431 	cases.push_back(CaseParameter("matrix",			"%m3fvec3 = OpTypeMatrix %fvec3 3\n"
4432 													"%ten = OpConstant %f32 10.\n"
4433 													"%fzero = OpConstant %f32 0.\n"
4434 													"%vec = OpConstantComposite %fvec3 %ten %fzero %ten\n"
4435 													"%mat = OpConstantComposite %m3fvec3 %vec %vec %vec"));
4436 	cases.push_back(CaseParameter("struct",			"%m2vec3 = OpTypeMatrix %fvec3 2\n"
4437 													"%struct = OpTypeStruct %i32 %f32 %fvec3 %m2vec3\n"
4438 													"%fzero = OpConstant %f32 0.\n"
4439 													"%one = OpConstant %f32 1.\n"
4440 													"%point5 = OpConstant %f32 0.5\n"
4441 													"%vec = OpConstantComposite %fvec3 %one %one %fzero\n"
4442 													"%mat = OpConstantComposite %m2vec3 %vec %vec\n"
4443 													"%const = OpConstantComposite %struct %zero %point5 %vec %mat"));
4444 	cases.push_back(CaseParameter("nested_struct",	"%st1 = OpTypeStruct %u32 %f32\n"
4445 													"%st2 = OpTypeStruct %i32 %i32\n"
4446 													"%struct = OpTypeStruct %st1 %st2\n"
4447 													"%point5 = OpConstant %f32 0.5\n"
4448 													"%one = OpConstant %u32 1\n"
4449 													"%ten = OpConstant %i32 10\n"
4450 													"%st1val = OpConstantComposite %st1 %one %point5\n"
4451 													"%st2val = OpConstantComposite %st2 %ten %ten\n"
4452 													"%const = OpConstantComposite %struct %st1val %st2val"));
4453 
4454 	fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4455 
4456 	for (size_t ndx = 0; ndx < numElements; ++ndx)
4457 		negativeFloats[ndx] = -positiveFloats[ndx];
4458 
4459 	for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4460 	{
4461 		map<string, string>		specializations;
4462 		ComputeShaderSpec		spec;
4463 
4464 		specializations["CONSTANT"] = cases[caseNdx].param;
4465 		spec.assembly = shaderTemplate.specialize(specializations);
4466 		spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4467 		spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4468 		spec.numWorkGroups = IVec3(numElements, 1, 1);
4469 
4470 		group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4471 	}
4472 
4473 	return group.release();
4474 }
4475 
4476 // Creates a floating point number with the given exponent, and significand
4477 // bits set. It can only create normalized numbers. Only the least significant
4478 // 24 bits of the significand will be examined. The final bit of the
4479 // significand will also be ignored. This allows alignment to be written
4480 // similarly to C99 hex-floats.
4481 // For example if you wanted to write 0x1.7f34p-12 you would call
4482 // constructNormalizedFloat(-12, 0x7f3400)
constructNormalizedFloat(deInt32 exponent,deUint32 significand)4483 float constructNormalizedFloat (deInt32 exponent, deUint32 significand)
4484 {
4485 	float f = 1.0f;
4486 
4487 	for (deInt32 idx = 0; idx < 23; ++idx)
4488 	{
4489 		f += ((significand & 0x800000) == 0) ? 0.f : std::ldexp(1.0f, -(idx + 1));
4490 		significand <<= 1;
4491 	}
4492 
4493 	return std::ldexp(f, exponent);
4494 }
4495 
4496 // Compare instruction for the OpQuantizeF16 compute exact case.
4497 // Returns true if the output is what is expected from the test case.
compareOpQuantizeF16ComputeExactCase(const std::vector<Resource> &,const vector<AllocationSp> & outputAllocs,const std::vector<Resource> & expectedOutputs,TestLog &)4498 bool compareOpQuantizeF16ComputeExactCase (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
4499 {
4500 	if (outputAllocs.size() != 1)
4501 		return false;
4502 
4503 	// Only size is needed because we cannot compare Nans.
4504 	size_t byteSize = expectedOutputs[0].getByteSize();
4505 
4506 	const float*	outputAsFloat	= static_cast<const float*>(outputAllocs[0]->getHostPtr());
4507 
4508 	if (byteSize != 4*sizeof(float)) {
4509 		return false;
4510 	}
4511 
4512 	if (*outputAsFloat != constructNormalizedFloat(8, 0x304000) &&
4513 		*outputAsFloat != constructNormalizedFloat(8, 0x300000)) {
4514 		return false;
4515 	}
4516 	outputAsFloat++;
4517 
4518 	if (*outputAsFloat != -constructNormalizedFloat(-7, 0x600000) &&
4519 		*outputAsFloat != -constructNormalizedFloat(-7, 0x604000)) {
4520 		return false;
4521 	}
4522 	outputAsFloat++;
4523 
4524 	if (*outputAsFloat != constructNormalizedFloat(2, 0x01C000) &&
4525 		*outputAsFloat != constructNormalizedFloat(2, 0x020000)) {
4526 		return false;
4527 	}
4528 	outputAsFloat++;
4529 
4530 	if (*outputAsFloat != constructNormalizedFloat(1, 0xFFC000) &&
4531 		*outputAsFloat != constructNormalizedFloat(2, 0x000000)) {
4532 		return false;
4533 	}
4534 
4535 	return true;
4536 }
4537 
4538 // Checks that every output from a test-case is a float NaN.
compareNan(const std::vector<Resource> &,const vector<AllocationSp> & outputAllocs,const std::vector<Resource> & expectedOutputs,TestLog &)4539 bool compareNan (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
4540 {
4541 	if (outputAllocs.size() != 1)
4542 		return false;
4543 
4544 	// Only size is needed because we cannot compare Nans.
4545 	size_t byteSize = expectedOutputs[0].getByteSize();
4546 
4547 	const float* const	output_as_float	= static_cast<const float*>(outputAllocs[0]->getHostPtr());
4548 
4549 	for (size_t idx = 0; idx < byteSize / sizeof(float); ++idx)
4550 	{
4551 		if (!deFloatIsNaN(output_as_float[idx]))
4552 		{
4553 			return false;
4554 		}
4555 	}
4556 
4557 	return true;
4558 }
4559 
4560 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
createOpQuantizeToF16Group(tcu::TestContext & testCtx)4561 tcu::TestCaseGroup* createOpQuantizeToF16Group (tcu::TestContext& testCtx)
4562 {
4563 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "opquantize", "Tests the OpQuantizeToF16 instruction"));
4564 
4565 	const std::string shader (
4566 		string(getComputeAsmShaderPreamble()) +
4567 
4568 		"OpSource GLSL 430\n"
4569 		"OpName %main           \"main\"\n"
4570 		"OpName %id             \"gl_GlobalInvocationID\"\n"
4571 
4572 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
4573 
4574 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4575 
4576 		"%id        = OpVariable %uvec3ptr Input\n"
4577 		"%zero      = OpConstant %i32 0\n"
4578 
4579 		"%main      = OpFunction %void None %voidf\n"
4580 		"%label     = OpLabel\n"
4581 		"%idval     = OpLoad %uvec3 %id\n"
4582 		"%x         = OpCompositeExtract %u32 %idval 0\n"
4583 		"%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4584 		"%inval     = OpLoad %f32 %inloc\n"
4585 		"%quant     = OpQuantizeToF16 %f32 %inval\n"
4586 		"%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4587 		"             OpStore %outloc %quant\n"
4588 		"             OpReturn\n"
4589 		"             OpFunctionEnd\n");
4590 
4591 	{
4592 		ComputeShaderSpec	spec;
4593 		const deUint32		numElements		= 100;
4594 		vector<float>		infinities;
4595 		vector<float>		results;
4596 
4597 		infinities.reserve(numElements);
4598 		results.reserve(numElements);
4599 
4600 		for (size_t idx = 0; idx < numElements; ++idx)
4601 		{
4602 			switch(idx % 4)
4603 			{
4604 				case 0:
4605 					infinities.push_back(std::numeric_limits<float>::infinity());
4606 					results.push_back(std::numeric_limits<float>::infinity());
4607 					break;
4608 				case 1:
4609 					infinities.push_back(-std::numeric_limits<float>::infinity());
4610 					results.push_back(-std::numeric_limits<float>::infinity());
4611 					break;
4612 				case 2:
4613 					infinities.push_back(std::ldexp(1.0f, 16));
4614 					results.push_back(std::numeric_limits<float>::infinity());
4615 					break;
4616 				case 3:
4617 					infinities.push_back(std::ldexp(-1.0f, 32));
4618 					results.push_back(-std::numeric_limits<float>::infinity());
4619 					break;
4620 			}
4621 		}
4622 
4623 		spec.assembly = shader;
4624 		spec.inputs.push_back(BufferSp(new Float32Buffer(infinities)));
4625 		spec.outputs.push_back(BufferSp(new Float32Buffer(results)));
4626 		spec.numWorkGroups = IVec3(numElements, 1, 1);
4627 
4628 		group->addChild(new SpvAsmComputeShaderCase(
4629 			testCtx, "infinities", "Check that infinities propagated and created", spec));
4630 	}
4631 
4632 	{
4633 		ComputeShaderSpec	spec;
4634 		vector<float>		nans;
4635 		const deUint32		numElements		= 100;
4636 
4637 		nans.reserve(numElements);
4638 
4639 		for (size_t idx = 0; idx < numElements; ++idx)
4640 		{
4641 			if (idx % 2 == 0)
4642 			{
4643 				nans.push_back(std::numeric_limits<float>::quiet_NaN());
4644 			}
4645 			else
4646 			{
4647 				nans.push_back(-std::numeric_limits<float>::quiet_NaN());
4648 			}
4649 		}
4650 
4651 		spec.assembly = shader;
4652 		spec.inputs.push_back(BufferSp(new Float32Buffer(nans)));
4653 		spec.outputs.push_back(BufferSp(new Float32Buffer(nans)));
4654 		spec.numWorkGroups = IVec3(numElements, 1, 1);
4655 		spec.verifyIO = &compareNan;
4656 
4657 		group->addChild(new SpvAsmComputeShaderCase(
4658 			testCtx, "propagated_nans", "Check that nans are propagated", spec));
4659 	}
4660 
4661 	{
4662 		ComputeShaderSpec	spec;
4663 		vector<float>		small;
4664 		vector<float>		zeros;
4665 		const deUint32		numElements		= 100;
4666 
4667 		small.reserve(numElements);
4668 		zeros.reserve(numElements);
4669 
4670 		for (size_t idx = 0; idx < numElements; ++idx)
4671 		{
4672 			switch(idx % 6)
4673 			{
4674 				case 0:
4675 					small.push_back(0.f);
4676 					zeros.push_back(0.f);
4677 					break;
4678 				case 1:
4679 					small.push_back(-0.f);
4680 					zeros.push_back(-0.f);
4681 					break;
4682 				case 2:
4683 					small.push_back(std::ldexp(1.0f, -16));
4684 					zeros.push_back(0.f);
4685 					break;
4686 				case 3:
4687 					small.push_back(std::ldexp(-1.0f, -32));
4688 					zeros.push_back(-0.f);
4689 					break;
4690 				case 4:
4691 					small.push_back(std::ldexp(1.0f, -127));
4692 					zeros.push_back(0.f);
4693 					break;
4694 				case 5:
4695 					small.push_back(-std::ldexp(1.0f, -128));
4696 					zeros.push_back(-0.f);
4697 					break;
4698 			}
4699 		}
4700 
4701 		spec.assembly = shader;
4702 		spec.inputs.push_back(BufferSp(new Float32Buffer(small)));
4703 		spec.outputs.push_back(BufferSp(new Float32Buffer(zeros)));
4704 		spec.numWorkGroups = IVec3(numElements, 1, 1);
4705 
4706 		group->addChild(new SpvAsmComputeShaderCase(
4707 			testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
4708 	}
4709 
4710 	{
4711 		ComputeShaderSpec	spec;
4712 		vector<float>		exact;
4713 		const deUint32		numElements		= 200;
4714 
4715 		exact.reserve(numElements);
4716 
4717 		for (size_t idx = 0; idx < numElements; ++idx)
4718 			exact.push_back(static_cast<float>(static_cast<int>(idx) - 100));
4719 
4720 		spec.assembly = shader;
4721 		spec.inputs.push_back(BufferSp(new Float32Buffer(exact)));
4722 		spec.outputs.push_back(BufferSp(new Float32Buffer(exact)));
4723 		spec.numWorkGroups = IVec3(numElements, 1, 1);
4724 
4725 		group->addChild(new SpvAsmComputeShaderCase(
4726 			testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
4727 	}
4728 
4729 	{
4730 		ComputeShaderSpec	spec;
4731 		vector<float>		inputs;
4732 		const deUint32		numElements		= 4;
4733 
4734 		inputs.push_back(constructNormalizedFloat(8,	0x300300));
4735 		inputs.push_back(-constructNormalizedFloat(-7,	0x600800));
4736 		inputs.push_back(constructNormalizedFloat(2,	0x01E000));
4737 		inputs.push_back(constructNormalizedFloat(1,	0xFFE000));
4738 
4739 		spec.assembly = shader;
4740 		spec.verifyIO = &compareOpQuantizeF16ComputeExactCase;
4741 		spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4742 		spec.outputs.push_back(BufferSp(new Float32Buffer(inputs)));
4743 		spec.numWorkGroups = IVec3(numElements, 1, 1);
4744 
4745 		group->addChild(new SpvAsmComputeShaderCase(
4746 			testCtx, "rounded", "Check that are rounded when needed", spec));
4747 	}
4748 
4749 	return group.release();
4750 }
4751 
createSpecConstantOpQuantizeToF16Group(tcu::TestContext & testCtx)4752 tcu::TestCaseGroup* createSpecConstantOpQuantizeToF16Group (tcu::TestContext& testCtx)
4753 {
4754 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "opspecconstantop_opquantize", "Tests the OpQuantizeToF16 opcode for the OpSpecConstantOp instruction"));
4755 
4756 	const std::string shader (
4757 		string(getComputeAsmShaderPreamble()) +
4758 
4759 		"OpName %main           \"main\"\n"
4760 		"OpName %id             \"gl_GlobalInvocationID\"\n"
4761 
4762 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
4763 
4764 		"OpDecorate %sc_0  SpecId 0\n"
4765 		"OpDecorate %sc_1  SpecId 1\n"
4766 		"OpDecorate %sc_2  SpecId 2\n"
4767 		"OpDecorate %sc_3  SpecId 3\n"
4768 		"OpDecorate %sc_4  SpecId 4\n"
4769 		"OpDecorate %sc_5  SpecId 5\n"
4770 
4771 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4772 
4773 		"%id        = OpVariable %uvec3ptr Input\n"
4774 		"%zero      = OpConstant %i32 0\n"
4775 		"%c_u32_6   = OpConstant %u32 6\n"
4776 
4777 		"%sc_0      = OpSpecConstant %f32 0.\n"
4778 		"%sc_1      = OpSpecConstant %f32 0.\n"
4779 		"%sc_2      = OpSpecConstant %f32 0.\n"
4780 		"%sc_3      = OpSpecConstant %f32 0.\n"
4781 		"%sc_4      = OpSpecConstant %f32 0.\n"
4782 		"%sc_5      = OpSpecConstant %f32 0.\n"
4783 
4784 		"%sc_0_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_0\n"
4785 		"%sc_1_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_1\n"
4786 		"%sc_2_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_2\n"
4787 		"%sc_3_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_3\n"
4788 		"%sc_4_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_4\n"
4789 		"%sc_5_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_5\n"
4790 
4791 		"%main      = OpFunction %void None %voidf\n"
4792 		"%label     = OpLabel\n"
4793 		"%idval     = OpLoad %uvec3 %id\n"
4794 		"%x         = OpCompositeExtract %u32 %idval 0\n"
4795 		"%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4796 		"%selector  = OpUMod %u32 %x %c_u32_6\n"
4797 		"            OpSelectionMerge %exit None\n"
4798 		"            OpSwitch %selector %exit 0 %case0 1 %case1 2 %case2 3 %case3 4 %case4 5 %case5\n"
4799 
4800 		"%case0     = OpLabel\n"
4801 		"             OpStore %outloc %sc_0_quant\n"
4802 		"             OpBranch %exit\n"
4803 
4804 		"%case1     = OpLabel\n"
4805 		"             OpStore %outloc %sc_1_quant\n"
4806 		"             OpBranch %exit\n"
4807 
4808 		"%case2     = OpLabel\n"
4809 		"             OpStore %outloc %sc_2_quant\n"
4810 		"             OpBranch %exit\n"
4811 
4812 		"%case3     = OpLabel\n"
4813 		"             OpStore %outloc %sc_3_quant\n"
4814 		"             OpBranch %exit\n"
4815 
4816 		"%case4     = OpLabel\n"
4817 		"             OpStore %outloc %sc_4_quant\n"
4818 		"             OpBranch %exit\n"
4819 
4820 		"%case5     = OpLabel\n"
4821 		"             OpStore %outloc %sc_5_quant\n"
4822 		"             OpBranch %exit\n"
4823 
4824 		"%exit      = OpLabel\n"
4825 		"             OpReturn\n"
4826 
4827 		"             OpFunctionEnd\n");
4828 
4829 	{
4830 		ComputeShaderSpec	spec;
4831 		const deUint8		numCases	= 4;
4832 		vector<float>		inputs		(numCases, 0.f);
4833 		vector<float>		outputs;
4834 
4835 		spec.assembly		= shader;
4836 		spec.numWorkGroups	= IVec3(numCases, 1, 1);
4837 
4838 		spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::numeric_limits<float>::infinity()));
4839 		spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-std::numeric_limits<float>::infinity()));
4840 		spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, 16)));
4841 		spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(-1.0f, 32)));
4842 
4843 		outputs.push_back(std::numeric_limits<float>::infinity());
4844 		outputs.push_back(-std::numeric_limits<float>::infinity());
4845 		outputs.push_back(std::numeric_limits<float>::infinity());
4846 		outputs.push_back(-std::numeric_limits<float>::infinity());
4847 
4848 		spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4849 		spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4850 
4851 		group->addChild(new SpvAsmComputeShaderCase(
4852 			testCtx, "infinities", "Check that infinities propagated and created", spec));
4853 	}
4854 
4855 	{
4856 		ComputeShaderSpec	spec;
4857 		const deUint8		numCases	= 2;
4858 		vector<float>		inputs		(numCases, 0.f);
4859 		vector<float>		outputs;
4860 
4861 		spec.assembly		= shader;
4862 		spec.numWorkGroups	= IVec3(numCases, 1, 1);
4863 		spec.verifyIO		= &compareNan;
4864 
4865 		outputs.push_back(std::numeric_limits<float>::quiet_NaN());
4866 		outputs.push_back(-std::numeric_limits<float>::quiet_NaN());
4867 
4868 		for (deUint8 idx = 0; idx < numCases; ++idx)
4869 			spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(outputs[idx]));
4870 
4871 		spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4872 		spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4873 
4874 		group->addChild(new SpvAsmComputeShaderCase(
4875 			testCtx, "propagated_nans", "Check that nans are propagated", spec));
4876 	}
4877 
4878 	{
4879 		ComputeShaderSpec	spec;
4880 		const deUint8		numCases	= 6;
4881 		vector<float>		inputs		(numCases, 0.f);
4882 		vector<float>		outputs;
4883 
4884 		spec.assembly		= shader;
4885 		spec.numWorkGroups	= IVec3(numCases, 1, 1);
4886 
4887 		spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(0.f));
4888 		spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-0.f));
4889 		spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, -16)));
4890 		spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(-1.0f, -32)));
4891 		spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, -127)));
4892 		spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-std::ldexp(1.0f, -128)));
4893 
4894 		outputs.push_back(0.f);
4895 		outputs.push_back(-0.f);
4896 		outputs.push_back(0.f);
4897 		outputs.push_back(-0.f);
4898 		outputs.push_back(0.f);
4899 		outputs.push_back(-0.f);
4900 
4901 		spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4902 		spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4903 
4904 		group->addChild(new SpvAsmComputeShaderCase(
4905 			testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
4906 	}
4907 
4908 	{
4909 		ComputeShaderSpec	spec;
4910 		const deUint8		numCases	= 6;
4911 		vector<float>		inputs		(numCases, 0.f);
4912 		vector<float>		outputs;
4913 
4914 		spec.assembly		= shader;
4915 		spec.numWorkGroups	= IVec3(numCases, 1, 1);
4916 
4917 		for (deUint8 idx = 0; idx < 6; ++idx)
4918 		{
4919 			const float f = static_cast<float>(idx * 10 - 30) / 4.f;
4920 			spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(f));
4921 			outputs.push_back(f);
4922 		}
4923 
4924 		spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4925 		spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4926 
4927 		group->addChild(new SpvAsmComputeShaderCase(
4928 			testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
4929 	}
4930 
4931 	{
4932 		ComputeShaderSpec	spec;
4933 		const deUint8		numCases	= 4;
4934 		vector<float>		inputs		(numCases, 0.f);
4935 		vector<float>		outputs;
4936 
4937 		spec.assembly		= shader;
4938 		spec.numWorkGroups	= IVec3(numCases, 1, 1);
4939 		spec.verifyIO		= &compareOpQuantizeF16ComputeExactCase;
4940 
4941 		outputs.push_back(constructNormalizedFloat(8, 0x300300));
4942 		outputs.push_back(-constructNormalizedFloat(-7, 0x600800));
4943 		outputs.push_back(constructNormalizedFloat(2, 0x01E000));
4944 		outputs.push_back(constructNormalizedFloat(1, 0xFFE000));
4945 
4946 		for (deUint8 idx = 0; idx < numCases; ++idx)
4947 			spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(outputs[idx]));
4948 
4949 		spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4950 		spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4951 
4952 		group->addChild(new SpvAsmComputeShaderCase(
4953 			testCtx, "rounded", "Check that are rounded when needed", spec));
4954 	}
4955 
4956 	return group.release();
4957 }
4958 
4959 // Checks that constant null/composite values can be used in computation.
createOpConstantUsageGroup(tcu::TestContext & testCtx)4960 tcu::TestCaseGroup* createOpConstantUsageGroup (tcu::TestContext& testCtx)
4961 {
4962 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "opconstantnullcomposite", "Spotcheck the OpConstantNull & OpConstantComposite instruction"));
4963 	ComputeShaderSpec				spec;
4964 	de::Random						rnd				(deStringHash(group->getName()));
4965 	const int						numElements		= 100;
4966 	vector<float>					positiveFloats	(numElements, 0);
4967 	vector<float>					negativeFloats	(numElements, 0);
4968 
4969 	fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4970 
4971 	for (size_t ndx = 0; ndx < numElements; ++ndx)
4972 		negativeFloats[ndx] = -positiveFloats[ndx];
4973 
4974 	spec.assembly =
4975 		"OpCapability Shader\n"
4976 		"%std450 = OpExtInstImport \"GLSL.std.450\"\n"
4977 		"OpMemoryModel Logical GLSL450\n"
4978 		"OpEntryPoint GLCompute %main \"main\" %id\n"
4979 		"OpExecutionMode %main LocalSize 1 1 1\n"
4980 
4981 		"OpSource GLSL 430\n"
4982 		"OpName %main           \"main\"\n"
4983 		"OpName %id             \"gl_GlobalInvocationID\"\n"
4984 
4985 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
4986 
4987 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4988 
4989 		"%fmat      = OpTypeMatrix %fvec3 3\n"
4990 		"%ten       = OpConstant %u32 10\n"
4991 		"%f32arr10  = OpTypeArray %f32 %ten\n"
4992 		"%fst       = OpTypeStruct %f32 %f32\n"
4993 
4994 		+ string(getComputeAsmInputOutputBuffer()) +
4995 
4996 		"%id        = OpVariable %uvec3ptr Input\n"
4997 		"%zero      = OpConstant %i32 0\n"
4998 
4999 		// Create a bunch of null values
5000 		"%unull     = OpConstantNull %u32\n"
5001 		"%fnull     = OpConstantNull %f32\n"
5002 		"%vnull     = OpConstantNull %fvec3\n"
5003 		"%mnull     = OpConstantNull %fmat\n"
5004 		"%anull     = OpConstantNull %f32arr10\n"
5005 		"%snull     = OpConstantComposite %fst %fnull %fnull\n"
5006 
5007 		"%main      = OpFunction %void None %voidf\n"
5008 		"%label     = OpLabel\n"
5009 		"%idval     = OpLoad %uvec3 %id\n"
5010 		"%x         = OpCompositeExtract %u32 %idval 0\n"
5011 		"%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5012 		"%inval     = OpLoad %f32 %inloc\n"
5013 		"%neg       = OpFNegate %f32 %inval\n"
5014 
5015 		// Get the abs() of (a certain element of) those null values
5016 		"%unull_cov = OpConvertUToF %f32 %unull\n"
5017 		"%unull_abs = OpExtInst %f32 %std450 FAbs %unull_cov\n"
5018 		"%fnull_abs = OpExtInst %f32 %std450 FAbs %fnull\n"
5019 		"%vnull_0   = OpCompositeExtract %f32 %vnull 0\n"
5020 		"%vnull_abs = OpExtInst %f32 %std450 FAbs %vnull_0\n"
5021 		"%mnull_12  = OpCompositeExtract %f32 %mnull 1 2\n"
5022 		"%mnull_abs = OpExtInst %f32 %std450 FAbs %mnull_12\n"
5023 		"%anull_3   = OpCompositeExtract %f32 %anull 3\n"
5024 		"%anull_abs = OpExtInst %f32 %std450 FAbs %anull_3\n"
5025 		"%snull_1   = OpCompositeExtract %f32 %snull 1\n"
5026 		"%snull_abs = OpExtInst %f32 %std450 FAbs %snull_1\n"
5027 
5028 		// Add them all
5029 		"%add1      = OpFAdd %f32 %neg  %unull_abs\n"
5030 		"%add2      = OpFAdd %f32 %add1 %fnull_abs\n"
5031 		"%add3      = OpFAdd %f32 %add2 %vnull_abs\n"
5032 		"%add4      = OpFAdd %f32 %add3 %mnull_abs\n"
5033 		"%add5      = OpFAdd %f32 %add4 %anull_abs\n"
5034 		"%final     = OpFAdd %f32 %add5 %snull_abs\n"
5035 
5036 		"%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5037 		"             OpStore %outloc %final\n" // write to output
5038 		"             OpReturn\n"
5039 		"             OpFunctionEnd\n";
5040 	spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
5041 	spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
5042 	spec.numWorkGroups = IVec3(numElements, 1, 1);
5043 
5044 	group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "Check that values constructed via OpConstantNull & OpConstantComposite can be used", spec));
5045 
5046 	return group.release();
5047 }
5048 
5049 // Assembly code used for testing loop control is based on GLSL source code:
5050 // #version 430
5051 //
5052 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5053 //   float elements[];
5054 // } input_data;
5055 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5056 //   float elements[];
5057 // } output_data;
5058 //
5059 // void main() {
5060 //   uint x = gl_GlobalInvocationID.x;
5061 //   output_data.elements[x] = input_data.elements[x];
5062 //   for (uint i = 0; i < 4; ++i)
5063 //     output_data.elements[x] += 1.f;
5064 // }
createLoopControlGroup(tcu::TestContext & testCtx)5065 tcu::TestCaseGroup* createLoopControlGroup (tcu::TestContext& testCtx)
5066 {
5067 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "loop_control", "Tests loop control cases"));
5068 	vector<CaseParameter>			cases;
5069 	de::Random						rnd				(deStringHash(group->getName()));
5070 	const int						numElements		= 100;
5071 	vector<float>					inputFloats		(numElements, 0);
5072 	vector<float>					outputFloats	(numElements, 0);
5073 	const StringTemplate			shaderTemplate	(
5074 		string(getComputeAsmShaderPreamble()) +
5075 
5076 		"OpSource GLSL 430\n"
5077 		"OpName %main \"main\"\n"
5078 		"OpName %id \"gl_GlobalInvocationID\"\n"
5079 
5080 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
5081 
5082 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5083 
5084 		"%u32ptr      = OpTypePointer Function %u32\n"
5085 
5086 		"%id          = OpVariable %uvec3ptr Input\n"
5087 		"%zero        = OpConstant %i32 0\n"
5088 		"%uzero       = OpConstant %u32 0\n"
5089 		"%one         = OpConstant %i32 1\n"
5090 		"%constf1     = OpConstant %f32 1.0\n"
5091 		"%four        = OpConstant %u32 4\n"
5092 
5093 		"%main        = OpFunction %void None %voidf\n"
5094 		"%entry       = OpLabel\n"
5095 		"%i           = OpVariable %u32ptr Function\n"
5096 		"               OpStore %i %uzero\n"
5097 
5098 		"%idval       = OpLoad %uvec3 %id\n"
5099 		"%x           = OpCompositeExtract %u32 %idval 0\n"
5100 		"%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
5101 		"%inval       = OpLoad %f32 %inloc\n"
5102 		"%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
5103 		"               OpStore %outloc %inval\n"
5104 		"               OpBranch %loop_entry\n"
5105 
5106 		"%loop_entry  = OpLabel\n"
5107 		"%i_val       = OpLoad %u32 %i\n"
5108 		"%cmp_lt      = OpULessThan %bool %i_val %four\n"
5109 		"               OpLoopMerge %loop_merge %loop_body ${CONTROL}\n"
5110 		"               OpBranchConditional %cmp_lt %loop_body %loop_merge\n"
5111 		"%loop_body   = OpLabel\n"
5112 		"%outval      = OpLoad %f32 %outloc\n"
5113 		"%addf1       = OpFAdd %f32 %outval %constf1\n"
5114 		"               OpStore %outloc %addf1\n"
5115 		"%new_i       = OpIAdd %u32 %i_val %one\n"
5116 		"               OpStore %i %new_i\n"
5117 		"               OpBranch %loop_entry\n"
5118 		"%loop_merge  = OpLabel\n"
5119 		"               OpReturn\n"
5120 		"               OpFunctionEnd\n");
5121 
5122 	cases.push_back(CaseParameter("none",				"None"));
5123 	cases.push_back(CaseParameter("unroll",				"Unroll"));
5124 	cases.push_back(CaseParameter("dont_unroll",		"DontUnroll"));
5125 
5126 	fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5127 
5128 	for (size_t ndx = 0; ndx < numElements; ++ndx)
5129 		outputFloats[ndx] = inputFloats[ndx] + 4.f;
5130 
5131 	for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5132 	{
5133 		map<string, string>		specializations;
5134 		ComputeShaderSpec		spec;
5135 
5136 		specializations["CONTROL"] = cases[caseNdx].param;
5137 		spec.assembly = shaderTemplate.specialize(specializations);
5138 		spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5139 		spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5140 		spec.numWorkGroups = IVec3(numElements, 1, 1);
5141 
5142 		group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5143 	}
5144 
5145 	group->addChild(new SpvAsmLoopControlDependencyLengthCase(testCtx, "dependency_length", "dependency_length"));
5146 	group->addChild(new SpvAsmLoopControlDependencyInfiniteCase(testCtx, "dependency_infinite", "dependency_infinite"));
5147 
5148 	return group.release();
5149 }
5150 
5151 // Assembly code used for testing selection control is based on GLSL source code:
5152 // #version 430
5153 //
5154 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5155 //   float elements[];
5156 // } input_data;
5157 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5158 //   float elements[];
5159 // } output_data;
5160 //
5161 // void main() {
5162 //   uint x = gl_GlobalInvocationID.x;
5163 //   float val = input_data.elements[x];
5164 //   if (val > 10.f)
5165 //     output_data.elements[x] = val + 1.f;
5166 //   else
5167 //     output_data.elements[x] = val - 1.f;
5168 // }
createSelectionControlGroup(tcu::TestContext & testCtx)5169 tcu::TestCaseGroup* createSelectionControlGroup (tcu::TestContext& testCtx)
5170 {
5171 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "selection_control", "Tests selection control cases"));
5172 	vector<CaseParameter>			cases;
5173 	de::Random						rnd				(deStringHash(group->getName()));
5174 	const int						numElements		= 100;
5175 	vector<float>					inputFloats		(numElements, 0);
5176 	vector<float>					outputFloats	(numElements, 0);
5177 	const StringTemplate			shaderTemplate	(
5178 		string(getComputeAsmShaderPreamble()) +
5179 
5180 		"OpSource GLSL 430\n"
5181 		"OpName %main \"main\"\n"
5182 		"OpName %id \"gl_GlobalInvocationID\"\n"
5183 
5184 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
5185 
5186 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5187 
5188 		"%id       = OpVariable %uvec3ptr Input\n"
5189 		"%zero     = OpConstant %i32 0\n"
5190 		"%constf1  = OpConstant %f32 1.0\n"
5191 		"%constf10 = OpConstant %f32 10.0\n"
5192 
5193 		"%main     = OpFunction %void None %voidf\n"
5194 		"%entry    = OpLabel\n"
5195 		"%idval    = OpLoad %uvec3 %id\n"
5196 		"%x        = OpCompositeExtract %u32 %idval 0\n"
5197 		"%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
5198 		"%inval    = OpLoad %f32 %inloc\n"
5199 		"%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
5200 		"%cmp_gt   = OpFOrdGreaterThan %bool %inval %constf10\n"
5201 
5202 		"            OpSelectionMerge %if_end ${CONTROL}\n"
5203 		"            OpBranchConditional %cmp_gt %if_true %if_false\n"
5204 		"%if_true  = OpLabel\n"
5205 		"%addf1    = OpFAdd %f32 %inval %constf1\n"
5206 		"            OpStore %outloc %addf1\n"
5207 		"            OpBranch %if_end\n"
5208 		"%if_false = OpLabel\n"
5209 		"%subf1    = OpFSub %f32 %inval %constf1\n"
5210 		"            OpStore %outloc %subf1\n"
5211 		"            OpBranch %if_end\n"
5212 		"%if_end   = OpLabel\n"
5213 		"            OpReturn\n"
5214 		"            OpFunctionEnd\n");
5215 
5216 	cases.push_back(CaseParameter("none",					"None"));
5217 	cases.push_back(CaseParameter("flatten",				"Flatten"));
5218 	cases.push_back(CaseParameter("dont_flatten",			"DontFlatten"));
5219 	cases.push_back(CaseParameter("flatten_dont_flatten",	"DontFlatten|Flatten"));
5220 
5221 	fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5222 
5223 	// CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
5224 	floorAll(inputFloats);
5225 
5226 	for (size_t ndx = 0; ndx < numElements; ++ndx)
5227 		outputFloats[ndx] = inputFloats[ndx] + (inputFloats[ndx] > 10.f ? 1.f : -1.f);
5228 
5229 	for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5230 	{
5231 		map<string, string>		specializations;
5232 		ComputeShaderSpec		spec;
5233 
5234 		specializations["CONTROL"] = cases[caseNdx].param;
5235 		spec.assembly = shaderTemplate.specialize(specializations);
5236 		spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5237 		spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5238 		spec.numWorkGroups = IVec3(numElements, 1, 1);
5239 
5240 		group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5241 	}
5242 
5243 	return group.release();
5244 }
5245 
getOpNameAbuseCases(vector<CaseParameter> & abuseCases)5246 void getOpNameAbuseCases (vector<CaseParameter> &abuseCases)
5247 {
5248 	// Generate a long name.
5249 	std::string longname;
5250 	longname.resize(65535, 'k'); // max string literal, spir-v 2.17
5251 
5252 	// Some bad names, abusing utf-8 encoding. This may also cause problems
5253 	// with the logs.
5254 	// 1. Various illegal code points in utf-8
5255 	std::string utf8illegal =
5256 		"Illegal bytes in UTF-8: "
5257 		"\xc0 \xc1 \xf5 \xf6 \xf7 \xf8 \xf9 \xfa \xfb \xfc \xfd \xfe \xff"
5258 		"illegal surrogates: \xed\xad\xbf \xed\xbe\x80";
5259 
5260 	// 2. Zero encoded as overlong, not exactly legal but often supported to differentiate from terminating zero
5261 	std::string utf8nul = "UTF-8 encoded nul \xC0\x80 (should not end name)";
5262 
5263 	// 3. Some overlong encodings
5264 	std::string utf8overlong =
5265 		"UTF-8 overlong \xF0\x82\x82\xAC \xfc\x83\xbf\xbf\xbf\xbf \xf8\x87\xbf\xbf\xbf "
5266 		"\xf0\x8f\xbf\xbf";
5267 
5268 	// 4. Internet "zalgo" meme "bleeding text"
5269 	std::string utf8zalgo =
5270 		"\x56\xcc\xb5\xcc\x85\xcc\x94\xcc\x88\xcd\x8a\xcc\x91\xcc\x88\xcd\x91\xcc\x83\xcd\x82"
5271 		"\xcc\x83\xcd\x90\xcc\x8a\xcc\x92\xcc\x92\xcd\x8b\xcc\x94\xcd\x9d\xcc\x98\xcc\xab\xcc"
5272 		"\xae\xcc\xa9\xcc\xad\xcc\x97\xcc\xb0\x75\xcc\xb6\xcc\xbe\xcc\x80\xcc\x82\xcc\x84\xcd"
5273 		"\x84\xcc\x90\xcd\x86\xcc\x9a\xcd\x84\xcc\x9b\xcd\x86\xcd\x92\xcc\x9a\xcd\x99\xcd\x99"
5274 		"\xcc\xbb\xcc\x98\xcd\x8e\xcd\x88\xcd\x9a\xcc\xa6\xcc\x9c\xcc\xab\xcc\x99\xcd\x94\xcd"
5275 		"\x99\xcd\x95\xcc\xa5\xcc\xab\xcd\x89\x6c\xcc\xb8\xcc\x8e\xcc\x8b\xcc\x8b\xcc\x9a\xcc"
5276 		"\x8e\xcd\x9d\xcc\x80\xcc\xa1\xcc\xad\xcd\x9c\xcc\xba\xcc\x96\xcc\xb3\xcc\xa2\xcd\x8e"
5277 		"\xcc\xa2\xcd\x96\x6b\xcc\xb8\xcc\x84\xcd\x81\xcc\xbf\xcc\x8d\xcc\x89\xcc\x85\xcc\x92"
5278 		"\xcc\x84\xcc\x90\xcd\x81\xcc\x93\xcd\x90\xcd\x92\xcd\x9d\xcc\x84\xcd\x98\xcd\x9d\xcd"
5279 		"\xa0\xcd\x91\xcc\x94\xcc\xb9\xcd\x93\xcc\xa5\xcd\x87\xcc\xad\xcc\xa7\xcd\x96\xcd\x99"
5280 		"\xcc\x9d\xcc\xbc\xcd\x96\xcd\x93\xcc\x9d\xcc\x99\xcc\xa8\xcc\xb1\xcd\x85\xcc\xba\xcc"
5281 		"\xa7\x61\xcc\xb8\xcc\x8e\xcc\x81\xcd\x90\xcd\x84\xcd\x8c\xcc\x8c\xcc\x85\xcd\x86\xcc"
5282 		"\x84\xcd\x84\xcc\x90\xcc\x84\xcc\x8d\xcd\x99\xcd\x8d\xcc\xb0\xcc\xa3\xcc\xa6\xcd\x89"
5283 		"\xcd\x8d\xcd\x87\xcc\x98\xcd\x8d\xcc\xa4\xcd\x9a\xcd\x8e\xcc\xab\xcc\xb9\xcc\xac\xcc"
5284 		"\xa2\xcd\x87\xcc\xa0\xcc\xb3\xcd\x89\xcc\xb9\xcc\xa7\xcc\xa6\xcd\x89\xcd\x95\x6e\xcc"
5285 		"\xb8\xcd\x8a\xcc\x8a\xcd\x82\xcc\x9b\xcd\x81\xcd\x90\xcc\x85\xcc\x9b\xcd\x80\xcd\x91"
5286 		"\xcd\x9b\xcc\x81\xcd\x81\xcc\x9a\xcc\xb3\xcd\x9c\xcc\x9e\xcc\x9d\xcd\x99\xcc\xa2\xcd"
5287 		"\x93\xcd\x96\xcc\x97\xff";
5288 
5289 	// General name abuses
5290 	abuseCases.push_back(CaseParameter("_has_very_long_name", longname));
5291 	abuseCases.push_back(CaseParameter("_utf8_illegal", utf8illegal));
5292 	abuseCases.push_back(CaseParameter("_utf8_nul", utf8nul));
5293 	abuseCases.push_back(CaseParameter("_utf8_overlong", utf8overlong));
5294 	abuseCases.push_back(CaseParameter("_utf8_zalgo", utf8zalgo));
5295 
5296 	// GL keywords
5297 	abuseCases.push_back(CaseParameter("_is_gl_Position", "gl_Position"));
5298 	abuseCases.push_back(CaseParameter("_is_gl_InstanceID", "gl_InstanceID"));
5299 	abuseCases.push_back(CaseParameter("_is_gl_PrimitiveID", "gl_PrimitiveID"));
5300 	abuseCases.push_back(CaseParameter("_is_gl_TessCoord", "gl_TessCoord"));
5301 	abuseCases.push_back(CaseParameter("_is_gl_PerVertex", "gl_PerVertex"));
5302 	abuseCases.push_back(CaseParameter("_is_gl_InvocationID", "gl_InvocationID"));
5303 	abuseCases.push_back(CaseParameter("_is_gl_PointSize", "gl_PointSize"));
5304 	abuseCases.push_back(CaseParameter("_is_gl_PointCoord", "gl_PointCoord"));
5305 	abuseCases.push_back(CaseParameter("_is_gl_Layer", "gl_Layer"));
5306 	abuseCases.push_back(CaseParameter("_is_gl_FragDepth", "gl_FragDepth"));
5307 	abuseCases.push_back(CaseParameter("_is_gl_NumWorkGroups", "gl_NumWorkGroups"));
5308 	abuseCases.push_back(CaseParameter("_is_gl_WorkGroupID", "gl_WorkGroupID"));
5309 	abuseCases.push_back(CaseParameter("_is_gl_LocalInvocationID", "gl_LocalInvocationID"));
5310 	abuseCases.push_back(CaseParameter("_is_gl_GlobalInvocationID", "gl_GlobalInvocationID"));
5311 	abuseCases.push_back(CaseParameter("_is_gl_MaxVertexAttribs", "gl_MaxVertexAttribs"));
5312 	abuseCases.push_back(CaseParameter("_is_gl_MaxViewports", "gl_MaxViewports"));
5313 	abuseCases.push_back(CaseParameter("_is_gl_MaxComputeWorkGroupCount", "gl_MaxComputeWorkGroupCount"));
5314 	abuseCases.push_back(CaseParameter("_is_mat3", "mat3"));
5315 	abuseCases.push_back(CaseParameter("_is_volatile", "volatile"));
5316 	abuseCases.push_back(CaseParameter("_is_inout", "inout"));
5317 	abuseCases.push_back(CaseParameter("_is_isampler3d", "isampler3d"));
5318 }
5319 
createOpNameGroup(tcu::TestContext & testCtx)5320 tcu::TestCaseGroup* createOpNameGroup (tcu::TestContext& testCtx)
5321 {
5322 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "opname", "Tests OpName cases"));
5323 	de::MovePtr<tcu::TestCaseGroup>	entryMainGroup	(new tcu::TestCaseGroup(testCtx, "entry_main", "OpName tests with entry main"));
5324 	de::MovePtr<tcu::TestCaseGroup>	entryNotGroup	(new tcu::TestCaseGroup(testCtx, "entry_rdc", "OpName tests with entry rdc"));
5325 	de::MovePtr<tcu::TestCaseGroup>	abuseGroup		(new tcu::TestCaseGroup(testCtx, "abuse", "OpName abuse tests"));
5326 	vector<CaseParameter>			cases;
5327 	vector<CaseParameter>			abuseCases;
5328 	vector<string>					testFunc;
5329 	de::Random						rnd				(deStringHash(group->getName()));
5330 	const int						numElements		= 128;
5331 	vector<float>					inputFloats		(numElements, 0);
5332 	vector<float>					outputFloats	(numElements, 0);
5333 
5334 	getOpNameAbuseCases(abuseCases);
5335 
5336 	fillRandomScalars(rnd, -100.0f, 100.0f, &inputFloats[0], numElements);
5337 
5338 	for(size_t ndx = 0; ndx < numElements; ++ndx)
5339 		outputFloats[ndx] = -inputFloats[ndx];
5340 
5341 	const string commonShaderHeader =
5342 		"OpCapability Shader\n"
5343 		"OpMemoryModel Logical GLSL450\n"
5344 		"OpEntryPoint GLCompute %main \"main\" %id\n"
5345 		"OpExecutionMode %main LocalSize 1 1 1\n";
5346 
5347 	const string commonShaderFooter =
5348 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
5349 
5350 		+ string(getComputeAsmInputOutputBufferTraits())
5351 		+ string(getComputeAsmCommonTypes())
5352 		+ string(getComputeAsmInputOutputBuffer()) +
5353 
5354 		"%id        = OpVariable %uvec3ptr Input\n"
5355 		"%zero      = OpConstant %i32 0\n"
5356 
5357 		"%func      = OpFunction %void None %voidf\n"
5358 		"%5         = OpLabel\n"
5359 		"             OpReturn\n"
5360 		"             OpFunctionEnd\n"
5361 
5362 		"%main      = OpFunction %void None %voidf\n"
5363 		"%entry     = OpLabel\n"
5364 		"%7         = OpFunctionCall %void %func\n"
5365 
5366 		"%idval     = OpLoad %uvec3 %id\n"
5367 		"%x         = OpCompositeExtract %u32 %idval 0\n"
5368 
5369 		"%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5370 		"%inval     = OpLoad %f32 %inloc\n"
5371 		"%neg       = OpFNegate %f32 %inval\n"
5372 		"%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5373 		"             OpStore %outloc %neg\n"
5374 
5375 		"             OpReturn\n"
5376 		"             OpFunctionEnd\n";
5377 
5378 	const StringTemplate shaderTemplate (
5379 		"OpCapability Shader\n"
5380 		"OpMemoryModel Logical GLSL450\n"
5381 		"OpEntryPoint GLCompute %main \"${ENTRY}\" %id\n"
5382 		"OpExecutionMode %main LocalSize 1 1 1\n"
5383 		"OpName %${ID} \"${NAME}\"\n" +
5384 		commonShaderFooter);
5385 
5386 	const std::string multipleNames =
5387 		commonShaderHeader +
5388 		"OpName %main \"to_be\"\n"
5389 		"OpName %id   \"or_not\"\n"
5390 		"OpName %main \"to_be\"\n"
5391 		"OpName %main \"makes_no\"\n"
5392 		"OpName %func \"difference\"\n"
5393 		"OpName %5    \"to_me\"\n" +
5394 		commonShaderFooter;
5395 
5396 	{
5397 		ComputeShaderSpec	spec;
5398 
5399 		spec.assembly		= multipleNames;
5400 		spec.numWorkGroups	= IVec3(numElements, 1, 1);
5401 		spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5402 		spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5403 
5404 		abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "main_has_multiple_names", "multiple_names", spec));
5405 	}
5406 
5407 	const std::string everythingNamed =
5408 		commonShaderHeader +
5409 		"OpName %main   \"name1\"\n"
5410 		"OpName %id     \"name2\"\n"
5411 		"OpName %zero   \"name3\"\n"
5412 		"OpName %entry  \"name4\"\n"
5413 		"OpName %func   \"name5\"\n"
5414 		"OpName %5      \"name6\"\n"
5415 		"OpName %7      \"name7\"\n"
5416 		"OpName %idval  \"name8\"\n"
5417 		"OpName %inloc  \"name9\"\n"
5418 		"OpName %inval  \"name10\"\n"
5419 		"OpName %neg    \"name11\"\n"
5420 		"OpName %outloc \"name12\"\n"+
5421 		commonShaderFooter;
5422 	{
5423 		ComputeShaderSpec	spec;
5424 
5425 		spec.assembly		= everythingNamed;
5426 		spec.numWorkGroups	= IVec3(numElements, 1, 1);
5427 		spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5428 		spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5429 
5430 		abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named", "everything_named", spec));
5431 	}
5432 
5433 	const std::string everythingNamedTheSame =
5434 		commonShaderHeader +
5435 		"OpName %main   \"the_same\"\n"
5436 		"OpName %id     \"the_same\"\n"
5437 		"OpName %zero   \"the_same\"\n"
5438 		"OpName %entry  \"the_same\"\n"
5439 		"OpName %func   \"the_same\"\n"
5440 		"OpName %5      \"the_same\"\n"
5441 		"OpName %7      \"the_same\"\n"
5442 		"OpName %idval  \"the_same\"\n"
5443 		"OpName %inloc  \"the_same\"\n"
5444 		"OpName %inval  \"the_same\"\n"
5445 		"OpName %neg    \"the_same\"\n"
5446 		"OpName %outloc \"the_same\"\n"+
5447 		commonShaderFooter;
5448 	{
5449 		ComputeShaderSpec	spec;
5450 
5451 		spec.assembly		= everythingNamedTheSame;
5452 		spec.numWorkGroups	= IVec3(numElements, 1, 1);
5453 		spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5454 		spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5455 
5456 		abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named_the_same", "everything_named_the_same", spec));
5457 	}
5458 
5459 	// main_is_...
5460 	for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5461 	{
5462 		map<string, string>	specializations;
5463 		ComputeShaderSpec	spec;
5464 
5465 		specializations["ENTRY"]	= "main";
5466 		specializations["ID"]		= "main";
5467 		specializations["NAME"]		= abuseCases[ndx].param;
5468 		spec.assembly				= shaderTemplate.specialize(specializations);
5469 		spec.numWorkGroups			= IVec3(numElements, 1, 1);
5470 		spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5471 		spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5472 
5473 		abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("main") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5474 	}
5475 
5476 	// x_is_....
5477 	for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5478 	{
5479 		map<string, string>	specializations;
5480 		ComputeShaderSpec	spec;
5481 
5482 		specializations["ENTRY"]	= "main";
5483 		specializations["ID"]		= "x";
5484 		specializations["NAME"]		= abuseCases[ndx].param;
5485 		spec.assembly				= shaderTemplate.specialize(specializations);
5486 		spec.numWorkGroups			= IVec3(numElements, 1, 1);
5487 		spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5488 		spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5489 
5490 		abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("x") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5491 	}
5492 
5493 	cases.push_back(CaseParameter("_is_main", "main"));
5494 	cases.push_back(CaseParameter("_is_not_main", "not_main"));
5495 	testFunc.push_back("main");
5496 	testFunc.push_back("func");
5497 
5498 	for(size_t fNdx = 0; fNdx < testFunc.size(); ++fNdx)
5499 	{
5500 		for(size_t ndx = 0; ndx < cases.size(); ++ndx)
5501 		{
5502 			map<string, string>	specializations;
5503 			ComputeShaderSpec	spec;
5504 
5505 			specializations["ENTRY"]	= "main";
5506 			specializations["ID"]		= testFunc[fNdx];
5507 			specializations["NAME"]		= cases[ndx].param;
5508 			spec.assembly				= shaderTemplate.specialize(specializations);
5509 			spec.numWorkGroups			= IVec3(numElements, 1, 1);
5510 			spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5511 			spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5512 
5513 			entryMainGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (testFunc[fNdx] + cases[ndx].name).c_str(), cases[ndx].name, spec));
5514 		}
5515 	}
5516 
5517 	cases.push_back(CaseParameter("_is_entry", "rdc"));
5518 
5519 	for(size_t fNdx = 0; fNdx < testFunc.size(); ++fNdx)
5520 	{
5521 		for(size_t ndx = 0; ndx < cases.size(); ++ndx)
5522 		{
5523 			map<string, string>     specializations;
5524 			ComputeShaderSpec       spec;
5525 
5526 			specializations["ENTRY"]	= "rdc";
5527 			specializations["ID"]		= testFunc[fNdx];
5528 			specializations["NAME"]		= cases[ndx].param;
5529 			spec.assembly				= shaderTemplate.specialize(specializations);
5530 			spec.numWorkGroups			= IVec3(numElements, 1, 1);
5531 			spec.entryPoint				= "rdc";
5532 			spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5533 			spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5534 
5535 			entryNotGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (testFunc[fNdx] + cases[ndx].name).c_str(), cases[ndx].name, spec));
5536 		}
5537 	}
5538 
5539 	group->addChild(entryMainGroup.release());
5540 	group->addChild(entryNotGroup.release());
5541 	group->addChild(abuseGroup.release());
5542 
5543 	return group.release();
5544 }
5545 
createOpMemberNameGroup(tcu::TestContext & testCtx)5546 tcu::TestCaseGroup* createOpMemberNameGroup (tcu::TestContext& testCtx)
5547 {
5548 	de::MovePtr<tcu::TestCaseGroup>	group(new tcu::TestCaseGroup(testCtx, "opmembername", "Tests OpMemberName cases"));
5549 	de::MovePtr<tcu::TestCaseGroup>	abuseGroup(new tcu::TestCaseGroup(testCtx, "abuse", "OpMemberName abuse tests"));
5550 	vector<CaseParameter>			abuseCases;
5551 	vector<string>					testFunc;
5552 	de::Random						rnd(deStringHash(group->getName()));
5553 	const int						numElements = 128;
5554 	vector<float>					inputFloats(numElements, 0);
5555 	vector<float>					outputFloats(numElements, 0);
5556 
5557 	getOpNameAbuseCases(abuseCases);
5558 
5559 	fillRandomScalars(rnd, -100.0f, 100.0f, &inputFloats[0], numElements);
5560 
5561 	for (size_t ndx = 0; ndx < numElements; ++ndx)
5562 		outputFloats[ndx] = -inputFloats[ndx];
5563 
5564 	const string commonShaderHeader =
5565 		"OpCapability Shader\n"
5566 		"OpMemoryModel Logical GLSL450\n"
5567 		"OpEntryPoint GLCompute %main \"main\" %id\n"
5568 		"OpExecutionMode %main LocalSize 1 1 1\n";
5569 
5570 	const string commonShaderFooter =
5571 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
5572 
5573 		+ string(getComputeAsmInputOutputBufferTraits())
5574 		+ string(getComputeAsmCommonTypes())
5575 		+ string(getComputeAsmInputOutputBuffer()) +
5576 
5577 		"%u3str     = OpTypeStruct %u32 %u32 %u32\n"
5578 
5579 		"%id        = OpVariable %uvec3ptr Input\n"
5580 		"%zero      = OpConstant %i32 0\n"
5581 
5582 		"%main      = OpFunction %void None %voidf\n"
5583 		"%entry     = OpLabel\n"
5584 
5585 		"%idval     = OpLoad %uvec3 %id\n"
5586 		"%x0        = OpCompositeExtract %u32 %idval 0\n"
5587 
5588 		"%idstr     = OpCompositeConstruct %u3str %x0 %x0 %x0\n"
5589 		"%x         = OpCompositeExtract %u32 %idstr 0\n"
5590 
5591 		"%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5592 		"%inval     = OpLoad %f32 %inloc\n"
5593 		"%neg       = OpFNegate %f32 %inval\n"
5594 		"%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5595 		"             OpStore %outloc %neg\n"
5596 
5597 		"             OpReturn\n"
5598 		"             OpFunctionEnd\n";
5599 
5600 	const StringTemplate shaderTemplate(
5601 		commonShaderHeader +
5602 		"OpMemberName %u3str 0 \"${NAME}\"\n" +
5603 		commonShaderFooter);
5604 
5605 	const std::string multipleNames =
5606 		commonShaderHeader +
5607 		"OpMemberName %u3str 0 \"to_be\"\n"
5608 		"OpMemberName %u3str 1 \"or_not\"\n"
5609 		"OpMemberName %u3str 0 \"to_be\"\n"
5610 		"OpMemberName %u3str 2 \"makes_no\"\n"
5611 		"OpMemberName %u3str 0 \"difference\"\n"
5612 		"OpMemberName %u3str 0 \"to_me\"\n" +
5613 		commonShaderFooter;
5614 	{
5615 		ComputeShaderSpec	spec;
5616 
5617 		spec.assembly = multipleNames;
5618 		spec.numWorkGroups = IVec3(numElements, 1, 1);
5619 		spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5620 		spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5621 
5622 		abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "u3str_x_has_multiple_names", "multiple_names", spec));
5623 	}
5624 
5625 	const std::string everythingNamedTheSame =
5626 		commonShaderHeader +
5627 		"OpMemberName %u3str 0 \"the_same\"\n"
5628 		"OpMemberName %u3str 1 \"the_same\"\n"
5629 		"OpMemberName %u3str 2 \"the_same\"\n" +
5630 		commonShaderFooter;
5631 
5632 	{
5633 		ComputeShaderSpec	spec;
5634 
5635 		spec.assembly = everythingNamedTheSame;
5636 		spec.numWorkGroups = IVec3(numElements, 1, 1);
5637 		spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5638 		spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5639 
5640 		abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named_the_same", "everything_named_the_same", spec));
5641 	}
5642 
5643 	// u3str_x_is_....
5644 	for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5645 	{
5646 		map<string, string>	specializations;
5647 		ComputeShaderSpec	spec;
5648 
5649 		specializations["NAME"] = abuseCases[ndx].param;
5650 		spec.assembly = shaderTemplate.specialize(specializations);
5651 		spec.numWorkGroups = IVec3(numElements, 1, 1);
5652 		spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5653 		spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5654 
5655 		abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("u3str_x") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5656 	}
5657 
5658 	group->addChild(abuseGroup.release());
5659 
5660 	return group.release();
5661 }
5662 
5663 // Assembly code used for testing function control is based on GLSL source code:
5664 //
5665 // #version 430
5666 //
5667 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5668 //   float elements[];
5669 // } input_data;
5670 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5671 //   float elements[];
5672 // } output_data;
5673 //
5674 // float const10() { return 10.f; }
5675 //
5676 // void main() {
5677 //   uint x = gl_GlobalInvocationID.x;
5678 //   output_data.elements[x] = input_data.elements[x] + const10();
5679 // }
createFunctionControlGroup(tcu::TestContext & testCtx)5680 tcu::TestCaseGroup* createFunctionControlGroup (tcu::TestContext& testCtx)
5681 {
5682 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "function_control", "Tests function control cases"));
5683 	vector<CaseParameter>			cases;
5684 	de::Random						rnd				(deStringHash(group->getName()));
5685 	const int						numElements		= 100;
5686 	vector<float>					inputFloats		(numElements, 0);
5687 	vector<float>					outputFloats	(numElements, 0);
5688 	const StringTemplate			shaderTemplate	(
5689 		string(getComputeAsmShaderPreamble()) +
5690 
5691 		"OpSource GLSL 430\n"
5692 		"OpName %main \"main\"\n"
5693 		"OpName %func_const10 \"const10(\"\n"
5694 		"OpName %id \"gl_GlobalInvocationID\"\n"
5695 
5696 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
5697 
5698 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5699 
5700 		"%f32f = OpTypeFunction %f32\n"
5701 		"%id = OpVariable %uvec3ptr Input\n"
5702 		"%zero = OpConstant %i32 0\n"
5703 		"%constf10 = OpConstant %f32 10.0\n"
5704 
5705 		"%main         = OpFunction %void None %voidf\n"
5706 		"%entry        = OpLabel\n"
5707 		"%idval        = OpLoad %uvec3 %id\n"
5708 		"%x            = OpCompositeExtract %u32 %idval 0\n"
5709 		"%inloc        = OpAccessChain %f32ptr %indata %zero %x\n"
5710 		"%inval        = OpLoad %f32 %inloc\n"
5711 		"%ret_10       = OpFunctionCall %f32 %func_const10\n"
5712 		"%fadd         = OpFAdd %f32 %inval %ret_10\n"
5713 		"%outloc       = OpAccessChain %f32ptr %outdata %zero %x\n"
5714 		"                OpStore %outloc %fadd\n"
5715 		"                OpReturn\n"
5716 		"                OpFunctionEnd\n"
5717 
5718 		"%func_const10 = OpFunction %f32 ${CONTROL} %f32f\n"
5719 		"%label        = OpLabel\n"
5720 		"                OpReturnValue %constf10\n"
5721 		"                OpFunctionEnd\n");
5722 
5723 	cases.push_back(CaseParameter("none",						"None"));
5724 	cases.push_back(CaseParameter("inline",						"Inline"));
5725 	cases.push_back(CaseParameter("dont_inline",				"DontInline"));
5726 	cases.push_back(CaseParameter("pure",						"Pure"));
5727 	cases.push_back(CaseParameter("const",						"Const"));
5728 	cases.push_back(CaseParameter("inline_pure",				"Inline|Pure"));
5729 	cases.push_back(CaseParameter("const_dont_inline",			"Const|DontInline"));
5730 	cases.push_back(CaseParameter("inline_dont_inline",			"Inline|DontInline"));
5731 	cases.push_back(CaseParameter("pure_inline_dont_inline",	"Pure|Inline|DontInline"));
5732 
5733 	fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5734 
5735 	// CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
5736 	floorAll(inputFloats);
5737 
5738 	for (size_t ndx = 0; ndx < numElements; ++ndx)
5739 		outputFloats[ndx] = inputFloats[ndx] + 10.f;
5740 
5741 	for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5742 	{
5743 		map<string, string>		specializations;
5744 		ComputeShaderSpec		spec;
5745 
5746 		specializations["CONTROL"] = cases[caseNdx].param;
5747 		spec.assembly = shaderTemplate.specialize(specializations);
5748 		spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5749 		spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5750 		spec.numWorkGroups = IVec3(numElements, 1, 1);
5751 
5752 		group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5753 	}
5754 
5755 	return group.release();
5756 }
5757 
createMemoryAccessGroup(tcu::TestContext & testCtx)5758 tcu::TestCaseGroup* createMemoryAccessGroup (tcu::TestContext& testCtx)
5759 {
5760 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "memory_access", "Tests memory access cases"));
5761 	vector<CaseParameter>			cases;
5762 	de::Random						rnd				(deStringHash(group->getName()));
5763 	const int						numElements		= 100;
5764 	vector<float>					inputFloats		(numElements, 0);
5765 	vector<float>					outputFloats	(numElements, 0);
5766 	const StringTemplate			shaderTemplate	(
5767 		string(getComputeAsmShaderPreamble()) +
5768 
5769 		"OpSource GLSL 430\n"
5770 		"OpName %main           \"main\"\n"
5771 		"OpName %id             \"gl_GlobalInvocationID\"\n"
5772 
5773 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
5774 
5775 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5776 
5777 		"%f32ptr_f  = OpTypePointer Function %f32\n"
5778 
5779 		"%id        = OpVariable %uvec3ptr Input\n"
5780 		"%zero      = OpConstant %i32 0\n"
5781 		"%four      = OpConstant %i32 4\n"
5782 
5783 		"%main      = OpFunction %void None %voidf\n"
5784 		"%label     = OpLabel\n"
5785 		"%copy      = OpVariable %f32ptr_f Function\n"
5786 		"%idval     = OpLoad %uvec3 %id ${ACCESS}\n"
5787 		"%x         = OpCompositeExtract %u32 %idval 0\n"
5788 		"%inloc     = OpAccessChain %f32ptr %indata  %zero %x\n"
5789 		"%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5790 		"             OpCopyMemory %copy %inloc ${ACCESS}\n"
5791 		"%val1      = OpLoad %f32 %copy\n"
5792 		"%val2      = OpLoad %f32 %inloc\n"
5793 		"%add       = OpFAdd %f32 %val1 %val2\n"
5794 		"             OpStore %outloc %add ${ACCESS}\n"
5795 		"             OpReturn\n"
5796 		"             OpFunctionEnd\n");
5797 
5798 	cases.push_back(CaseParameter("null",					""));
5799 	cases.push_back(CaseParameter("none",					"None"));
5800 	cases.push_back(CaseParameter("volatile",				"Volatile"));
5801 	cases.push_back(CaseParameter("aligned",				"Aligned 4"));
5802 	cases.push_back(CaseParameter("nontemporal",			"Nontemporal"));
5803 	cases.push_back(CaseParameter("aligned_nontemporal",	"Aligned|Nontemporal 4"));
5804 	cases.push_back(CaseParameter("aligned_volatile",		"Volatile|Aligned 4"));
5805 
5806 	fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5807 
5808 	for (size_t ndx = 0; ndx < numElements; ++ndx)
5809 		outputFloats[ndx] = inputFloats[ndx] + inputFloats[ndx];
5810 
5811 	for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5812 	{
5813 		map<string, string>		specializations;
5814 		ComputeShaderSpec		spec;
5815 
5816 		specializations["ACCESS"] = cases[caseNdx].param;
5817 		spec.assembly = shaderTemplate.specialize(specializations);
5818 		spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5819 		spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5820 		spec.numWorkGroups = IVec3(numElements, 1, 1);
5821 
5822 		group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5823 	}
5824 
5825 	return group.release();
5826 }
5827 
5828 // Checks that we can get undefined values for various types, without exercising a computation with it.
createOpUndefGroup(tcu::TestContext & testCtx)5829 tcu::TestCaseGroup* createOpUndefGroup (tcu::TestContext& testCtx)
5830 {
5831 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "opundef", "Tests the OpUndef instruction"));
5832 	vector<CaseParameter>			cases;
5833 	de::Random						rnd				(deStringHash(group->getName()));
5834 	const int						numElements		= 100;
5835 	vector<float>					positiveFloats	(numElements, 0);
5836 	vector<float>					negativeFloats	(numElements, 0);
5837 	const StringTemplate			shaderTemplate	(
5838 		string(getComputeAsmShaderPreamble()) +
5839 
5840 		"OpSource GLSL 430\n"
5841 		"OpName %main           \"main\"\n"
5842 		"OpName %id             \"gl_GlobalInvocationID\"\n"
5843 
5844 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
5845 
5846 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
5847 		"%uvec2     = OpTypeVector %u32 2\n"
5848 		"%fvec4     = OpTypeVector %f32 4\n"
5849 		"%fmat33    = OpTypeMatrix %fvec3 3\n"
5850 		"%image     = OpTypeImage %f32 2D 0 0 0 1 Unknown\n"
5851 		"%sampler   = OpTypeSampler\n"
5852 		"%simage    = OpTypeSampledImage %image\n"
5853 		"%const100  = OpConstant %u32 100\n"
5854 		"%uarr100   = OpTypeArray %i32 %const100\n"
5855 		"%struct    = OpTypeStruct %f32 %i32 %u32\n"
5856 		"%pointer   = OpTypePointer Function %i32\n"
5857 		+ string(getComputeAsmInputOutputBuffer()) +
5858 
5859 		"%id        = OpVariable %uvec3ptr Input\n"
5860 		"%zero      = OpConstant %i32 0\n"
5861 
5862 		"%main      = OpFunction %void None %voidf\n"
5863 		"%label     = OpLabel\n"
5864 
5865 		"%undef     = OpUndef ${TYPE}\n"
5866 
5867 		"%idval     = OpLoad %uvec3 %id\n"
5868 		"%x         = OpCompositeExtract %u32 %idval 0\n"
5869 
5870 		"%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5871 		"%inval     = OpLoad %f32 %inloc\n"
5872 		"%neg       = OpFNegate %f32 %inval\n"
5873 		"%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5874 		"             OpStore %outloc %neg\n"
5875 		"             OpReturn\n"
5876 		"             OpFunctionEnd\n");
5877 
5878 	cases.push_back(CaseParameter("bool",			"%bool"));
5879 	cases.push_back(CaseParameter("sint32",			"%i32"));
5880 	cases.push_back(CaseParameter("uint32",			"%u32"));
5881 	cases.push_back(CaseParameter("float32",		"%f32"));
5882 	cases.push_back(CaseParameter("vec4float32",	"%fvec4"));
5883 	cases.push_back(CaseParameter("vec2uint32",		"%uvec2"));
5884 	cases.push_back(CaseParameter("matrix",			"%fmat33"));
5885 	cases.push_back(CaseParameter("image",			"%image"));
5886 	cases.push_back(CaseParameter("sampler",		"%sampler"));
5887 	cases.push_back(CaseParameter("sampledimage",	"%simage"));
5888 	cases.push_back(CaseParameter("array",			"%uarr100"));
5889 	cases.push_back(CaseParameter("runtimearray",	"%f32arr"));
5890 	cases.push_back(CaseParameter("struct",			"%struct"));
5891 	cases.push_back(CaseParameter("pointer",		"%pointer"));
5892 
5893 	fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
5894 
5895 	for (size_t ndx = 0; ndx < numElements; ++ndx)
5896 		negativeFloats[ndx] = -positiveFloats[ndx];
5897 
5898 	for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5899 	{
5900 		map<string, string>		specializations;
5901 		ComputeShaderSpec		spec;
5902 
5903 		specializations["TYPE"] = cases[caseNdx].param;
5904 		spec.assembly = shaderTemplate.specialize(specializations);
5905 		spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
5906 		spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
5907 		spec.numWorkGroups = IVec3(numElements, 1, 1);
5908 
5909 		group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5910 	}
5911 
5912 		return group.release();
5913 }
5914 
5915 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
createFloat16OpConstantCompositeGroup(tcu::TestContext & testCtx)5916 tcu::TestCaseGroup* createFloat16OpConstantCompositeGroup (tcu::TestContext& testCtx)
5917 {
5918 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "Tests the OpConstantComposite instruction"));
5919 	vector<CaseParameter>			cases;
5920 	de::Random						rnd				(deStringHash(group->getName()));
5921 	const int						numElements		= 100;
5922 	vector<float>					positiveFloats	(numElements, 0);
5923 	vector<float>					negativeFloats	(numElements, 0);
5924 	const StringTemplate			shaderTemplate	(
5925 		"OpCapability Shader\n"
5926 		"OpCapability Float16\n"
5927 		"OpMemoryModel Logical GLSL450\n"
5928 		"OpEntryPoint GLCompute %main \"main\" %id\n"
5929 		"OpExecutionMode %main LocalSize 1 1 1\n"
5930 		"OpSource GLSL 430\n"
5931 		"OpName %main           \"main\"\n"
5932 		"OpName %id             \"gl_GlobalInvocationID\"\n"
5933 
5934 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
5935 
5936 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5937 
5938 		"%id        = OpVariable %uvec3ptr Input\n"
5939 		"%zero      = OpConstant %i32 0\n"
5940 		"%f16       = OpTypeFloat 16\n"
5941 		"%c_f16_0   = OpConstant %f16 0.0\n"
5942 		"%c_f16_0_5 = OpConstant %f16 0.5\n"
5943 		"%c_f16_1   = OpConstant %f16 1.0\n"
5944 		"%v2f16     = OpTypeVector %f16 2\n"
5945 		"%v3f16     = OpTypeVector %f16 3\n"
5946 		"%v4f16     = OpTypeVector %f16 4\n"
5947 
5948 		"${CONSTANT}\n"
5949 
5950 		"%main      = OpFunction %void None %voidf\n"
5951 		"%label     = OpLabel\n"
5952 		"%idval     = OpLoad %uvec3 %id\n"
5953 		"%x         = OpCompositeExtract %u32 %idval 0\n"
5954 		"%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5955 		"%inval     = OpLoad %f32 %inloc\n"
5956 		"%neg       = OpFNegate %f32 %inval\n"
5957 		"%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5958 		"             OpStore %outloc %neg\n"
5959 		"             OpReturn\n"
5960 		"             OpFunctionEnd\n");
5961 
5962 
5963 	cases.push_back(CaseParameter("vector",			"%const = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"));
5964 	cases.push_back(CaseParameter("matrix",			"%m3v3f16 = OpTypeMatrix %v3f16 3\n"
5965 													"%vec = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"
5966 													"%mat = OpConstantComposite %m3v3f16 %vec %vec %vec"));
5967 	cases.push_back(CaseParameter("struct",			"%m2v3f16 = OpTypeMatrix %v3f16 2\n"
5968 													"%struct = OpTypeStruct %i32 %f16 %v3f16 %m2v3f16\n"
5969 													"%vec = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"
5970 													"%mat = OpConstantComposite %m2v3f16 %vec %vec\n"
5971 													"%const = OpConstantComposite %struct %zero %c_f16_0_5 %vec %mat\n"));
5972 	cases.push_back(CaseParameter("nested_struct",	"%st1 = OpTypeStruct %i32 %f16\n"
5973 													"%st2 = OpTypeStruct %i32 %i32\n"
5974 													"%struct = OpTypeStruct %st1 %st2\n"
5975 													"%st1val = OpConstantComposite %st1 %zero %c_f16_0_5\n"
5976 													"%st2val = OpConstantComposite %st2 %zero %zero\n"
5977 													"%const = OpConstantComposite %struct %st1val %st2val"));
5978 
5979 	fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
5980 
5981 	for (size_t ndx = 0; ndx < numElements; ++ndx)
5982 		negativeFloats[ndx] = -positiveFloats[ndx];
5983 
5984 	for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5985 	{
5986 		map<string, string>		specializations;
5987 		ComputeShaderSpec		spec;
5988 
5989 		specializations["CONSTANT"] = cases[caseNdx].param;
5990 		spec.assembly = shaderTemplate.specialize(specializations);
5991 		spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
5992 		spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
5993 		spec.numWorkGroups = IVec3(numElements, 1, 1);
5994 
5995 		spec.extensions.push_back("VK_KHR_16bit_storage");
5996 		spec.extensions.push_back("VK_KHR_shader_float16_int8");
5997 
5998 		spec.requestedVulkanFeatures.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
5999 		spec.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
6000 
6001 		group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
6002 	}
6003 
6004 	return group.release();
6005 }
6006 
squarize(const vector<deFloat16> & inData,const deUint32 argNo)6007 const vector<deFloat16> squarize(const vector<deFloat16>& inData, const deUint32 argNo)
6008 {
6009 	const size_t		inDataLength	= inData.size();
6010 	vector<deFloat16>	result;
6011 
6012 	result.reserve(inDataLength * inDataLength);
6013 
6014 	if (argNo == 0)
6015 	{
6016 		for (size_t numIdx = 0; numIdx < inDataLength; ++numIdx)
6017 			result.insert(result.end(), inData.begin(), inData.end());
6018 	}
6019 
6020 	if (argNo == 1)
6021 	{
6022 		for (size_t numIdx = 0; numIdx < inDataLength; ++numIdx)
6023 		{
6024 			const vector<deFloat16>	tmp(inDataLength, inData[numIdx]);
6025 
6026 			result.insert(result.end(), tmp.begin(), tmp.end());
6027 		}
6028 	}
6029 
6030 	return result;
6031 }
6032 
squarizeVector(const vector<deFloat16> & inData,const deUint32 argNo)6033 const vector<deFloat16> squarizeVector(const vector<deFloat16>& inData, const deUint32 argNo)
6034 {
6035 	vector<deFloat16>	vec;
6036 	vector<deFloat16>	result;
6037 
6038 	// Create vectors. vec will contain each possible pair from inData
6039 	{
6040 		const size_t	inDataLength	= inData.size();
6041 
6042 		DE_ASSERT(inDataLength <= 64);
6043 
6044 		vec.reserve(2 * inDataLength * inDataLength);
6045 
6046 		for (size_t numIdxX = 0; numIdxX < inDataLength; ++numIdxX)
6047 		for (size_t numIdxY = 0; numIdxY < inDataLength; ++numIdxY)
6048 		{
6049 			vec.push_back(inData[numIdxX]);
6050 			vec.push_back(inData[numIdxY]);
6051 		}
6052 	}
6053 
6054 	// Create vector pairs. result will contain each possible pair from vec
6055 	{
6056 		const size_t	coordsPerVector	= 2;
6057 		const size_t	vectorsCount	= vec.size() / coordsPerVector;
6058 
6059 		result.reserve(coordsPerVector * vectorsCount * vectorsCount);
6060 
6061 		if (argNo == 0)
6062 		{
6063 			for (size_t numIdxX = 0; numIdxX < vectorsCount; ++numIdxX)
6064 			for (size_t numIdxY = 0; numIdxY < vectorsCount; ++numIdxY)
6065 			{
6066 				for (size_t coordNdx = 0; coordNdx < coordsPerVector; ++coordNdx)
6067 					result.push_back(vec[coordsPerVector * numIdxY + coordNdx]);
6068 			}
6069 		}
6070 
6071 		if (argNo == 1)
6072 		{
6073 			for (size_t numIdxX = 0; numIdxX < vectorsCount; ++numIdxX)
6074 			for (size_t numIdxY = 0; numIdxY < vectorsCount; ++numIdxY)
6075 			{
6076 				for (size_t coordNdx = 0; coordNdx < coordsPerVector; ++coordNdx)
6077 					result.push_back(vec[coordsPerVector * numIdxX + coordNdx]);
6078 			}
6079 		}
6080 	}
6081 
6082 	return result;
6083 }
6084 
operator ()vkt::SpirVAssembly::__anon68fe7dee0111::fp16isNan6085 struct fp16isNan			{ bool operator()(const tcu::Float16 in1, const tcu::Float16)		{ return in1.isNaN(); } };
operator ()vkt::SpirVAssembly::__anon68fe7dee0111::fp16isInf6086 struct fp16isInf			{ bool operator()(const tcu::Float16 in1, const tcu::Float16)		{ return in1.isInf(); } };
operator ()vkt::SpirVAssembly::__anon68fe7dee0111::fp16isEqual6087 struct fp16isEqual			{ bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)	{ return in1.asFloat() == in2.asFloat(); } };
operator ()vkt::SpirVAssembly::__anon68fe7dee0111::fp16isUnequal6088 struct fp16isUnequal		{ bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)	{ return in1.asFloat() != in2.asFloat(); } };
operator ()vkt::SpirVAssembly::__anon68fe7dee0111::fp16isLess6089 struct fp16isLess			{ bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)	{ return in1.asFloat() <  in2.asFloat(); } };
operator ()vkt::SpirVAssembly::__anon68fe7dee0111::fp16isGreater6090 struct fp16isGreater		{ bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)	{ return in1.asFloat() >  in2.asFloat(); } };
operator ()vkt::SpirVAssembly::__anon68fe7dee0111::fp16isLessOrEqual6091 struct fp16isLessOrEqual	{ bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)	{ return in1.asFloat() <= in2.asFloat(); } };
operator ()vkt::SpirVAssembly::__anon68fe7dee0111::fp16isGreaterOrEqual6092 struct fp16isGreaterOrEqual	{ bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)	{ return in1.asFloat() >= in2.asFloat(); } };
6093 
6094 template <class TestedLogicalFunction, bool onlyTestFunc, bool unationModeAnd, bool nanSupported>
compareFP16Logical(const std::vector<Resource> & inputs,const vector<AllocationSp> & outputAllocs,const std::vector<Resource> &,TestLog & log)6095 bool compareFP16Logical (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
6096 {
6097 	if (inputs.size() != 2 || outputAllocs.size() != 1)
6098 		return false;
6099 
6100 	vector<deUint8>	input1Bytes;
6101 	vector<deUint8>	input2Bytes;
6102 
6103 	inputs[0].getBytes(input1Bytes);
6104 	inputs[1].getBytes(input2Bytes);
6105 
6106 	const deUint32			denormModesCount			= 2;
6107 	const deFloat16			float16one					= tcu::Float16(1.0f).bits();
6108 	const deFloat16			float16zero					= tcu::Float16(0.0f).bits();
6109 	const tcu::Float16		zero						= tcu::Float16::zero(1);
6110 	const deFloat16* const	outputAsFP16				= static_cast<deFloat16*>(outputAllocs[0]->getHostPtr());
6111 	const deFloat16* const	input1AsFP16				= reinterpret_cast<deFloat16* const>(&input1Bytes.front());
6112 	const deFloat16* const	input2AsFP16				= reinterpret_cast<deFloat16* const>(&input2Bytes.front());
6113 	deUint32				successfulRuns				= denormModesCount;
6114 	std::string				results[denormModesCount];
6115 	TestedLogicalFunction	testedLogicalFunction;
6116 
6117 	for (deUint32 denormMode = 0; denormMode < denormModesCount; denormMode++)
6118 	{
6119 		const bool flushToZero = (denormMode == 1);
6120 
6121 		for (size_t idx = 0; idx < input1Bytes.size() / sizeof(deFloat16); ++idx)
6122 		{
6123 			const tcu::Float16	f1pre			= tcu::Float16(input1AsFP16[idx]);
6124 			const tcu::Float16	f2pre			= tcu::Float16(input2AsFP16[idx]);
6125 			const tcu::Float16	f1				= (flushToZero && f1pre.isDenorm()) ? zero : f1pre;
6126 			const tcu::Float16	f2				= (flushToZero && f2pre.isDenorm()) ? zero : f2pre;
6127 			deFloat16			expectedOutput	= float16zero;
6128 
6129 			if (onlyTestFunc)
6130 			{
6131 				if (testedLogicalFunction(f1, f2))
6132 					expectedOutput = float16one;
6133 			}
6134 			else
6135 			{
6136 				const bool	f1nan	= f1.isNaN();
6137 				const bool	f2nan	= f2.isNaN();
6138 
6139 				// Skip NaN floats if not supported by implementation
6140 				if (!nanSupported && (f1nan || f2nan))
6141 					continue;
6142 
6143 				if (unationModeAnd)
6144 				{
6145 					const bool	ordered		= !f1nan && !f2nan;
6146 
6147 					if (ordered && testedLogicalFunction(f1, f2))
6148 						expectedOutput = float16one;
6149 				}
6150 				else
6151 				{
6152 					const bool	unordered	= f1nan || f2nan;
6153 
6154 					if (unordered || testedLogicalFunction(f1, f2))
6155 						expectedOutput = float16one;
6156 				}
6157 			}
6158 
6159 			if (outputAsFP16[idx] != expectedOutput)
6160 			{
6161 				std::ostringstream str;
6162 
6163 				str << "ERROR: Sub-case #" << idx
6164 					<< " flushToZero:" << flushToZero
6165 					<< std::hex
6166 					<< " failed, inputs: 0x" << f1.bits()
6167 					<< ";0x" << f2.bits()
6168 					<< " output: 0x" << outputAsFP16[idx]
6169 					<< " expected output: 0x" << expectedOutput;
6170 
6171 				results[denormMode] = str.str();
6172 
6173 				successfulRuns--;
6174 
6175 				break;
6176 			}
6177 		}
6178 	}
6179 
6180 	if (successfulRuns == 0)
6181 		for (deUint32 denormMode = 0; denormMode < denormModesCount; denormMode++)
6182 			log << TestLog::Message << results[denormMode] << TestLog::EndMessage;
6183 
6184 	return successfulRuns > 0;
6185 }
6186 
6187 } // anonymous
6188 
createOpSourceTests(tcu::TestContext & testCtx)6189 tcu::TestCaseGroup* createOpSourceTests (tcu::TestContext& testCtx)
6190 {
6191 	struct NameCodePair { string name, code; };
6192 	RGBA							defaultColors[4];
6193 	de::MovePtr<tcu::TestCaseGroup> opSourceTests			(new tcu::TestCaseGroup(testCtx, "opsource", "OpSource instruction"));
6194 	const std::string				opsourceGLSLWithFile	= "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile ";
6195 	map<string, string>				fragments				= passthruFragments();
6196 	const NameCodePair				tests[]					=
6197 	{
6198 		{"unknown", "OpSource Unknown 321"},
6199 		{"essl", "OpSource ESSL 310"},
6200 		{"glsl", "OpSource GLSL 450"},
6201 		{"opencl_cpp", "OpSource OpenCL_CPP 120"},
6202 		{"opencl_c", "OpSource OpenCL_C 120"},
6203 		{"multiple", "OpSource GLSL 450\nOpSource GLSL 450"},
6204 		{"file", opsourceGLSLWithFile},
6205 		{"source", opsourceGLSLWithFile + "\"void main(){}\""},
6206 		// Longest possible source string: SPIR-V limits instructions to 65535
6207 		// words, of which the first 4 are opsourceGLSLWithFile; the rest will
6208 		// contain 65530 UTF8 characters (one word each) plus one last word
6209 		// containing 3 ASCII characters and \0.
6210 		{"longsource", opsourceGLSLWithFile + '"' + makeLongUTF8String(65530) + "ccc" + '"'}
6211 	};
6212 
6213 	getDefaultColors(defaultColors);
6214 	for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
6215 	{
6216 		fragments["debug"] = tests[testNdx].code;
6217 		createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
6218 	}
6219 
6220 	return opSourceTests.release();
6221 }
6222 
createOpSourceContinuedTests(tcu::TestContext & testCtx)6223 tcu::TestCaseGroup* createOpSourceContinuedTests (tcu::TestContext& testCtx)
6224 {
6225 	struct NameCodePair { string name, code; };
6226 	RGBA								defaultColors[4];
6227 	de::MovePtr<tcu::TestCaseGroup>		opSourceTests		(new tcu::TestCaseGroup(testCtx, "opsourcecontinued", "OpSourceContinued instruction"));
6228 	map<string, string>					fragments			= passthruFragments();
6229 	const std::string					opsource			= "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile \"void main(){}\"\n";
6230 	const NameCodePair					tests[]				=
6231 	{
6232 		{"empty", opsource + "OpSourceContinued \"\""},
6233 		{"short", opsource + "OpSourceContinued \"abcde\""},
6234 		{"multiple", opsource + "OpSourceContinued \"abcde\"\nOpSourceContinued \"fghij\""},
6235 		// Longest possible source string: SPIR-V limits instructions to 65535
6236 		// words, of which the first one is OpSourceContinued/length; the rest
6237 		// will contain 65533 UTF8 characters (one word each) plus one last word
6238 		// containing 3 ASCII characters and \0.
6239 		{"long", opsource + "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\""}
6240 	};
6241 
6242 	getDefaultColors(defaultColors);
6243 	for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
6244 	{
6245 		fragments["debug"] = tests[testNdx].code;
6246 		createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
6247 	}
6248 
6249 	return opSourceTests.release();
6250 }
createOpNoLineTests(tcu::TestContext & testCtx)6251 tcu::TestCaseGroup* createOpNoLineTests(tcu::TestContext& testCtx)
6252 {
6253 	RGBA								 defaultColors[4];
6254 	de::MovePtr<tcu::TestCaseGroup>		 opLineTests		 (new tcu::TestCaseGroup(testCtx, "opnoline", "OpNoLine instruction"));
6255 	map<string, string>					 fragments;
6256 	getDefaultColors(defaultColors);
6257 	fragments["debug"]			=
6258 		"%name = OpString \"name\"\n";
6259 
6260 	fragments["pre_main"]	=
6261 		"OpNoLine\n"
6262 		"OpNoLine\n"
6263 		"OpLine %name 1 1\n"
6264 		"OpNoLine\n"
6265 		"OpLine %name 1 1\n"
6266 		"OpLine %name 1 1\n"
6267 		"%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6268 		"OpNoLine\n"
6269 		"OpLine %name 1 1\n"
6270 		"OpNoLine\n"
6271 		"OpLine %name 1 1\n"
6272 		"OpLine %name 1 1\n"
6273 		"%second_param1 = OpFunctionParameter %v4f32\n"
6274 		"OpNoLine\n"
6275 		"OpNoLine\n"
6276 		"%label_secondfunction = OpLabel\n"
6277 		"OpNoLine\n"
6278 		"OpReturnValue %second_param1\n"
6279 		"OpFunctionEnd\n"
6280 		"OpNoLine\n"
6281 		"OpNoLine\n";
6282 
6283 	fragments["testfun"]		=
6284 		// A %test_code function that returns its argument unchanged.
6285 		"OpNoLine\n"
6286 		"OpNoLine\n"
6287 		"OpLine %name 1 1\n"
6288 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6289 		"OpNoLine\n"
6290 		"%param1 = OpFunctionParameter %v4f32\n"
6291 		"OpNoLine\n"
6292 		"OpNoLine\n"
6293 		"%label_testfun = OpLabel\n"
6294 		"OpNoLine\n"
6295 		"%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6296 		"OpReturnValue %val1\n"
6297 		"OpFunctionEnd\n"
6298 		"OpLine %name 1 1\n"
6299 		"OpNoLine\n";
6300 
6301 	createTestsForAllStages("opnoline", defaultColors, defaultColors, fragments, opLineTests.get());
6302 
6303 	return opLineTests.release();
6304 }
6305 
createOpModuleProcessedTests(tcu::TestContext & testCtx)6306 tcu::TestCaseGroup* createOpModuleProcessedTests(tcu::TestContext& testCtx)
6307 {
6308 	RGBA								defaultColors[4];
6309 	de::MovePtr<tcu::TestCaseGroup>		opModuleProcessedTests			(new tcu::TestCaseGroup(testCtx, "opmoduleprocessed", "OpModuleProcessed instruction"));
6310 	map<string, string>					fragments;
6311 	std::vector<std::string>			noExtensions;
6312 	GraphicsResources					resources;
6313 
6314 	getDefaultColors(defaultColors);
6315 	resources.verifyBinary = veryfiBinaryShader;
6316 	resources.spirvVersion = SPIRV_VERSION_1_3;
6317 
6318 	fragments["moduleprocessed"]							=
6319 		"OpModuleProcessed \"VULKAN CTS\"\n"
6320 		"OpModuleProcessed \"Negative values\"\n"
6321 		"OpModuleProcessed \"Date: 2017/09/21\"\n";
6322 
6323 	fragments["pre_main"]	=
6324 		"%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6325 		"%second_param1 = OpFunctionParameter %v4f32\n"
6326 		"%label_secondfunction = OpLabel\n"
6327 		"OpReturnValue %second_param1\n"
6328 		"OpFunctionEnd\n";
6329 
6330 	fragments["testfun"]		=
6331 		// A %test_code function that returns its argument unchanged.
6332 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6333 		"%param1 = OpFunctionParameter %v4f32\n"
6334 		"%label_testfun = OpLabel\n"
6335 		"%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6336 		"OpReturnValue %val1\n"
6337 		"OpFunctionEnd\n";
6338 
6339 	createTestsForAllStages ("opmoduleprocessed", defaultColors, defaultColors, fragments, resources, noExtensions, opModuleProcessedTests.get());
6340 
6341 	return opModuleProcessedTests.release();
6342 }
6343 
6344 
createOpLineTests(tcu::TestContext & testCtx)6345 tcu::TestCaseGroup* createOpLineTests(tcu::TestContext& testCtx)
6346 {
6347 	RGBA													defaultColors[4];
6348 	de::MovePtr<tcu::TestCaseGroup>							opLineTests			(new tcu::TestCaseGroup(testCtx, "opline", "OpLine instruction"));
6349 	map<string, string>										fragments;
6350 	std::vector<std::pair<std::string, std::string> >		problemStrings;
6351 
6352 	problemStrings.push_back(std::make_pair<std::string, std::string>("empty_name", ""));
6353 	problemStrings.push_back(std::make_pair<std::string, std::string>("short_name", "short_name"));
6354 	problemStrings.push_back(std::make_pair<std::string, std::string>("long_name", makeLongUTF8String(65530) + "ccc"));
6355 	getDefaultColors(defaultColors);
6356 
6357 	fragments["debug"]			=
6358 		"%other_name = OpString \"other_name\"\n";
6359 
6360 	fragments["pre_main"]	=
6361 		"OpLine %file_name 32 0\n"
6362 		"OpLine %file_name 32 32\n"
6363 		"OpLine %file_name 32 40\n"
6364 		"OpLine %other_name 32 40\n"
6365 		"OpLine %other_name 0 100\n"
6366 		"OpLine %other_name 0 4294967295\n"
6367 		"OpLine %other_name 4294967295 0\n"
6368 		"OpLine %other_name 32 40\n"
6369 		"OpLine %file_name 0 0\n"
6370 		"%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6371 		"OpLine %file_name 1 0\n"
6372 		"%second_param1 = OpFunctionParameter %v4f32\n"
6373 		"OpLine %file_name 1 3\n"
6374 		"OpLine %file_name 1 2\n"
6375 		"%label_secondfunction = OpLabel\n"
6376 		"OpLine %file_name 0 2\n"
6377 		"OpReturnValue %second_param1\n"
6378 		"OpFunctionEnd\n"
6379 		"OpLine %file_name 0 2\n"
6380 		"OpLine %file_name 0 2\n";
6381 
6382 	fragments["testfun"]		=
6383 		// A %test_code function that returns its argument unchanged.
6384 		"OpLine %file_name 1 0\n"
6385 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6386 		"OpLine %file_name 16 330\n"
6387 		"%param1 = OpFunctionParameter %v4f32\n"
6388 		"OpLine %file_name 14 442\n"
6389 		"%label_testfun = OpLabel\n"
6390 		"OpLine %file_name 11 1024\n"
6391 		"%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6392 		"OpLine %file_name 2 97\n"
6393 		"OpReturnValue %val1\n"
6394 		"OpFunctionEnd\n"
6395 		"OpLine %file_name 5 32\n";
6396 
6397 	for (size_t i = 0; i < problemStrings.size(); ++i)
6398 	{
6399 		map<string, string> testFragments = fragments;
6400 		testFragments["debug"] += "%file_name = OpString \"" + problemStrings[i].second + "\"\n";
6401 		createTestsForAllStages(string("opline") + "_" + problemStrings[i].first, defaultColors, defaultColors, testFragments, opLineTests.get());
6402 	}
6403 
6404 	return opLineTests.release();
6405 }
6406 
createOpConstantNullTests(tcu::TestContext & testCtx)6407 tcu::TestCaseGroup* createOpConstantNullTests(tcu::TestContext& testCtx)
6408 {
6409 	de::MovePtr<tcu::TestCaseGroup> opConstantNullTests		(new tcu::TestCaseGroup(testCtx, "opconstantnull", "OpConstantNull instruction"));
6410 	RGBA							colors[4];
6411 
6412 
6413 	const char						functionStart[] =
6414 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6415 		"%param1 = OpFunctionParameter %v4f32\n"
6416 		"%lbl    = OpLabel\n";
6417 
6418 	const char						functionEnd[]	=
6419 		"OpReturnValue %transformed_param\n"
6420 		"OpFunctionEnd\n";
6421 
6422 	struct NameConstantsCode
6423 	{
6424 		string name;
6425 		string constants;
6426 		string code;
6427 	};
6428 
6429 	NameConstantsCode tests[] =
6430 	{
6431 		{
6432 			"vec4",
6433 			"%cnull = OpConstantNull %v4f32\n",
6434 			"%transformed_param = OpFAdd %v4f32 %param1 %cnull\n"
6435 		},
6436 		{
6437 			"float",
6438 			"%cnull = OpConstantNull %f32\n",
6439 			"%vp = OpVariable %fp_v4f32 Function\n"
6440 			"%v  = OpLoad %v4f32 %vp\n"
6441 			"%v0 = OpVectorInsertDynamic %v4f32 %v %cnull %c_i32_0\n"
6442 			"%v1 = OpVectorInsertDynamic %v4f32 %v0 %cnull %c_i32_1\n"
6443 			"%v2 = OpVectorInsertDynamic %v4f32 %v1 %cnull %c_i32_2\n"
6444 			"%v3 = OpVectorInsertDynamic %v4f32 %v2 %cnull %c_i32_3\n"
6445 			"%transformed_param = OpFAdd %v4f32 %param1 %v3\n"
6446 		},
6447 		{
6448 			"bool",
6449 			"%cnull             = OpConstantNull %bool\n",
6450 			"%v                 = OpVariable %fp_v4f32 Function\n"
6451 			"                     OpStore %v %param1\n"
6452 			"                     OpSelectionMerge %false_label None\n"
6453 			"                     OpBranchConditional %cnull %true_label %false_label\n"
6454 			"%true_label        = OpLabel\n"
6455 			"                     OpStore %v %c_v4f32_0_5_0_5_0_5_0_5\n"
6456 			"                     OpBranch %false_label\n"
6457 			"%false_label       = OpLabel\n"
6458 			"%transformed_param = OpLoad %v4f32 %v\n"
6459 		},
6460 		{
6461 			"i32",
6462 			"%cnull             = OpConstantNull %i32\n",
6463 			"%v                 = OpVariable %fp_v4f32 Function %c_v4f32_0_5_0_5_0_5_0_5\n"
6464 			"%b                 = OpIEqual %bool %cnull %c_i32_0\n"
6465 			"                     OpSelectionMerge %false_label None\n"
6466 			"                     OpBranchConditional %b %true_label %false_label\n"
6467 			"%true_label        = OpLabel\n"
6468 			"                     OpStore %v %param1\n"
6469 			"                     OpBranch %false_label\n"
6470 			"%false_label       = OpLabel\n"
6471 			"%transformed_param = OpLoad %v4f32 %v\n"
6472 		},
6473 		{
6474 			"struct",
6475 			"%stype             = OpTypeStruct %f32 %v4f32\n"
6476 			"%fp_stype          = OpTypePointer Function %stype\n"
6477 			"%cnull             = OpConstantNull %stype\n",
6478 			"%v                 = OpVariable %fp_stype Function %cnull\n"
6479 			"%f                 = OpAccessChain %fp_v4f32 %v %c_i32_1\n"
6480 			"%f_val             = OpLoad %v4f32 %f\n"
6481 			"%transformed_param = OpFAdd %v4f32 %param1 %f_val\n"
6482 		},
6483 		{
6484 			"array",
6485 			"%a4_v4f32          = OpTypeArray %v4f32 %c_u32_4\n"
6486 			"%fp_a4_v4f32       = OpTypePointer Function %a4_v4f32\n"
6487 			"%cnull             = OpConstantNull %a4_v4f32\n",
6488 			"%v                 = OpVariable %fp_a4_v4f32 Function %cnull\n"
6489 			"%f                 = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
6490 			"%f1                = OpAccessChain %fp_v4f32 %v %c_u32_1\n"
6491 			"%f2                = OpAccessChain %fp_v4f32 %v %c_u32_2\n"
6492 			"%f3                = OpAccessChain %fp_v4f32 %v %c_u32_3\n"
6493 			"%f_val             = OpLoad %v4f32 %f\n"
6494 			"%f1_val            = OpLoad %v4f32 %f1\n"
6495 			"%f2_val            = OpLoad %v4f32 %f2\n"
6496 			"%f3_val            = OpLoad %v4f32 %f3\n"
6497 			"%t0                = OpFAdd %v4f32 %param1 %f_val\n"
6498 			"%t1                = OpFAdd %v4f32 %t0 %f1_val\n"
6499 			"%t2                = OpFAdd %v4f32 %t1 %f2_val\n"
6500 			"%transformed_param = OpFAdd %v4f32 %t2 %f3_val\n"
6501 		},
6502 		{
6503 			"matrix",
6504 			"%mat4x4_f32        = OpTypeMatrix %v4f32 4\n"
6505 			"%cnull             = OpConstantNull %mat4x4_f32\n",
6506 			// Our null matrix * any vector should result in a zero vector.
6507 			"%v                 = OpVectorTimesMatrix %v4f32 %param1 %cnull\n"
6508 			"%transformed_param = OpFAdd %v4f32 %param1 %v\n"
6509 		}
6510 	};
6511 
6512 	getHalfColorsFullAlpha(colors);
6513 
6514 	for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
6515 	{
6516 		map<string, string> fragments;
6517 		fragments["pre_main"] = tests[testNdx].constants;
6518 		fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
6519 		createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, opConstantNullTests.get());
6520 	}
6521 	return opConstantNullTests.release();
6522 }
createOpConstantCompositeTests(tcu::TestContext & testCtx)6523 tcu::TestCaseGroup* createOpConstantCompositeTests(tcu::TestContext& testCtx)
6524 {
6525 	de::MovePtr<tcu::TestCaseGroup> opConstantCompositeTests		(new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "OpConstantComposite instruction"));
6526 	RGBA							inputColors[4];
6527 	RGBA							outputColors[4];
6528 
6529 
6530 	const char						functionStart[]	 =
6531 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6532 		"%param1 = OpFunctionParameter %v4f32\n"
6533 		"%lbl    = OpLabel\n";
6534 
6535 	const char						functionEnd[]		=
6536 		"OpReturnValue %transformed_param\n"
6537 		"OpFunctionEnd\n";
6538 
6539 	struct NameConstantsCode
6540 	{
6541 		string name;
6542 		string constants;
6543 		string code;
6544 	};
6545 
6546 	NameConstantsCode tests[] =
6547 	{
6548 		{
6549 			"vec4",
6550 
6551 			"%cval              = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0\n",
6552 			"%transformed_param = OpFAdd %v4f32 %param1 %cval\n"
6553 		},
6554 		{
6555 			"struct",
6556 
6557 			"%stype             = OpTypeStruct %v4f32 %f32\n"
6558 			"%fp_stype          = OpTypePointer Function %stype\n"
6559 			"%f32_n_1           = OpConstant %f32 -1.0\n"
6560 			"%f32_1_5           = OpConstant %f32 !0x3fc00000\n" // +1.5
6561 			"%cvec              = OpConstantComposite %v4f32 %f32_1_5 %f32_1_5 %f32_1_5 %c_f32_1\n"
6562 			"%cval              = OpConstantComposite %stype %cvec %f32_n_1\n",
6563 
6564 			"%v                 = OpVariable %fp_stype Function %cval\n"
6565 			"%vec_ptr           = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
6566 			"%f32_ptr           = OpAccessChain %fp_f32 %v %c_u32_1\n"
6567 			"%vec_val           = OpLoad %v4f32 %vec_ptr\n"
6568 			"%f32_val           = OpLoad %f32 %f32_ptr\n"
6569 			"%tmp1              = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_1 %f32_val\n" // vec4(-1)
6570 			"%tmp2              = OpFAdd %v4f32 %tmp1 %param1\n" // param1 + vec4(-1)
6571 			"%transformed_param = OpFAdd %v4f32 %tmp2 %vec_val\n" // param1 + vec4(-1) + vec4(1.5, 1.5, 1.5, 1.0)
6572 		},
6573 		{
6574 			// [1|0|0|0.5] [x] = x + 0.5
6575 			// [0|1|0|0.5] [y] = y + 0.5
6576 			// [0|0|1|0.5] [z] = z + 0.5
6577 			// [0|0|0|1  ] [1] = 1
6578 			"matrix",
6579 
6580 			"%mat4x4_f32          = OpTypeMatrix %v4f32 4\n"
6581 			"%v4f32_1_0_0_0       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_0 %c_f32_0 %c_f32_0\n"
6582 			"%v4f32_0_1_0_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_1 %c_f32_0 %c_f32_0\n"
6583 			"%v4f32_0_0_1_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_1 %c_f32_0\n"
6584 			"%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"
6585 			"%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",
6586 
6587 			"%transformed_param   = OpMatrixTimesVector %v4f32 %cval %param1\n"
6588 		},
6589 		{
6590 			"array",
6591 
6592 			"%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
6593 			"%fp_a4f32            = OpTypePointer Function %a4f32\n"
6594 			"%f32_n_1             = OpConstant %f32 -1.0\n"
6595 			"%f32_1_5             = OpConstant %f32 !0x3fc00000\n" // +1.5
6596 			"%carr                = OpConstantComposite %a4f32 %c_f32_0 %f32_n_1 %f32_1_5 %c_f32_0\n",
6597 
6598 			"%v                   = OpVariable %fp_a4f32 Function %carr\n"
6599 			"%f                   = OpAccessChain %fp_f32 %v %c_u32_0\n"
6600 			"%f1                  = OpAccessChain %fp_f32 %v %c_u32_1\n"
6601 			"%f2                  = OpAccessChain %fp_f32 %v %c_u32_2\n"
6602 			"%f3                  = OpAccessChain %fp_f32 %v %c_u32_3\n"
6603 			"%f_val               = OpLoad %f32 %f\n"
6604 			"%f1_val              = OpLoad %f32 %f1\n"
6605 			"%f2_val              = OpLoad %f32 %f2\n"
6606 			"%f3_val              = OpLoad %f32 %f3\n"
6607 			"%ftot1               = OpFAdd %f32 %f_val %f1_val\n"
6608 			"%ftot2               = OpFAdd %f32 %ftot1 %f2_val\n"
6609 			"%ftot3               = OpFAdd %f32 %ftot2 %f3_val\n"  // 0 - 1 + 1.5 + 0
6610 			"%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %ftot3\n"
6611 			"%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
6612 		},
6613 		{
6614 			//
6615 			// [
6616 			//   {
6617 			//      0.0,
6618 			//      [ 1.0, 1.0, 1.0, 1.0]
6619 			//   },
6620 			//   {
6621 			//      1.0,
6622 			//      [ 0.0, 0.5, 0.0, 0.0]
6623 			//   }, //     ^^^
6624 			//   {
6625 			//      0.0,
6626 			//      [ 1.0, 1.0, 1.0, 1.0]
6627 			//   }
6628 			// ]
6629 			"array_of_struct_of_array",
6630 
6631 			"%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
6632 			"%fp_a4f32            = OpTypePointer Function %a4f32\n"
6633 			"%stype               = OpTypeStruct %f32 %a4f32\n"
6634 			"%a3stype             = OpTypeArray %stype %c_u32_3\n"
6635 			"%fp_a3stype          = OpTypePointer Function %a3stype\n"
6636 			"%ca4f32_0            = OpConstantComposite %a4f32 %c_f32_0 %c_f32_0_5 %c_f32_0 %c_f32_0\n"
6637 			"%ca4f32_1            = OpConstantComposite %a4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
6638 			"%cstype1             = OpConstantComposite %stype %c_f32_0 %ca4f32_1\n"
6639 			"%cstype2             = OpConstantComposite %stype %c_f32_1 %ca4f32_0\n"
6640 			"%carr                = OpConstantComposite %a3stype %cstype1 %cstype2 %cstype1",
6641 
6642 			"%v                   = OpVariable %fp_a3stype Function %carr\n"
6643 			"%f                   = OpAccessChain %fp_f32 %v %c_u32_1 %c_u32_1 %c_u32_1\n"
6644 			"%f_l                 = OpLoad %f32 %f\n"
6645 			"%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %f_l\n"
6646 			"%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
6647 		}
6648 	};
6649 
6650 	getHalfColorsFullAlpha(inputColors);
6651 	outputColors[0] = RGBA(255, 255, 255, 255);
6652 	outputColors[1] = RGBA(255, 127, 127, 255);
6653 	outputColors[2] = RGBA(127, 255, 127, 255);
6654 	outputColors[3] = RGBA(127, 127, 255, 255);
6655 
6656 	for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
6657 	{
6658 		map<string, string> fragments;
6659 		fragments["pre_main"] = tests[testNdx].constants;
6660 		fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
6661 		createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, opConstantCompositeTests.get());
6662 	}
6663 	return opConstantCompositeTests.release();
6664 }
6665 
createSelectionBlockOrderTests(tcu::TestContext & testCtx)6666 tcu::TestCaseGroup* createSelectionBlockOrderTests(tcu::TestContext& testCtx)
6667 {
6668 	de::MovePtr<tcu::TestCaseGroup> group				(new tcu::TestCaseGroup(testCtx, "selection_block_order", "Out-of-order blocks for selection"));
6669 	RGBA							inputColors[4];
6670 	RGBA							outputColors[4];
6671 	map<string, string>				fragments;
6672 
6673 	// vec4 test_code(vec4 param) {
6674 	//   vec4 result = param;
6675 	//   for (int i = 0; i < 4; ++i) {
6676 	//     if (i == 0) result[i] = 0.;
6677 	//     else        result[i] = 1. - result[i];
6678 	//   }
6679 	//   return result;
6680 	// }
6681 	const char						function[]			=
6682 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6683 		"%param1    = OpFunctionParameter %v4f32\n"
6684 		"%lbl       = OpLabel\n"
6685 		"%iptr      = OpVariable %fp_i32 Function\n"
6686 		"%result    = OpVariable %fp_v4f32 Function\n"
6687 		"             OpStore %iptr %c_i32_0\n"
6688 		"             OpStore %result %param1\n"
6689 		"             OpBranch %loop\n"
6690 
6691 		// Loop entry block.
6692 		"%loop      = OpLabel\n"
6693 		"%ival      = OpLoad %i32 %iptr\n"
6694 		"%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6695 		"             OpLoopMerge %exit %if_entry None\n"
6696 		"             OpBranchConditional %lt_4 %if_entry %exit\n"
6697 
6698 		// Merge block for loop.
6699 		"%exit      = OpLabel\n"
6700 		"%ret       = OpLoad %v4f32 %result\n"
6701 		"             OpReturnValue %ret\n"
6702 
6703 		// If-statement entry block.
6704 		"%if_entry  = OpLabel\n"
6705 		"%loc       = OpAccessChain %fp_f32 %result %ival\n"
6706 		"%eq_0      = OpIEqual %bool %ival %c_i32_0\n"
6707 		"             OpSelectionMerge %if_exit None\n"
6708 		"             OpBranchConditional %eq_0 %if_true %if_false\n"
6709 
6710 		// False branch for if-statement.
6711 		"%if_false  = OpLabel\n"
6712 		"%val       = OpLoad %f32 %loc\n"
6713 		"%sub       = OpFSub %f32 %c_f32_1 %val\n"
6714 		"             OpStore %loc %sub\n"
6715 		"             OpBranch %if_exit\n"
6716 
6717 		// Merge block for if-statement.
6718 		"%if_exit   = OpLabel\n"
6719 		"%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
6720 		"             OpStore %iptr %ival_next\n"
6721 		"             OpBranch %loop\n"
6722 
6723 		// True branch for if-statement.
6724 		"%if_true   = OpLabel\n"
6725 		"             OpStore %loc %c_f32_0\n"
6726 		"             OpBranch %if_exit\n"
6727 
6728 		"             OpFunctionEnd\n";
6729 
6730 	fragments["testfun"]	= function;
6731 
6732 	inputColors[0]			= RGBA(127, 127, 127, 0);
6733 	inputColors[1]			= RGBA(127, 0,   0,   0);
6734 	inputColors[2]			= RGBA(0,   127, 0,   0);
6735 	inputColors[3]			= RGBA(0,   0,   127, 0);
6736 
6737 	outputColors[0]			= RGBA(0, 128, 128, 255);
6738 	outputColors[1]			= RGBA(0, 255, 255, 255);
6739 	outputColors[2]			= RGBA(0, 128, 255, 255);
6740 	outputColors[3]			= RGBA(0, 255, 128, 255);
6741 
6742 	createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
6743 
6744 	return group.release();
6745 }
6746 
createSwitchBlockOrderTests(tcu::TestContext & testCtx)6747 tcu::TestCaseGroup* createSwitchBlockOrderTests(tcu::TestContext& testCtx)
6748 {
6749 	de::MovePtr<tcu::TestCaseGroup> group				(new tcu::TestCaseGroup(testCtx, "switch_block_order", "Out-of-order blocks for switch"));
6750 	RGBA							inputColors[4];
6751 	RGBA							outputColors[4];
6752 	map<string, string>				fragments;
6753 
6754 	const char						typesAndConstants[]	=
6755 		"%c_f32_p2  = OpConstant %f32 0.2\n"
6756 		"%c_f32_p4  = OpConstant %f32 0.4\n"
6757 		"%c_f32_p6  = OpConstant %f32 0.6\n"
6758 		"%c_f32_p8  = OpConstant %f32 0.8\n";
6759 
6760 	// vec4 test_code(vec4 param) {
6761 	//   vec4 result = param;
6762 	//   for (int i = 0; i < 4; ++i) {
6763 	//     switch (i) {
6764 	//       case 0: result[i] += .2; break;
6765 	//       case 1: result[i] += .6; break;
6766 	//       case 2: result[i] += .4; break;
6767 	//       case 3: result[i] += .8; break;
6768 	//       default: break; // unreachable
6769 	//     }
6770 	//   }
6771 	//   return result;
6772 	// }
6773 	const char						function[]			=
6774 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6775 		"%param1    = OpFunctionParameter %v4f32\n"
6776 		"%lbl       = OpLabel\n"
6777 		"%iptr      = OpVariable %fp_i32 Function\n"
6778 		"%result    = OpVariable %fp_v4f32 Function\n"
6779 		"             OpStore %iptr %c_i32_0\n"
6780 		"             OpStore %result %param1\n"
6781 		"             OpBranch %loop\n"
6782 
6783 		// Loop entry block.
6784 		"%loop      = OpLabel\n"
6785 		"%ival      = OpLoad %i32 %iptr\n"
6786 		"%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6787 		"             OpLoopMerge %exit %switch_exit None\n"
6788 		"             OpBranchConditional %lt_4 %switch_entry %exit\n"
6789 
6790 		// Merge block for loop.
6791 		"%exit      = OpLabel\n"
6792 		"%ret       = OpLoad %v4f32 %result\n"
6793 		"             OpReturnValue %ret\n"
6794 
6795 		// Switch-statement entry block.
6796 		"%switch_entry   = OpLabel\n"
6797 		"%loc            = OpAccessChain %fp_f32 %result %ival\n"
6798 		"%val            = OpLoad %f32 %loc\n"
6799 		"                  OpSelectionMerge %switch_exit None\n"
6800 		"                  OpSwitch %ival %switch_default 0 %case0 1 %case1 2 %case2 3 %case3\n"
6801 
6802 		"%case2          = OpLabel\n"
6803 		"%addp4          = OpFAdd %f32 %val %c_f32_p4\n"
6804 		"                  OpStore %loc %addp4\n"
6805 		"                  OpBranch %switch_exit\n"
6806 
6807 		"%switch_default = OpLabel\n"
6808 		"                  OpUnreachable\n"
6809 
6810 		"%case3          = OpLabel\n"
6811 		"%addp8          = OpFAdd %f32 %val %c_f32_p8\n"
6812 		"                  OpStore %loc %addp8\n"
6813 		"                  OpBranch %switch_exit\n"
6814 
6815 		"%case0          = OpLabel\n"
6816 		"%addp2          = OpFAdd %f32 %val %c_f32_p2\n"
6817 		"                  OpStore %loc %addp2\n"
6818 		"                  OpBranch %switch_exit\n"
6819 
6820 		// Merge block for switch-statement.
6821 		"%switch_exit    = OpLabel\n"
6822 		"%ival_next      = OpIAdd %i32 %ival %c_i32_1\n"
6823 		"                  OpStore %iptr %ival_next\n"
6824 		"                  OpBranch %loop\n"
6825 
6826 		"%case1          = OpLabel\n"
6827 		"%addp6          = OpFAdd %f32 %val %c_f32_p6\n"
6828 		"                  OpStore %loc %addp6\n"
6829 		"                  OpBranch %switch_exit\n"
6830 
6831 		"                  OpFunctionEnd\n";
6832 
6833 	fragments["pre_main"]	= typesAndConstants;
6834 	fragments["testfun"]	= function;
6835 
6836 	inputColors[0]			= RGBA(127, 27,  127, 51);
6837 	inputColors[1]			= RGBA(127, 0,   0,   51);
6838 	inputColors[2]			= RGBA(0,   27,  0,   51);
6839 	inputColors[3]			= RGBA(0,   0,   127, 51);
6840 
6841 	outputColors[0]			= RGBA(178, 180, 229, 255);
6842 	outputColors[1]			= RGBA(178, 153, 102, 255);
6843 	outputColors[2]			= RGBA(51,  180, 102, 255);
6844 	outputColors[3]			= RGBA(51,  153, 229, 255);
6845 
6846 	createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
6847 
6848 	return group.release();
6849 }
6850 
createDecorationGroupTests(tcu::TestContext & testCtx)6851 tcu::TestCaseGroup* createDecorationGroupTests(tcu::TestContext& testCtx)
6852 {
6853 	de::MovePtr<tcu::TestCaseGroup> group				(new tcu::TestCaseGroup(testCtx, "decoration_group", "Decoration group tests"));
6854 	RGBA							inputColors[4];
6855 	RGBA							outputColors[4];
6856 	map<string, string>				fragments;
6857 
6858 	const char						decorations[]		=
6859 		"OpDecorate %array_group         ArrayStride 4\n"
6860 		"OpDecorate %struct_member_group Offset 0\n"
6861 		"%array_group         = OpDecorationGroup\n"
6862 		"%struct_member_group = OpDecorationGroup\n"
6863 
6864 		"OpDecorate %group1 RelaxedPrecision\n"
6865 		"OpDecorate %group3 RelaxedPrecision\n"
6866 		"OpDecorate %group3 Invariant\n"
6867 		"OpDecorate %group3 Restrict\n"
6868 		"%group0 = OpDecorationGroup\n"
6869 		"%group1 = OpDecorationGroup\n"
6870 		"%group3 = OpDecorationGroup\n";
6871 
6872 	const char						typesAndConstants[]	=
6873 		"%a3f32     = OpTypeArray %f32 %c_u32_3\n"
6874 		"%struct1   = OpTypeStruct %a3f32\n"
6875 		"%struct2   = OpTypeStruct %a3f32\n"
6876 		"%fp_struct1 = OpTypePointer Function %struct1\n"
6877 		"%fp_struct2 = OpTypePointer Function %struct2\n"
6878 		"%c_f32_2    = OpConstant %f32 2.\n"
6879 		"%c_f32_n2   = OpConstant %f32 -2.\n"
6880 
6881 		"%c_a3f32_1 = OpConstantComposite %a3f32 %c_f32_1 %c_f32_2 %c_f32_1\n"
6882 		"%c_a3f32_2 = OpConstantComposite %a3f32 %c_f32_n1 %c_f32_n2 %c_f32_n1\n"
6883 		"%c_struct1 = OpConstantComposite %struct1 %c_a3f32_1\n"
6884 		"%c_struct2 = OpConstantComposite %struct2 %c_a3f32_2\n";
6885 
6886 	const char						function[]			=
6887 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6888 		"%param     = OpFunctionParameter %v4f32\n"
6889 		"%entry     = OpLabel\n"
6890 		"%result    = OpVariable %fp_v4f32 Function\n"
6891 		"%v_struct1 = OpVariable %fp_struct1 Function\n"
6892 		"%v_struct2 = OpVariable %fp_struct2 Function\n"
6893 		"             OpStore %result %param\n"
6894 		"             OpStore %v_struct1 %c_struct1\n"
6895 		"             OpStore %v_struct2 %c_struct2\n"
6896 		"%ptr1      = OpAccessChain %fp_f32 %v_struct1 %c_i32_0 %c_i32_2\n"
6897 		"%val1      = OpLoad %f32 %ptr1\n"
6898 		"%ptr2      = OpAccessChain %fp_f32 %v_struct2 %c_i32_0 %c_i32_2\n"
6899 		"%val2      = OpLoad %f32 %ptr2\n"
6900 		"%addvalues = OpFAdd %f32 %val1 %val2\n"
6901 		"%ptr       = OpAccessChain %fp_f32 %result %c_i32_1\n"
6902 		"%val       = OpLoad %f32 %ptr\n"
6903 		"%addresult = OpFAdd %f32 %addvalues %val\n"
6904 		"             OpStore %ptr %addresult\n"
6905 		"%ret       = OpLoad %v4f32 %result\n"
6906 		"             OpReturnValue %ret\n"
6907 		"             OpFunctionEnd\n";
6908 
6909 	struct CaseNameDecoration
6910 	{
6911 		string name;
6912 		string decoration;
6913 	};
6914 
6915 	CaseNameDecoration tests[] =
6916 	{
6917 		{
6918 			"same_decoration_group_on_multiple_types",
6919 			"OpGroupMemberDecorate %struct_member_group %struct1 0 %struct2 0\n"
6920 		},
6921 		{
6922 			"empty_decoration_group",
6923 			"OpGroupDecorate %group0      %a3f32\n"
6924 			"OpGroupDecorate %group0      %result\n"
6925 		},
6926 		{
6927 			"one_element_decoration_group",
6928 			"OpGroupDecorate %array_group %a3f32\n"
6929 		},
6930 		{
6931 			"multiple_elements_decoration_group",
6932 			"OpGroupDecorate %group3      %v_struct1\n"
6933 		},
6934 		{
6935 			"multiple_decoration_groups_on_same_variable",
6936 			"OpGroupDecorate %group0      %v_struct2\n"
6937 			"OpGroupDecorate %group1      %v_struct2\n"
6938 			"OpGroupDecorate %group3      %v_struct2\n"
6939 		},
6940 		{
6941 			"same_decoration_group_multiple_times",
6942 			"OpGroupDecorate %group1      %addvalues\n"
6943 			"OpGroupDecorate %group1      %addvalues\n"
6944 			"OpGroupDecorate %group1      %addvalues\n"
6945 		},
6946 
6947 	};
6948 
6949 	getHalfColorsFullAlpha(inputColors);
6950 	getHalfColorsFullAlpha(outputColors);
6951 
6952 	for (size_t idx = 0; idx < (sizeof(tests) / sizeof(tests[0])); ++idx)
6953 	{
6954 		fragments["decoration"]	= decorations + tests[idx].decoration;
6955 		fragments["pre_main"]	= typesAndConstants;
6956 		fragments["testfun"]	= function;
6957 
6958 		createTestsForAllStages(tests[idx].name, inputColors, outputColors, fragments, group.get());
6959 	}
6960 
6961 	return group.release();
6962 }
6963 
6964 struct SpecConstantTwoIntGraphicsCase
6965 {
6966 	const char*		caseName;
6967 	const char*		scDefinition0;
6968 	const char*		scDefinition1;
6969 	const char*		scResultType;
6970 	const char*		scOperation;
6971 	deInt32			scActualValue0;
6972 	deInt32			scActualValue1;
6973 	const char*		resultOperation;
6974 	RGBA			expectedColors[4];
6975 	deInt32			scActualValueLength;
6976 
SpecConstantTwoIntGraphicsCasevkt::SpirVAssembly::SpecConstantTwoIntGraphicsCase6977 					SpecConstantTwoIntGraphicsCase (const char*		name,
6978 													const char*		definition0,
6979 													const char*		definition1,
6980 													const char*		resultType,
6981 													const char*		operation,
6982 													const deInt32	value0,
6983 													const deInt32	value1,
6984 													const char*		resultOp,
6985 													const RGBA		(&output)[4],
6986 													const deInt32	valueLength = sizeof(deInt32))
6987 						: caseName				(name)
6988 						, scDefinition0			(definition0)
6989 						, scDefinition1			(definition1)
6990 						, scResultType			(resultType)
6991 						, scOperation			(operation)
6992 						, scActualValue0		(value0)
6993 						, scActualValue1		(value1)
6994 						, resultOperation		(resultOp)
6995 						, scActualValueLength	(valueLength)
6996 	{
6997 		expectedColors[0] = output[0];
6998 		expectedColors[1] = output[1];
6999 		expectedColors[2] = output[2];
7000 		expectedColors[3] = output[3];
7001 	}
7002 };
7003 
createSpecConstantTests(tcu::TestContext & testCtx)7004 tcu::TestCaseGroup* createSpecConstantTests (tcu::TestContext& testCtx)
7005 {
7006 	de::MovePtr<tcu::TestCaseGroup> group				(new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
7007 	vector<SpecConstantTwoIntGraphicsCase>	cases;
7008 	RGBA							inputColors[4];
7009 	RGBA							outputColors0[4];
7010 	RGBA							outputColors1[4];
7011 	RGBA							outputColors2[4];
7012 
7013 	const deInt32					m1AsFloat16			= 0xbc00; // -1(fp16) == 1 01111 0000000000 == 1011 1100 0000 0000
7014 
7015 	const char	decorations1[]			=
7016 		"OpDecorate %sc_0  SpecId 0\n"
7017 		"OpDecorate %sc_1  SpecId 1\n";
7018 
7019 	const char	typesAndConstants1[]	=
7020 		"${OPTYPE_DEFINITIONS:opt}"
7021 		"%sc_0      = OpSpecConstant${SC_DEF0}\n"
7022 		"%sc_1      = OpSpecConstant${SC_DEF1}\n"
7023 		"%sc_op     = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n";
7024 
7025 	const char	function1[]				=
7026 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7027 		"%param     = OpFunctionParameter %v4f32\n"
7028 		"%label     = OpLabel\n"
7029 		"%result    = OpVariable %fp_v4f32 Function\n"
7030 		"${TYPE_CONVERT:opt}"
7031 		"             OpStore %result %param\n"
7032 		"%gen       = ${GEN_RESULT}\n"
7033 		"%index     = OpIAdd %i32 %gen %c_i32_1\n"
7034 		"%loc       = OpAccessChain %fp_f32 %result %index\n"
7035 		"%val       = OpLoad %f32 %loc\n"
7036 		"%add       = OpFAdd %f32 %val %c_f32_0_5\n"
7037 		"             OpStore %loc %add\n"
7038 		"%ret       = OpLoad %v4f32 %result\n"
7039 		"             OpReturnValue %ret\n"
7040 		"             OpFunctionEnd\n";
7041 
7042 	inputColors[0] = RGBA(127, 127, 127, 255);
7043 	inputColors[1] = RGBA(127, 0,   0,   255);
7044 	inputColors[2] = RGBA(0,   127, 0,   255);
7045 	inputColors[3] = RGBA(0,   0,   127, 255);
7046 
7047 	// Derived from inputColors[x] by adding 128 to inputColors[x][0].
7048 	outputColors0[0] = RGBA(255, 127, 127, 255);
7049 	outputColors0[1] = RGBA(255, 0,   0,   255);
7050 	outputColors0[2] = RGBA(128, 127, 0,   255);
7051 	outputColors0[3] = RGBA(128, 0,   127, 255);
7052 
7053 	// Derived from inputColors[x] by adding 128 to inputColors[x][1].
7054 	outputColors1[0] = RGBA(127, 255, 127, 255);
7055 	outputColors1[1] = RGBA(127, 128, 0,   255);
7056 	outputColors1[2] = RGBA(0,   255, 0,   255);
7057 	outputColors1[3] = RGBA(0,   128, 127, 255);
7058 
7059 	// Derived from inputColors[x] by adding 128 to inputColors[x][2].
7060 	outputColors2[0] = RGBA(127, 127, 255, 255);
7061 	outputColors2[1] = RGBA(127, 0,   128, 255);
7062 	outputColors2[2] = RGBA(0,   127, 128, 255);
7063 	outputColors2[3] = RGBA(0,   0,   255, 255);
7064 
7065 	const char addZeroToSc[]		= "OpIAdd %i32 %c_i32_0 %sc_op";
7066 	const char addZeroToSc32[]		= "OpIAdd %i32 %c_i32_0 %sc_op32";
7067 	const char selectTrueUsingSc[]	= "OpSelect %i32 %sc_op %c_i32_1 %c_i32_0";
7068 	const char selectFalseUsingSc[]	= "OpSelect %i32 %sc_op %c_i32_0 %c_i32_1";
7069 
7070 	cases.push_back(SpecConstantTwoIntGraphicsCase("iadd",					" %i32 0",		" %i32 0",		"%i32",		"IAdd                 %sc_0 %sc_1",				19,		-20,	addZeroToSc,		outputColors0));
7071 	cases.push_back(SpecConstantTwoIntGraphicsCase("isub",					" %i32 0",		" %i32 0",		"%i32",		"ISub                 %sc_0 %sc_1",				19,		20,		addZeroToSc,		outputColors0));
7072 	cases.push_back(SpecConstantTwoIntGraphicsCase("imul",					" %i32 0",		" %i32 0",		"%i32",		"IMul                 %sc_0 %sc_1",				-1,		-1,		addZeroToSc,		outputColors2));
7073 	cases.push_back(SpecConstantTwoIntGraphicsCase("sdiv",					" %i32 0",		" %i32 0",		"%i32",		"SDiv                 %sc_0 %sc_1",				-126,	126,	addZeroToSc,		outputColors0));
7074 	cases.push_back(SpecConstantTwoIntGraphicsCase("udiv",					" %i32 0",		" %i32 0",		"%i32",		"UDiv                 %sc_0 %sc_1",				126,	126,	addZeroToSc,		outputColors2));
7075 	cases.push_back(SpecConstantTwoIntGraphicsCase("srem",					" %i32 0",		" %i32 0",		"%i32",		"SRem                 %sc_0 %sc_1",				3,		2,		addZeroToSc,		outputColors2));
7076 	cases.push_back(SpecConstantTwoIntGraphicsCase("smod",					" %i32 0",		" %i32 0",		"%i32",		"SMod                 %sc_0 %sc_1",				3,		2,		addZeroToSc,		outputColors2));
7077 	cases.push_back(SpecConstantTwoIntGraphicsCase("umod",					" %i32 0",		" %i32 0",		"%i32",		"UMod                 %sc_0 %sc_1",				1001,	500,	addZeroToSc,		outputColors2));
7078 	cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseand",			" %i32 0",		" %i32 0",		"%i32",		"BitwiseAnd           %sc_0 %sc_1",				0x33,	0x0d,	addZeroToSc,		outputColors2));
7079 	cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseor",				" %i32 0",		" %i32 0",		"%i32",		"BitwiseOr            %sc_0 %sc_1",				0,		1,		addZeroToSc,		outputColors2));
7080 	cases.push_back(SpecConstantTwoIntGraphicsCase("bitwisexor",			" %i32 0",		" %i32 0",		"%i32",		"BitwiseXor           %sc_0 %sc_1",				0x2e,	0x2f,	addZeroToSc,		outputColors2));
7081 	cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightlogical",		" %i32 0",		" %i32 0",		"%i32",		"ShiftRightLogical    %sc_0 %sc_1",				2,		1,		addZeroToSc,		outputColors2));
7082 	cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightarithmetic",	" %i32 0",		" %i32 0",		"%i32",		"ShiftRightArithmetic %sc_0 %sc_1",				-4,		2,		addZeroToSc,		outputColors0));
7083 	cases.push_back(SpecConstantTwoIntGraphicsCase("shiftleftlogical",		" %i32 0",		" %i32 0",		"%i32",		"ShiftLeftLogical     %sc_0 %sc_1",				1,		0,		addZeroToSc,		outputColors2));
7084 	cases.push_back(SpecConstantTwoIntGraphicsCase("slessthan",				" %i32 0",		" %i32 0",		"%bool",	"SLessThan            %sc_0 %sc_1",				-20,	-10,	selectTrueUsingSc,	outputColors2));
7085 	cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthan",				" %i32 0",		" %i32 0",		"%bool",	"ULessThan            %sc_0 %sc_1",				10,		20,		selectTrueUsingSc,	outputColors2));
7086 	cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthan",			" %i32 0",		" %i32 0",		"%bool",	"SGreaterThan         %sc_0 %sc_1",				-1000,	50,		selectFalseUsingSc,	outputColors2));
7087 	cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthan",			" %i32 0",		" %i32 0",		"%bool",	"UGreaterThan         %sc_0 %sc_1",				10,		5,		selectTrueUsingSc,	outputColors2));
7088 	cases.push_back(SpecConstantTwoIntGraphicsCase("slessthanequal",		" %i32 0",		" %i32 0",		"%bool",	"SLessThanEqual       %sc_0 %sc_1",				-10,	-10,	selectTrueUsingSc,	outputColors2));
7089 	cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthanequal",		" %i32 0",		" %i32 0",		"%bool",	"ULessThanEqual       %sc_0 %sc_1",				50,		100,	selectTrueUsingSc,	outputColors2));
7090 	cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthanequal",		" %i32 0",		" %i32 0",		"%bool",	"SGreaterThanEqual    %sc_0 %sc_1",				-1000,	50,		selectFalseUsingSc,	outputColors2));
7091 	cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthanequal",		" %i32 0",		" %i32 0",		"%bool",	"UGreaterThanEqual    %sc_0 %sc_1",				10,		10,		selectTrueUsingSc,	outputColors2));
7092 	cases.push_back(SpecConstantTwoIntGraphicsCase("iequal",				" %i32 0",		" %i32 0",		"%bool",	"IEqual               %sc_0 %sc_1",				42,		24,		selectFalseUsingSc,	outputColors2));
7093 	cases.push_back(SpecConstantTwoIntGraphicsCase("inotequal",				" %i32 0",		" %i32 0",		"%bool",	"INotEqual            %sc_0 %sc_1",				42,		24,		selectTrueUsingSc,	outputColors2));
7094 	cases.push_back(SpecConstantTwoIntGraphicsCase("logicaland",			"True %bool",	"True %bool",	"%bool",	"LogicalAnd           %sc_0 %sc_1",				0,		1,		selectFalseUsingSc,	outputColors2));
7095 	cases.push_back(SpecConstantTwoIntGraphicsCase("logicalor",				"False %bool",	"False %bool",	"%bool",	"LogicalOr            %sc_0 %sc_1",				1,		0,		selectTrueUsingSc,	outputColors2));
7096 	cases.push_back(SpecConstantTwoIntGraphicsCase("logicalequal",			"True %bool",	"True %bool",	"%bool",	"LogicalEqual         %sc_0 %sc_1",				0,		1,		selectFalseUsingSc,	outputColors2));
7097 	cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnotequal",		"False %bool",	"False %bool",	"%bool",	"LogicalNotEqual      %sc_0 %sc_1",				1,		0,		selectTrueUsingSc,	outputColors2));
7098 	cases.push_back(SpecConstantTwoIntGraphicsCase("snegate",				" %i32 0",		" %i32 0",		"%i32",		"SNegate              %sc_0",					-1,		0,		addZeroToSc,		outputColors2));
7099 	cases.push_back(SpecConstantTwoIntGraphicsCase("not",					" %i32 0",		" %i32 0",		"%i32",		"Not                  %sc_0",					-2,		0,		addZeroToSc,		outputColors2));
7100 	cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnot",			"False %bool",	"False %bool",	"%bool",	"LogicalNot           %sc_0",					1,		0,		selectFalseUsingSc,	outputColors2));
7101 	cases.push_back(SpecConstantTwoIntGraphicsCase("select",				"False %bool",	" %i32 0",		"%i32",		"Select               %sc_0 %sc_1 %c_i32_0",	1,		1,		addZeroToSc,		outputColors2));
7102 	cases.push_back(SpecConstantTwoIntGraphicsCase("sconvert",				" %i32 0",		" %i32 0",		"%i16",		"SConvert             %sc_0",					-1,		0,		addZeroToSc32,		outputColors0));
7103 	// -1082130432 stored as 32-bit two's complement is the binary representation of -1 as IEEE-754 Float
7104 	cases.push_back(SpecConstantTwoIntGraphicsCase("fconvert",				" %f32 0",		" %f32 0",		"%f64",		"FConvert             %sc_0",					-1082130432, 0,	addZeroToSc32,		outputColors0));
7105 	cases.push_back(SpecConstantTwoIntGraphicsCase("fconvert16",			" %f16 0",		" %f16 0",		"%f32",		"FConvert             %sc_0",					m1AsFloat16, 0,	addZeroToSc32,		outputColors0, sizeof(deFloat16)));
7106 	// \todo[2015-12-1 antiagainst] OpQuantizeToF16
7107 
7108 	for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
7109 	{
7110 		map<string, string>			specializations;
7111 		map<string, string>			fragments;
7112 		SpecConstants				specConstants;
7113 		PushConstants				noPushConstants;
7114 		GraphicsResources			noResources;
7115 		GraphicsInterfaces			noInterfaces;
7116 		vector<string>				extensions;
7117 		VulkanFeatures				requiredFeatures;
7118 
7119 		// Special SPIR-V code for SConvert-case
7120 		if (strcmp(cases[caseNdx].caseName, "sconvert") == 0)
7121 		{
7122 			requiredFeatures.coreFeatures.shaderInt16 = VK_TRUE;
7123 			fragments["capability"]					= "OpCapability Int16\n";					// Adds 16-bit integer capability
7124 			specializations["OPTYPE_DEFINITIONS"]	= "%i16 = OpTypeInt 16 1\n";				// Adds 16-bit integer type
7125 			specializations["TYPE_CONVERT"]			= "%sc_op32 = OpSConvert %i32 %sc_op\n";	// Converts 16-bit integer to 32-bit integer
7126 		}
7127 
7128 		// Special SPIR-V code for FConvert-case
7129 		if (strcmp(cases[caseNdx].caseName, "fconvert") == 0)
7130 		{
7131 			requiredFeatures.coreFeatures.shaderFloat64 = VK_TRUE;
7132 			fragments["capability"]					= "OpCapability Float64\n";					// Adds 64-bit float capability
7133 			specializations["OPTYPE_DEFINITIONS"]	= "%f64 = OpTypeFloat 64\n";				// Adds 64-bit float type
7134 			specializations["TYPE_CONVERT"]			= "%sc_op32 = OpConvertFToS %i32 %sc_op\n";	// Converts 64-bit float to 32-bit integer
7135 		}
7136 
7137 		// Special SPIR-V code for FConvert-case for 16-bit floats
7138 		if (strcmp(cases[caseNdx].caseName, "fconvert16") == 0)
7139 		{
7140 			extensions.push_back("VK_KHR_shader_float16_int8");
7141 			requiredFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
7142 			fragments["capability"]					= "OpCapability Float16\n";					// Adds 16-bit float capability
7143 			specializations["OPTYPE_DEFINITIONS"]	= "%f16 = OpTypeFloat 16\n";				// Adds 16-bit float type
7144 			specializations["TYPE_CONVERT"]			= "%sc_op32 = OpConvertFToS %i32 %sc_op\n";	// Converts 16-bit float to 32-bit integer
7145 		}
7146 
7147 		specializations["SC_DEF0"]			= cases[caseNdx].scDefinition0;
7148 		specializations["SC_DEF1"]			= cases[caseNdx].scDefinition1;
7149 		specializations["SC_RESULT_TYPE"]	= cases[caseNdx].scResultType;
7150 		specializations["SC_OP"]			= cases[caseNdx].scOperation;
7151 		specializations["GEN_RESULT"]		= cases[caseNdx].resultOperation;
7152 
7153 		fragments["decoration"]				= tcu::StringTemplate(decorations1).specialize(specializations);
7154 		fragments["pre_main"]				= tcu::StringTemplate(typesAndConstants1).specialize(specializations);
7155 		fragments["testfun"]				= tcu::StringTemplate(function1).specialize(specializations);
7156 
7157 		specConstants.append(&cases[caseNdx].scActualValue0, cases[caseNdx].scActualValueLength);
7158 		specConstants.append(&cases[caseNdx].scActualValue1, cases[caseNdx].scActualValueLength);
7159 
7160 		createTestsForAllStages(
7161 			cases[caseNdx].caseName, inputColors, cases[caseNdx].expectedColors, fragments, specConstants,
7162 			noPushConstants, noResources, noInterfaces, extensions, requiredFeatures, group.get());
7163 	}
7164 
7165 	const char	decorations2[]			=
7166 		"OpDecorate %sc_0  SpecId 0\n"
7167 		"OpDecorate %sc_1  SpecId 1\n"
7168 		"OpDecorate %sc_2  SpecId 2\n";
7169 
7170 	const char	typesAndConstants2[]	=
7171 		"%vec3_0      = OpConstantComposite %v3i32 %c_i32_0 %c_i32_0 %c_i32_0\n"
7172 		"%vec3_undef  = OpUndef %v3i32\n"
7173 
7174 		"%sc_0        = OpSpecConstant %i32 0\n"
7175 		"%sc_1        = OpSpecConstant %i32 0\n"
7176 		"%sc_2        = OpSpecConstant %i32 0\n"
7177 		"%sc_vec3_0   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_0        %vec3_0      0\n"							// (sc_0, 0,    0)
7178 		"%sc_vec3_1   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_1        %vec3_0      1\n"							// (0,    sc_1, 0)
7179 		"%sc_vec3_2   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_2        %vec3_0      2\n"							// (0,    0,    sc_2)
7180 		"%sc_vec3_0_s = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_0   %vec3_undef  0          0xFFFFFFFF 2\n"	// (sc_0, ???,  0)
7181 		"%sc_vec3_1_s = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_1   %vec3_undef  0xFFFFFFFF 1          0\n"	// (???,  sc_1, 0)
7182 		"%sc_vec3_2_s = OpSpecConstantOp %v3i32 VectorShuffle    %vec3_undef  %sc_vec3_2   5          0xFFFFFFFF 5\n"	// (sc_2, ???,  sc_2)
7183 		"%sc_vec3_01  = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_0_s %sc_vec3_1_s 1 0 4\n"						// (0,    sc_0, sc_1)
7184 		"%sc_vec3_012 = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_01  %sc_vec3_2_s 5 1 2\n"						// (sc_2, sc_0, sc_1)
7185 		"%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              0\n"							// sc_2
7186 		"%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              1\n"							// sc_0
7187 		"%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              2\n"							// sc_1
7188 		"%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"								// (sc_2 - sc_0)
7189 		"%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n";								// (sc_2 - sc_0) * sc_1
7190 
7191 	const char	function2[]				=
7192 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7193 		"%param     = OpFunctionParameter %v4f32\n"
7194 		"%label     = OpLabel\n"
7195 		"%result    = OpVariable %fp_v4f32 Function\n"
7196 		"             OpStore %result %param\n"
7197 		"%loc       = OpAccessChain %fp_f32 %result %sc_final\n"
7198 		"%val       = OpLoad %f32 %loc\n"
7199 		"%add       = OpFAdd %f32 %val %c_f32_0_5\n"
7200 		"             OpStore %loc %add\n"
7201 		"%ret       = OpLoad %v4f32 %result\n"
7202 		"             OpReturnValue %ret\n"
7203 		"             OpFunctionEnd\n";
7204 
7205 	map<string, string>	fragments;
7206 	SpecConstants		specConstants;
7207 
7208 	fragments["decoration"]	= decorations2;
7209 	fragments["pre_main"]	= typesAndConstants2;
7210 	fragments["testfun"]	= function2;
7211 
7212 	specConstants.append<deInt32>(56789);
7213 	specConstants.append<deInt32>(-2);
7214 	specConstants.append<deInt32>(56788);
7215 
7216 	createTestsForAllStages("vector_related", inputColors, outputColors2, fragments, specConstants, group.get());
7217 
7218 	return group.release();
7219 }
7220 
createOpPhiTests(tcu::TestContext & testCtx)7221 tcu::TestCaseGroup* createOpPhiTests(tcu::TestContext& testCtx)
7222 {
7223 	de::MovePtr<tcu::TestCaseGroup> group				(new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
7224 	RGBA							inputColors[4];
7225 	RGBA							outputColors1[4];
7226 	RGBA							outputColors2[4];
7227 	RGBA							outputColors3[4];
7228 	RGBA							outputColors4[4];
7229 	map<string, string>				fragments1;
7230 	map<string, string>				fragments2;
7231 	map<string, string>				fragments3;
7232 	map<string, string>				fragments4;
7233 	std::vector<std::string>		extensions4;
7234 	GraphicsResources				resources4;
7235 	VulkanFeatures					vulkanFeatures4;
7236 
7237 	const char	typesAndConstants1[]	=
7238 		"%c_f32_p2  = OpConstant %f32 0.2\n"
7239 		"%c_f32_p4  = OpConstant %f32 0.4\n"
7240 		"%c_f32_p5  = OpConstant %f32 0.5\n"
7241 		"%c_f32_p8  = OpConstant %f32 0.8\n";
7242 
7243 	// vec4 test_code(vec4 param) {
7244 	//   vec4 result = param;
7245 	//   for (int i = 0; i < 4; ++i) {
7246 	//     float operand;
7247 	//     switch (i) {
7248 	//       case 0: operand = .2; break;
7249 	//       case 1: operand = .5; break;
7250 	//       case 2: operand = .4; break;
7251 	//       case 3: operand = .0; break;
7252 	//       default: break; // unreachable
7253 	//     }
7254 	//     result[i] += operand;
7255 	//   }
7256 	//   return result;
7257 	// }
7258 	const char	function1[]				=
7259 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7260 		"%param1    = OpFunctionParameter %v4f32\n"
7261 		"%lbl       = OpLabel\n"
7262 		"%iptr      = OpVariable %fp_i32 Function\n"
7263 		"%result    = OpVariable %fp_v4f32 Function\n"
7264 		"             OpStore %iptr %c_i32_0\n"
7265 		"             OpStore %result %param1\n"
7266 		"             OpBranch %loop\n"
7267 
7268 		"%loop      = OpLabel\n"
7269 		"%ival      = OpLoad %i32 %iptr\n"
7270 		"%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
7271 		"             OpLoopMerge %exit %phi None\n"
7272 		"             OpBranchConditional %lt_4 %entry %exit\n"
7273 
7274 		"%entry     = OpLabel\n"
7275 		"%loc       = OpAccessChain %fp_f32 %result %ival\n"
7276 		"%val       = OpLoad %f32 %loc\n"
7277 		"             OpSelectionMerge %phi None\n"
7278 		"             OpSwitch %ival %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
7279 
7280 		"%case0     = OpLabel\n"
7281 		"             OpBranch %phi\n"
7282 		"%case1     = OpLabel\n"
7283 		"             OpBranch %phi\n"
7284 		"%case2     = OpLabel\n"
7285 		"             OpBranch %phi\n"
7286 		"%case3     = OpLabel\n"
7287 		"             OpBranch %phi\n"
7288 
7289 		"%default   = OpLabel\n"
7290 		"             OpUnreachable\n"
7291 
7292 		"%phi       = OpLabel\n"
7293 		"%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
7294 		"%add       = OpFAdd %f32 %val %operand\n"
7295 		"             OpStore %loc %add\n"
7296 		"%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
7297 		"             OpStore %iptr %ival_next\n"
7298 		"             OpBranch %loop\n"
7299 
7300 		"%exit      = OpLabel\n"
7301 		"%ret       = OpLoad %v4f32 %result\n"
7302 		"             OpReturnValue %ret\n"
7303 
7304 		"             OpFunctionEnd\n";
7305 
7306 	fragments1["pre_main"]	= typesAndConstants1;
7307 	fragments1["testfun"]	= function1;
7308 
7309 	getHalfColorsFullAlpha(inputColors);
7310 
7311 	outputColors1[0]		= RGBA(178, 255, 229, 255);
7312 	outputColors1[1]		= RGBA(178, 127, 102, 255);
7313 	outputColors1[2]		= RGBA(51,  255, 102, 255);
7314 	outputColors1[3]		= RGBA(51,  127, 229, 255);
7315 
7316 	createTestsForAllStages("out_of_order", inputColors, outputColors1, fragments1, group.get());
7317 
7318 	const char	typesAndConstants2[]	=
7319 		"%c_f32_p2  = OpConstant %f32 0.2\n";
7320 
7321 	// Add .4 to the second element of the given parameter.
7322 	const char	function2[]				=
7323 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7324 		"%param     = OpFunctionParameter %v4f32\n"
7325 		"%entry     = OpLabel\n"
7326 		"%result    = OpVariable %fp_v4f32 Function\n"
7327 		"             OpStore %result %param\n"
7328 		"%loc       = OpAccessChain %fp_f32 %result %c_i32_1\n"
7329 		"%val       = OpLoad %f32 %loc\n"
7330 		"             OpBranch %phi\n"
7331 
7332 		"%phi        = OpLabel\n"
7333 		"%step       = OpPhi %i32 %c_i32_0  %entry %step_next  %phi\n"
7334 		"%accum      = OpPhi %f32 %val      %entry %accum_next %phi\n"
7335 		"%step_next  = OpIAdd %i32 %step  %c_i32_1\n"
7336 		"%accum_next = OpFAdd %f32 %accum %c_f32_p2\n"
7337 		"%still_loop = OpSLessThan %bool %step %c_i32_2\n"
7338 		"              OpLoopMerge %exit %phi None\n"
7339 		"              OpBranchConditional %still_loop %phi %exit\n"
7340 
7341 		"%exit       = OpLabel\n"
7342 		"              OpStore %loc %accum\n"
7343 		"%ret        = OpLoad %v4f32 %result\n"
7344 		"              OpReturnValue %ret\n"
7345 
7346 		"              OpFunctionEnd\n";
7347 
7348 	fragments2["pre_main"]	= typesAndConstants2;
7349 	fragments2["testfun"]	= function2;
7350 
7351 	outputColors2[0]			= RGBA(127, 229, 127, 255);
7352 	outputColors2[1]			= RGBA(127, 102, 0,   255);
7353 	outputColors2[2]			= RGBA(0,   229, 0,   255);
7354 	outputColors2[3]			= RGBA(0,   102, 127, 255);
7355 
7356 	createTestsForAllStages("induction", inputColors, outputColors2, fragments2, group.get());
7357 
7358 	const char	typesAndConstants3[]	=
7359 		"%true      = OpConstantTrue %bool\n"
7360 		"%false     = OpConstantFalse %bool\n"
7361 		"%c_f32_p2  = OpConstant %f32 0.2\n";
7362 
7363 	// Swap the second and the third element of the given parameter.
7364 	const char	function3[]				=
7365 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7366 		"%param     = OpFunctionParameter %v4f32\n"
7367 		"%entry     = OpLabel\n"
7368 		"%result    = OpVariable %fp_v4f32 Function\n"
7369 		"             OpStore %result %param\n"
7370 		"%a_loc     = OpAccessChain %fp_f32 %result %c_i32_1\n"
7371 		"%a_init    = OpLoad %f32 %a_loc\n"
7372 		"%b_loc     = OpAccessChain %fp_f32 %result %c_i32_2\n"
7373 		"%b_init    = OpLoad %f32 %b_loc\n"
7374 		"             OpBranch %phi\n"
7375 
7376 		"%phi        = OpLabel\n"
7377 		"%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
7378 		"%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
7379 		"%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
7380 		"              OpLoopMerge %exit %phi None\n"
7381 		"              OpBranchConditional %still_loop %phi %exit\n"
7382 
7383 		"%exit       = OpLabel\n"
7384 		"              OpStore %a_loc %a_next\n"
7385 		"              OpStore %b_loc %b_next\n"
7386 		"%ret        = OpLoad %v4f32 %result\n"
7387 		"              OpReturnValue %ret\n"
7388 
7389 		"              OpFunctionEnd\n";
7390 
7391 	fragments3["pre_main"]	= typesAndConstants3;
7392 	fragments3["testfun"]	= function3;
7393 
7394 	outputColors3[0]			= RGBA(127, 127, 127, 255);
7395 	outputColors3[1]			= RGBA(127, 0,   0,   255);
7396 	outputColors3[2]			= RGBA(0,   0,   127, 255);
7397 	outputColors3[3]			= RGBA(0,   127, 0,   255);
7398 
7399 	createTestsForAllStages("swap", inputColors, outputColors3, fragments3, group.get());
7400 
7401 	const char	typesAndConstants4[]	=
7402 		"%f16        = OpTypeFloat 16\n"
7403 		"%v4f16      = OpTypeVector %f16 4\n"
7404 		"%fp_f16     = OpTypePointer Function %f16\n"
7405 		"%fp_v4f16   = OpTypePointer Function %v4f16\n"
7406 		"%true       = OpConstantTrue %bool\n"
7407 		"%false      = OpConstantFalse %bool\n"
7408 		"%c_f32_p2   = OpConstant %f32 0.2\n";
7409 
7410 	// Swap the second and the third element of the given parameter.
7411 	const char	function4[]				=
7412 		"%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7413 		"%param      = OpFunctionParameter %v4f32\n"
7414 		"%entry      = OpLabel\n"
7415 		"%result     = OpVariable %fp_v4f16 Function\n"
7416 		"%param16    = OpFConvert %v4f16 %param\n"
7417 		"              OpStore %result %param16\n"
7418 		"%a_loc      = OpAccessChain %fp_f16 %result %c_i32_1\n"
7419 		"%a_init     = OpLoad %f16 %a_loc\n"
7420 		"%b_loc      = OpAccessChain %fp_f16 %result %c_i32_2\n"
7421 		"%b_init     = OpLoad %f16 %b_loc\n"
7422 		"              OpBranch %phi\n"
7423 
7424 		"%phi        = OpLabel\n"
7425 		"%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
7426 		"%a_next     = OpPhi %f16  %a_init %entry %b_next %phi\n"
7427 		"%b_next     = OpPhi %f16  %b_init %entry %a_next %phi\n"
7428 		"              OpLoopMerge %exit %phi None\n"
7429 		"              OpBranchConditional %still_loop %phi %exit\n"
7430 
7431 		"%exit       = OpLabel\n"
7432 		"              OpStore %a_loc %a_next\n"
7433 		"              OpStore %b_loc %b_next\n"
7434 		"%ret16      = OpLoad %v4f16 %result\n"
7435 		"%ret        = OpFConvert %v4f32 %ret16\n"
7436 		"              OpReturnValue %ret\n"
7437 
7438 		"              OpFunctionEnd\n";
7439 
7440 	fragments4["pre_main"]		= typesAndConstants4;
7441 	fragments4["testfun"]		= function4;
7442 	fragments4["capability"]	= "OpCapability StorageUniformBufferBlock16\n";
7443 	fragments4["extension"]		= "OpExtension \"SPV_KHR_16bit_storage\"";
7444 
7445 	extensions4.push_back("VK_KHR_16bit_storage");
7446 	extensions4.push_back("VK_KHR_shader_float16_int8");
7447 
7448 	vulkanFeatures4.ext16BitStorage	= EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
7449 	vulkanFeatures4.extFloat16Int8	= EXTFLOAT16INT8FEATURES_FLOAT16;
7450 
7451 	outputColors4[0]			= RGBA(127, 127, 127, 255);
7452 	outputColors4[1]			= RGBA(127, 0,   0,   255);
7453 	outputColors4[2]			= RGBA(0,   0,   127, 255);
7454 	outputColors4[3]			= RGBA(0,   127, 0,   255);
7455 
7456 	createTestsForAllStages("swap16", inputColors, outputColors4, fragments4, resources4, extensions4, group.get(), vulkanFeatures4);
7457 
7458 	return group.release();
7459 }
7460 
createNoContractionTests(tcu::TestContext & testCtx)7461 tcu::TestCaseGroup* createNoContractionTests(tcu::TestContext& testCtx)
7462 {
7463 	de::MovePtr<tcu::TestCaseGroup> group			(new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
7464 	RGBA							inputColors[4];
7465 	RGBA							outputColors[4];
7466 
7467 	// With NoContraction, (1 + 2^-23) * (1 - 2^-23) - 1 should be conducted as a multiplication and an addition separately.
7468 	// For the multiplication, the result is 1 - 2^-46, which is out of the precision range for 32-bit float. (32-bit float
7469 	// only have 23-bit fraction.) So it will be rounded to 1. Or 0x1.fffffc. Then the final result is 0 or -0x1p-24.
7470 	// On the contrary, the result will be 2^-46, which is a normalized number perfectly representable as 32-bit float.
7471 	const char						constantsAndTypes[]	 =
7472 		"%c_vec4_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_0 %c_f32_1\n"
7473 		"%c_vec4_1       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
7474 		"%c_f32_1pl2_23  = OpConstant %f32 0x1.000002p+0\n" // 1 + 2^-23
7475 		"%c_f32_1mi2_23  = OpConstant %f32 0x1.fffffcp-1\n" // 1 - 2^-23
7476 		"%c_f32_n1pn24   = OpConstant %f32 -0x1p-24\n";
7477 
7478 	const char						function[]	 =
7479 		"%test_code      = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7480 		"%param          = OpFunctionParameter %v4f32\n"
7481 		"%label          = OpLabel\n"
7482 		"%var1           = OpVariable %fp_f32 Function %c_f32_1pl2_23\n"
7483 		"%var2           = OpVariable %fp_f32 Function\n"
7484 		"%red            = OpCompositeExtract %f32 %param 0\n"
7485 		"%plus_red       = OpFAdd %f32 %c_f32_1mi2_23 %red\n"
7486 		"                  OpStore %var2 %plus_red\n"
7487 		"%val1           = OpLoad %f32 %var1\n"
7488 		"%val2           = OpLoad %f32 %var2\n"
7489 		"%mul            = OpFMul %f32 %val1 %val2\n"
7490 		"%add            = OpFAdd %f32 %mul %c_f32_n1\n"
7491 		"%is0            = OpFOrdEqual %bool %add %c_f32_0\n"
7492 		"%isn1n24         = OpFOrdEqual %bool %add %c_f32_n1pn24\n"
7493 		"%success        = OpLogicalOr %bool %is0 %isn1n24\n"
7494 		"%v4success      = OpCompositeConstruct %v4bool %success %success %success %success\n"
7495 		"%ret            = OpSelect %v4f32 %v4success %c_vec4_0 %c_vec4_1\n"
7496 		"                  OpReturnValue %ret\n"
7497 		"                  OpFunctionEnd\n";
7498 
7499 	struct CaseNameDecoration
7500 	{
7501 		string name;
7502 		string decoration;
7503 	};
7504 
7505 
7506 	CaseNameDecoration tests[] = {
7507 		{"multiplication",	"OpDecorate %mul NoContraction"},
7508 		{"addition",		"OpDecorate %add NoContraction"},
7509 		{"both",			"OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"},
7510 	};
7511 
7512 	getHalfColorsFullAlpha(inputColors);
7513 
7514 	for (deUint8 idx = 0; idx < 4; ++idx)
7515 	{
7516 		inputColors[idx].setRed(0);
7517 		outputColors[idx] = RGBA(0, 0, 0, 255);
7518 	}
7519 
7520 	for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(CaseNameDecoration); ++testNdx)
7521 	{
7522 		map<string, string> fragments;
7523 
7524 		fragments["decoration"] = tests[testNdx].decoration;
7525 		fragments["pre_main"] = constantsAndTypes;
7526 		fragments["testfun"] = function;
7527 
7528 		createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, group.get());
7529 	}
7530 
7531 	return group.release();
7532 }
7533 
createMemoryAccessTests(tcu::TestContext & testCtx)7534 tcu::TestCaseGroup* createMemoryAccessTests(tcu::TestContext& testCtx)
7535 {
7536 	de::MovePtr<tcu::TestCaseGroup> memoryAccessTests (new tcu::TestCaseGroup(testCtx, "opmemoryaccess", "Memory Semantics"));
7537 	RGBA							colors[4];
7538 
7539 	const char						constantsAndTypes[]	 =
7540 		"%c_a2f32_1         = OpConstantComposite %a2f32 %c_f32_1 %c_f32_1\n"
7541 		"%fp_a2f32          = OpTypePointer Function %a2f32\n"
7542 		"%stype             = OpTypeStruct  %v4f32 %a2f32 %f32\n"
7543 		"%fp_stype          = OpTypePointer Function %stype\n";
7544 
7545 	const char						function[]	 =
7546 		"%test_code         = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7547 		"%param1            = OpFunctionParameter %v4f32\n"
7548 		"%lbl               = OpLabel\n"
7549 		"%v1                = OpVariable %fp_v4f32 Function\n"
7550 		"%v2                = OpVariable %fp_a2f32 Function\n"
7551 		"%v3                = OpVariable %fp_f32 Function\n"
7552 		"%v                 = OpVariable %fp_stype Function\n"
7553 		"%vv                = OpVariable %fp_stype Function\n"
7554 		"%vvv               = OpVariable %fp_f32 Function\n"
7555 
7556 		"                     OpStore %v1 %c_v4f32_1_1_1_1\n"
7557 		"                     OpStore %v2 %c_a2f32_1\n"
7558 		"                     OpStore %v3 %c_f32_1\n"
7559 
7560 		"%p_v4f32          = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
7561 		"%p_a2f32          = OpAccessChain %fp_a2f32 %v %c_u32_1\n"
7562 		"%p_f32            = OpAccessChain %fp_f32 %v %c_u32_2\n"
7563 		"%v1_v             = OpLoad %v4f32 %v1 ${access_type}\n"
7564 		"%v2_v             = OpLoad %a2f32 %v2 ${access_type}\n"
7565 		"%v3_v             = OpLoad %f32 %v3 ${access_type}\n"
7566 
7567 		"                    OpStore %p_v4f32 %v1_v ${access_type}\n"
7568 		"                    OpStore %p_a2f32 %v2_v ${access_type}\n"
7569 		"                    OpStore %p_f32 %v3_v ${access_type}\n"
7570 
7571 		"                    OpCopyMemory %vv %v ${access_type}\n"
7572 		"                    OpCopyMemory %vvv %p_f32 ${access_type}\n"
7573 
7574 		"%p_f32_2          = OpAccessChain %fp_f32 %vv %c_u32_2\n"
7575 		"%v_f32_2          = OpLoad %f32 %p_f32_2\n"
7576 		"%v_f32_3          = OpLoad %f32 %vvv\n"
7577 
7578 		"%ret1             = OpVectorTimesScalar %v4f32 %param1 %v_f32_2\n"
7579 		"%ret2             = OpVectorTimesScalar %v4f32 %ret1 %v_f32_3\n"
7580 		"                    OpReturnValue %ret2\n"
7581 		"                    OpFunctionEnd\n";
7582 
7583 	struct NameMemoryAccess
7584 	{
7585 		string name;
7586 		string accessType;
7587 	};
7588 
7589 
7590 	NameMemoryAccess tests[] =
7591 	{
7592 		{ "none", "" },
7593 		{ "volatile", "Volatile" },
7594 		{ "aligned",  "Aligned 1" },
7595 		{ "volatile_aligned",  "Volatile|Aligned 1" },
7596 		{ "nontemporal_aligned",  "Nontemporal|Aligned 1" },
7597 		{ "volatile_nontemporal",  "Volatile|Nontemporal" },
7598 		{ "volatile_nontermporal_aligned",  "Volatile|Nontemporal|Aligned 1" },
7599 	};
7600 
7601 	getHalfColorsFullAlpha(colors);
7602 
7603 	for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameMemoryAccess); ++testNdx)
7604 	{
7605 		map<string, string> fragments;
7606 		map<string, string> memoryAccess;
7607 		memoryAccess["access_type"] = tests[testNdx].accessType;
7608 
7609 		fragments["pre_main"] = constantsAndTypes;
7610 		fragments["testfun"] = tcu::StringTemplate(function).specialize(memoryAccess);
7611 		createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, memoryAccessTests.get());
7612 	}
7613 	return memoryAccessTests.release();
7614 }
createOpUndefTests(tcu::TestContext & testCtx)7615 tcu::TestCaseGroup* createOpUndefTests(tcu::TestContext& testCtx)
7616 {
7617 	de::MovePtr<tcu::TestCaseGroup>		opUndefTests		 (new tcu::TestCaseGroup(testCtx, "opundef", "Test OpUndef"));
7618 	RGBA								defaultColors[4];
7619 	map<string, string>					fragments;
7620 	getDefaultColors(defaultColors);
7621 
7622 	// First, simple cases that don't do anything with the OpUndef result.
7623 	struct NameCodePair { string name, decl, type; };
7624 	const NameCodePair tests[] =
7625 	{
7626 		{"bool", "", "%bool"},
7627 		{"vec2uint32", "", "%v2u32"},
7628 		{"image", "%type = OpTypeImage %f32 2D 0 0 0 1 Unknown", "%type"},
7629 		{"sampler", "%type = OpTypeSampler", "%type"},
7630 		{"sampledimage", "%img = OpTypeImage %f32 2D 0 0 0 1 Unknown\n" "%type = OpTypeSampledImage %img", "%type"},
7631 		{"pointer", "", "%fp_i32"},
7632 		{"runtimearray", "%type = OpTypeRuntimeArray %f32", "%type"},
7633 		{"array", "%c_u32_100 = OpConstant %u32 100\n" "%type = OpTypeArray %i32 %c_u32_100", "%type"},
7634 		{"struct", "%type = OpTypeStruct %f32 %i32 %u32", "%type"}};
7635 	for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
7636 	{
7637 		fragments["undef_type"] = tests[testNdx].type;
7638 		fragments["testfun"] = StringTemplate(
7639 			"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7640 			"%param1 = OpFunctionParameter %v4f32\n"
7641 			"%label_testfun = OpLabel\n"
7642 			"%undef = OpUndef ${undef_type}\n"
7643 			"OpReturnValue %param1\n"
7644 			"OpFunctionEnd\n").specialize(fragments);
7645 		fragments["pre_main"] = tests[testNdx].decl;
7646 		createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opUndefTests.get());
7647 	}
7648 	fragments.clear();
7649 
7650 	fragments["testfun"] =
7651 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7652 		"%param1 = OpFunctionParameter %v4f32\n"
7653 		"%label_testfun = OpLabel\n"
7654 		"%undef = OpUndef %f32\n"
7655 		"%zero = OpFMul %f32 %undef %c_f32_0\n"
7656 		"%is_nan = OpIsNan %bool %zero\n" //OpUndef may result in NaN which may turn %zero into Nan.
7657 		"%actually_zero = OpSelect %f32 %is_nan %c_f32_0 %zero\n"
7658 		"%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7659 		"%b = OpFAdd %f32 %a %actually_zero\n"
7660 		"%ret = OpVectorInsertDynamic %v4f32 %param1 %b %c_i32_0\n"
7661 		"OpReturnValue %ret\n"
7662 		"OpFunctionEnd\n";
7663 
7664 	createTestsForAllStages("float32", defaultColors, defaultColors, fragments, opUndefTests.get());
7665 
7666 	fragments["testfun"] =
7667 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7668 		"%param1 = OpFunctionParameter %v4f32\n"
7669 		"%label_testfun = OpLabel\n"
7670 		"%undef = OpUndef %i32\n"
7671 		"%zero = OpIMul %i32 %undef %c_i32_0\n"
7672 		"%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
7673 		"%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
7674 		"OpReturnValue %ret\n"
7675 		"OpFunctionEnd\n";
7676 
7677 	createTestsForAllStages("sint32", defaultColors, defaultColors, fragments, opUndefTests.get());
7678 
7679 	fragments["testfun"] =
7680 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7681 		"%param1 = OpFunctionParameter %v4f32\n"
7682 		"%label_testfun = OpLabel\n"
7683 		"%undef = OpUndef %u32\n"
7684 		"%zero = OpIMul %u32 %undef %c_i32_0\n"
7685 		"%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
7686 		"%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
7687 		"OpReturnValue %ret\n"
7688 		"OpFunctionEnd\n";
7689 
7690 	createTestsForAllStages("uint32", defaultColors, defaultColors, fragments, opUndefTests.get());
7691 
7692 	fragments["testfun"] =
7693 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7694 		"%param1 = OpFunctionParameter %v4f32\n"
7695 		"%label_testfun = OpLabel\n"
7696 		"%undef = OpUndef %v4f32\n"
7697 		"%vzero = OpVectorTimesScalar %v4f32 %undef %c_f32_0\n"
7698 		"%zero_0 = OpVectorExtractDynamic %f32 %vzero %c_i32_0\n"
7699 		"%zero_1 = OpVectorExtractDynamic %f32 %vzero %c_i32_1\n"
7700 		"%zero_2 = OpVectorExtractDynamic %f32 %vzero %c_i32_2\n"
7701 		"%zero_3 = OpVectorExtractDynamic %f32 %vzero %c_i32_3\n"
7702 		"%is_nan_0 = OpIsNan %bool %zero_0\n"
7703 		"%is_nan_1 = OpIsNan %bool %zero_1\n"
7704 		"%is_nan_2 = OpIsNan %bool %zero_2\n"
7705 		"%is_nan_3 = OpIsNan %bool %zero_3\n"
7706 		"%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
7707 		"%actually_zero_1 = OpSelect %f32 %is_nan_1 %c_f32_0 %zero_1\n"
7708 		"%actually_zero_2 = OpSelect %f32 %is_nan_2 %c_f32_0 %zero_2\n"
7709 		"%actually_zero_3 = OpSelect %f32 %is_nan_3 %c_f32_0 %zero_3\n"
7710 		"%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7711 		"%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
7712 		"%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
7713 		"%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
7714 		"%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
7715 		"%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
7716 		"%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
7717 		"%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
7718 		"%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
7719 		"%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
7720 		"%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
7721 		"%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
7722 		"OpReturnValue %ret\n"
7723 		"OpFunctionEnd\n";
7724 
7725 	createTestsForAllStages("vec4float32", defaultColors, defaultColors, fragments, opUndefTests.get());
7726 
7727 	fragments["pre_main"] =
7728 		"%m2x2f32 = OpTypeMatrix %v2f32 2\n";
7729 	fragments["testfun"] =
7730 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7731 		"%param1 = OpFunctionParameter %v4f32\n"
7732 		"%label_testfun = OpLabel\n"
7733 		"%undef = OpUndef %m2x2f32\n"
7734 		"%mzero = OpMatrixTimesScalar %m2x2f32 %undef %c_f32_0\n"
7735 		"%zero_0 = OpCompositeExtract %f32 %mzero 0 0\n"
7736 		"%zero_1 = OpCompositeExtract %f32 %mzero 0 1\n"
7737 		"%zero_2 = OpCompositeExtract %f32 %mzero 1 0\n"
7738 		"%zero_3 = OpCompositeExtract %f32 %mzero 1 1\n"
7739 		"%is_nan_0 = OpIsNan %bool %zero_0\n"
7740 		"%is_nan_1 = OpIsNan %bool %zero_1\n"
7741 		"%is_nan_2 = OpIsNan %bool %zero_2\n"
7742 		"%is_nan_3 = OpIsNan %bool %zero_3\n"
7743 		"%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
7744 		"%actually_zero_1 = OpSelect %f32 %is_nan_1 %c_f32_0 %zero_1\n"
7745 		"%actually_zero_2 = OpSelect %f32 %is_nan_2 %c_f32_0 %zero_2\n"
7746 		"%actually_zero_3 = OpSelect %f32 %is_nan_3 %c_f32_0 %zero_3\n"
7747 		"%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7748 		"%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
7749 		"%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
7750 		"%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
7751 		"%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
7752 		"%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
7753 		"%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
7754 		"%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
7755 		"%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
7756 		"%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
7757 		"%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
7758 		"%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
7759 		"OpReturnValue %ret\n"
7760 		"OpFunctionEnd\n";
7761 
7762 	createTestsForAllStages("matrix", defaultColors, defaultColors, fragments, opUndefTests.get());
7763 
7764 	return opUndefTests.release();
7765 }
7766 
createOpQuantizeSingleOptionTests(tcu::TestCaseGroup * testCtx)7767 void createOpQuantizeSingleOptionTests(tcu::TestCaseGroup* testCtx)
7768 {
7769 	const RGBA		inputColors[4]		=
7770 	{
7771 		RGBA(0,		0,		0,		255),
7772 		RGBA(0,		0,		255,	255),
7773 		RGBA(0,		255,	0,		255),
7774 		RGBA(0,		255,	255,	255)
7775 	};
7776 
7777 	const RGBA		expectedColors[4]	=
7778 	{
7779 		RGBA(255,	 0,		 0,		 255),
7780 		RGBA(255,	 0,		 0,		 255),
7781 		RGBA(255,	 0,		 0,		 255),
7782 		RGBA(255,	 0,		 0,		 255)
7783 	};
7784 
7785 	const struct SingleFP16Possibility
7786 	{
7787 		const char* name;
7788 		const char* constant;  // Value to assign to %test_constant.
7789 		float		valueAsFloat;
7790 		const char* condition; // Must assign to %cond an expression that evaluates to true after %c = OpQuantizeToF16(%test_constant + 0).
7791 	}				tests[]				=
7792 	{
7793 		{
7794 			"negative",
7795 			"-0x1.3p1\n",
7796 			-constructNormalizedFloat(1, 0x300000),
7797 			"%cond = OpFOrdEqual %bool %c %test_constant\n"
7798 		}, // -19
7799 		{
7800 			"positive",
7801 			"0x1.0p7\n",
7802 			constructNormalizedFloat(7, 0x000000),
7803 			"%cond = OpFOrdEqual %bool %c %test_constant\n"
7804 		},  // +128
7805 		// SPIR-V requires that OpQuantizeToF16 flushes
7806 		// any numbers that would end up denormalized in F16 to zero.
7807 		{
7808 			"denorm",
7809 			"0x0.0006p-126\n",
7810 			std::ldexp(1.5f, -140),
7811 			"%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7812 		},  // denorm
7813 		{
7814 			"negative_denorm",
7815 			"-0x0.0006p-126\n",
7816 			-std::ldexp(1.5f, -140),
7817 			"%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7818 		}, // -denorm
7819 		{
7820 			"too_small",
7821 			"0x1.0p-16\n",
7822 			std::ldexp(1.0f, -16),
7823 			"%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7824 		},     // too small positive
7825 		{
7826 			"negative_too_small",
7827 			"-0x1.0p-32\n",
7828 			-std::ldexp(1.0f, -32),
7829 			"%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7830 		},      // too small negative
7831 		{
7832 			"negative_inf",
7833 			"-0x1.0p128\n",
7834 			-std::ldexp(1.0f, 128),
7835 
7836 			"%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
7837 			"%inf = OpIsInf %bool %c\n"
7838 			"%cond = OpLogicalAnd %bool %gz %inf\n"
7839 		},     // -inf to -inf
7840 		{
7841 			"inf",
7842 			"0x1.0p128\n",
7843 			std::ldexp(1.0f, 128),
7844 
7845 			"%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
7846 			"%inf = OpIsInf %bool %c\n"
7847 			"%cond = OpLogicalAnd %bool %gz %inf\n"
7848 		},     // +inf to +inf
7849 		{
7850 			"round_to_negative_inf",
7851 			"-0x1.0p32\n",
7852 			-std::ldexp(1.0f, 32),
7853 
7854 			"%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
7855 			"%inf = OpIsInf %bool %c\n"
7856 			"%cond = OpLogicalAnd %bool %gz %inf\n"
7857 		},     // round to -inf
7858 		{
7859 			"round_to_inf",
7860 			"0x1.0p16\n",
7861 			std::ldexp(1.0f, 16),
7862 
7863 			"%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
7864 			"%inf = OpIsInf %bool %c\n"
7865 			"%cond = OpLogicalAnd %bool %gz %inf\n"
7866 		},     // round to +inf
7867 		{
7868 			"nan",
7869 			"0x1.1p128\n",
7870 			std::numeric_limits<float>::quiet_NaN(),
7871 
7872 			// Test for any NaN value, as NaNs are not preserved
7873 			"%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
7874 			"%cond = OpIsNan %bool %direct_quant\n"
7875 		}, // nan
7876 		{
7877 			"negative_nan",
7878 			"-0x1.0001p128\n",
7879 			std::numeric_limits<float>::quiet_NaN(),
7880 
7881 			// Test for any NaN value, as NaNs are not preserved
7882 			"%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
7883 			"%cond = OpIsNan %bool %direct_quant\n"
7884 		} // -nan
7885 	};
7886 	const char*		constants			=
7887 		"%test_constant = OpConstant %f32 ";  // The value will be test.constant.
7888 
7889 	StringTemplate	function			(
7890 		"%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7891 		"%param1        = OpFunctionParameter %v4f32\n"
7892 		"%label_testfun = OpLabel\n"
7893 		"%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7894 		"%b             = OpFAdd %f32 %test_constant %a\n"
7895 		"%c             = OpQuantizeToF16 %f32 %b\n"
7896 		"${condition}\n"
7897 		"%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
7898 		"%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
7899 		"                 OpReturnValue %retval\n"
7900 		"OpFunctionEnd\n"
7901 	);
7902 
7903 	const char*		specDecorations		= "OpDecorate %test_constant SpecId 0\n";
7904 	const char*		specConstants		=
7905 			"%test_constant = OpSpecConstant %f32 0.\n"
7906 			"%c             = OpSpecConstantOp %f32 QuantizeToF16 %test_constant\n";
7907 
7908 	StringTemplate	specConstantFunction(
7909 		"%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7910 		"%param1        = OpFunctionParameter %v4f32\n"
7911 		"%label_testfun = OpLabel\n"
7912 		"${condition}\n"
7913 		"%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
7914 		"%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
7915 		"                 OpReturnValue %retval\n"
7916 		"OpFunctionEnd\n"
7917 	);
7918 
7919 	for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
7920 	{
7921 		map<string, string>								codeSpecialization;
7922 		map<string, string>								fragments;
7923 		codeSpecialization["condition"]					= tests[idx].condition;
7924 		fragments["testfun"]							= function.specialize(codeSpecialization);
7925 		fragments["pre_main"]							= string(constants) + tests[idx].constant + "\n";
7926 		createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
7927 	}
7928 
7929 	for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
7930 	{
7931 		map<string, string>								codeSpecialization;
7932 		map<string, string>								fragments;
7933 		SpecConstants									passConstants;
7934 
7935 		codeSpecialization["condition"]					= tests[idx].condition;
7936 		fragments["testfun"]							= specConstantFunction.specialize(codeSpecialization);
7937 		fragments["decoration"]							= specDecorations;
7938 		fragments["pre_main"]							= specConstants;
7939 
7940 		passConstants.append<float>(tests[idx].valueAsFloat);
7941 
7942 		createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
7943 	}
7944 }
7945 
createOpQuantizeTwoPossibilityTests(tcu::TestCaseGroup * testCtx)7946 void createOpQuantizeTwoPossibilityTests(tcu::TestCaseGroup* testCtx)
7947 {
7948 	RGBA inputColors[4] =  {
7949 		RGBA(0,		0,		0,		255),
7950 		RGBA(0,		0,		255,	255),
7951 		RGBA(0,		255,	0,		255),
7952 		RGBA(0,		255,	255,	255)
7953 	};
7954 
7955 	RGBA expectedColors[4] =
7956 	{
7957 		RGBA(255,	 0,		 0,		 255),
7958 		RGBA(255,	 0,		 0,		 255),
7959 		RGBA(255,	 0,		 0,		 255),
7960 		RGBA(255,	 0,		 0,		 255)
7961 	};
7962 
7963 	struct DualFP16Possibility
7964 	{
7965 		const char* name;
7966 		const char* input;
7967 		float		inputAsFloat;
7968 		const char* possibleOutput1;
7969 		const char* possibleOutput2;
7970 	} tests[] = {
7971 		{
7972 			"positive_round_up_or_round_down",
7973 			"0x1.3003p8",
7974 			constructNormalizedFloat(8, 0x300300),
7975 			"0x1.304p8",
7976 			"0x1.3p8"
7977 		},
7978 		{
7979 			"negative_round_up_or_round_down",
7980 			"-0x1.6008p-7",
7981 			-constructNormalizedFloat(-7, 0x600800),
7982 			"-0x1.6p-7",
7983 			"-0x1.604p-7"
7984 		},
7985 		{
7986 			"carry_bit",
7987 			"0x1.01ep2",
7988 			constructNormalizedFloat(2, 0x01e000),
7989 			"0x1.01cp2",
7990 			"0x1.02p2"
7991 		},
7992 		{
7993 			"carry_to_exponent",
7994 			"0x1.ffep1",
7995 			constructNormalizedFloat(1, 0xffe000),
7996 			"0x1.ffcp1",
7997 			"0x1.0p2"
7998 		},
7999 	};
8000 	StringTemplate constants (
8001 		"%input_const = OpConstant %f32 ${input}\n"
8002 		"%possible_solution1 = OpConstant %f32 ${output1}\n"
8003 		"%possible_solution2 = OpConstant %f32 ${output2}\n"
8004 		);
8005 
8006 	StringTemplate specConstants (
8007 		"%input_const = OpSpecConstant %f32 0.\n"
8008 		"%possible_solution1 = OpConstant %f32 ${output1}\n"
8009 		"%possible_solution2 = OpConstant %f32 ${output2}\n"
8010 	);
8011 
8012 	const char* specDecorations = "OpDecorate %input_const  SpecId 0\n";
8013 
8014 	const char* function  =
8015 		"%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8016 		"%param1        = OpFunctionParameter %v4f32\n"
8017 		"%label_testfun = OpLabel\n"
8018 		"%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8019 		// For the purposes of this test we assume that 0.f will always get
8020 		// faithfully passed through the pipeline stages.
8021 		"%b             = OpFAdd %f32 %input_const %a\n"
8022 		"%c             = OpQuantizeToF16 %f32 %b\n"
8023 		"%eq_1          = OpFOrdEqual %bool %c %possible_solution1\n"
8024 		"%eq_2          = OpFOrdEqual %bool %c %possible_solution2\n"
8025 		"%cond          = OpLogicalOr %bool %eq_1 %eq_2\n"
8026 		"%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
8027 		"%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1"
8028 		"                 OpReturnValue %retval\n"
8029 		"OpFunctionEnd\n";
8030 
8031 	for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
8032 		map<string, string>									fragments;
8033 		map<string, string>									constantSpecialization;
8034 
8035 		constantSpecialization["input"]						= tests[idx].input;
8036 		constantSpecialization["output1"]					= tests[idx].possibleOutput1;
8037 		constantSpecialization["output2"]					= tests[idx].possibleOutput2;
8038 		fragments["testfun"]								= function;
8039 		fragments["pre_main"]								= constants.specialize(constantSpecialization);
8040 		createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
8041 	}
8042 
8043 	for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
8044 		map<string, string>									fragments;
8045 		map<string, string>									constantSpecialization;
8046 		SpecConstants										passConstants;
8047 
8048 		constantSpecialization["output1"]					= tests[idx].possibleOutput1;
8049 		constantSpecialization["output2"]					= tests[idx].possibleOutput2;
8050 		fragments["testfun"]								= function;
8051 		fragments["decoration"]								= specDecorations;
8052 		fragments["pre_main"]								= specConstants.specialize(constantSpecialization);
8053 
8054 		passConstants.append<float>(tests[idx].inputAsFloat);
8055 
8056 		createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
8057 	}
8058 }
8059 
createOpQuantizeTests(tcu::TestContext & testCtx)8060 tcu::TestCaseGroup* createOpQuantizeTests(tcu::TestContext& testCtx)
8061 {
8062 	de::MovePtr<tcu::TestCaseGroup> opQuantizeTests (new tcu::TestCaseGroup(testCtx, "opquantize", "Test OpQuantizeToF16"));
8063 	createOpQuantizeSingleOptionTests(opQuantizeTests.get());
8064 	createOpQuantizeTwoPossibilityTests(opQuantizeTests.get());
8065 	return opQuantizeTests.release();
8066 }
8067 
8068 struct ShaderPermutation
8069 {
8070 	deUint8 vertexPermutation;
8071 	deUint8 geometryPermutation;
8072 	deUint8 tesscPermutation;
8073 	deUint8 tessePermutation;
8074 	deUint8 fragmentPermutation;
8075 };
8076 
getShaderPermutation(deUint8 inputValue)8077 ShaderPermutation getShaderPermutation(deUint8 inputValue)
8078 {
8079 	ShaderPermutation	permutation =
8080 	{
8081 		static_cast<deUint8>(inputValue & 0x10? 1u: 0u),
8082 		static_cast<deUint8>(inputValue & 0x08? 1u: 0u),
8083 		static_cast<deUint8>(inputValue & 0x04? 1u: 0u),
8084 		static_cast<deUint8>(inputValue & 0x02? 1u: 0u),
8085 		static_cast<deUint8>(inputValue & 0x01? 1u: 0u)
8086 	};
8087 	return permutation;
8088 }
8089 
createModuleTests(tcu::TestContext & testCtx)8090 tcu::TestCaseGroup* createModuleTests(tcu::TestContext& testCtx)
8091 {
8092 	RGBA								defaultColors[4];
8093 	RGBA								invertedColors[4];
8094 	de::MovePtr<tcu::TestCaseGroup>		moduleTests			(new tcu::TestCaseGroup(testCtx, "module", "Multiple entry points into shaders"));
8095 
8096 	getDefaultColors(defaultColors);
8097 	getInvertedDefaultColors(invertedColors);
8098 
8099 	// Combined module tests
8100 	{
8101 		// Shader stages: vertex and fragment
8102 		{
8103 			const ShaderElement combinedPipeline[]	=
8104 			{
8105 				ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8106 				ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8107 			};
8108 
8109 			addFunctionCaseWithPrograms<InstanceContext>(
8110 				moduleTests.get(), "same_module", "", createCombinedModule, runAndVerifyDefaultPipeline,
8111 				createInstanceContext(combinedPipeline, map<string, string>()));
8112 		}
8113 
8114 		// Shader stages: vertex, geometry and fragment
8115 		{
8116 			const ShaderElement combinedPipeline[]	=
8117 			{
8118 				ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8119 				ShaderElement("module", "main", VK_SHADER_STAGE_GEOMETRY_BIT),
8120 				ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8121 			};
8122 
8123 			addFunctionCaseWithPrograms<InstanceContext>(
8124 				moduleTests.get(), "same_module_geom", "", createCombinedModule, runAndVerifyDefaultPipeline,
8125 				createInstanceContext(combinedPipeline, map<string, string>()));
8126 		}
8127 
8128 		// Shader stages: vertex, tessellation control, tessellation evaluation and fragment
8129 		{
8130 			const ShaderElement combinedPipeline[]	=
8131 			{
8132 				ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8133 				ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8134 				ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8135 				ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8136 			};
8137 
8138 			addFunctionCaseWithPrograms<InstanceContext>(
8139 				moduleTests.get(), "same_module_tessc_tesse", "", createCombinedModule, runAndVerifyDefaultPipeline,
8140 				createInstanceContext(combinedPipeline, map<string, string>()));
8141 		}
8142 
8143 		// Shader stages: vertex, tessellation control, tessellation evaluation, geometry and fragment
8144 		{
8145 			const ShaderElement combinedPipeline[]	=
8146 			{
8147 				ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8148 				ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8149 				ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8150 				ShaderElement("module", "main", VK_SHADER_STAGE_GEOMETRY_BIT),
8151 				ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8152 			};
8153 
8154 			addFunctionCaseWithPrograms<InstanceContext>(
8155 				moduleTests.get(), "same_module_tessc_tesse_geom", "", createCombinedModule, runAndVerifyDefaultPipeline,
8156 				createInstanceContext(combinedPipeline, map<string, string>()));
8157 		}
8158 	}
8159 
8160 	const char* numbers[] =
8161 	{
8162 		"1", "2"
8163 	};
8164 
8165 	for (deInt8 idx = 0; idx < 32; ++idx)
8166 	{
8167 		ShaderPermutation			permutation		= getShaderPermutation(idx);
8168 		string						name			= string("vert") + numbers[permutation.vertexPermutation] + "_geom" + numbers[permutation.geometryPermutation] + "_tessc" + numbers[permutation.tesscPermutation] + "_tesse" + numbers[permutation.tessePermutation] + "_frag" + numbers[permutation.fragmentPermutation];
8169 		const ShaderElement			pipeline[]		=
8170 		{
8171 			ShaderElement("vert",	string("vert") +	numbers[permutation.vertexPermutation],		VK_SHADER_STAGE_VERTEX_BIT),
8172 			ShaderElement("geom",	string("geom") +	numbers[permutation.geometryPermutation],	VK_SHADER_STAGE_GEOMETRY_BIT),
8173 			ShaderElement("tessc",	string("tessc") +	numbers[permutation.tesscPermutation],		VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8174 			ShaderElement("tesse",	string("tesse") +	numbers[permutation.tessePermutation],		VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8175 			ShaderElement("frag",	string("frag") +	numbers[permutation.fragmentPermutation],	VK_SHADER_STAGE_FRAGMENT_BIT)
8176 		};
8177 
8178 		// If there are an even number of swaps, then it should be no-op.
8179 		// If there are an odd number, the color should be flipped.
8180 		if ((permutation.vertexPermutation + permutation.geometryPermutation + permutation.tesscPermutation + permutation.tessePermutation + permutation.fragmentPermutation) % 2 == 0)
8181 		{
8182 			addFunctionCaseWithPrograms<InstanceContext>(
8183 					moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline,
8184 					createInstanceContext(pipeline, defaultColors, defaultColors, map<string, string>()));
8185 		}
8186 		else
8187 		{
8188 			addFunctionCaseWithPrograms<InstanceContext>(
8189 					moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline,
8190 					createInstanceContext(pipeline, defaultColors, invertedColors, map<string, string>()));
8191 		}
8192 	}
8193 	return moduleTests.release();
8194 }
8195 
createLoopTests(tcu::TestContext & testCtx)8196 tcu::TestCaseGroup* createLoopTests(tcu::TestContext& testCtx)
8197 {
8198 	de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "loop", "Looping control flow"));
8199 	RGBA defaultColors[4];
8200 	getDefaultColors(defaultColors);
8201 	map<string, string> fragments;
8202 	fragments["pre_main"] =
8203 		"%c_f32_5 = OpConstant %f32 5.\n";
8204 
8205 	// A loop with a single block. The Continue Target is the loop block
8206 	// itself. In SPIR-V terms, the "loop construct" contains no blocks at all
8207 	// -- the "continue construct" forms the entire loop.
8208 	fragments["testfun"] =
8209 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8210 		"%param1 = OpFunctionParameter %v4f32\n"
8211 
8212 		"%entry = OpLabel\n"
8213 		"%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8214 		"OpBranch %loop\n"
8215 
8216 		";adds and subtracts 1.0 to %val in alternate iterations\n"
8217 		"%loop = OpLabel\n"
8218 		"%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
8219 		"%delta = OpPhi %f32 %c_f32_1 %entry %minus_delta %loop\n"
8220 		"%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
8221 		"%val = OpFAdd %f32 %val1 %delta\n"
8222 		"%minus_delta = OpFSub %f32 %c_f32_0 %delta\n"
8223 		"%count__ = OpISub %i32 %count %c_i32_1\n"
8224 		"%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8225 		"OpLoopMerge %exit %loop None\n"
8226 		"OpBranchConditional %again %loop %exit\n"
8227 
8228 		"%exit = OpLabel\n"
8229 		"%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8230 		"OpReturnValue %result\n"
8231 
8232 		"OpFunctionEnd\n";
8233 
8234 	createTestsForAllStages("single_block", defaultColors, defaultColors, fragments, testGroup.get());
8235 
8236 	// Body comprised of multiple basic blocks.
8237 	const StringTemplate multiBlock(
8238 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8239 		"%param1 = OpFunctionParameter %v4f32\n"
8240 
8241 		"%entry = OpLabel\n"
8242 		"%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8243 		"OpBranch %loop\n"
8244 
8245 		";adds and subtracts 1.0 to %val in alternate iterations\n"
8246 		"%loop = OpLabel\n"
8247 		"%count = OpPhi %i32 %c_i32_4 %entry %count__ %gather\n"
8248 		"%delta = OpPhi %f32 %c_f32_1 %entry %delta_next %gather\n"
8249 		"%val1 = OpPhi %f32 %val0 %entry %val %gather\n"
8250 		// There are several possibilities for the Continue Target below.  Each
8251 		// will be specialized into a separate test case.
8252 		"OpLoopMerge %exit ${continue_target} None\n"
8253 		"OpBranch %if\n"
8254 
8255 		"%if = OpLabel\n"
8256 		";delta_next = (delta > 0) ? -1 : 1;\n"
8257 		"%gt0 = OpFOrdGreaterThan %bool %delta %c_f32_0\n"
8258 		"OpSelectionMerge %gather DontFlatten\n"
8259 		"OpBranchConditional %gt0 %even %odd ;tells us if %count is even or odd\n"
8260 
8261 		"%odd = OpLabel\n"
8262 		"OpBranch %gather\n"
8263 
8264 		"%even = OpLabel\n"
8265 		"OpBranch %gather\n"
8266 
8267 		"%gather = OpLabel\n"
8268 		"%delta_next = OpPhi %f32 %c_f32_n1 %even %c_f32_1 %odd\n"
8269 		"%val = OpFAdd %f32 %val1 %delta\n"
8270 		"%count__ = OpISub %i32 %count %c_i32_1\n"
8271 		"%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8272 		"OpBranchConditional %again %loop %exit\n"
8273 
8274 		"%exit = OpLabel\n"
8275 		"%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8276 		"OpReturnValue %result\n"
8277 
8278 		"OpFunctionEnd\n");
8279 
8280 	map<string, string> continue_target;
8281 
8282 	// The Continue Target is the loop block itself.
8283 	continue_target["continue_target"] = "%loop";
8284 	fragments["testfun"] = multiBlock.specialize(continue_target);
8285 	createTestsForAllStages("multi_block_continue_construct", defaultColors, defaultColors, fragments, testGroup.get());
8286 
8287 	// The Continue Target is at the end of the loop.
8288 	continue_target["continue_target"] = "%gather";
8289 	fragments["testfun"] = multiBlock.specialize(continue_target);
8290 	createTestsForAllStages("multi_block_loop_construct", defaultColors, defaultColors, fragments, testGroup.get());
8291 
8292 	// A loop with continue statement.
8293 	fragments["testfun"] =
8294 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8295 		"%param1 = OpFunctionParameter %v4f32\n"
8296 
8297 		"%entry = OpLabel\n"
8298 		"%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8299 		"OpBranch %loop\n"
8300 
8301 		";adds 4, 3, and 1 to %val0 (skips 2)\n"
8302 		"%loop = OpLabel\n"
8303 		"%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8304 		"%val1 = OpPhi %f32 %val0 %entry %val %continue\n"
8305 		"OpLoopMerge %exit %continue None\n"
8306 		"OpBranch %if\n"
8307 
8308 		"%if = OpLabel\n"
8309 		";skip if %count==2\n"
8310 		"%eq2 = OpIEqual %bool %count %c_i32_2\n"
8311 		"OpSelectionMerge %continue DontFlatten\n"
8312 		"OpBranchConditional %eq2 %continue %body\n"
8313 
8314 		"%body = OpLabel\n"
8315 		"%fcount = OpConvertSToF %f32 %count\n"
8316 		"%val2 = OpFAdd %f32 %val1 %fcount\n"
8317 		"OpBranch %continue\n"
8318 
8319 		"%continue = OpLabel\n"
8320 		"%val = OpPhi %f32 %val2 %body %val1 %if\n"
8321 		"%count__ = OpISub %i32 %count %c_i32_1\n"
8322 		"%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8323 		"OpBranchConditional %again %loop %exit\n"
8324 
8325 		"%exit = OpLabel\n"
8326 		"%same = OpFSub %f32 %val %c_f32_8\n"
8327 		"%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8328 		"OpReturnValue %result\n"
8329 		"OpFunctionEnd\n";
8330 	createTestsForAllStages("continue", defaultColors, defaultColors, fragments, testGroup.get());
8331 
8332 	// A loop with break.
8333 	fragments["testfun"] =
8334 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8335 		"%param1 = OpFunctionParameter %v4f32\n"
8336 
8337 		"%entry = OpLabel\n"
8338 		";param1 components are between 0 and 1, so dot product is 4 or less\n"
8339 		"%dot = OpDot %f32 %param1 %param1\n"
8340 		"%div = OpFDiv %f32 %dot %c_f32_5\n"
8341 		"%zero = OpConvertFToU %u32 %div\n"
8342 		"%two = OpIAdd %i32 %zero %c_i32_2\n"
8343 		"%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8344 		"OpBranch %loop\n"
8345 
8346 		";adds 4 and 3 to %val0 (exits early)\n"
8347 		"%loop = OpLabel\n"
8348 		"%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8349 		"%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
8350 		"OpLoopMerge %exit %continue None\n"
8351 		"OpBranch %if\n"
8352 
8353 		"%if = OpLabel\n"
8354 		";end loop if %count==%two\n"
8355 		"%above2 = OpSGreaterThan %bool %count %two\n"
8356 		"OpSelectionMerge %continue DontFlatten\n"
8357 		"OpBranchConditional %above2 %body %exit\n"
8358 
8359 		"%body = OpLabel\n"
8360 		"%fcount = OpConvertSToF %f32 %count\n"
8361 		"%val2 = OpFAdd %f32 %val1 %fcount\n"
8362 		"OpBranch %continue\n"
8363 
8364 		"%continue = OpLabel\n"
8365 		"%count__ = OpISub %i32 %count %c_i32_1\n"
8366 		"%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8367 		"OpBranchConditional %again %loop %exit\n"
8368 
8369 		"%exit = OpLabel\n"
8370 		"%val_post = OpPhi %f32 %val2 %continue %val1 %if\n"
8371 		"%same = OpFSub %f32 %val_post %c_f32_7\n"
8372 		"%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8373 		"OpReturnValue %result\n"
8374 		"OpFunctionEnd\n";
8375 	createTestsForAllStages("break", defaultColors, defaultColors, fragments, testGroup.get());
8376 
8377 	// A loop with return.
8378 	fragments["testfun"] =
8379 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8380 		"%param1 = OpFunctionParameter %v4f32\n"
8381 
8382 		"%entry = OpLabel\n"
8383 		";param1 components are between 0 and 1, so dot product is 4 or less\n"
8384 		"%dot = OpDot %f32 %param1 %param1\n"
8385 		"%div = OpFDiv %f32 %dot %c_f32_5\n"
8386 		"%zero = OpConvertFToU %u32 %div\n"
8387 		"%two = OpIAdd %i32 %zero %c_i32_2\n"
8388 		"%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8389 		"OpBranch %loop\n"
8390 
8391 		";returns early without modifying %param1\n"
8392 		"%loop = OpLabel\n"
8393 		"%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8394 		"%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
8395 		"OpLoopMerge %exit %continue None\n"
8396 		"OpBranch %if\n"
8397 
8398 		"%if = OpLabel\n"
8399 		";return if %count==%two\n"
8400 		"%above2 = OpSGreaterThan %bool %count %two\n"
8401 		"OpSelectionMerge %continue DontFlatten\n"
8402 		"OpBranchConditional %above2 %body %early_exit\n"
8403 
8404 		"%early_exit = OpLabel\n"
8405 		"OpReturnValue %param1\n"
8406 
8407 		"%body = OpLabel\n"
8408 		"%fcount = OpConvertSToF %f32 %count\n"
8409 		"%val2 = OpFAdd %f32 %val1 %fcount\n"
8410 		"OpBranch %continue\n"
8411 
8412 		"%continue = OpLabel\n"
8413 		"%count__ = OpISub %i32 %count %c_i32_1\n"
8414 		"%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8415 		"OpBranchConditional %again %loop %exit\n"
8416 
8417 		"%exit = OpLabel\n"
8418 		";should never get here, so return an incorrect result\n"
8419 		"%result = OpVectorInsertDynamic %v4f32 %param1 %val2 %c_i32_0\n"
8420 		"OpReturnValue %result\n"
8421 		"OpFunctionEnd\n";
8422 	createTestsForAllStages("return", defaultColors, defaultColors, fragments, testGroup.get());
8423 
8424 	// Continue inside a switch block to break to enclosing loop's merge block.
8425 	// Matches roughly the following GLSL code:
8426 	// for (; keep_going; keep_going = false)
8427 	// {
8428 	//     switch (int(param1.x))
8429 	//     {
8430 	//         case 0: continue;
8431 	//         case 1: continue;
8432 	//         default: continue;
8433 	//     }
8434 	//     dead code: modify return value to invalid result.
8435 	// }
8436 	fragments["pre_main"] =
8437 		"%fp_bool = OpTypePointer Function %bool\n"
8438 		"%true = OpConstantTrue %bool\n"
8439 		"%false = OpConstantFalse %bool\n";
8440 
8441 	fragments["testfun"] =
8442 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8443 		"%param1 = OpFunctionParameter %v4f32\n"
8444 
8445 		"%entry = OpLabel\n"
8446 		"%keep_going = OpVariable %fp_bool Function\n"
8447 		"%val_ptr = OpVariable %fp_f32 Function\n"
8448 		"%param1_x = OpCompositeExtract %f32 %param1 0\n"
8449 		"OpStore %keep_going %true\n"
8450 		"OpBranch %forloop_begin\n"
8451 
8452 		"%forloop_begin = OpLabel\n"
8453 		"OpLoopMerge %forloop_merge %forloop_continue None\n"
8454 		"OpBranch %forloop\n"
8455 
8456 		"%forloop = OpLabel\n"
8457 		"%for_condition = OpLoad %bool %keep_going\n"
8458 		"OpBranchConditional %for_condition %forloop_body %forloop_merge\n"
8459 
8460 		"%forloop_body = OpLabel\n"
8461 		"OpStore %val_ptr %param1_x\n"
8462 		"%param1_x_int = OpConvertFToS %i32 %param1_x\n"
8463 
8464 		"OpSelectionMerge %switch_merge None\n"
8465 		"OpSwitch %param1_x_int %default 0 %case_0 1 %case_1\n"
8466 		"%case_0 = OpLabel\n"
8467 		"OpBranch %forloop_continue\n"
8468 		"%case_1 = OpLabel\n"
8469 		"OpBranch %forloop_continue\n"
8470 		"%default = OpLabel\n"
8471 		"OpBranch %forloop_continue\n"
8472 		"%switch_merge = OpLabel\n"
8473 		";should never get here, so change the return value to invalid result\n"
8474 		"OpStore %val_ptr %c_f32_1\n"
8475 		"OpBranch %forloop_continue\n"
8476 
8477 		"%forloop_continue = OpLabel\n"
8478 		"OpStore %keep_going %false\n"
8479 		"OpBranch %forloop_begin\n"
8480 		"%forloop_merge = OpLabel\n"
8481 
8482 		"%val = OpLoad %f32 %val_ptr\n"
8483 		"%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8484 		"OpReturnValue %result\n"
8485 		"OpFunctionEnd\n";
8486 	createTestsForAllStages("switch_continue", defaultColors, defaultColors, fragments, testGroup.get());
8487 
8488 	return testGroup.release();
8489 }
8490 
8491 // A collection of tests putting OpControlBarrier in places GLSL forbids but SPIR-V allows.
createBarrierTests(tcu::TestContext & testCtx)8492 tcu::TestCaseGroup* createBarrierTests(tcu::TestContext& testCtx)
8493 {
8494 	de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "barrier", "OpControlBarrier"));
8495 	map<string, string> fragments;
8496 
8497 	// A barrier inside a function body.
8498 	fragments["pre_main"] =
8499 		"%Workgroup = OpConstant %i32 2\n"
8500 		"%WorkgroupAcquireRelease = OpConstant %i32 0x108\n";
8501 	fragments["testfun"] =
8502 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8503 		"%param1 = OpFunctionParameter %v4f32\n"
8504 		"%label_testfun = OpLabel\n"
8505 		"OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8506 		"OpReturnValue %param1\n"
8507 		"OpFunctionEnd\n";
8508 	addTessCtrlTest(testGroup.get(), "in_function", fragments);
8509 
8510 	// Common setup code for the following tests.
8511 	fragments["pre_main"] =
8512 		"%Workgroup = OpConstant %i32 2\n"
8513 		"%WorkgroupAcquireRelease = OpConstant %i32 0x108\n"
8514 		"%c_f32_5 = OpConstant %f32 5.\n";
8515 	const string setupPercentZero =	 // Begins %test_code function with code that sets %zero to 0u but cannot be optimized away.
8516 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8517 		"%param1 = OpFunctionParameter %v4f32\n"
8518 		"%entry = OpLabel\n"
8519 		";param1 components are between 0 and 1, so dot product is 4 or less\n"
8520 		"%dot = OpDot %f32 %param1 %param1\n"
8521 		"%div = OpFDiv %f32 %dot %c_f32_5\n"
8522 		"%zero = OpConvertFToU %u32 %div\n";
8523 
8524 	// Barriers inside OpSwitch branches.
8525 	fragments["testfun"] =
8526 		setupPercentZero +
8527 		"OpSelectionMerge %switch_exit None\n"
8528 		"OpSwitch %zero %switch_default 0 %case0 1 %case1 ;should always go to %case0\n"
8529 
8530 		"%case1 = OpLabel\n"
8531 		";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8532 		"OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8533 		"%wrong_branch_alert1 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8534 		"OpBranch %switch_exit\n"
8535 
8536 		"%switch_default = OpLabel\n"
8537 		"%wrong_branch_alert2 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8538 		";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8539 		"OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8540 		"OpBranch %switch_exit\n"
8541 
8542 		"%case0 = OpLabel\n"
8543 		"OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8544 		"OpBranch %switch_exit\n"
8545 
8546 		"%switch_exit = OpLabel\n"
8547 		"%ret = OpPhi %v4f32 %param1 %case0 %wrong_branch_alert1 %case1 %wrong_branch_alert2 %switch_default\n"
8548 		"OpReturnValue %ret\n"
8549 		"OpFunctionEnd\n";
8550 	addTessCtrlTest(testGroup.get(), "in_switch", fragments);
8551 
8552 	// Barriers inside if-then-else.
8553 	fragments["testfun"] =
8554 		setupPercentZero +
8555 		"%eq0 = OpIEqual %bool %zero %c_u32_0\n"
8556 		"OpSelectionMerge %exit DontFlatten\n"
8557 		"OpBranchConditional %eq0 %then %else\n"
8558 
8559 		"%else = OpLabel\n"
8560 		";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8561 		"OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8562 		"%wrong_branch_alert = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8563 		"OpBranch %exit\n"
8564 
8565 		"%then = OpLabel\n"
8566 		"OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8567 		"OpBranch %exit\n"
8568 		"%exit = OpLabel\n"
8569 		"%ret = OpPhi %v4f32 %param1 %then %wrong_branch_alert %else\n"
8570 		"OpReturnValue %ret\n"
8571 		"OpFunctionEnd\n";
8572 	addTessCtrlTest(testGroup.get(), "in_if", fragments);
8573 
8574 	// A barrier after control-flow reconvergence, tempting the compiler to attempt something like this:
8575 	// http://lists.llvm.org/pipermail/llvm-dev/2009-October/026317.html.
8576 	fragments["testfun"] =
8577 		setupPercentZero +
8578 		"%thread_id = OpLoad %i32 %BP_gl_InvocationID\n"
8579 		"%thread0 = OpIEqual %bool %thread_id %c_i32_0\n"
8580 		"OpSelectionMerge %exit DontFlatten\n"
8581 		"OpBranchConditional %thread0 %then %else\n"
8582 
8583 		"%else = OpLabel\n"
8584 		"%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8585 		"OpBranch %exit\n"
8586 
8587 		"%then = OpLabel\n"
8588 		"%val1 = OpVectorExtractDynamic %f32 %param1 %zero\n"
8589 		"OpBranch %exit\n"
8590 
8591 		"%exit = OpLabel\n"
8592 		"%val = OpPhi %f32 %val0 %else %val1 %then\n"
8593 		"OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8594 		"%ret = OpVectorInsertDynamic %v4f32 %param1 %val %zero\n"
8595 		"OpReturnValue %ret\n"
8596 		"OpFunctionEnd\n";
8597 	addTessCtrlTest(testGroup.get(), "after_divergent_if", fragments);
8598 
8599 	// A barrier inside a loop.
8600 	fragments["pre_main"] =
8601 		"%Workgroup = OpConstant %i32 2\n"
8602 		"%WorkgroupAcquireRelease = OpConstant %i32 0x108\n"
8603 		"%c_f32_10 = OpConstant %f32 10.\n";
8604 	fragments["testfun"] =
8605 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8606 		"%param1 = OpFunctionParameter %v4f32\n"
8607 		"%entry = OpLabel\n"
8608 		"%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8609 		"OpBranch %loop\n"
8610 
8611 		";adds 4, 3, 2, and 1 to %val0\n"
8612 		"%loop = OpLabel\n"
8613 		"%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
8614 		"%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
8615 		"OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8616 		"%fcount = OpConvertSToF %f32 %count\n"
8617 		"%val = OpFAdd %f32 %val1 %fcount\n"
8618 		"%count__ = OpISub %i32 %count %c_i32_1\n"
8619 		"%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8620 		"OpLoopMerge %exit %loop None\n"
8621 		"OpBranchConditional %again %loop %exit\n"
8622 
8623 		"%exit = OpLabel\n"
8624 		"%same = OpFSub %f32 %val %c_f32_10\n"
8625 		"%ret = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8626 		"OpReturnValue %ret\n"
8627 		"OpFunctionEnd\n";
8628 	addTessCtrlTest(testGroup.get(), "in_loop", fragments);
8629 
8630 	return testGroup.release();
8631 }
8632 
8633 // Test for the OpFRem instruction.
createFRemTests(tcu::TestContext & testCtx)8634 tcu::TestCaseGroup* createFRemTests(tcu::TestContext& testCtx)
8635 {
8636 	de::MovePtr<tcu::TestCaseGroup>		testGroup(new tcu::TestCaseGroup(testCtx, "frem", "OpFRem"));
8637 	map<string, string>					fragments;
8638 	RGBA								inputColors[4];
8639 	RGBA								outputColors[4];
8640 
8641 	fragments["pre_main"]				 =
8642 		"%c_f32_3 = OpConstant %f32 3.0\n"
8643 		"%c_f32_n3 = OpConstant %f32 -3.0\n"
8644 		"%c_f32_4 = OpConstant %f32 4.0\n"
8645 		"%c_f32_p75 = OpConstant %f32 0.75\n"
8646 		"%c_v4f32_p75_p75_p75_p75 = OpConstantComposite %v4f32 %c_f32_p75 %c_f32_p75 %c_f32_p75 %c_f32_p75 \n"
8647 		"%c_v4f32_4_4_4_4 = OpConstantComposite %v4f32 %c_f32_4 %c_f32_4 %c_f32_4 %c_f32_4\n"
8648 		"%c_v4f32_3_n3_3_n3 = OpConstantComposite %v4f32 %c_f32_3 %c_f32_n3 %c_f32_3 %c_f32_n3\n";
8649 
8650 	// The test does the following.
8651 	// vec4 result = (param1 * 8.0) - 4.0;
8652 	// return (frem(result.x,3) + 0.75, frem(result.y, -3) + 0.75, 0, 1)
8653 	fragments["testfun"]				 =
8654 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8655 		"%param1 = OpFunctionParameter %v4f32\n"
8656 		"%label_testfun = OpLabel\n"
8657 		"%v_times_8 = OpVectorTimesScalar %v4f32 %param1 %c_f32_8\n"
8658 		"%minus_4 = OpFSub %v4f32 %v_times_8 %c_v4f32_4_4_4_4\n"
8659 		"%frem = OpFRem %v4f32 %minus_4 %c_v4f32_3_n3_3_n3\n"
8660 		"%added = OpFAdd %v4f32 %frem %c_v4f32_p75_p75_p75_p75\n"
8661 		"%xyz_1 = OpVectorInsertDynamic %v4f32 %added %c_f32_1 %c_i32_3\n"
8662 		"%xy_0_1 = OpVectorInsertDynamic %v4f32 %xyz_1 %c_f32_0 %c_i32_2\n"
8663 		"OpReturnValue %xy_0_1\n"
8664 		"OpFunctionEnd\n";
8665 
8666 
8667 	inputColors[0]		= RGBA(16,	16,		0, 255);
8668 	inputColors[1]		= RGBA(232, 232,	0, 255);
8669 	inputColors[2]		= RGBA(232, 16,		0, 255);
8670 	inputColors[3]		= RGBA(16,	232,	0, 255);
8671 
8672 	outputColors[0]		= RGBA(64,	64,		0, 255);
8673 	outputColors[1]		= RGBA(255, 255,	0, 255);
8674 	outputColors[2]		= RGBA(255, 64,		0, 255);
8675 	outputColors[3]		= RGBA(64,	255,	0, 255);
8676 
8677 	createTestsForAllStages("frem", inputColors, outputColors, fragments, testGroup.get());
8678 	return testGroup.release();
8679 }
8680 
8681 // Test for the OpSRem instruction.
createOpSRemGraphicsTests(tcu::TestContext & testCtx,qpTestResult negFailResult)8682 tcu::TestCaseGroup* createOpSRemGraphicsTests(tcu::TestContext& testCtx, qpTestResult negFailResult)
8683 {
8684 	de::MovePtr<tcu::TestCaseGroup>		testGroup(new tcu::TestCaseGroup(testCtx, "srem", "OpSRem"));
8685 	map<string, string>					fragments;
8686 
8687 	fragments["pre_main"]				 =
8688 		"%c_f32_255 = OpConstant %f32 255.0\n"
8689 		"%c_i32_128 = OpConstant %i32 128\n"
8690 		"%c_i32_255 = OpConstant %i32 255\n"
8691 		"%c_v4f32_255 = OpConstantComposite %v4f32 %c_f32_255 %c_f32_255 %c_f32_255 %c_f32_255 \n"
8692 		"%c_v4f32_0_5 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 \n"
8693 		"%c_v4i32_128 = OpConstantComposite %v4i32 %c_i32_128 %c_i32_128 %c_i32_128 %c_i32_128 \n";
8694 
8695 	// The test does the following.
8696 	// ivec4 ints = int(param1 * 255.0 + 0.5) - 128;
8697 	// ivec4 result = ivec4(srem(ints.x, ints.y), srem(ints.y, ints.z), srem(ints.z, ints.x), 255);
8698 	// return float(result + 128) / 255.0;
8699 	fragments["testfun"]				 =
8700 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8701 		"%param1 = OpFunctionParameter %v4f32\n"
8702 		"%label_testfun = OpLabel\n"
8703 		"%div255 = OpFMul %v4f32 %param1 %c_v4f32_255\n"
8704 		"%add0_5 = OpFAdd %v4f32 %div255 %c_v4f32_0_5\n"
8705 		"%uints_in = OpConvertFToS %v4i32 %add0_5\n"
8706 		"%ints_in = OpISub %v4i32 %uints_in %c_v4i32_128\n"
8707 		"%x_in = OpCompositeExtract %i32 %ints_in 0\n"
8708 		"%y_in = OpCompositeExtract %i32 %ints_in 1\n"
8709 		"%z_in = OpCompositeExtract %i32 %ints_in 2\n"
8710 		"%x_out = OpSRem %i32 %x_in %y_in\n"
8711 		"%y_out = OpSRem %i32 %y_in %z_in\n"
8712 		"%z_out = OpSRem %i32 %z_in %x_in\n"
8713 		"%ints_out = OpCompositeConstruct %v4i32 %x_out %y_out %z_out %c_i32_255\n"
8714 		"%ints_offset = OpIAdd %v4i32 %ints_out %c_v4i32_128\n"
8715 		"%f_ints_offset = OpConvertSToF %v4f32 %ints_offset\n"
8716 		"%float_out = OpFDiv %v4f32 %f_ints_offset %c_v4f32_255\n"
8717 		"OpReturnValue %float_out\n"
8718 		"OpFunctionEnd\n";
8719 
8720 	const struct CaseParams
8721 	{
8722 		const char*		name;
8723 		const char*		failMessageTemplate;	// customized status message
8724 		qpTestResult	failResult;				// override status on failure
8725 		int				operands[4][3];			// four (x, y, z) vectors of operands
8726 		int				results[4][3];			// four (x, y, z) vectors of results
8727 	} cases[] =
8728 	{
8729 		{
8730 			"positive",
8731 			"${reason}",
8732 			QP_TEST_RESULT_FAIL,
8733 			{ { 5, 12, 17 }, { 5, 5, 7 }, { 75, 8, 81 }, { 25, 60, 100 } },			// operands
8734 			{ { 5, 12,  2 }, { 0, 5, 2 }, {  3, 8,  6 }, { 25, 60,   0 } },			// results
8735 		},
8736 		{
8737 			"all",
8738 			"Inconsistent results, but within specification: ${reason}",
8739 			negFailResult,															// negative operands, not required by the spec
8740 			{ { 5, 12, -17 }, { -5, -5, 7 }, { 75, 8, -81 }, { 25, -60, 100 } },	// operands
8741 			{ { 5, 12,  -2 }, {  0, -5, 2 }, {  3, 8,  -6 }, { 25, -60,   0 } },	// results
8742 		},
8743 	};
8744 	// If either operand is negative the result is undefined. Some implementations may still return correct values.
8745 
8746 	for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
8747 	{
8748 		const CaseParams&	params			= cases[caseNdx];
8749 		RGBA				inputColors[4];
8750 		RGBA				outputColors[4];
8751 
8752 		for (int i = 0; i < 4; ++i)
8753 		{
8754 			inputColors [i] = RGBA(params.operands[i][0] + 128, params.operands[i][1] + 128, params.operands[i][2] + 128, 255);
8755 			outputColors[i] = RGBA(params.results [i][0] + 128, params.results [i][1] + 128, params.results [i][2] + 128, 255);
8756 		}
8757 
8758 		createTestsForAllStages(params.name, inputColors, outputColors, fragments, testGroup.get(), params.failResult, params.failMessageTemplate);
8759 	}
8760 
8761 	return testGroup.release();
8762 }
8763 
8764 // Test for the OpSMod instruction.
createOpSModGraphicsTests(tcu::TestContext & testCtx,qpTestResult negFailResult)8765 tcu::TestCaseGroup* createOpSModGraphicsTests(tcu::TestContext& testCtx, qpTestResult negFailResult)
8766 {
8767 	de::MovePtr<tcu::TestCaseGroup>		testGroup(new tcu::TestCaseGroup(testCtx, "smod", "OpSMod"));
8768 	map<string, string>					fragments;
8769 
8770 	fragments["pre_main"]				 =
8771 		"%c_f32_255 = OpConstant %f32 255.0\n"
8772 		"%c_i32_128 = OpConstant %i32 128\n"
8773 		"%c_i32_255 = OpConstant %i32 255\n"
8774 		"%c_v4f32_255 = OpConstantComposite %v4f32 %c_f32_255 %c_f32_255 %c_f32_255 %c_f32_255 \n"
8775 		"%c_v4f32_0_5 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 \n"
8776 		"%c_v4i32_128 = OpConstantComposite %v4i32 %c_i32_128 %c_i32_128 %c_i32_128 %c_i32_128 \n";
8777 
8778 	// The test does the following.
8779 	// ivec4 ints = int(param1 * 255.0 + 0.5) - 128;
8780 	// ivec4 result = ivec4(smod(ints.x, ints.y), smod(ints.y, ints.z), smod(ints.z, ints.x), 255);
8781 	// return float(result + 128) / 255.0;
8782 	fragments["testfun"]				 =
8783 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8784 		"%param1 = OpFunctionParameter %v4f32\n"
8785 		"%label_testfun = OpLabel\n"
8786 		"%div255 = OpFMul %v4f32 %param1 %c_v4f32_255\n"
8787 		"%add0_5 = OpFAdd %v4f32 %div255 %c_v4f32_0_5\n"
8788 		"%uints_in = OpConvertFToS %v4i32 %add0_5\n"
8789 		"%ints_in = OpISub %v4i32 %uints_in %c_v4i32_128\n"
8790 		"%x_in = OpCompositeExtract %i32 %ints_in 0\n"
8791 		"%y_in = OpCompositeExtract %i32 %ints_in 1\n"
8792 		"%z_in = OpCompositeExtract %i32 %ints_in 2\n"
8793 		"%x_out = OpSMod %i32 %x_in %y_in\n"
8794 		"%y_out = OpSMod %i32 %y_in %z_in\n"
8795 		"%z_out = OpSMod %i32 %z_in %x_in\n"
8796 		"%ints_out = OpCompositeConstruct %v4i32 %x_out %y_out %z_out %c_i32_255\n"
8797 		"%ints_offset = OpIAdd %v4i32 %ints_out %c_v4i32_128\n"
8798 		"%f_ints_offset = OpConvertSToF %v4f32 %ints_offset\n"
8799 		"%float_out = OpFDiv %v4f32 %f_ints_offset %c_v4f32_255\n"
8800 		"OpReturnValue %float_out\n"
8801 		"OpFunctionEnd\n";
8802 
8803 	const struct CaseParams
8804 	{
8805 		const char*		name;
8806 		const char*		failMessageTemplate;	// customized status message
8807 		qpTestResult	failResult;				// override status on failure
8808 		int				operands[4][3];			// four (x, y, z) vectors of operands
8809 		int				results[4][3];			// four (x, y, z) vectors of results
8810 	} cases[] =
8811 	{
8812 		{
8813 			"positive",
8814 			"${reason}",
8815 			QP_TEST_RESULT_FAIL,
8816 			{ { 5, 12, 17 }, { 5, 5, 7 }, { 75, 8, 81 }, { 25, 60, 100 } },				// operands
8817 			{ { 5, 12,  2 }, { 0, 5, 2 }, {  3, 8,  6 }, { 25, 60,   0 } },				// results
8818 		},
8819 		{
8820 			"all",
8821 			"Inconsistent results, but within specification: ${reason}",
8822 			negFailResult,																// negative operands, not required by the spec
8823 			{ { 5, 12, -17 }, { -5, -5,  7 }, { 75,   8, -81 }, {  25, -60, 100 } },	// operands
8824 			{ { 5, -5,   3 }, {  0,  2, -3 }, {  3, -73,  69 }, { -35,  40,   0 } },	// results
8825 		},
8826 	};
8827 	// If either operand is negative the result is undefined. Some implementations may still return correct values.
8828 
8829 	for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
8830 	{
8831 		const CaseParams&	params			= cases[caseNdx];
8832 		RGBA				inputColors[4];
8833 		RGBA				outputColors[4];
8834 
8835 		for (int i = 0; i < 4; ++i)
8836 		{
8837 			inputColors [i] = RGBA(params.operands[i][0] + 128, params.operands[i][1] + 128, params.operands[i][2] + 128, 255);
8838 			outputColors[i] = RGBA(params.results [i][0] + 128, params.results [i][1] + 128, params.results [i][2] + 128, 255);
8839 		}
8840 
8841 		createTestsForAllStages(params.name, inputColors, outputColors, fragments, testGroup.get(), params.failResult, params.failMessageTemplate);
8842 	}
8843 	return testGroup.release();
8844 }
8845 
8846 enum ConversionDataType
8847 {
8848 	DATA_TYPE_SIGNED_8,
8849 	DATA_TYPE_SIGNED_16,
8850 	DATA_TYPE_SIGNED_32,
8851 	DATA_TYPE_SIGNED_64,
8852 	DATA_TYPE_UNSIGNED_8,
8853 	DATA_TYPE_UNSIGNED_16,
8854 	DATA_TYPE_UNSIGNED_32,
8855 	DATA_TYPE_UNSIGNED_64,
8856 	DATA_TYPE_FLOAT_16,
8857 	DATA_TYPE_FLOAT_32,
8858 	DATA_TYPE_FLOAT_64,
8859 	DATA_TYPE_VEC2_SIGNED_16,
8860 	DATA_TYPE_VEC2_SIGNED_32
8861 };
8862 
getBitWidthStr(ConversionDataType type)8863 const string getBitWidthStr (ConversionDataType type)
8864 {
8865 	switch (type)
8866 	{
8867 		case DATA_TYPE_SIGNED_8:
8868 		case DATA_TYPE_UNSIGNED_8:
8869 			return "8";
8870 
8871 		case DATA_TYPE_SIGNED_16:
8872 		case DATA_TYPE_UNSIGNED_16:
8873 		case DATA_TYPE_FLOAT_16:
8874 			return "16";
8875 
8876 		case DATA_TYPE_SIGNED_32:
8877 		case DATA_TYPE_UNSIGNED_32:
8878 		case DATA_TYPE_FLOAT_32:
8879 		case DATA_TYPE_VEC2_SIGNED_16:
8880 			return "32";
8881 
8882 		case DATA_TYPE_SIGNED_64:
8883 		case DATA_TYPE_UNSIGNED_64:
8884 		case DATA_TYPE_FLOAT_64:
8885 		case DATA_TYPE_VEC2_SIGNED_32:
8886 			return "64";
8887 
8888 		default:
8889 			DE_ASSERT(false);
8890 	}
8891 	return "";
8892 }
8893 
getByteWidthStr(ConversionDataType type)8894 const string getByteWidthStr (ConversionDataType type)
8895 {
8896 	switch (type)
8897 	{
8898 		case DATA_TYPE_SIGNED_8:
8899 		case DATA_TYPE_UNSIGNED_8:
8900 			return "1";
8901 
8902 		case DATA_TYPE_SIGNED_16:
8903 		case DATA_TYPE_UNSIGNED_16:
8904 		case DATA_TYPE_FLOAT_16:
8905 			return "2";
8906 
8907 		case DATA_TYPE_SIGNED_32:
8908 		case DATA_TYPE_UNSIGNED_32:
8909 		case DATA_TYPE_FLOAT_32:
8910 		case DATA_TYPE_VEC2_SIGNED_16:
8911 			return "4";
8912 
8913 		case DATA_TYPE_SIGNED_64:
8914 		case DATA_TYPE_UNSIGNED_64:
8915 		case DATA_TYPE_FLOAT_64:
8916 		case DATA_TYPE_VEC2_SIGNED_32:
8917 			return "8";
8918 
8919 		default:
8920 			DE_ASSERT(false);
8921 	}
8922 	return "";
8923 }
8924 
isSigned(ConversionDataType type)8925 bool isSigned (ConversionDataType type)
8926 {
8927 	switch (type)
8928 	{
8929 		case DATA_TYPE_SIGNED_8:
8930 		case DATA_TYPE_SIGNED_16:
8931 		case DATA_TYPE_SIGNED_32:
8932 		case DATA_TYPE_SIGNED_64:
8933 		case DATA_TYPE_FLOAT_16:
8934 		case DATA_TYPE_FLOAT_32:
8935 		case DATA_TYPE_FLOAT_64:
8936 		case DATA_TYPE_VEC2_SIGNED_16:
8937 		case DATA_TYPE_VEC2_SIGNED_32:
8938 			return true;
8939 
8940 		case DATA_TYPE_UNSIGNED_8:
8941 		case DATA_TYPE_UNSIGNED_16:
8942 		case DATA_TYPE_UNSIGNED_32:
8943 		case DATA_TYPE_UNSIGNED_64:
8944 			return false;
8945 
8946 		default:
8947 			DE_ASSERT(false);
8948 	}
8949 	return false;
8950 }
8951 
isInt(ConversionDataType type)8952 bool isInt (ConversionDataType type)
8953 {
8954 	switch (type)
8955 	{
8956 		case DATA_TYPE_SIGNED_8:
8957 		case DATA_TYPE_SIGNED_16:
8958 		case DATA_TYPE_SIGNED_32:
8959 		case DATA_TYPE_SIGNED_64:
8960 		case DATA_TYPE_UNSIGNED_8:
8961 		case DATA_TYPE_UNSIGNED_16:
8962 		case DATA_TYPE_UNSIGNED_32:
8963 		case DATA_TYPE_UNSIGNED_64:
8964 			return true;
8965 
8966 		case DATA_TYPE_FLOAT_16:
8967 		case DATA_TYPE_FLOAT_32:
8968 		case DATA_TYPE_FLOAT_64:
8969 		case DATA_TYPE_VEC2_SIGNED_16:
8970 		case DATA_TYPE_VEC2_SIGNED_32:
8971 			return false;
8972 
8973 		default:
8974 			DE_ASSERT(false);
8975 	}
8976 	return false;
8977 }
8978 
isFloat(ConversionDataType type)8979 bool isFloat (ConversionDataType type)
8980 {
8981 	switch (type)
8982 	{
8983 		case DATA_TYPE_SIGNED_8:
8984 		case DATA_TYPE_SIGNED_16:
8985 		case DATA_TYPE_SIGNED_32:
8986 		case DATA_TYPE_SIGNED_64:
8987 		case DATA_TYPE_UNSIGNED_8:
8988 		case DATA_TYPE_UNSIGNED_16:
8989 		case DATA_TYPE_UNSIGNED_32:
8990 		case DATA_TYPE_UNSIGNED_64:
8991 		case DATA_TYPE_VEC2_SIGNED_16:
8992 		case DATA_TYPE_VEC2_SIGNED_32:
8993 			return false;
8994 
8995 		case DATA_TYPE_FLOAT_16:
8996 		case DATA_TYPE_FLOAT_32:
8997 		case DATA_TYPE_FLOAT_64:
8998 			return true;
8999 
9000 		default:
9001 			DE_ASSERT(false);
9002 	}
9003 	return false;
9004 }
9005 
getTypeName(ConversionDataType type)9006 const string getTypeName (ConversionDataType type)
9007 {
9008 	string prefix = isSigned(type) ? "" : "u";
9009 
9010 	if		(isInt(type))						return prefix + "int"	+ getBitWidthStr(type);
9011 	else if (isFloat(type))						return prefix + "float"	+ getBitWidthStr(type);
9012 	else if (type == DATA_TYPE_VEC2_SIGNED_16)	return "i16vec2";
9013 	else if (type == DATA_TYPE_VEC2_SIGNED_32)	return "i32vec2";
9014 	else										DE_ASSERT(false);
9015 
9016 	return "";
9017 }
9018 
getTestName(ConversionDataType from,ConversionDataType to,const char * suffix)9019 const string getTestName (ConversionDataType from, ConversionDataType to, const char* suffix)
9020 {
9021 	const string fullSuffix(suffix == DE_NULL ? "" : string("_") + string(suffix));
9022 
9023 	return getTypeName(from) + "_to_" + getTypeName(to) + fullSuffix;
9024 }
9025 
getAsmTypeName(ConversionDataType type)9026 const string getAsmTypeName (ConversionDataType type)
9027 {
9028 	string prefix;
9029 
9030 	if		(isInt(type))						prefix = isSigned(type) ? "i" : "u";
9031 	else if (isFloat(type))						prefix = "f";
9032 	else if (type == DATA_TYPE_VEC2_SIGNED_16)	return "i16vec2";
9033 	else if (type == DATA_TYPE_VEC2_SIGNED_32)	return "v2i32";
9034 	else										DE_ASSERT(false);
9035 
9036 	return prefix + getBitWidthStr(type);
9037 }
9038 
9039 template<typename T>
getSpecializedBuffer(deInt64 number)9040 BufferSp getSpecializedBuffer (deInt64 number)
9041 {
9042 	return BufferSp(new Buffer<T>(vector<T>(1, (T)number)));
9043 }
9044 
getBuffer(ConversionDataType type,deInt64 number)9045 BufferSp getBuffer (ConversionDataType type, deInt64 number)
9046 {
9047 	switch (type)
9048 	{
9049 		case DATA_TYPE_SIGNED_8:		return getSpecializedBuffer<deInt8>(number);
9050 		case DATA_TYPE_SIGNED_16:		return getSpecializedBuffer<deInt16>(number);
9051 		case DATA_TYPE_SIGNED_32:		return getSpecializedBuffer<deInt32>(number);
9052 		case DATA_TYPE_SIGNED_64:		return getSpecializedBuffer<deInt64>(number);
9053 		case DATA_TYPE_UNSIGNED_8:		return getSpecializedBuffer<deUint8>(number);
9054 		case DATA_TYPE_UNSIGNED_16:		return getSpecializedBuffer<deUint16>(number);
9055 		case DATA_TYPE_UNSIGNED_32:		return getSpecializedBuffer<deUint32>(number);
9056 		case DATA_TYPE_UNSIGNED_64:		return getSpecializedBuffer<deUint64>(number);
9057 		case DATA_TYPE_FLOAT_16:		return getSpecializedBuffer<deUint16>(number);
9058 		case DATA_TYPE_FLOAT_32:		return getSpecializedBuffer<deUint32>(number);
9059 		case DATA_TYPE_FLOAT_64:		return getSpecializedBuffer<deUint64>(number);
9060 		case DATA_TYPE_VEC2_SIGNED_16:	return getSpecializedBuffer<deUint32>(number);
9061 		case DATA_TYPE_VEC2_SIGNED_32:	return getSpecializedBuffer<deUint64>(number);
9062 
9063 		default:						TCU_THROW(InternalError, "Unimplemented type passed");
9064 	}
9065 }
9066 
usesInt8(ConversionDataType from,ConversionDataType to)9067 bool usesInt8 (ConversionDataType from, ConversionDataType to)
9068 {
9069 	return (from == DATA_TYPE_SIGNED_8 || to == DATA_TYPE_SIGNED_8 ||
9070 			from == DATA_TYPE_UNSIGNED_8 || to == DATA_TYPE_UNSIGNED_8);
9071 }
9072 
usesInt16(ConversionDataType from,ConversionDataType to)9073 bool usesInt16 (ConversionDataType from, ConversionDataType to)
9074 {
9075 	return (from == DATA_TYPE_SIGNED_16 || to == DATA_TYPE_SIGNED_16 ||
9076 			from == DATA_TYPE_UNSIGNED_16 || to == DATA_TYPE_UNSIGNED_16 ||
9077 			from == DATA_TYPE_VEC2_SIGNED_16 || to == DATA_TYPE_VEC2_SIGNED_16);
9078 }
9079 
usesInt32(ConversionDataType from,ConversionDataType to)9080 bool usesInt32 (ConversionDataType from, ConversionDataType to)
9081 {
9082 	return (from == DATA_TYPE_SIGNED_32 || to == DATA_TYPE_SIGNED_32 ||
9083 			from == DATA_TYPE_UNSIGNED_32 || to == DATA_TYPE_UNSIGNED_32 ||
9084 			from == DATA_TYPE_VEC2_SIGNED_32|| to == DATA_TYPE_VEC2_SIGNED_32);
9085 }
9086 
usesInt64(ConversionDataType from,ConversionDataType to)9087 bool usesInt64 (ConversionDataType from, ConversionDataType to)
9088 {
9089 	return (from == DATA_TYPE_SIGNED_64 || to == DATA_TYPE_SIGNED_64 ||
9090 			from == DATA_TYPE_UNSIGNED_64 || to == DATA_TYPE_UNSIGNED_64);
9091 }
9092 
usesFloat16(ConversionDataType from,ConversionDataType to)9093 bool usesFloat16 (ConversionDataType from, ConversionDataType to)
9094 {
9095 	return (from == DATA_TYPE_FLOAT_16 || to == DATA_TYPE_FLOAT_16);
9096 }
9097 
usesFloat32(ConversionDataType from,ConversionDataType to)9098 bool usesFloat32 (ConversionDataType from, ConversionDataType to)
9099 {
9100 	return (from == DATA_TYPE_FLOAT_32 || to == DATA_TYPE_FLOAT_32);
9101 }
9102 
usesFloat64(ConversionDataType from,ConversionDataType to)9103 bool usesFloat64 (ConversionDataType from, ConversionDataType to)
9104 {
9105 	return (from == DATA_TYPE_FLOAT_64 || to == DATA_TYPE_FLOAT_64);
9106 }
9107 
getVulkanFeaturesAndExtensions(ConversionDataType from,ConversionDataType to,VulkanFeatures & vulkanFeatures,vector<string> & extensions)9108 void getVulkanFeaturesAndExtensions (ConversionDataType from, ConversionDataType to, VulkanFeatures& vulkanFeatures, vector<string>& extensions)
9109 {
9110 	if (usesInt16(from, to) && !usesInt32(from, to))
9111 		vulkanFeatures.coreFeatures.shaderInt16 = DE_TRUE;
9112 
9113 	if (usesInt64(from, to))
9114 		vulkanFeatures.coreFeatures.shaderInt64 = DE_TRUE;
9115 
9116 	if (usesFloat64(from, to))
9117 		vulkanFeatures.coreFeatures.shaderFloat64 = DE_TRUE;
9118 
9119 	if (usesInt16(from, to) || usesFloat16(from, to))
9120 	{
9121 		extensions.push_back("VK_KHR_16bit_storage");
9122 		vulkanFeatures.ext16BitStorage |= EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
9123 	}
9124 
9125 	if (usesFloat16(from, to) || usesInt8(from, to))
9126 	{
9127 		extensions.push_back("VK_KHR_shader_float16_int8");
9128 
9129 		if (usesFloat16(from, to))
9130 		{
9131 			vulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_FLOAT16;
9132 		}
9133 
9134 		if (usesInt8(from, to))
9135 		{
9136 			vulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_INT8;
9137 
9138 			extensions.push_back("VK_KHR_8bit_storage");
9139 			vulkanFeatures.ext8BitStorage |= EXT8BITSTORAGEFEATURES_STORAGE_BUFFER;
9140 		}
9141 	}
9142 }
9143 
9144 struct ConvertCase
9145 {
ConvertCasevkt::SpirVAssembly::ConvertCase9146 	ConvertCase (const string& instruction, ConversionDataType from, ConversionDataType to, deInt64 number, bool separateOutput = false, deInt64 outputNumber = 0, const char* suffix = DE_NULL)
9147 	: m_fromType		(from)
9148 	, m_toType			(to)
9149 	, m_name			(getTestName(from, to, suffix))
9150 	, m_inputBuffer		(getBuffer(from, number))
9151 	{
9152 		string caps;
9153 		string decl;
9154 		string exts;
9155 
9156 		m_asmTypes["inputType"]		= getAsmTypeName(from);
9157 		m_asmTypes["outputType"]	= getAsmTypeName(to);
9158 
9159 		if (separateOutput)
9160 			m_outputBuffer = getBuffer(to, outputNumber);
9161 		else
9162 			m_outputBuffer = getBuffer(to, number);
9163 
9164 		if (usesInt8(from, to))
9165 		{
9166 			bool requiresInt8Capability = true;
9167 			if (instruction == "OpUConvert" || instruction == "OpSConvert")
9168 			{
9169 				// Conversions between 8 and 32 bit are provided by SPV_KHR_8bit_storage. The rest requires explicit Int8
9170 				if (usesInt32(from, to))
9171 					requiresInt8Capability = false;
9172 			}
9173 
9174 			caps += "OpCapability StorageBuffer8BitAccess\n";
9175 			if (requiresInt8Capability)
9176 				caps += "OpCapability Int8\n";
9177 
9178 			decl += "%i8         = OpTypeInt 8 1\n"
9179 					"%u8         = OpTypeInt 8 0\n";
9180 			exts += "OpExtension \"SPV_KHR_8bit_storage\"\n";
9181 		}
9182 
9183 		if (usesInt16(from, to))
9184 		{
9185 			bool requiresInt16Capability = true;
9186 
9187 			if (instruction == "OpUConvert" || instruction == "OpSConvert" || instruction == "OpFConvert")
9188 			{
9189 				// Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Int16
9190 				if (usesInt32(from, to) || usesFloat32(from, to))
9191 					requiresInt16Capability = false;
9192 			}
9193 
9194 			decl += "%i16        = OpTypeInt 16 1\n"
9195 					"%u16        = OpTypeInt 16 0\n"
9196 					"%i16vec2    = OpTypeVector %i16 2\n";
9197 
9198 			// Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Int16
9199 			if (requiresInt16Capability)
9200 				caps += "OpCapability Int16\n";
9201 		}
9202 
9203 		if (usesFloat16(from, to))
9204 		{
9205 			decl += "%f16        = OpTypeFloat 16\n";
9206 
9207 			// Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Float16
9208 			if (!(usesInt32(from, to) || usesFloat32(from, to)))
9209 				caps += "OpCapability Float16\n";
9210 		}
9211 
9212 		if (usesInt16(from, to) || usesFloat16(from, to))
9213 		{
9214 			caps += "OpCapability StorageUniformBufferBlock16\n";
9215 			exts += "OpExtension \"SPV_KHR_16bit_storage\"\n";
9216 		}
9217 
9218 		if (usesInt64(from, to))
9219 		{
9220 			caps += "OpCapability Int64\n";
9221 			decl += "%i64        = OpTypeInt 64 1\n"
9222 					"%u64        = OpTypeInt 64 0\n";
9223 		}
9224 
9225 		if (usesFloat64(from, to))
9226 		{
9227 			caps += "OpCapability Float64\n";
9228 			decl += "%f64        = OpTypeFloat 64\n";
9229 		}
9230 
9231 		m_asmTypes["datatype_capabilities"]		= caps;
9232 		m_asmTypes["datatype_additional_decl"]	= decl;
9233 		m_asmTypes["datatype_extensions"]		= exts;
9234 	}
9235 
9236 	ConversionDataType		m_fromType;
9237 	ConversionDataType		m_toType;
9238 	string					m_name;
9239 	map<string, string>		m_asmTypes;
9240 	BufferSp				m_inputBuffer;
9241 	BufferSp				m_outputBuffer;
9242 };
9243 
getConvertCaseShaderStr(const string & instruction,const ConvertCase & convertCase)9244 const string getConvertCaseShaderStr (const string& instruction, const ConvertCase& convertCase)
9245 {
9246 	map<string, string> params = convertCase.m_asmTypes;
9247 
9248 	params["instruction"]	= instruction;
9249 	params["inDecorator"]	= getByteWidthStr(convertCase.m_fromType);
9250 	params["outDecorator"]	= getByteWidthStr(convertCase.m_toType);
9251 
9252 	const StringTemplate shader (
9253 		"OpCapability Shader\n"
9254 		"${datatype_capabilities}"
9255 		"${datatype_extensions:opt}"
9256 		"OpMemoryModel Logical GLSL450\n"
9257 		"OpEntryPoint GLCompute %main \"main\"\n"
9258 		"OpExecutionMode %main LocalSize 1 1 1\n"
9259 		"OpSource GLSL 430\n"
9260 		"OpName %main           \"main\"\n"
9261 		// Decorators
9262 		"OpDecorate %indata DescriptorSet 0\n"
9263 		"OpDecorate %indata Binding 0\n"
9264 		"OpDecorate %outdata DescriptorSet 0\n"
9265 		"OpDecorate %outdata Binding 1\n"
9266 		"OpDecorate %in_buf BufferBlock\n"
9267 		"OpDecorate %out_buf BufferBlock\n"
9268 		"OpMemberDecorate %in_buf 0 Offset 0\n"
9269 		"OpMemberDecorate %out_buf 0 Offset 0\n"
9270 		// Base types
9271 		"%void       = OpTypeVoid\n"
9272 		"%voidf      = OpTypeFunction %void\n"
9273 		"%u32        = OpTypeInt 32 0\n"
9274 		"%i32        = OpTypeInt 32 1\n"
9275 		"%f32        = OpTypeFloat 32\n"
9276 		"%v2i32      = OpTypeVector %i32 2\n"
9277 		"${datatype_additional_decl}"
9278 		"%uvec3      = OpTypeVector %u32 3\n"
9279 		// Derived types
9280 		"%in_ptr     = OpTypePointer Uniform %${inputType}\n"
9281 		"%out_ptr    = OpTypePointer Uniform %${outputType}\n"
9282 		"%in_buf     = OpTypeStruct %${inputType}\n"
9283 		"%out_buf    = OpTypeStruct %${outputType}\n"
9284 		"%in_bufptr  = OpTypePointer Uniform %in_buf\n"
9285 		"%out_bufptr = OpTypePointer Uniform %out_buf\n"
9286 		"%indata     = OpVariable %in_bufptr Uniform\n"
9287 		"%outdata    = OpVariable %out_bufptr Uniform\n"
9288 		// Constants
9289 		"%zero       = OpConstant %i32 0\n"
9290 		// Main function
9291 		"%main       = OpFunction %void None %voidf\n"
9292 		"%label      = OpLabel\n"
9293 		"%inloc      = OpAccessChain %in_ptr %indata %zero\n"
9294 		"%outloc     = OpAccessChain %out_ptr %outdata %zero\n"
9295 		"%inval      = OpLoad %${inputType} %inloc\n"
9296 		"%conv       = ${instruction} %${outputType} %inval\n"
9297 		"              OpStore %outloc %conv\n"
9298 		"              OpReturn\n"
9299 		"              OpFunctionEnd\n"
9300 	);
9301 
9302 	return shader.specialize(params);
9303 }
9304 
createConvertCases(vector<ConvertCase> & testCases,const string & instruction)9305 void createConvertCases (vector<ConvertCase>& testCases, const string& instruction)
9306 {
9307 	if (instruction == "OpUConvert")
9308 	{
9309 		// Convert unsigned int to unsigned int
9310 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_8,		DATA_TYPE_UNSIGNED_16,		42));
9311 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_8,		DATA_TYPE_UNSIGNED_32,		73));
9312 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_8,		DATA_TYPE_UNSIGNED_64,		121));
9313 
9314 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_16,		DATA_TYPE_UNSIGNED_8,		33));
9315 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_16,		DATA_TYPE_UNSIGNED_32,		60653));
9316 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_16,		DATA_TYPE_UNSIGNED_64,		17991));
9317 
9318 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_32,		DATA_TYPE_UNSIGNED_64,		904256275));
9319 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_32,		DATA_TYPE_UNSIGNED_16,		6275));
9320 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_32,		DATA_TYPE_UNSIGNED_8,		17));
9321 
9322 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_64,		DATA_TYPE_UNSIGNED_32,		701256243));
9323 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_64,		DATA_TYPE_UNSIGNED_16,		4741));
9324 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_64,		DATA_TYPE_UNSIGNED_8,		65));
9325 	}
9326 	else if (instruction == "OpSConvert")
9327 	{
9328 		// Sign extension int->int
9329 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_8,			DATA_TYPE_SIGNED_16,		-30));
9330 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_8,			DATA_TYPE_SIGNED_32,		55));
9331 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_8,			DATA_TYPE_SIGNED_64,		-3));
9332 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_16,		DATA_TYPE_SIGNED_32,		14669));
9333 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_16,		DATA_TYPE_SIGNED_64,		-3341));
9334 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_32,		DATA_TYPE_SIGNED_64,		973610259));
9335 
9336 		// Truncate for int->int
9337 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_16,		DATA_TYPE_SIGNED_8,			81));
9338 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_32,		DATA_TYPE_SIGNED_8,			-93));
9339 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_64,		DATA_TYPE_SIGNED_8,			3182748172687672ll,					true,	56));
9340 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_32,		DATA_TYPE_SIGNED_16,		12382));
9341 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_64,		DATA_TYPE_SIGNED_32,		-972812359));
9342 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_64,		DATA_TYPE_SIGNED_16,		-1067742499291926803ll,				true,	-4371));
9343 
9344 		// Sign extension for int->uint
9345 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_8,			DATA_TYPE_UNSIGNED_16,		56));
9346 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_8,			DATA_TYPE_UNSIGNED_32,		-47,								true,	4294967249u));
9347 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_8,			DATA_TYPE_UNSIGNED_64,		-5,									true,	18446744073709551611ull));
9348 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_16,		DATA_TYPE_UNSIGNED_32,		14669));
9349 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_16,		DATA_TYPE_UNSIGNED_64,		-3341,								true,	18446744073709548275ull));
9350 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_32,		DATA_TYPE_UNSIGNED_64,		973610259));
9351 
9352 		// Truncate for int->uint
9353 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_16,		DATA_TYPE_UNSIGNED_8,		-25711,								true,	145));
9354 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_32,		DATA_TYPE_UNSIGNED_8,		103));
9355 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_64,		DATA_TYPE_UNSIGNED_8,		-1067742499291926803ll,				true,	61165));
9356 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_32,		DATA_TYPE_UNSIGNED_16,		12382));
9357 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_64,		DATA_TYPE_UNSIGNED_32,		-972812359,							true,	3322154937u));
9358 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_64,		DATA_TYPE_UNSIGNED_16,		-1067742499291926803ll,				true,	61165));
9359 
9360 		// Sign extension for uint->int
9361 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_8,		DATA_TYPE_SIGNED_16,		71));
9362 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_8,		DATA_TYPE_SIGNED_32,		201,								true,	-55));
9363 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_8,		DATA_TYPE_SIGNED_64,		188,								true,	-68));
9364 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_16,		DATA_TYPE_SIGNED_32,		14669));
9365 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_16,		DATA_TYPE_SIGNED_64,		62195,								true,	-3341));
9366 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_32,		DATA_TYPE_SIGNED_64,		973610259));
9367 
9368 		// Truncate for uint->int
9369 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_16,		DATA_TYPE_SIGNED_8,			67));
9370 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_32,		DATA_TYPE_SIGNED_8,			133,								true,	-123));
9371 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_64,		DATA_TYPE_SIGNED_8,			836927654193256494ull,				true,	46));
9372 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_32,		DATA_TYPE_SIGNED_16,		12382));
9373 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_64,		DATA_TYPE_SIGNED_32,		18446744072736739257ull,			true,	-972812359));
9374 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_64,		DATA_TYPE_SIGNED_16,		17379001574417624813ull,			true,	-4371));
9375 
9376 		// Convert i16vec2 to i32vec2 and vice versa
9377 		// Unsigned values are used here to represent negative signed values and to allow defined shifting behaviour.
9378 		// The actual signed value -32123 is used here as uint16 value 33413 and uint32 value 4294935173
9379 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_VEC2_SIGNED_16,	DATA_TYPE_VEC2_SIGNED_32,	(33413u << 16)			| 27593,	true,	(4294935173ull << 32)	| 27593));
9380 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_VEC2_SIGNED_32,	DATA_TYPE_VEC2_SIGNED_16,	(4294935173ull << 32)	| 27593,	true,	(33413u << 16)			| 27593));
9381 	}
9382 	else if (instruction == "OpFConvert")
9383 	{
9384 		// All hexadecimal values below represent 1234.0 as 16/32/64-bit IEEE 754 float
9385 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_32,			DATA_TYPE_FLOAT_64,			0x449a4000,							true,	0x4093480000000000));
9386 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_64,			DATA_TYPE_FLOAT_32,			0x4093480000000000,					true,	0x449a4000));
9387 
9388 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_32,			DATA_TYPE_FLOAT_16,			0x449a4000,							true,	0x64D2));
9389 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_FLOAT_32,			0x64D2,								true,	0x449a4000));
9390 
9391 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_FLOAT_64,			0x64D2,								true,	0x4093480000000000));
9392 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_64,			DATA_TYPE_FLOAT_16,			0x4093480000000000,					true,	0x64D2));
9393 	}
9394 	else if (instruction == "OpConvertFToU")
9395 	{
9396 		// Normal numbers from uint8 range
9397 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_UNSIGNED_8,		0x5020,								true,	33,									"33"));
9398 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_32,			DATA_TYPE_UNSIGNED_8,		0x42280000,							true,	42,									"42"));
9399 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_64,			DATA_TYPE_UNSIGNED_8,		0x4067800000000000ull,				true,	188,								"188"));
9400 
9401 		// Maximum uint8 value
9402 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_UNSIGNED_8,		0x5BF8,								true,	255,								"max"));
9403 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_32,			DATA_TYPE_UNSIGNED_8,		0x437F0000,							true,	255,								"max"));
9404 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_64,			DATA_TYPE_UNSIGNED_8,		0x406FE00000000000ull,				true,	255,								"max"));
9405 
9406 		// +0
9407 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_UNSIGNED_8,		0x0000,								true,	0,									"p0"));
9408 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_32,			DATA_TYPE_UNSIGNED_8,		0x00000000,							true,	0,									"p0"));
9409 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_64,			DATA_TYPE_UNSIGNED_8,		0x0000000000000000ull,				true,	0,									"p0"));
9410 
9411 		// -0
9412 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_UNSIGNED_8,		0x8000,								true,	0,									"m0"));
9413 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_32,			DATA_TYPE_UNSIGNED_8,		0x80000000,							true,	0,									"m0"));
9414 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_64,			DATA_TYPE_UNSIGNED_8,		0x8000000000000000ull,				true,	0,									"m0"));
9415 
9416 		// All hexadecimal values below represent 1234.0 as 16/32/64-bit IEEE 754 float
9417 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_UNSIGNED_16,		0x64D2,								true,	1234,								"1234"));
9418 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_UNSIGNED_32,		0x64D2,								true,	1234,								"1234"));
9419 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_UNSIGNED_64,		0x64D2,								true,	1234,								"1234"));
9420 
9421 		// 0x7BFF = 0111 1011 1111 1111 = 0 11110 1111111111 = 65504
9422 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_UNSIGNED_16,		0x7BFF,								true,	65504,								"max"));
9423 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_UNSIGNED_32,		0x7BFF,								true,	65504,								"max"));
9424 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_UNSIGNED_64,		0x7BFF,								true,	65504,								"max"));
9425 
9426 		// +0
9427 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_UNSIGNED_32,		0x0000,								true,	0,									"p0"));
9428 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_UNSIGNED_16,		0x0000,								true,	0,									"p0"));
9429 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_UNSIGNED_64,		0x0000,								true,	0,									"p0"));
9430 
9431 		// -0
9432 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_UNSIGNED_16,		0x8000,								true,	0,									"m0"));
9433 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_UNSIGNED_32,		0x8000,								true,	0,									"m0"));
9434 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_UNSIGNED_64,		0x8000,								true,	0,									"m0"));
9435 
9436 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_32,			DATA_TYPE_UNSIGNED_16,		0x449a4000,							true,	1234));
9437 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_32,			DATA_TYPE_UNSIGNED_32,		0x449a4000,							true,	1234));
9438 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_32,			DATA_TYPE_UNSIGNED_64,		0x449a4000,							true,	1234));
9439 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_64,			DATA_TYPE_UNSIGNED_16,		0x4093480000000000,					true,	1234));
9440 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_64,			DATA_TYPE_UNSIGNED_32,		0x4093480000000000,					true,	1234));
9441 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_64,			DATA_TYPE_UNSIGNED_64,		0x4093480000000000,					true,	1234));
9442 	}
9443 	else if (instruction == "OpConvertUToF")
9444 	{
9445 		// Normal numbers from uint8 range
9446 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_8,		DATA_TYPE_FLOAT_16,			116,								true,	0x5740,								"116"));
9447 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_8,		DATA_TYPE_FLOAT_32,			232,								true,	0x43680000,							"232"));
9448 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_8,		DATA_TYPE_FLOAT_64,			164,								true,	0x4064800000000000ull,				"164"));
9449 
9450 		// Maximum uint8 value
9451 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_8,		DATA_TYPE_FLOAT_16,			255,								true,	0x5BF8,								"max"));
9452 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_8,		DATA_TYPE_FLOAT_32,			255,								true,	0x437F0000,							"max"));
9453 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_8,		DATA_TYPE_FLOAT_64,			255,								true,	0x406FE00000000000ull,				"max"));
9454 
9455 		// All hexadecimal values below represent 1234.0 as 32/64-bit IEEE 754 float
9456 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_16,		DATA_TYPE_FLOAT_16,			1234,								true,	0x64D2,								"1234"));
9457 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_32,		DATA_TYPE_FLOAT_16,			1234,								true,	0x64D2,								"1234"));
9458 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_64,		DATA_TYPE_FLOAT_16,			1234,								true,	0x64D2,								"1234"));
9459 
9460 		// 0x7BFF = 0111 1011 1111 1111 = 0 11110 1111111111 = 65504
9461 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_16,		DATA_TYPE_FLOAT_16,			65504,								true,	0x7BFF,								"max"));
9462 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_32,		DATA_TYPE_FLOAT_16,			65504,								true,	0x7BFF,								"max"));
9463 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_64,		DATA_TYPE_FLOAT_16,			65504,								true,	0x7BFF,								"max"));
9464 
9465 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_16,		DATA_TYPE_FLOAT_32,			1234,								true,	0x449a4000));
9466 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_16,		DATA_TYPE_FLOAT_64,			1234,								true,	0x4093480000000000));
9467 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_32,		DATA_TYPE_FLOAT_32,			1234,								true,	0x449a4000));
9468 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_32,		DATA_TYPE_FLOAT_64,			1234,								true,	0x4093480000000000));
9469 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_64,		DATA_TYPE_FLOAT_32,			1234,								true,	0x449a4000));
9470 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_UNSIGNED_64,		DATA_TYPE_FLOAT_64,			1234,								true,	0x4093480000000000));
9471 	}
9472 	else if (instruction == "OpConvertFToS")
9473 	{
9474 		// Normal numbers from int8 range
9475 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_SIGNED_8,			0xC980,								true,	-11,								"m11"));
9476 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_32,			DATA_TYPE_SIGNED_8,			0xC2140000,							true,	-37,								"m37"));
9477 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_64,			DATA_TYPE_SIGNED_8,			0xC050800000000000ull,				true,	-66,								"m66"));
9478 
9479 		// Minimum int8 value
9480 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_SIGNED_8,			0xD800,								true,	-128,								"min"));
9481 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_32,			DATA_TYPE_SIGNED_8,			0xC3000000,							true,	-128,								"min"));
9482 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_64,			DATA_TYPE_SIGNED_8,			0xC060000000000000ull,				true,	-128,								"min"));
9483 
9484 		// Maximum int8 value
9485 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_SIGNED_8,			0x57F0,								true,	127,								"max"));
9486 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_32,			DATA_TYPE_SIGNED_8,			0x42FE0000,							true,	127,								"max"));
9487 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_64,			DATA_TYPE_SIGNED_8,			0x405FC00000000000ull,				true,	127,								"max"));
9488 
9489 		// +0
9490 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_SIGNED_8,			0x0000,								true,	0,									"p0"));
9491 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_32,			DATA_TYPE_SIGNED_8,			0x00000000,							true,	0,									"p0"));
9492 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_64,			DATA_TYPE_SIGNED_8,			0x0000000000000000ull,				true,	0,									"p0"));
9493 
9494 		// -0
9495 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_SIGNED_8,			0x8000,								true,	0,									"m0"));
9496 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_32,			DATA_TYPE_SIGNED_8,			0x80000000,							true,	0,									"m0"));
9497 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_64,			DATA_TYPE_SIGNED_8,			0x8000000000000000ull,				true,	0,									"m0"));
9498 
9499 		// All hexadecimal values below represent -1234.0 as 32/64-bit IEEE 754 float
9500 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_SIGNED_16,		0xE4D2,								true,	-1234,								"m1234"));
9501 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_SIGNED_32,		0xE4D2,								true,	-1234,								"m1234"));
9502 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_SIGNED_64,		0xE4D2,								true,	-1234,								"m1234"));
9503 
9504 		// 0xF800 = 1111 1000 0000 0000 = 1 11110 0000000000 = -32768
9505 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_SIGNED_16,		0xF800,								true,	-32768,								"min"));
9506 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_SIGNED_32,		0xF800,								true,	-32768,								"min"));
9507 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_SIGNED_64,		0xF800,								true,	-32768,								"min"));
9508 
9509 		// 0x77FF = 0111 0111 1111 1111 = 0 11101 1111111111 = 32752
9510 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_SIGNED_16,		0x77FF,								true,	32752,								"max"));
9511 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_SIGNED_32,		0x77FF,								true,	32752,								"max"));
9512 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_SIGNED_64,		0x77FF,								true,	32752,								"max"));
9513 
9514 		// +0
9515 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_SIGNED_16,		0x0000,								true,	0,									"p0"));
9516 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_SIGNED_32,		0x0000,								true,	0,									"p0"));
9517 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_SIGNED_64,		0x0000,								true,	0,									"p0"));
9518 
9519 		// -0
9520 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_SIGNED_16,		0x8000,								true,	0,									"m0"));
9521 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_SIGNED_32,		0x8000,								true,	0,									"m0"));
9522 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_16,			DATA_TYPE_SIGNED_64,		0x8000,								true,	0,									"m0"));
9523 
9524 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_32,			DATA_TYPE_SIGNED_16,		0xc49a4000,							true,	-1234));
9525 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_32,			DATA_TYPE_SIGNED_32,		0xc49a4000,							true,	-1234));
9526 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_32,			DATA_TYPE_SIGNED_64,		0xc49a4000,							true,	-1234));
9527 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_64,			DATA_TYPE_SIGNED_16,		0xc093480000000000,					true,	-1234));
9528 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_64,			DATA_TYPE_SIGNED_32,		0xc093480000000000,					true,	-1234));
9529 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_64,			DATA_TYPE_SIGNED_64,		0xc093480000000000,					true,	-1234));
9530 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_32,			DATA_TYPE_SIGNED_16,		0x453b9000,							true,	 3001,								"p3001"));
9531 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_FLOAT_32,			DATA_TYPE_SIGNED_16,		0xc53b9000,							true,	-3001,								"m3001"));
9532 	}
9533 	else if (instruction == "OpConvertSToF")
9534 	{
9535 		// Normal numbers from int8 range
9536 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_8,			DATA_TYPE_FLOAT_16,			-12,								true,	0xCA00,								"m21"));
9537 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_8,			DATA_TYPE_FLOAT_32,			-21,								true,	0xC1A80000,							"m21"));
9538 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_8,			DATA_TYPE_FLOAT_64,			-99,								true,	0xC058C00000000000ull,				"m99"));
9539 
9540 		// Minimum int8 value
9541 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_8,			DATA_TYPE_FLOAT_16,			-128,								true,	0xD800,								"min"));
9542 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_8,			DATA_TYPE_FLOAT_32,			-128,								true,	0xC3000000,							"min"));
9543 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_8,			DATA_TYPE_FLOAT_64,			-128,								true,	0xC060000000000000ull,				"min"));
9544 
9545 		// Maximum int8 value
9546 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_8,			DATA_TYPE_FLOAT_16,			127,								true,	0x57F0,								"max"));
9547 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_8,			DATA_TYPE_FLOAT_32,			127,								true,	0x42FE0000,							"max"));
9548 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_8,			DATA_TYPE_FLOAT_64,			127,								true,	0x405FC00000000000ull,				"max"));
9549 
9550 		// All hexadecimal values below represent 1234.0 as 32/64-bit IEEE 754 float
9551 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_16,		DATA_TYPE_FLOAT_16,			-1234,								true,	0xE4D2,								"m1234"));
9552 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_32,		DATA_TYPE_FLOAT_16,			-1234,								true,	0xE4D2,								"m1234"));
9553 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_64,		DATA_TYPE_FLOAT_16,			-1234,								true,	0xE4D2,								"m1234"));
9554 
9555 		// 0xF800 = 1111 1000 0000 0000 = 1 11110 0000000000 = -32768
9556 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_16,		DATA_TYPE_FLOAT_16,			-32768,								true,	0xF800,								"min"));
9557 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_32,		DATA_TYPE_FLOAT_16,			-32768,								true,	0xF800,								"min"));
9558 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_64,		DATA_TYPE_FLOAT_16,			-32768,								true,	0xF800,								"min"));
9559 
9560 		// 0x77FF = 0111 0111 1111 1111 = 0 11101 1111111111 = 32752
9561 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_16,		DATA_TYPE_FLOAT_16,			32752,								true,	0x77FF,								"max"));
9562 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_32,		DATA_TYPE_FLOAT_16,			32752,								true,	0x77FF,								"max"));
9563 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_64,		DATA_TYPE_FLOAT_16,			32752,								true,	0x77FF,								"max"));
9564 
9565 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_16,		DATA_TYPE_FLOAT_32,			-1234,								true,	0xc49a4000));
9566 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_16,		DATA_TYPE_FLOAT_64,			-1234,								true,	0xc093480000000000));
9567 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_32,		DATA_TYPE_FLOAT_32,			-1234,								true,	0xc49a4000));
9568 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_32,		DATA_TYPE_FLOAT_64,			-1234,								true,	0xc093480000000000));
9569 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_64,		DATA_TYPE_FLOAT_32,			-1234,								true,	0xc49a4000));
9570 		testCases.push_back(ConvertCase(instruction,	DATA_TYPE_SIGNED_64,		DATA_TYPE_FLOAT_64,			-1234,								true,	0xc093480000000000));
9571 	}
9572 	else
9573 		DE_FATAL("Unknown instruction");
9574 }
9575 
getConvertCaseFragments(string instruction,const ConvertCase & convertCase)9576 const map<string, string> getConvertCaseFragments (string instruction, const ConvertCase& convertCase)
9577 {
9578 	map<string, string> params = convertCase.m_asmTypes;
9579 	map<string, string> fragments;
9580 
9581 	params["instruction"] = instruction;
9582 	params["inDecorator"] = getByteWidthStr(convertCase.m_fromType);
9583 
9584 	const StringTemplate decoration (
9585 		"      OpDecorate %SSBOi DescriptorSet 0\n"
9586 		"      OpDecorate %SSBOo DescriptorSet 0\n"
9587 		"      OpDecorate %SSBOi Binding 0\n"
9588 		"      OpDecorate %SSBOo Binding 1\n"
9589 		"      OpDecorate %s_SSBOi Block\n"
9590 		"      OpDecorate %s_SSBOo Block\n"
9591 		"OpMemberDecorate %s_SSBOi 0 Offset 0\n"
9592 		"OpMemberDecorate %s_SSBOo 0 Offset 0\n");
9593 
9594 	const StringTemplate pre_main (
9595 		"${datatype_additional_decl:opt}"
9596 		"    %ptr_in = OpTypePointer StorageBuffer %${inputType}\n"
9597 		"   %ptr_out = OpTypePointer StorageBuffer %${outputType}\n"
9598 		"   %s_SSBOi = OpTypeStruct %${inputType}\n"
9599 		"   %s_SSBOo = OpTypeStruct %${outputType}\n"
9600 		" %ptr_SSBOi = OpTypePointer StorageBuffer %s_SSBOi\n"
9601 		" %ptr_SSBOo = OpTypePointer StorageBuffer %s_SSBOo\n"
9602 		"     %SSBOi = OpVariable %ptr_SSBOi StorageBuffer\n"
9603 		"     %SSBOo = OpVariable %ptr_SSBOo StorageBuffer\n");
9604 
9605 	const StringTemplate testfun (
9606 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9607 		"%param     = OpFunctionParameter %v4f32\n"
9608 		"%label     = OpLabel\n"
9609 		"%iLoc      = OpAccessChain %ptr_in %SSBOi %c_u32_0\n"
9610 		"%oLoc      = OpAccessChain %ptr_out %SSBOo %c_u32_0\n"
9611 		"%valIn     = OpLoad %${inputType} %iLoc\n"
9612 		"%valOut    = ${instruction} %${outputType} %valIn\n"
9613 		"             OpStore %oLoc %valOut\n"
9614 		"             OpReturnValue %param\n"
9615 		"             OpFunctionEnd\n");
9616 
9617 	params["datatype_extensions"] =
9618 		params["datatype_extensions"] +
9619 		"OpExtension \"SPV_KHR_storage_buffer_storage_class\"\n";
9620 
9621 	fragments["capability"]	= params["datatype_capabilities"];
9622 	fragments["extension"]	= params["datatype_extensions"];
9623 	fragments["decoration"]	= decoration.specialize(params);
9624 	fragments["pre_main"]	= pre_main.specialize(params);
9625 	fragments["testfun"]	= testfun.specialize(params);
9626 
9627 	return fragments;
9628 }
9629 
9630 // Test for OpSConvert, OpUConvert, OpFConvert and OpConvert* in compute shaders
createConvertComputeTests(tcu::TestContext & testCtx,const string & instruction,const string & name)9631 tcu::TestCaseGroup* createConvertComputeTests (tcu::TestContext& testCtx, const string& instruction, const string& name)
9632 {
9633 	de::MovePtr<tcu::TestCaseGroup>		group(new tcu::TestCaseGroup(testCtx, name.c_str(), instruction.c_str()));
9634 	vector<ConvertCase>					testCases;
9635 	createConvertCases(testCases, instruction);
9636 
9637 	for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
9638 	{
9639 		ComputeShaderSpec spec;
9640 		spec.assembly			= getConvertCaseShaderStr(instruction, *test);
9641 		spec.numWorkGroups		= IVec3(1, 1, 1);
9642 		spec.inputs.push_back	(test->m_inputBuffer);
9643 		spec.outputs.push_back	(test->m_outputBuffer);
9644 
9645 		getVulkanFeaturesAndExtensions(test->m_fromType, test->m_toType, spec.requestedVulkanFeatures, spec.extensions);
9646 
9647 		group->addChild(new SpvAsmComputeShaderCase(testCtx, test->m_name.c_str(), "", spec));
9648 	}
9649 	return group.release();
9650 }
9651 
9652 // Test for OpSConvert, OpUConvert, OpFConvert and OpConvert* in graphics shaders
createConvertGraphicsTests(tcu::TestContext & testCtx,const string & instruction,const string & name)9653 tcu::TestCaseGroup* createConvertGraphicsTests (tcu::TestContext& testCtx, const string& instruction, const string& name)
9654 {
9655 	de::MovePtr<tcu::TestCaseGroup>		group(new tcu::TestCaseGroup(testCtx, name.c_str(), instruction.c_str()));
9656 	vector<ConvertCase>					testCases;
9657 	createConvertCases(testCases, instruction);
9658 
9659 	for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
9660 	{
9661 		map<string, string>	fragments		= getConvertCaseFragments(instruction, *test);
9662 		VulkanFeatures		vulkanFeatures;
9663 		GraphicsResources	resources;
9664 		vector<string>		extensions;
9665 		SpecConstants		noSpecConstants;
9666 		PushConstants		noPushConstants;
9667 		GraphicsInterfaces	noInterfaces;
9668 		tcu::RGBA			defaultColors[4];
9669 
9670 		getDefaultColors			(defaultColors);
9671 		resources.inputs.push_back	(Resource(test->m_inputBuffer, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9672 		resources.outputs.push_back	(Resource(test->m_outputBuffer, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9673 		extensions.push_back		("VK_KHR_storage_buffer_storage_class");
9674 
9675 		getVulkanFeaturesAndExtensions(test->m_fromType, test->m_toType, vulkanFeatures, extensions);
9676 
9677 		createTestsForAllStages(
9678 			test->m_name, defaultColors, defaultColors, fragments, noSpecConstants,
9679 			noPushConstants, resources, noInterfaces, extensions, vulkanFeatures, group.get());
9680 	}
9681 	return group.release();
9682 }
9683 
9684 // Constant-Creation Instructions: OpConstant, OpConstantComposite
createOpConstantFloat16Tests(tcu::TestContext & testCtx)9685 tcu::TestCaseGroup* createOpConstantFloat16Tests(tcu::TestContext& testCtx)
9686 {
9687 	de::MovePtr<tcu::TestCaseGroup> opConstantCompositeTests		(new tcu::TestCaseGroup(testCtx, "opconstant", "OpConstant and OpConstantComposite instruction"));
9688 	RGBA							inputColors[4];
9689 	RGBA							outputColors[4];
9690 	vector<string>					extensions;
9691 	GraphicsResources				resources;
9692 	VulkanFeatures					features;
9693 
9694 	const char						functionStart[]	 =
9695 		"%test_code             = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9696 		"%param1                = OpFunctionParameter %v4f32\n"
9697 		"%lbl                   = OpLabel\n";
9698 
9699 	const char						functionEnd[]		=
9700 		"%transformed_param_32  = OpFConvert %v4f32 %transformed_param\n"
9701 		"                         OpReturnValue %transformed_param_32\n"
9702 		"                         OpFunctionEnd\n";
9703 
9704 	struct NameConstantsCode
9705 	{
9706 		string name;
9707 		string constants;
9708 		string code;
9709 	};
9710 
9711 #define FLOAT_16_COMMON_TYPES_AND_CONSTS \
9712 			"%f16                  = OpTypeFloat 16\n"                                                 \
9713 			"%c_f16_0              = OpConstant %f16 0.0\n"                                            \
9714 			"%c_f16_0_5            = OpConstant %f16 0.5\n"                                            \
9715 			"%c_f16_1              = OpConstant %f16 1.0\n"                                            \
9716 			"%v4f16                = OpTypeVector %f16 4\n"                                            \
9717 			"%fp_f16               = OpTypePointer Function %f16\n"                                    \
9718 			"%fp_v4f16             = OpTypePointer Function %v4f16\n"                                  \
9719 			"%c_v4f16_1_1_1_1      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_1\n" \
9720 			"%a4f16                = OpTypeArray %f16 %c_u32_4\n"                                      \
9721 
9722 	NameConstantsCode				tests[] =
9723 	{
9724 		{
9725 			"vec4",
9726 
9727 			FLOAT_16_COMMON_TYPES_AND_CONSTS
9728 			"%cval                 = OpConstantComposite %v4f16 %c_f16_0_5 %c_f16_0_5 %c_f16_0_5 %c_f16_0\n",
9729 			"%param1_16            = OpFConvert %v4f16 %param1\n"
9730 			"%transformed_param    = OpFAdd %v4f16 %param1_16 %cval\n"
9731 		},
9732 		{
9733 			"struct",
9734 
9735 			FLOAT_16_COMMON_TYPES_AND_CONSTS
9736 			"%stype                = OpTypeStruct %v4f16 %f16\n"
9737 			"%fp_stype             = OpTypePointer Function %stype\n"
9738 			"%f16_n_1              = OpConstant %f16 -1.0\n"
9739 			"%f16_1_5              = OpConstant %f16 !0x3e00\n" // +1.5
9740 			"%cvec                 = OpConstantComposite %v4f16 %f16_1_5 %f16_1_5 %f16_1_5 %c_f16_1\n"
9741 			"%cval                 = OpConstantComposite %stype %cvec %f16_n_1\n",
9742 
9743 			"%v                    = OpVariable %fp_stype Function %cval\n"
9744 			"%vec_ptr              = OpAccessChain %fp_v4f16 %v %c_u32_0\n"
9745 			"%f16_ptr              = OpAccessChain %fp_f16 %v %c_u32_1\n"
9746 			"%vec_val              = OpLoad %v4f16 %vec_ptr\n"
9747 			"%f16_val              = OpLoad %f16 %f16_ptr\n"
9748 			"%tmp1                 = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_1 %f16_val\n" // vec4(-1)
9749 			"%param1_16            = OpFConvert %v4f16 %param1\n"
9750 			"%tmp2                 = OpFAdd %v4f16 %tmp1 %param1_16\n" // param1 + vec4(-1)
9751 			"%transformed_param    = OpFAdd %v4f16 %tmp2 %vec_val\n" // param1 + vec4(-1) + vec4(1.5, 1.5, 1.5, 1.0)
9752 		},
9753 		{
9754 			// [1|0|0|0.5] [x] = x + 0.5
9755 			// [0|1|0|0.5] [y] = y + 0.5
9756 			// [0|0|1|0.5] [z] = z + 0.5
9757 			// [0|0|0|1  ] [1] = 1
9758 			"matrix",
9759 
9760 			FLOAT_16_COMMON_TYPES_AND_CONSTS
9761 			"%mat4x4_f16           = OpTypeMatrix %v4f16 4\n"
9762 			"%v4f16_1_0_0_0        = OpConstantComposite %v4f16 %c_f16_1 %c_f16_0 %c_f16_0 %c_f16_0\n"
9763 			"%v4f16_0_1_0_0        = OpConstantComposite %v4f16 %c_f16_0 %c_f16_1 %c_f16_0 %c_f16_0\n"
9764 			"%v4f16_0_0_1_0        = OpConstantComposite %v4f16 %c_f16_0 %c_f16_0 %c_f16_1 %c_f16_0\n"
9765 			"%v4f16_0_5_0_5_0_5_1  = OpConstantComposite %v4f16 %c_f16_0_5 %c_f16_0_5 %c_f16_0_5 %c_f16_1\n"
9766 			"%cval                 = OpConstantComposite %mat4x4_f16 %v4f16_1_0_0_0 %v4f16_0_1_0_0 %v4f16_0_0_1_0 %v4f16_0_5_0_5_0_5_1\n",
9767 
9768 			"%param1_16            = OpFConvert %v4f16 %param1\n"
9769 			"%transformed_param    = OpMatrixTimesVector %v4f16 %cval %param1_16\n"
9770 		},
9771 		{
9772 			"array",
9773 
9774 			FLOAT_16_COMMON_TYPES_AND_CONSTS
9775 			"%c_v4f16_1_1_1_0      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_0\n"
9776 			"%fp_a4f16             = OpTypePointer Function %a4f16\n"
9777 			"%f16_n_1              = OpConstant %f16 -1.0\n"
9778 			"%f16_1_5              = OpConstant %f16 !0x3e00\n" // +1.5
9779 			"%carr                 = OpConstantComposite %a4f16 %c_f16_0 %f16_n_1 %f16_1_5 %c_f16_0\n",
9780 
9781 			"%v                    = OpVariable %fp_a4f16 Function %carr\n"
9782 			"%f                    = OpAccessChain %fp_f16 %v %c_u32_0\n"
9783 			"%f1                   = OpAccessChain %fp_f16 %v %c_u32_1\n"
9784 			"%f2                   = OpAccessChain %fp_f16 %v %c_u32_2\n"
9785 			"%f3                   = OpAccessChain %fp_f16 %v %c_u32_3\n"
9786 			"%f_val                = OpLoad %f16 %f\n"
9787 			"%f1_val               = OpLoad %f16 %f1\n"
9788 			"%f2_val               = OpLoad %f16 %f2\n"
9789 			"%f3_val               = OpLoad %f16 %f3\n"
9790 			"%ftot1                = OpFAdd %f16 %f_val %f1_val\n"
9791 			"%ftot2                = OpFAdd %f16 %ftot1 %f2_val\n"
9792 			"%ftot3                = OpFAdd %f16 %ftot2 %f3_val\n"  // 0 - 1 + 1.5 + 0
9793 			"%add_vec              = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_0 %ftot3\n"
9794 			"%param1_16            = OpFConvert %v4f16 %param1\n"
9795 			"%transformed_param    = OpFAdd %v4f16 %param1_16 %add_vec\n"
9796 		},
9797 		{
9798 			//
9799 			// [
9800 			//   {
9801 			//      0.0,
9802 			//      [ 1.0, 1.0, 1.0, 1.0]
9803 			//   },
9804 			//   {
9805 			//      1.0,
9806 			//      [ 0.0, 0.5, 0.0, 0.0]
9807 			//   }, //     ^^^
9808 			//   {
9809 			//      0.0,
9810 			//      [ 1.0, 1.0, 1.0, 1.0]
9811 			//   }
9812 			// ]
9813 			"array_of_struct_of_array",
9814 
9815 			FLOAT_16_COMMON_TYPES_AND_CONSTS
9816 			"%c_v4f16_1_1_1_0      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_0\n"
9817 			"%fp_a4f16             = OpTypePointer Function %a4f16\n"
9818 			"%stype                = OpTypeStruct %f16 %a4f16\n"
9819 			"%a3stype              = OpTypeArray %stype %c_u32_3\n"
9820 			"%fp_a3stype           = OpTypePointer Function %a3stype\n"
9821 			"%ca4f16_0             = OpConstantComposite %a4f16 %c_f16_0 %c_f16_0_5 %c_f16_0 %c_f16_0\n"
9822 			"%ca4f16_1             = OpConstantComposite %a4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_1\n"
9823 			"%cstype1              = OpConstantComposite %stype %c_f16_0 %ca4f16_1\n"
9824 			"%cstype2              = OpConstantComposite %stype %c_f16_1 %ca4f16_0\n"
9825 			"%carr                 = OpConstantComposite %a3stype %cstype1 %cstype2 %cstype1",
9826 
9827 			"%v                    = OpVariable %fp_a3stype Function %carr\n"
9828 			"%f                    = OpAccessChain %fp_f16 %v %c_u32_1 %c_u32_1 %c_u32_1\n"
9829 			"%f_l                  = OpLoad %f16 %f\n"
9830 			"%add_vec              = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_0 %f_l\n"
9831 			"%param1_16            = OpFConvert %v4f16 %param1\n"
9832 			"%transformed_param    = OpFAdd %v4f16 %param1_16 %add_vec\n"
9833 		}
9834 	};
9835 
9836 	getHalfColorsFullAlpha(inputColors);
9837 	outputColors[0] = RGBA(255, 255, 255, 255);
9838 	outputColors[1] = RGBA(255, 127, 127, 255);
9839 	outputColors[2] = RGBA(127, 255, 127, 255);
9840 	outputColors[3] = RGBA(127, 127, 255, 255);
9841 
9842 	extensions.push_back("VK_KHR_16bit_storage");
9843 	extensions.push_back("VK_KHR_shader_float16_int8");
9844 	features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
9845 
9846 	for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
9847 	{
9848 		map<string, string> fragments;
9849 
9850 		fragments["extension"]	= "OpExtension \"SPV_KHR_16bit_storage\"";
9851 		fragments["capability"]	= "OpCapability Float16\n";
9852 		fragments["pre_main"]	= tests[testNdx].constants;
9853 		fragments["testfun"]	= string(functionStart) + tests[testNdx].code + functionEnd;
9854 
9855 		createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, resources, extensions, opConstantCompositeTests.get(), features);
9856 	}
9857 	return opConstantCompositeTests.release();
9858 }
9859 
9860 template<typename T>
9861 void finalizeTestsCreation (T&							specResource,
9862 							const map<string, string>&	fragments,
9863 							tcu::TestContext&			testCtx,
9864 							tcu::TestCaseGroup&			testGroup,
9865 							const std::string&			testName,
9866 							const VulkanFeatures&		vulkanFeatures,
9867 							const vector<string>&		extensions,
9868 							const IVec3&				numWorkGroups);
9869 
9870 template<>
finalizeTestsCreation(GraphicsResources & specResource,const map<string,string> & fragments,tcu::TestContext &,tcu::TestCaseGroup & testGroup,const std::string & testName,const VulkanFeatures & vulkanFeatures,const vector<string> & extensions,const IVec3 &)9871 void finalizeTestsCreation (GraphicsResources&			specResource,
9872 							const map<string, string>&	fragments,
9873 							tcu::TestContext&			,
9874 							tcu::TestCaseGroup&			testGroup,
9875 							const std::string&			testName,
9876 							const VulkanFeatures&		vulkanFeatures,
9877 							const vector<string>&		extensions,
9878 							const IVec3&				)
9879 {
9880 	RGBA defaultColors[4];
9881 	getDefaultColors(defaultColors);
9882 
9883 	createTestsForAllStages(testName, defaultColors, defaultColors, fragments, specResource, extensions, &testGroup, vulkanFeatures);
9884 }
9885 
9886 template<>
finalizeTestsCreation(ComputeShaderSpec & specResource,const map<string,string> & fragments,tcu::TestContext & testCtx,tcu::TestCaseGroup & testGroup,const std::string & testName,const VulkanFeatures & vulkanFeatures,const vector<string> & extensions,const IVec3 & numWorkGroups)9887 void finalizeTestsCreation (ComputeShaderSpec&			specResource,
9888 							const map<string, string>&	fragments,
9889 							tcu::TestContext&			testCtx,
9890 							tcu::TestCaseGroup&			testGroup,
9891 							const std::string&			testName,
9892 							const VulkanFeatures&		vulkanFeatures,
9893 							const vector<string>&		extensions,
9894 							const IVec3&				numWorkGroups)
9895 {
9896 	specResource.numWorkGroups = numWorkGroups;
9897 	specResource.requestedVulkanFeatures = vulkanFeatures;
9898 	specResource.extensions = extensions;
9899 
9900 	specResource.assembly = makeComputeShaderAssembly(fragments);
9901 
9902 	testGroup.addChild(new SpvAsmComputeShaderCase(testCtx, testName.c_str(), "", specResource));
9903 }
9904 
9905 template<class SpecResource>
createFloat16LogicalSet(tcu::TestContext & testCtx,const bool nanSupported)9906 tcu::TestCaseGroup* createFloat16LogicalSet (tcu::TestContext& testCtx, const bool nanSupported)
9907 {
9908 	const string						nan					= nanSupported ? "_nan" : "";
9909 	const string						groupName			= "logical" + nan;
9910 	de::MovePtr<tcu::TestCaseGroup>		testGroup			(new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Float 16 logical tests"));
9911 
9912 	de::Random							rnd					(deStringHash(testGroup->getName()));
9913 	const string						spvCapabilities		= string("OpCapability StorageUniformBufferBlock16\n") + (nanSupported ? "OpCapability SignedZeroInfNanPreserve\n" : "");
9914 	const string						spvExtensions		= string("OpExtension \"SPV_KHR_16bit_storage\"\n") + (nanSupported ? "OpExtension \"SPV_KHR_float_controls\"\n" : "");
9915 	const string						spvExecutionMode	= nanSupported ? "OpExecutionMode %BP_main SignedZeroInfNanPreserve 16\n" : "";
9916 	const deUint32						numDataPoints		= 16;
9917 	const vector<deFloat16>				float16Data			= getFloat16s(rnd, numDataPoints);
9918 	const vector<deFloat16>				float16Data1		= squarize(float16Data, 0);
9919 	const vector<deFloat16>				float16Data2		= squarize(float16Data, 1);
9920 	const vector<deFloat16>				float16DataVec1		= squarizeVector(float16Data, 0);
9921 	const vector<deFloat16>				float16DataVec2		= squarizeVector(float16Data, 1);
9922 	const vector<deFloat16>				float16OutDummy		(float16Data1.size(), 0);
9923 	const vector<deFloat16>				float16OutVecDummy	(float16DataVec1.size(), 0);
9924 
9925 	struct TestOp
9926 	{
9927 		const char*		opCode;
9928 		VerifyIOFunc	verifyFuncNan;
9929 		VerifyIOFunc	verifyFuncNonNan;
9930 		const deUint32	argCount;
9931 	};
9932 
9933 	const TestOp	testOps[]	=
9934 	{
9935 		{ "OpIsNan"						,	compareFP16Logical<fp16isNan,				true,  false, true>,	compareFP16Logical<fp16isNan,				true,  false, false>,	1	},
9936 		{ "OpIsInf"						,	compareFP16Logical<fp16isInf,				true,  false, true>,	compareFP16Logical<fp16isInf,				true,  false, false>,	1	},
9937 		{ "OpFOrdEqual"					,	compareFP16Logical<fp16isEqual,				false, true,  true>,	compareFP16Logical<fp16isEqual,				false, true,  false>,	2	},
9938 		{ "OpFUnordEqual"				,	compareFP16Logical<fp16isEqual,				false, false, true>,	compareFP16Logical<fp16isEqual,				false, false, false>,	2	},
9939 		{ "OpFOrdNotEqual"				,	compareFP16Logical<fp16isUnequal,			false, true,  true>,	compareFP16Logical<fp16isUnequal,			false, true,  false>,	2	},
9940 		{ "OpFUnordNotEqual"			,	compareFP16Logical<fp16isUnequal,			false, false, true>,	compareFP16Logical<fp16isUnequal,			false, false, false>,	2	},
9941 		{ "OpFOrdLessThan"				,	compareFP16Logical<fp16isLess,				false, true,  true>,	compareFP16Logical<fp16isLess,				false, true,  false>,	2	},
9942 		{ "OpFUnordLessThan"			,	compareFP16Logical<fp16isLess,				false, false, true>,	compareFP16Logical<fp16isLess,				false, false, false>,	2	},
9943 		{ "OpFOrdGreaterThan"			,	compareFP16Logical<fp16isGreater,			false, true,  true>,	compareFP16Logical<fp16isGreater,			false, true,  false>,	2	},
9944 		{ "OpFUnordGreaterThan"			,	compareFP16Logical<fp16isGreater,			false, false, true>,	compareFP16Logical<fp16isGreater,			false, false, false>,	2	},
9945 		{ "OpFOrdLessThanEqual"			,	compareFP16Logical<fp16isLessOrEqual,		false, true,  true>,	compareFP16Logical<fp16isLessOrEqual,		false, true,  false>,	2	},
9946 		{ "OpFUnordLessThanEqual"		,	compareFP16Logical<fp16isLessOrEqual,		false, false, true>,	compareFP16Logical<fp16isLessOrEqual,		false, false, false>,	2	},
9947 		{ "OpFOrdGreaterThanEqual"		,	compareFP16Logical<fp16isGreaterOrEqual,	false, true,  true>,	compareFP16Logical<fp16isGreaterOrEqual,	false, true,  false>,	2	},
9948 		{ "OpFUnordGreaterThanEqual"	,	compareFP16Logical<fp16isGreaterOrEqual,	false, false, true>,	compareFP16Logical<fp16isGreaterOrEqual,	false, false, false>,	2	},
9949 	};
9950 
9951 	{ // scalar cases
9952 		const StringTemplate preMain
9953 		(
9954 			"%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
9955 			"      %f16 = OpTypeFloat 16\n"
9956 			"  %c_f16_0 = OpConstant %f16 0.0\n"
9957 			"  %c_f16_1 = OpConstant %f16 1.0\n"
9958 			"   %up_f16 = OpTypePointer Uniform %f16\n"
9959 			"   %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
9960 			"   %SSBO16 = OpTypeStruct %ra_f16\n"
9961 			"%up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
9962 			"%ssbo_src0 = OpVariable %up_SSBO16 Uniform\n"
9963 			"%ssbo_src1 = OpVariable %up_SSBO16 Uniform\n"
9964 			" %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
9965 		);
9966 
9967 		const StringTemplate decoration
9968 		(
9969 			"OpDecorate %ra_f16 ArrayStride 2\n"
9970 			"OpMemberDecorate %SSBO16 0 Offset 0\n"
9971 			"OpDecorate %SSBO16 BufferBlock\n"
9972 			"OpDecorate %ssbo_src0 DescriptorSet 0\n"
9973 			"OpDecorate %ssbo_src0 Binding 0\n"
9974 			"OpDecorate %ssbo_src1 DescriptorSet 0\n"
9975 			"OpDecorate %ssbo_src1 Binding 1\n"
9976 			"OpDecorate %ssbo_dst DescriptorSet 0\n"
9977 			"OpDecorate %ssbo_dst Binding 2\n"
9978 		);
9979 
9980 		const StringTemplate testFun
9981 		(
9982 			"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9983 			"    %param = OpFunctionParameter %v4f32\n"
9984 
9985 			"    %entry = OpLabel\n"
9986 			"        %i = OpVariable %fp_i32 Function\n"
9987 			"             OpStore %i %c_i32_0\n"
9988 			"             OpBranch %loop\n"
9989 
9990 			"     %loop = OpLabel\n"
9991 			"    %i_cmp = OpLoad %i32 %i\n"
9992 			"       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
9993 			"             OpLoopMerge %merge %next None\n"
9994 			"             OpBranchConditional %lt %write %merge\n"
9995 
9996 			"    %write = OpLabel\n"
9997 			"      %ndx = OpLoad %i32 %i\n"
9998 
9999 			"     %src0 = OpAccessChain %up_f16 %ssbo_src0 %c_i32_0 %ndx\n"
10000 			" %val_src0 = OpLoad %f16 %src0\n"
10001 
10002 			"${op_arg1_calc}"
10003 
10004 			" %val_bdst = ${op_code} %bool %val_src0 ${op_arg1}\n"
10005 			"  %val_dst = OpSelect %f16 %val_bdst %c_f16_1 %c_f16_0\n"
10006 			"      %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
10007 			"             OpStore %dst %val_dst\n"
10008 			"             OpBranch %next\n"
10009 
10010 			"     %next = OpLabel\n"
10011 			"    %i_cur = OpLoad %i32 %i\n"
10012 			"    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10013 			"             OpStore %i %i_new\n"
10014 			"             OpBranch %loop\n"
10015 
10016 			"    %merge = OpLabel\n"
10017 			"             OpReturnValue %param\n"
10018 
10019 			"             OpFunctionEnd\n"
10020 		);
10021 
10022 		const StringTemplate arg1Calc
10023 		(
10024 			"     %src1 = OpAccessChain %up_f16 %ssbo_src1 %c_i32_0 %ndx\n"
10025 			" %val_src1 = OpLoad %f16 %src1\n"
10026 		);
10027 
10028 		for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10029 		{
10030 			const size_t		iterations		= float16Data1.size();
10031 			const TestOp&		testOp			= testOps[testOpsIdx];
10032 			const string		testName		= de::toLower(string(testOp.opCode)) + "_scalar";
10033 			SpecResource		specResource;
10034 			map<string, string>	specs;
10035 			VulkanFeatures		features;
10036 			map<string, string>	fragments;
10037 			vector<string>		extensions;
10038 
10039 			specs["num_data_points"]	= de::toString(iterations);
10040 			specs["op_code"]			= testOp.opCode;
10041 			specs["op_arg1"]			= (testOp.argCount == 1) ? "" : "%val_src1";
10042 			specs["op_arg1_calc"]		= (testOp.argCount == 1) ? "" : arg1Calc.specialize(specs);
10043 
10044 			fragments["extension"]		= spvExtensions;
10045 			fragments["capability"]		= spvCapabilities;
10046 			fragments["execution_mode"]	= spvExecutionMode;
10047 			fragments["decoration"]		= decoration.specialize(specs);
10048 			fragments["pre_main"]		= preMain.specialize(specs);
10049 			fragments["testfun"]		= testFun.specialize(specs);
10050 
10051 			specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Data1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10052 			specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Data2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10053 			specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10054 			specResource.verifyIO = nanSupported ? testOp.verifyFuncNan : testOp.verifyFuncNonNan;
10055 
10056 			extensions.push_back("VK_KHR_16bit_storage");
10057 			extensions.push_back("VK_KHR_shader_float16_int8");
10058 
10059 			if (nanSupported)
10060 			{
10061 				extensions.push_back("VK_KHR_shader_float_controls");
10062 
10063 				features.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat16 = DE_TRUE;
10064 			}
10065 
10066 			features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10067 			features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10068 
10069 			finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10070 		}
10071 	}
10072 	{ // vector cases
10073 		const StringTemplate preMain
10074 		(
10075 			"  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10076 			"     %v2bool = OpTypeVector %bool 2\n"
10077 			"        %f16 = OpTypeFloat 16\n"
10078 			"    %c_f16_0 = OpConstant %f16 0.0\n"
10079 			"    %c_f16_1 = OpConstant %f16 1.0\n"
10080 			"      %v2f16 = OpTypeVector %f16 2\n"
10081 			"%c_v2f16_0_0 = OpConstantComposite %v2f16 %c_f16_0 %c_f16_0\n"
10082 			"%c_v2f16_1_1 = OpConstantComposite %v2f16 %c_f16_1 %c_f16_1\n"
10083 			"   %up_v2f16 = OpTypePointer Uniform %v2f16\n"
10084 			"   %ra_v2f16 = OpTypeArray %v2f16 %c_i32_ndp\n"
10085 			"     %SSBO16 = OpTypeStruct %ra_v2f16\n"
10086 			"  %up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10087 			"  %ssbo_src0 = OpVariable %up_SSBO16 Uniform\n"
10088 			"  %ssbo_src1 = OpVariable %up_SSBO16 Uniform\n"
10089 			"   %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10090 		);
10091 
10092 		const StringTemplate decoration
10093 		(
10094 			"OpDecorate %ra_v2f16 ArrayStride 4\n"
10095 			"OpMemberDecorate %SSBO16 0 Offset 0\n"
10096 			"OpDecorate %SSBO16 BufferBlock\n"
10097 			"OpDecorate %ssbo_src0 DescriptorSet 0\n"
10098 			"OpDecorate %ssbo_src0 Binding 0\n"
10099 			"OpDecorate %ssbo_src1 DescriptorSet 0\n"
10100 			"OpDecorate %ssbo_src1 Binding 1\n"
10101 			"OpDecorate %ssbo_dst DescriptorSet 0\n"
10102 			"OpDecorate %ssbo_dst Binding 2\n"
10103 		);
10104 
10105 		const StringTemplate testFun
10106 		(
10107 			"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10108 			"    %param = OpFunctionParameter %v4f32\n"
10109 
10110 			"    %entry = OpLabel\n"
10111 			"        %i = OpVariable %fp_i32 Function\n"
10112 			"             OpStore %i %c_i32_0\n"
10113 			"             OpBranch %loop\n"
10114 
10115 			"     %loop = OpLabel\n"
10116 			"    %i_cmp = OpLoad %i32 %i\n"
10117 			"       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10118 			"             OpLoopMerge %merge %next None\n"
10119 			"             OpBranchConditional %lt %write %merge\n"
10120 
10121 			"    %write = OpLabel\n"
10122 			"      %ndx = OpLoad %i32 %i\n"
10123 
10124 			"     %src0 = OpAccessChain %up_v2f16 %ssbo_src0 %c_i32_0 %ndx\n"
10125 			" %val_src0 = OpLoad %v2f16 %src0\n"
10126 
10127 			"${op_arg1_calc}"
10128 
10129 			" %val_bdst = ${op_code} %v2bool %val_src0 ${op_arg1}\n"
10130 			"  %val_dst = OpSelect %v2f16 %val_bdst %c_v2f16_1_1 %c_v2f16_0_0\n"
10131 			"      %dst = OpAccessChain %up_v2f16 %ssbo_dst %c_i32_0 %ndx\n"
10132 			"             OpStore %dst %val_dst\n"
10133 			"             OpBranch %next\n"
10134 
10135 			"     %next = OpLabel\n"
10136 			"    %i_cur = OpLoad %i32 %i\n"
10137 			"    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10138 			"             OpStore %i %i_new\n"
10139 			"             OpBranch %loop\n"
10140 
10141 			"    %merge = OpLabel\n"
10142 			"             OpReturnValue %param\n"
10143 
10144 			"             OpFunctionEnd\n"
10145 		);
10146 
10147 		const StringTemplate arg1Calc
10148 		(
10149 			"     %src1 = OpAccessChain %up_v2f16 %ssbo_src1 %c_i32_0 %ndx\n"
10150 			" %val_src1 = OpLoad %v2f16 %src1\n"
10151 		);
10152 
10153 		for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10154 		{
10155 			const deUint32		itemsPerVec	= 2;
10156 			const size_t		iterations	= float16DataVec1.size() / itemsPerVec;
10157 			const TestOp&		testOp		= testOps[testOpsIdx];
10158 			const string		testName	= de::toLower(string(testOp.opCode)) + "_vector";
10159 			SpecResource		specResource;
10160 			map<string, string>	specs;
10161 			vector<string>		extensions;
10162 			VulkanFeatures		features;
10163 			map<string, string>	fragments;
10164 
10165 			specs["num_data_points"]	= de::toString(iterations);
10166 			specs["op_code"]			= testOp.opCode;
10167 			specs["op_arg1"]			= (testOp.argCount == 1) ? "" : "%val_src1";
10168 			specs["op_arg1_calc"]		= (testOp.argCount == 1) ? "" : arg1Calc.specialize(specs);
10169 
10170 			fragments["extension"]		= spvExtensions;
10171 			fragments["capability"]		= spvCapabilities;
10172 			fragments["execution_mode"]	= spvExecutionMode;
10173 			fragments["decoration"]		= decoration.specialize(specs);
10174 			fragments["pre_main"]		= preMain.specialize(specs);
10175 			fragments["testfun"]		= testFun.specialize(specs);
10176 
10177 			specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16DataVec1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10178 			specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16DataVec2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10179 			specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutVecDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10180 			specResource.verifyIO = nanSupported ? testOp.verifyFuncNan : testOp.verifyFuncNonNan;
10181 
10182 			extensions.push_back("VK_KHR_16bit_storage");
10183 			extensions.push_back("VK_KHR_shader_float16_int8");
10184 
10185 			if (nanSupported)
10186 			{
10187 				extensions.push_back("VK_KHR_shader_float_controls");
10188 
10189 				features.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat16 = DE_TRUE;
10190 			}
10191 
10192 			features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10193 			features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10194 
10195 			finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10196 		}
10197 	}
10198 
10199 	return testGroup.release();
10200 }
10201 
compareFP16FunctionSetFunc(const std::vector<Resource> & inputs,const vector<AllocationSp> & outputAllocs,const std::vector<Resource> &,TestLog & log)10202 bool compareFP16FunctionSetFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10203 {
10204 	if (inputs.size() != 1 || outputAllocs.size() != 1)
10205 		return false;
10206 
10207 	vector<deUint8>	input1Bytes;
10208 
10209 	inputs[0].getBytes(input1Bytes);
10210 
10211 	const deUint16* const	input1AsFP16	= (const deUint16*)&input1Bytes[0];
10212 	const deUint16* const	outputAsFP16	= (const deUint16*)outputAllocs[0]->getHostPtr();
10213 	std::string				error;
10214 
10215 	for (size_t idx = 0; idx < input1Bytes.size() / sizeof(deUint16); ++idx)
10216 	{
10217 		if (!compare16BitFloat(input1AsFP16[idx], outputAsFP16[idx], error))
10218 		{
10219 			log << TestLog::Message << error << TestLog::EndMessage;
10220 
10221 			return false;
10222 		}
10223 	}
10224 
10225 	return true;
10226 }
10227 
10228 template<class SpecResource>
createFloat16FuncSet(tcu::TestContext & testCtx)10229 tcu::TestCaseGroup* createFloat16FuncSet (tcu::TestContext& testCtx)
10230 {
10231 	de::MovePtr<tcu::TestCaseGroup>		testGroup			(new tcu::TestCaseGroup(testCtx, "function", "Float 16 function call related tests"));
10232 
10233 	de::Random							rnd					(deStringHash(testGroup->getName()));
10234 	const StringTemplate				capabilities		("OpCapability ${cap}\n");
10235 	const deUint32						numDataPoints		= 256;
10236 	const vector<deFloat16>				float16InputData	= getFloat16s(rnd, numDataPoints);
10237 	const vector<deFloat16>				float16OutputDummy	(float16InputData.size(), 0);
10238 	map<string, string>					fragments;
10239 
10240 	struct TestType
10241 	{
10242 		const deUint32	typeComponents;
10243 		const char*		typeName;
10244 		const char*		typeDecls;
10245 	};
10246 
10247 	const TestType	testTypes[]	=
10248 	{
10249 		{
10250 			1,
10251 			"f16",
10252 			""
10253 		},
10254 		{
10255 			2,
10256 			"v2f16",
10257 			"      %v2f16 = OpTypeVector %f16 2\n"
10258 			"  %c_v2f16_0 = OpConstantComposite %v2f16 %c_f16_0 %c_f16_0\n"
10259 		},
10260 		{
10261 			4,
10262 			"v4f16",
10263 			"      %v4f16 = OpTypeVector %f16 4\n"
10264 			"  %c_v4f16_0 = OpConstantComposite %v4f16 %c_f16_0 %c_f16_0 %c_f16_0 %c_f16_0\n"
10265 		},
10266 	};
10267 
10268 	const StringTemplate preMain
10269 	(
10270 		"  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10271 		"     %v2bool = OpTypeVector %bool 2\n"
10272 		"        %f16 = OpTypeFloat 16\n"
10273 		"    %c_f16_0 = OpConstant %f16 0.0\n"
10274 
10275 		"${type_decls}"
10276 
10277 		"  %${tt}_fun = OpTypeFunction %${tt} %${tt}\n"
10278 		"   %up_${tt} = OpTypePointer Uniform %${tt}\n"
10279 		"   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10280 		"     %SSBO16 = OpTypeStruct %ra_${tt}\n"
10281 		"  %up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10282 		"   %ssbo_src = OpVariable %up_SSBO16 Uniform\n"
10283 		"   %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10284 	);
10285 
10286 	const StringTemplate decoration
10287 	(
10288 		"OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10289 		"OpMemberDecorate %SSBO16 0 Offset 0\n"
10290 		"OpDecorate %SSBO16 BufferBlock\n"
10291 		"OpDecorate %ssbo_src DescriptorSet 0\n"
10292 		"OpDecorate %ssbo_src Binding 0\n"
10293 		"OpDecorate %ssbo_dst DescriptorSet 0\n"
10294 		"OpDecorate %ssbo_dst Binding 1\n"
10295 	);
10296 
10297 	const StringTemplate testFun
10298 	(
10299 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10300 		"    %param = OpFunctionParameter %v4f32\n"
10301 		"    %entry = OpLabel\n"
10302 
10303 		"        %i = OpVariable %fp_i32 Function\n"
10304 		"             OpStore %i %c_i32_0\n"
10305 		"             OpBranch %loop\n"
10306 
10307 		"     %loop = OpLabel\n"
10308 		"    %i_cmp = OpLoad %i32 %i\n"
10309 		"       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10310 		"             OpLoopMerge %merge %next None\n"
10311 		"             OpBranchConditional %lt %write %merge\n"
10312 
10313 		"    %write = OpLabel\n"
10314 		"      %ndx = OpLoad %i32 %i\n"
10315 
10316 		"      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10317 		"  %val_src = OpLoad %${tt} %src\n"
10318 
10319 		"  %val_dst = OpFunctionCall %${tt} %pass_fun %val_src\n"
10320 		"      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
10321 		"             OpStore %dst %val_dst\n"
10322 		"             OpBranch %next\n"
10323 
10324 		"     %next = OpLabel\n"
10325 		"    %i_cur = OpLoad %i32 %i\n"
10326 		"    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10327 		"             OpStore %i %i_new\n"
10328 		"             OpBranch %loop\n"
10329 
10330 		"    %merge = OpLabel\n"
10331 		"             OpReturnValue %param\n"
10332 
10333 		"             OpFunctionEnd\n"
10334 
10335 		" %pass_fun = OpFunction %${tt} None %${tt}_fun\n"
10336 		"   %param0 = OpFunctionParameter %${tt}\n"
10337 		" %entry_pf = OpLabel\n"
10338 		"     %res0 = OpFAdd %${tt} %param0 %c_${tt}_0\n"
10339 		"             OpReturnValue %res0\n"
10340 		"             OpFunctionEnd\n"
10341 	);
10342 
10343 	for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
10344 	{
10345 		const TestType&		testType		= testTypes[testTypeIdx];
10346 		const string		testName		= testType.typeName;
10347 		const deUint32		itemsPerType	= testType.typeComponents;
10348 		const size_t		iterations		= float16InputData.size() / itemsPerType;
10349 		const size_t		typeStride		= itemsPerType * sizeof(deFloat16);
10350 		SpecResource		specResource;
10351 		map<string, string>	specs;
10352 		VulkanFeatures		features;
10353 		vector<string>		extensions;
10354 
10355 		specs["cap"]				= "StorageUniformBufferBlock16";
10356 		specs["num_data_points"]	= de::toString(iterations);
10357 		specs["tt"]					= testType.typeName;
10358 		specs["tt_stride"]			= de::toString(typeStride);
10359 		specs["type_decls"]			= testType.typeDecls;
10360 
10361 		fragments["extension"]		= "OpExtension \"SPV_KHR_16bit_storage\"";
10362 		fragments["capability"]		= capabilities.specialize(specs);
10363 		fragments["decoration"]		= decoration.specialize(specs);
10364 		fragments["pre_main"]		= preMain.specialize(specs);
10365 		fragments["testfun"]		= testFun.specialize(specs);
10366 
10367 		specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10368 		specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10369 		specResource.verifyIO = compareFP16FunctionSetFunc;
10370 
10371 		extensions.push_back("VK_KHR_16bit_storage");
10372 		extensions.push_back("VK_KHR_shader_float16_int8");
10373 
10374 		features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10375 		features.extFloat16Int8	= EXTFLOAT16INT8FEATURES_FLOAT16;
10376 
10377 		finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10378 	}
10379 
10380 	return testGroup.release();
10381 }
10382 
operator ()vkt::SpirVAssembly::getV_10383 struct getV_	{ deUint32 inline operator()(deUint32 v) const	{ return v;        } getV_(){} };
operator ()vkt::SpirVAssembly::getV010384 struct getV0	{ deUint32 inline operator()(deUint32 v) const	{ return v & (~1); } getV0(){} };
operator ()vkt::SpirVAssembly::getV110385 struct getV1	{ deUint32 inline operator()(deUint32 v) const	{ return v | ( 1); } getV1(){} };
10386 
10387 template<deUint32 R, deUint32 N>
getOffset(deUint32 x,deUint32 y,deUint32 n)10388 inline static deUint32 getOffset(deUint32 x, deUint32 y, deUint32 n)
10389 {
10390 	return N * ((R * y) + x) + n;
10391 }
10392 
10393 template<deUint32 R, deUint32 N, class X0, class X1, class Y0, class Y1>
10394 struct getFDelta
10395 {
operator ()vkt::SpirVAssembly::getFDelta10396 	float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10397 	{
10398 		DE_STATIC_ASSERT(R%2 == 0);
10399 		DE_ASSERT(flavor == 0);
10400 		DE_UNREF(flavor);
10401 
10402 		const X0			x0;
10403 		const X1			x1;
10404 		const Y0			y0;
10405 		const Y1			y1;
10406 		const deFloat16		v0	= data[getOffset<R, N>(x0(x), y0(y), n)];
10407 		const deFloat16		v1	= data[getOffset<R, N>(x1(x), y1(y), n)];
10408 		const tcu::Float16	f0	= tcu::Float16(v0);
10409 		const tcu::Float16	f1	= tcu::Float16(v1);
10410 		const float			d0	= f0.asFloat();
10411 		const float			d1	= f1.asFloat();
10412 		const float			d	= d1 - d0;
10413 
10414 		return d;
10415 	}
10416 
getFDeltavkt::SpirVAssembly::getFDelta10417 	getFDelta(){}
10418 };
10419 
10420 template<deUint32 F, class Class0, class Class1>
10421 struct getFOneOf
10422 {
operator ()vkt::SpirVAssembly::getFOneOf10423 	float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10424 	{
10425 		DE_ASSERT(flavor < F);
10426 
10427 		if (flavor == 0)
10428 		{
10429 			Class0 c;
10430 
10431 			return c(data, x, y, n, flavor);
10432 		}
10433 		else
10434 		{
10435 			Class1 c;
10436 
10437 			return c(data, x, y, n, flavor - 1);
10438 		}
10439 	}
10440 
getFOneOfvkt::SpirVAssembly::getFOneOf10441 	getFOneOf(){}
10442 };
10443 
10444 template<class FineX0, class FineX1, class FineY0, class FineY1>
10445 struct calcWidthOf4
10446 {
operator ()vkt::SpirVAssembly::calcWidthOf410447 	float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10448 	{
10449 		DE_ASSERT(flavor < 4);
10450 
10451 		const deUint32						flavorX = (flavor & 1) == 0 ? 0 : 1;
10452 		const deUint32						flavorY = (flavor & 2) == 0 ? 0 : 1;
10453 		const getFOneOf<2, FineX0, FineX1>	cx;
10454 		const getFOneOf<2, FineY0, FineY1>	cy;
10455 		float								v		= 0;
10456 
10457 		v += fabsf(cx(data, x, y, n, flavorX));
10458 		v += fabsf(cy(data, x, y, n, flavorY));
10459 
10460 		return v;
10461 	}
10462 
calcWidthOf4vkt::SpirVAssembly::calcWidthOf410463 	calcWidthOf4(){}
10464 };
10465 
10466 template<deUint32 R, deUint32 N, class Derivative>
compareDerivativeWithFlavor(const deFloat16 * inputAsFP16,const deFloat16 * outputAsFP16,deUint32 flavor,std::string & error)10467 bool compareDerivativeWithFlavor (const deFloat16* inputAsFP16, const deFloat16* outputAsFP16, deUint32 flavor, std::string& error)
10468 {
10469 	const deUint32		numDataPointsByAxis	= R;
10470 	const Derivative	derivativeFunc;
10471 
10472 	for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10473 	for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10474 	for (deUint32 n = 0; n < N; ++n)
10475 	{
10476 		const float		expectedFloat	= derivativeFunc(inputAsFP16, x, y, n, flavor);
10477 		deFloat16		expected		= deFloat32To16Round(expectedFloat, DE_ROUNDINGMODE_TO_NEAREST_EVEN);
10478 		const deFloat16	output			= outputAsFP16[getOffset<R, N>(x, y, n)];
10479 
10480 		bool			reportError		= !compare16BitFloat(expected, output, error);
10481 
10482 		if (reportError)
10483 		{
10484 			expected	= deFloat32To16Round(expectedFloat, DE_ROUNDINGMODE_TO_ZERO);
10485 			reportError	= !compare16BitFloat(expected, output, error);
10486 		}
10487 
10488 		if (reportError)
10489 		{
10490 			error = "subcase at " + de::toString(x) + "," + de::toString(y) + "," + de::toString(n) + ": " + error;
10491 
10492 			return false;
10493 		}
10494 	}
10495 
10496 	return true;
10497 }
10498 
10499 template<deUint32 R, deUint32 N, deUint32 FLAVOUR_COUNT, class Derivative>
compareDerivative(const std::vector<Resource> & inputs,const vector<AllocationSp> & outputAllocs,const std::vector<Resource> &,TestLog & log)10500 bool compareDerivative (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10501 {
10502 	if (inputs.size() != 1 || outputAllocs.size() != 1)
10503 		return false;
10504 
10505 	deUint32			successfulRuns			= FLAVOUR_COUNT;
10506 	std::string			results[FLAVOUR_COUNT];
10507 	vector<deUint8>		inputBytes;
10508 
10509 	inputs[0].getBytes(inputBytes);
10510 
10511 	const deFloat16*	inputAsFP16		= reinterpret_cast<deFloat16* const>(&inputBytes.front());
10512 	const deFloat16*	outputAsFP16	= static_cast<deFloat16*>(outputAllocs[0]->getHostPtr());
10513 
10514 	DE_ASSERT(inputBytes.size() ==  R * R * N * sizeof(deFloat16));
10515 
10516 	for (deUint32 flavor = 0; flavor < FLAVOUR_COUNT; ++flavor)
10517 		if (compareDerivativeWithFlavor<R, N, Derivative> (inputAsFP16, outputAsFP16, flavor, results[flavor]))
10518 		{
10519 			break;
10520 		}
10521 		else
10522 		{
10523 			successfulRuns--;
10524 		}
10525 
10526 	if (successfulRuns == 0)
10527 		for (deUint32 flavor = 0; flavor < FLAVOUR_COUNT; flavor++)
10528 			log << TestLog::Message << "At flavor #" << flavor << " " << results[flavor] << TestLog::EndMessage;
10529 
10530 	return successfulRuns > 0;
10531 }
10532 
10533 template<deUint32 R, deUint32 N>
createDerivativeTests(tcu::TestContext & testCtx)10534 tcu::TestCaseGroup* createDerivativeTests (tcu::TestContext& testCtx)
10535 {
10536 	typedef getFDelta<R, N, getV0, getV1, getV_, getV_> getFDxFine;
10537 	typedef getFDelta<R, N, getV_, getV_, getV0, getV1> getFDyFine;
10538 
10539 	typedef getFDelta<R, N, getV0, getV1, getV0, getV0> getFdxCoarse0;
10540 	typedef getFDelta<R, N, getV0, getV1, getV1, getV1> getFdxCoarse1;
10541 	typedef getFDelta<R, N, getV0, getV0, getV0, getV1> getFdyCoarse0;
10542 	typedef getFDelta<R, N, getV1, getV1, getV0, getV1> getFdyCoarse1;
10543 	typedef getFOneOf<2, getFdxCoarse0, getFdxCoarse1> getFDxCoarse;
10544 	typedef getFOneOf<2, getFdyCoarse0, getFdyCoarse1> getFDyCoarse;
10545 
10546 	typedef calcWidthOf4<getFDxFine, getFDxFine, getFDyFine, getFDyFine> getFWidthFine;
10547 	typedef calcWidthOf4<getFdxCoarse0, getFdxCoarse1, getFdyCoarse0, getFdyCoarse1> getFWidthCoarse;
10548 
10549 	typedef getFOneOf<3, getFDxFine, getFDxCoarse> getFDx;
10550 	typedef getFOneOf<3, getFDyFine, getFDyCoarse> getFDy;
10551 	typedef getFOneOf<5, getFWidthFine, getFWidthCoarse> getFWidth;
10552 
10553 	const std::string					testGroupName		(std::string("derivative_") + de::toString(N));
10554 	de::MovePtr<tcu::TestCaseGroup>		testGroup			(new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Derivative instruction tests"));
10555 
10556 	de::Random							rnd					(deStringHash(testGroup->getName()));
10557 	const deUint32						numDataPointsByAxis	= R;
10558 	const deUint32						numDataPoints		= N * numDataPointsByAxis * numDataPointsByAxis;
10559 	vector<deFloat16>					float16InputX;
10560 	vector<deFloat16>					float16InputY;
10561 	vector<deFloat16>					float16InputW;
10562 	vector<deFloat16>					float16OutputDummy	(numDataPoints, 0);
10563 	RGBA								defaultColors[4];
10564 
10565 	getDefaultColors(defaultColors);
10566 
10567 	float16InputX.reserve(numDataPoints);
10568 	for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10569 	for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10570 	for (deUint32 n = 0; n < N; ++n)
10571 	{
10572 		const float arg = static_cast<float>(2 * DE_PI) * static_cast<float>(x * (n + 1)) / static_cast<float>(1 * numDataPointsByAxis);
10573 
10574 		if (y%2 == 0)
10575 			float16InputX.push_back(tcu::Float16(sin(arg)).bits());
10576 		else
10577 			float16InputX.push_back(tcu::Float16(cos(arg)).bits());
10578 	}
10579 
10580 	float16InputY.reserve(numDataPoints);
10581 	for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10582 	for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10583 	for (deUint32 n = 0; n < N; ++n)
10584 	{
10585 		const float arg = static_cast<float>(2 * DE_PI) * static_cast<float>(y * (n + 1)) / static_cast<float>(1 * numDataPointsByAxis);
10586 
10587 		if (x%2 == 0)
10588 			float16InputY.push_back(tcu::Float16(sin(arg)).bits());
10589 		else
10590 			float16InputY.push_back(tcu::Float16(cos(arg)).bits());
10591 	}
10592 
10593 	const deFloat16 testNumbers[]	=
10594 	{
10595 		tcu::Float16( 2.0  ).bits(),
10596 		tcu::Float16( 4.0  ).bits(),
10597 		tcu::Float16( 8.0  ).bits(),
10598 		tcu::Float16( 16.0 ).bits(),
10599 		tcu::Float16( 32.0 ).bits(),
10600 		tcu::Float16( 64.0 ).bits(),
10601 		tcu::Float16( 128.0).bits(),
10602 		tcu::Float16( 256.0).bits(),
10603 		tcu::Float16( 512.0).bits(),
10604 		tcu::Float16(-2.0  ).bits(),
10605 		tcu::Float16(-4.0  ).bits(),
10606 		tcu::Float16(-8.0  ).bits(),
10607 		tcu::Float16(-16.0 ).bits(),
10608 		tcu::Float16(-32.0 ).bits(),
10609 		tcu::Float16(-64.0 ).bits(),
10610 		tcu::Float16(-128.0).bits(),
10611 		tcu::Float16(-256.0).bits(),
10612 		tcu::Float16(-512.0).bits(),
10613 	};
10614 
10615 	float16InputW.reserve(numDataPoints);
10616 	for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10617 	for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10618 	for (deUint32 n = 0; n < N; ++n)
10619 		float16InputW.push_back(testNumbers[rnd.getInt(0, DE_LENGTH_OF_ARRAY(testNumbers) - 1)]);
10620 
10621 	struct TestOp
10622 	{
10623 		const char*			opCode;
10624 		vector<deFloat16>&	inputData;
10625 		VerifyIOFunc		verifyFunc;
10626 	};
10627 
10628 	const TestOp	testOps[]	=
10629 	{
10630 		{ "OpDPdxFine"		,	float16InputX	,	compareDerivative<R, N, 1, getFDxFine		>	},
10631 		{ "OpDPdyFine"		,	float16InputY	,	compareDerivative<R, N, 1, getFDyFine		>	},
10632 		{ "OpFwidthFine"	,	float16InputW	,	compareDerivative<R, N, 1, getFWidthFine	>	},
10633 		{ "OpDPdxCoarse"	,	float16InputX	,	compareDerivative<R, N, 3, getFDx			>	},
10634 		{ "OpDPdyCoarse"	,	float16InputY	,	compareDerivative<R, N, 3, getFDy			>	},
10635 		{ "OpFwidthCoarse"	,	float16InputW	,	compareDerivative<R, N, 5, getFWidth		>	},
10636 		{ "OpDPdx"			,	float16InputX	,	compareDerivative<R, N, 3, getFDx			>	},
10637 		{ "OpDPdy"			,	float16InputY	,	compareDerivative<R, N, 3, getFDy			>	},
10638 		{ "OpFwidth"		,	float16InputW	,	compareDerivative<R, N, 5, getFWidth		>	},
10639 	};
10640 
10641 	struct TestType
10642 	{
10643 		const deUint32	typeComponents;
10644 		const char*		typeName;
10645 		const char*		typeDecls;
10646 	};
10647 
10648 	const TestType	testTypes[]	=
10649 	{
10650 		{
10651 			1,
10652 			"f16",
10653 			""
10654 		},
10655 		{
10656 			2,
10657 			"v2f16",
10658 			"      %v2f16 = OpTypeVector %f16 2\n"
10659 		},
10660 		{
10661 			4,
10662 			"v4f16",
10663 			"      %v4f16 = OpTypeVector %f16 4\n"
10664 		},
10665 	};
10666 
10667 	const deUint32	testTypeNdx	= (N == 1) ? 0
10668 								: (N == 2) ? 1
10669 								: (N == 4) ? 2
10670 								: DE_LENGTH_OF_ARRAY(testTypes);
10671 	const TestType&	testType	=	testTypes[testTypeNdx];
10672 
10673 	DE_ASSERT(testTypeNdx < DE_LENGTH_OF_ARRAY(testTypes));
10674 	DE_ASSERT(testType.typeComponents == N);
10675 
10676 	const StringTemplate preMain
10677 	(
10678 		"%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10679 		" %c_u32_xw = OpConstant %u32 ${items_by_x}\n"
10680 		"      %f16 = OpTypeFloat 16\n"
10681 		"${type_decls}"
10682 		" %up_${tt} = OpTypePointer Uniform %${tt}\n"
10683 		" %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10684 		"   %SSBO16 = OpTypeStruct %ra_${tt}\n"
10685 		"%up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10686 		" %ssbo_src = OpVariable %up_SSBO16 Uniform\n"
10687 		" %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10688 	);
10689 
10690 	const StringTemplate decoration
10691 	(
10692 		"OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10693 		"OpMemberDecorate %SSBO16 0 Offset 0\n"
10694 		"OpDecorate %SSBO16 BufferBlock\n"
10695 		"OpDecorate %ssbo_src DescriptorSet 0\n"
10696 		"OpDecorate %ssbo_src Binding 0\n"
10697 		"OpDecorate %ssbo_dst DescriptorSet 0\n"
10698 		"OpDecorate %ssbo_dst Binding 1\n"
10699 	);
10700 
10701 	const StringTemplate testFun
10702 	(
10703 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10704 		"    %param = OpFunctionParameter %v4f32\n"
10705 		"    %entry = OpLabel\n"
10706 
10707 		"  %loc_x_c = OpAccessChain %ip_f32 %BP_gl_FragCoord %c_i32_0\n"
10708 		"  %loc_y_c = OpAccessChain %ip_f32 %BP_gl_FragCoord %c_i32_1\n"
10709 		"      %x_c = OpLoad %f32 %loc_x_c\n"
10710 		"      %y_c = OpLoad %f32 %loc_y_c\n"
10711 		"    %x_idx = OpConvertFToU %u32 %x_c\n"
10712 		"    %y_idx = OpConvertFToU %u32 %y_c\n"
10713 		"    %ndx_y = OpIMul %u32 %y_idx %c_u32_xw\n"
10714 		"      %ndx = OpIAdd %u32 %ndx_y %x_idx\n"
10715 
10716 		"      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10717 		"  %val_src = OpLoad %${tt} %src\n"
10718 		"  %val_dst = ${op_code} %${tt} %val_src\n"
10719 		"      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
10720 		"             OpStore %dst %val_dst\n"
10721 		"             OpBranch %merge\n"
10722 
10723 		"    %merge = OpLabel\n"
10724 		"             OpReturnValue %param\n"
10725 
10726 		"             OpFunctionEnd\n"
10727 	);
10728 
10729 	for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10730 	{
10731 		const TestOp&		testOp			= testOps[testOpsIdx];
10732 		const string		testName		= de::toLower(string(testOp.opCode));
10733 		const size_t		typeStride		= N * sizeof(deFloat16);
10734 		GraphicsResources	specResource;
10735 		map<string, string>	specs;
10736 		VulkanFeatures		features;
10737 		vector<string>		extensions;
10738 		map<string, string>	fragments;
10739 		SpecConstants		noSpecConstants;
10740 		PushConstants		noPushConstants;
10741 		GraphicsInterfaces	noInterfaces;
10742 
10743 		specs["op_code"]			= testOp.opCode;
10744 		specs["num_data_points"]	= de::toString(testOp.inputData.size() / N);
10745 		specs["items_by_x"]			= de::toString(numDataPointsByAxis);
10746 		specs["tt"]					= testType.typeName;
10747 		specs["tt_stride"]			= de::toString(typeStride);
10748 		specs["type_decls"]			= testType.typeDecls;
10749 
10750 		fragments["extension"]		= "OpExtension \"SPV_KHR_16bit_storage\"";
10751 		fragments["capability"]		= "OpCapability DerivativeControl\nOpCapability StorageUniformBufferBlock16\n";
10752 		fragments["decoration"]		= decoration.specialize(specs);
10753 		fragments["pre_main"]		= preMain.specialize(specs);
10754 		fragments["testfun"]		= testFun.specialize(specs);
10755 
10756 		specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(testOp.inputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10757 		specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10758 		specResource.verifyIO = testOp.verifyFunc;
10759 
10760 		extensions.push_back("VK_KHR_16bit_storage");
10761 		extensions.push_back("VK_KHR_shader_float16_int8");
10762 
10763 		features.extFloat16Int8		= EXTFLOAT16INT8FEATURES_FLOAT16;
10764 		features.ext16BitStorage	= EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10765 
10766 		createTestForStage(VK_SHADER_STAGE_FRAGMENT_BIT, testName.c_str(), defaultColors, defaultColors, fragments, noSpecConstants,
10767 							noPushConstants, specResource, noInterfaces, extensions, features, testGroup.get(), QP_TEST_RESULT_FAIL, string(), true);
10768 	}
10769 
10770 	return testGroup.release();
10771 }
10772 
compareFP16VectorExtractFunc(const std::vector<Resource> & inputs,const vector<AllocationSp> & outputAllocs,const std::vector<Resource> &,TestLog & log)10773 bool compareFP16VectorExtractFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10774 {
10775 	if (inputs.size() != 2 || outputAllocs.size() != 1)
10776 		return false;
10777 
10778 	vector<deUint8>	input1Bytes;
10779 	vector<deUint8>	input2Bytes;
10780 
10781 	inputs[0].getBytes(input1Bytes);
10782 	inputs[1].getBytes(input2Bytes);
10783 
10784 	DE_ASSERT(input1Bytes.size() > 0);
10785 	DE_ASSERT(input2Bytes.size() > 0);
10786 	DE_ASSERT(input2Bytes.size() % sizeof(deUint32) == 0);
10787 
10788 	const size_t			iterations		= input2Bytes.size() / sizeof(deUint32);
10789 	const size_t			components		= input1Bytes.size() / (sizeof(deFloat16) * iterations);
10790 	const deFloat16* const	input1AsFP16	= (const deFloat16*)&input1Bytes[0];
10791 	const deUint32* const	inputIndices	= (const deUint32*)&input2Bytes[0];
10792 	const deFloat16* const	outputAsFP16	= (const deFloat16*)outputAllocs[0]->getHostPtr();
10793 	std::string				error;
10794 
10795 	DE_ASSERT(components == 2 || components == 4);
10796 	DE_ASSERT(input1Bytes.size() == iterations * components * sizeof(deFloat16));
10797 
10798 	for (size_t idx = 0; idx < iterations; ++idx)
10799 	{
10800 		const deUint32	componentNdx	= inputIndices[idx];
10801 
10802 		DE_ASSERT(componentNdx < components);
10803 
10804 		const deFloat16	expected		= input1AsFP16[components * idx + componentNdx];
10805 
10806 		if (!compare16BitFloat(expected, outputAsFP16[idx], error))
10807 		{
10808 			log << TestLog::Message << "At " << idx << error << TestLog::EndMessage;
10809 
10810 			return false;
10811 		}
10812 	}
10813 
10814 	return true;
10815 }
10816 
10817 template<class SpecResource>
createFloat16VectorExtractSet(tcu::TestContext & testCtx)10818 tcu::TestCaseGroup* createFloat16VectorExtractSet (tcu::TestContext& testCtx)
10819 {
10820 	de::MovePtr<tcu::TestCaseGroup>		testGroup			(new tcu::TestCaseGroup(testCtx, "opvectorextractdynamic", "OpVectorExtractDynamic tests"));
10821 
10822 	de::Random							rnd					(deStringHash(testGroup->getName()));
10823 	const deUint32						numDataPoints		= 256;
10824 	const vector<deFloat16>				float16InputData	= getFloat16s(rnd, numDataPoints);
10825 	const vector<deFloat16>				float16OutputDummy	(float16InputData.size(), 0);
10826 
10827 	struct TestType
10828 	{
10829 		const deUint32	typeComponents;
10830 		const size_t	typeStride;
10831 		const char*		typeName;
10832 		const char*		typeDecls;
10833 	};
10834 
10835 	const TestType	testTypes[]	=
10836 	{
10837 		{
10838 			2,
10839 			2 * sizeof(deFloat16),
10840 			"v2f16",
10841 			"      %v2f16 = OpTypeVector %f16 2\n"
10842 		},
10843 		{
10844 			3,
10845 			4 * sizeof(deFloat16),
10846 			"v3f16",
10847 			"      %v3f16 = OpTypeVector %f16 3\n"
10848 		},
10849 		{
10850 			4,
10851 			4 * sizeof(deFloat16),
10852 			"v4f16",
10853 			"      %v4f16 = OpTypeVector %f16 4\n"
10854 		},
10855 	};
10856 
10857 	const StringTemplate preMain
10858 	(
10859 		"  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10860 		"        %f16 = OpTypeFloat 16\n"
10861 
10862 		"${type_decl}"
10863 
10864 		"   %up_${tt} = OpTypePointer Uniform %${tt}\n"
10865 		"   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10866 		"   %SSBO_SRC = OpTypeStruct %ra_${tt}\n"
10867 		"%up_SSBO_SRC = OpTypePointer Uniform %SSBO_SRC\n"
10868 
10869 		"     %up_u32 = OpTypePointer Uniform %u32\n"
10870 		"     %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
10871 		"   %SSBO_IDX = OpTypeStruct %ra_u32\n"
10872 		"%up_SSBO_IDX = OpTypePointer Uniform %SSBO_IDX\n"
10873 
10874 		"     %up_f16 = OpTypePointer Uniform %f16\n"
10875 		"     %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
10876 		"   %SSBO_DST = OpTypeStruct %ra_f16\n"
10877 		"%up_SSBO_DST = OpTypePointer Uniform %SSBO_DST\n"
10878 
10879 		"   %ssbo_src = OpVariable %up_SSBO_SRC Uniform\n"
10880 		"   %ssbo_idx = OpVariable %up_SSBO_IDX Uniform\n"
10881 		"   %ssbo_dst = OpVariable %up_SSBO_DST Uniform\n"
10882 	);
10883 
10884 	const StringTemplate decoration
10885 	(
10886 		"OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10887 		"OpMemberDecorate %SSBO_SRC 0 Offset 0\n"
10888 		"OpDecorate %SSBO_SRC BufferBlock\n"
10889 		"OpDecorate %ssbo_src DescriptorSet 0\n"
10890 		"OpDecorate %ssbo_src Binding 0\n"
10891 
10892 		"OpDecorate %ra_u32 ArrayStride 4\n"
10893 		"OpMemberDecorate %SSBO_IDX 0 Offset 0\n"
10894 		"OpDecorate %SSBO_IDX BufferBlock\n"
10895 		"OpDecorate %ssbo_idx DescriptorSet 0\n"
10896 		"OpDecorate %ssbo_idx Binding 1\n"
10897 
10898 		"OpDecorate %ra_f16 ArrayStride 2\n"
10899 		"OpMemberDecorate %SSBO_DST 0 Offset 0\n"
10900 		"OpDecorate %SSBO_DST BufferBlock\n"
10901 		"OpDecorate %ssbo_dst DescriptorSet 0\n"
10902 		"OpDecorate %ssbo_dst Binding 2\n"
10903 	);
10904 
10905 	const StringTemplate testFun
10906 	(
10907 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10908 		"    %param = OpFunctionParameter %v4f32\n"
10909 		"    %entry = OpLabel\n"
10910 
10911 		"        %i = OpVariable %fp_i32 Function\n"
10912 		"             OpStore %i %c_i32_0\n"
10913 
10914 		" %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
10915 		"             OpSelectionMerge %end_if None\n"
10916 		"             OpBranchConditional %will_run %run_test %end_if\n"
10917 
10918 		" %run_test = OpLabel\n"
10919 		"             OpBranch %loop\n"
10920 
10921 		"     %loop = OpLabel\n"
10922 		"    %i_cmp = OpLoad %i32 %i\n"
10923 		"       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10924 		"             OpLoopMerge %merge %next None\n"
10925 		"             OpBranchConditional %lt %write %merge\n"
10926 
10927 		"    %write = OpLabel\n"
10928 		"      %ndx = OpLoad %i32 %i\n"
10929 
10930 		"      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10931 		"  %val_src = OpLoad %${tt} %src\n"
10932 
10933 		"  %src_idx = OpAccessChain %up_u32 %ssbo_idx %c_i32_0 %ndx\n"
10934 		"  %val_idx = OpLoad %u32 %src_idx\n"
10935 
10936 		"  %val_dst = OpVectorExtractDynamic %f16 %val_src %val_idx\n"
10937 		"      %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
10938 
10939 		"             OpStore %dst %val_dst\n"
10940 		"             OpBranch %next\n"
10941 
10942 		"     %next = OpLabel\n"
10943 		"    %i_cur = OpLoad %i32 %i\n"
10944 		"    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10945 		"             OpStore %i %i_new\n"
10946 		"             OpBranch %loop\n"
10947 
10948 		"    %merge = OpLabel\n"
10949 		"             OpBranch %end_if\n"
10950 		"   %end_if = OpLabel\n"
10951 		"             OpReturnValue %param\n"
10952 
10953 		"             OpFunctionEnd\n"
10954 	);
10955 
10956 	for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
10957 	{
10958 		const TestType&		testType		= testTypes[testTypeIdx];
10959 		const string		testName		= testType.typeName;
10960 		const size_t		itemsPerType	= testType.typeStride / sizeof(deFloat16);
10961 		const size_t		iterations		= float16InputData.size() / itemsPerType;
10962 		SpecResource		specResource;
10963 		map<string, string>	specs;
10964 		VulkanFeatures		features;
10965 		vector<deUint32>	inputDataNdx;
10966 		map<string, string>	fragments;
10967 		vector<string>		extensions;
10968 
10969 		for (deUint32 ndx = 0; ndx < iterations; ++ndx)
10970 			inputDataNdx.push_back(rnd.getUint32() % testType.typeComponents);
10971 
10972 		specs["num_data_points"]	= de::toString(iterations);
10973 		specs["tt"]					= testType.typeName;
10974 		specs["tt_stride"]			= de::toString(testType.typeStride);
10975 		specs["type_decl"]			= testType.typeDecls;
10976 
10977 		fragments["extension"]		= "OpExtension \"SPV_KHR_16bit_storage\"";
10978 		fragments["capability"]		= "OpCapability StorageUniformBufferBlock16\n";
10979 		fragments["decoration"]		= decoration.specialize(specs);
10980 		fragments["pre_main"]		= preMain.specialize(specs);
10981 		fragments["testfun"]		= testFun.specialize(specs);
10982 
10983 		specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10984 		specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inputDataNdx)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10985 		specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10986 		specResource.verifyIO = compareFP16VectorExtractFunc;
10987 
10988 		extensions.push_back("VK_KHR_16bit_storage");
10989 		extensions.push_back("VK_KHR_shader_float16_int8");
10990 
10991 		features.extFloat16Int8		= EXTFLOAT16INT8FEATURES_FLOAT16;
10992 		features.ext16BitStorage	= EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10993 
10994 		finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10995 	}
10996 
10997 	return testGroup.release();
10998 }
10999 
11000 template<deUint32 COMPONENTS_COUNT, deUint32 REPLACEMENT>
compareFP16VectorInsertFunc(const std::vector<Resource> & inputs,const vector<AllocationSp> & outputAllocs,const std::vector<Resource> &,TestLog & log)11001 bool compareFP16VectorInsertFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11002 {
11003 	if (inputs.size() != 2 || outputAllocs.size() != 1)
11004 		return false;
11005 
11006 	vector<deUint8>	input1Bytes;
11007 	vector<deUint8>	input2Bytes;
11008 
11009 	inputs[0].getBytes(input1Bytes);
11010 	inputs[1].getBytes(input2Bytes);
11011 
11012 	DE_ASSERT(input1Bytes.size() > 0);
11013 	DE_ASSERT(input2Bytes.size() > 0);
11014 	DE_ASSERT(input2Bytes.size() % sizeof(deUint32) == 0);
11015 
11016 	const size_t			iterations			= input2Bytes.size() / sizeof(deUint32);
11017 	const size_t			componentsStride	= input1Bytes.size() / (sizeof(deFloat16) * iterations);
11018 	const deFloat16* const	input1AsFP16		= (const deFloat16*)&input1Bytes[0];
11019 	const deUint32* const	inputIndices		= (const deUint32*)&input2Bytes[0];
11020 	const deFloat16* const	outputAsFP16		= (const deFloat16*)outputAllocs[0]->getHostPtr();
11021 	const deFloat16			magic				= tcu::Float16(float(REPLACEMENT)).bits();
11022 	std::string				error;
11023 
11024 	DE_ASSERT(componentsStride == 2 || componentsStride == 4);
11025 	DE_ASSERT(input1Bytes.size() == iterations * componentsStride * sizeof(deFloat16));
11026 
11027 	for (size_t idx = 0; idx < iterations; ++idx)
11028 	{
11029 		const deFloat16*	inputVec		= &input1AsFP16[componentsStride * idx];
11030 		const deFloat16*	outputVec		= &outputAsFP16[componentsStride * idx];
11031 		const deUint32		replacedCompNdx	= inputIndices[idx];
11032 
11033 		DE_ASSERT(replacedCompNdx < COMPONENTS_COUNT);
11034 
11035 		for (size_t compNdx = 0; compNdx < COMPONENTS_COUNT; ++compNdx)
11036 		{
11037 			const deFloat16	expected	= (compNdx == replacedCompNdx) ? magic : inputVec[compNdx];
11038 
11039 			if (!compare16BitFloat(expected, outputVec[compNdx], error))
11040 			{
11041 				log << TestLog::Message << "At " << idx << "[" << compNdx << "]: " << error << TestLog::EndMessage;
11042 
11043 				return false;
11044 			}
11045 		}
11046 	}
11047 
11048 	return true;
11049 }
11050 
11051 template<class SpecResource>
createFloat16VectorInsertSet(tcu::TestContext & testCtx)11052 tcu::TestCaseGroup* createFloat16VectorInsertSet (tcu::TestContext& testCtx)
11053 {
11054 	de::MovePtr<tcu::TestCaseGroup>		testGroup			(new tcu::TestCaseGroup(testCtx, "opvectorinsertdynamic", "OpVectorInsertDynamic tests"));
11055 
11056 	de::Random							rnd					(deStringHash(testGroup->getName()));
11057 	const deUint32						replacement			= 42;
11058 	const deUint32						numDataPoints		= 256;
11059 	const vector<deFloat16>				float16InputData	= getFloat16s(rnd, numDataPoints);
11060 	const vector<deFloat16>				float16OutputDummy	(float16InputData.size(), 0);
11061 
11062 	struct TestType
11063 	{
11064 		const deUint32	typeComponents;
11065 		const size_t	typeStride;
11066 		const char*		typeName;
11067 		const char*		typeDecls;
11068 		VerifyIOFunc	verifyIOFunc;
11069 	};
11070 
11071 	const TestType	testTypes[]	=
11072 	{
11073 		{
11074 			2,
11075 			2 * sizeof(deFloat16),
11076 			"v2f16",
11077 			"      %v2f16 = OpTypeVector %f16 2\n",
11078 			compareFP16VectorInsertFunc<2, replacement>
11079 		},
11080 		{
11081 			3,
11082 			4 * sizeof(deFloat16),
11083 			"v3f16",
11084 			"      %v3f16 = OpTypeVector %f16 3\n",
11085 			compareFP16VectorInsertFunc<3, replacement>
11086 		},
11087 		{
11088 			4,
11089 			4 * sizeof(deFloat16),
11090 			"v4f16",
11091 			"      %v4f16 = OpTypeVector %f16 4\n",
11092 			compareFP16VectorInsertFunc<4, replacement>
11093 		},
11094 	};
11095 
11096 	const StringTemplate preMain
11097 	(
11098 		"  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
11099 		"        %f16 = OpTypeFloat 16\n"
11100 		"  %c_f16_ins = OpConstant %f16 ${replacement}\n"
11101 
11102 		"${type_decl}"
11103 
11104 		"   %up_${tt} = OpTypePointer Uniform %${tt}\n"
11105 		"   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
11106 		"   %SSBO_SRC = OpTypeStruct %ra_${tt}\n"
11107 		"%up_SSBO_SRC = OpTypePointer Uniform %SSBO_SRC\n"
11108 
11109 		"     %up_u32 = OpTypePointer Uniform %u32\n"
11110 		"     %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
11111 		"   %SSBO_IDX = OpTypeStruct %ra_u32\n"
11112 		"%up_SSBO_IDX = OpTypePointer Uniform %SSBO_IDX\n"
11113 
11114 		"   %SSBO_DST = OpTypeStruct %ra_${tt}\n"
11115 		"%up_SSBO_DST = OpTypePointer Uniform %SSBO_DST\n"
11116 
11117 		"   %ssbo_src = OpVariable %up_SSBO_SRC Uniform\n"
11118 		"   %ssbo_idx = OpVariable %up_SSBO_IDX Uniform\n"
11119 		"   %ssbo_dst = OpVariable %up_SSBO_DST Uniform\n"
11120 	);
11121 
11122 	const StringTemplate decoration
11123 	(
11124 		"OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
11125 		"OpMemberDecorate %SSBO_SRC 0 Offset 0\n"
11126 		"OpDecorate %SSBO_SRC BufferBlock\n"
11127 		"OpDecorate %ssbo_src DescriptorSet 0\n"
11128 		"OpDecorate %ssbo_src Binding 0\n"
11129 
11130 		"OpDecorate %ra_u32 ArrayStride 4\n"
11131 		"OpMemberDecorate %SSBO_IDX 0 Offset 0\n"
11132 		"OpDecorate %SSBO_IDX BufferBlock\n"
11133 		"OpDecorate %ssbo_idx DescriptorSet 0\n"
11134 		"OpDecorate %ssbo_idx Binding 1\n"
11135 
11136 		"OpMemberDecorate %SSBO_DST 0 Offset 0\n"
11137 		"OpDecorate %SSBO_DST BufferBlock\n"
11138 		"OpDecorate %ssbo_dst DescriptorSet 0\n"
11139 		"OpDecorate %ssbo_dst Binding 2\n"
11140 	);
11141 
11142 	const StringTemplate testFun
11143 	(
11144 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11145 		"    %param = OpFunctionParameter %v4f32\n"
11146 		"    %entry = OpLabel\n"
11147 
11148 		"        %i = OpVariable %fp_i32 Function\n"
11149 		"             OpStore %i %c_i32_0\n"
11150 
11151 		" %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11152 		"             OpSelectionMerge %end_if None\n"
11153 		"             OpBranchConditional %will_run %run_test %end_if\n"
11154 
11155 		" %run_test = OpLabel\n"
11156 		"             OpBranch %loop\n"
11157 
11158 		"     %loop = OpLabel\n"
11159 		"    %i_cmp = OpLoad %i32 %i\n"
11160 		"       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11161 		"             OpLoopMerge %merge %next None\n"
11162 		"             OpBranchConditional %lt %write %merge\n"
11163 
11164 		"    %write = OpLabel\n"
11165 		"      %ndx = OpLoad %i32 %i\n"
11166 
11167 		"      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
11168 		"  %val_src = OpLoad %${tt} %src\n"
11169 
11170 		"  %src_idx = OpAccessChain %up_u32 %ssbo_idx %c_i32_0 %ndx\n"
11171 		"  %val_idx = OpLoad %u32 %src_idx\n"
11172 
11173 		"  %val_dst = OpVectorInsertDynamic %${tt} %val_src %c_f16_ins %val_idx\n"
11174 		"      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
11175 
11176 		"             OpStore %dst %val_dst\n"
11177 		"             OpBranch %next\n"
11178 
11179 		"     %next = OpLabel\n"
11180 		"    %i_cur = OpLoad %i32 %i\n"
11181 		"    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11182 		"             OpStore %i %i_new\n"
11183 		"             OpBranch %loop\n"
11184 
11185 		"    %merge = OpLabel\n"
11186 		"             OpBranch %end_if\n"
11187 		"   %end_if = OpLabel\n"
11188 		"             OpReturnValue %param\n"
11189 
11190 		"             OpFunctionEnd\n"
11191 	);
11192 
11193 	for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
11194 	{
11195 		const TestType&		testType		= testTypes[testTypeIdx];
11196 		const string		testName		= testType.typeName;
11197 		const size_t		itemsPerType	= testType.typeStride / sizeof(deFloat16);
11198 		const size_t		iterations		= float16InputData.size() / itemsPerType;
11199 		SpecResource		specResource;
11200 		map<string, string>	specs;
11201 		VulkanFeatures		features;
11202 		vector<deUint32>	inputDataNdx;
11203 		map<string, string>	fragments;
11204 		vector<string>		extensions;
11205 
11206 		for (deUint32 ndx = 0; ndx < iterations; ++ndx)
11207 			inputDataNdx.push_back(rnd.getUint32() % testType.typeComponents);
11208 
11209 		specs["num_data_points"]	= de::toString(iterations);
11210 		specs["tt"]					= testType.typeName;
11211 		specs["tt_stride"]			= de::toString(testType.typeStride);
11212 		specs["type_decl"]			= testType.typeDecls;
11213 		specs["replacement"]		= de::toString(replacement);
11214 
11215 		fragments["extension"]		= "OpExtension \"SPV_KHR_16bit_storage\"";
11216 		fragments["capability"]		= "OpCapability StorageUniformBufferBlock16\n";
11217 		fragments["decoration"]		= decoration.specialize(specs);
11218 		fragments["pre_main"]		= preMain.specialize(specs);
11219 		fragments["testfun"]		= testFun.specialize(specs);
11220 
11221 		specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11222 		specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inputDataNdx)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11223 		specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11224 		specResource.verifyIO = testType.verifyIOFunc;
11225 
11226 		extensions.push_back("VK_KHR_16bit_storage");
11227 		extensions.push_back("VK_KHR_shader_float16_int8");
11228 
11229 		features.extFloat16Int8		= EXTFLOAT16INT8FEATURES_FLOAT16;
11230 		features.ext16BitStorage	= EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11231 
11232 		finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11233 	}
11234 
11235 	return testGroup.release();
11236 }
11237 
getShuffledComponent(const size_t iteration,const size_t componentNdx,const deFloat16 * input1Vec,const deFloat16 * input2Vec,size_t vec1Len,size_t vec2Len,bool & validate)11238 inline deFloat16 getShuffledComponent (const size_t iteration, const size_t componentNdx, const deFloat16* input1Vec, const deFloat16* input2Vec, size_t vec1Len, size_t vec2Len, bool& validate)
11239 {
11240 	const size_t	compNdxCount	= (vec1Len + vec2Len + 1);
11241 	const size_t	compNdxLimited	= iteration % (compNdxCount * compNdxCount);
11242 	size_t			comp;
11243 
11244 	switch (componentNdx)
11245 	{
11246 		case 0: comp = compNdxLimited / compNdxCount; break;
11247 		case 1: comp = compNdxLimited % compNdxCount; break;
11248 		case 2: comp = 0; break;
11249 		case 3: comp = 1; break;
11250 		default: TCU_THROW(InternalError, "Impossible");
11251 	}
11252 
11253 	if (comp >= vec1Len + vec2Len)
11254 	{
11255 		validate = false;
11256 		return 0;
11257 	}
11258 	else
11259 	{
11260 		validate = true;
11261 		return (comp < vec1Len) ? input1Vec[comp] : input2Vec[comp - vec1Len];
11262 	}
11263 }
11264 
11265 template<deUint32 DST_COMPONENTS_COUNT, deUint32 SRC0_COMPONENTS_COUNT, deUint32 SRC1_COMPONENTS_COUNT>
compareFP16VectorShuffleFunc(const std::vector<Resource> & inputs,const vector<AllocationSp> & outputAllocs,const std::vector<Resource> &,TestLog & log)11266 bool compareFP16VectorShuffleFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11267 {
11268 	DE_STATIC_ASSERT(DST_COMPONENTS_COUNT == 2 || DST_COMPONENTS_COUNT == 3 || DST_COMPONENTS_COUNT == 4);
11269 	DE_STATIC_ASSERT(SRC0_COMPONENTS_COUNT == 2 || SRC0_COMPONENTS_COUNT == 3 || SRC0_COMPONENTS_COUNT == 4);
11270 	DE_STATIC_ASSERT(SRC1_COMPONENTS_COUNT == 2 || SRC1_COMPONENTS_COUNT == 3 || SRC1_COMPONENTS_COUNT == 4);
11271 
11272 	if (inputs.size() != 2 || outputAllocs.size() != 1)
11273 		return false;
11274 
11275 	vector<deUint8>	input1Bytes;
11276 	vector<deUint8>	input2Bytes;
11277 
11278 	inputs[0].getBytes(input1Bytes);
11279 	inputs[1].getBytes(input2Bytes);
11280 
11281 	DE_ASSERT(input1Bytes.size() > 0);
11282 	DE_ASSERT(input2Bytes.size() > 0);
11283 	DE_ASSERT(input2Bytes.size() % sizeof(deFloat16) == 0);
11284 
11285 	const size_t			componentsStrideDst		= (DST_COMPONENTS_COUNT == 3) ? 4 : DST_COMPONENTS_COUNT;
11286 	const size_t			componentsStrideSrc0	= (SRC0_COMPONENTS_COUNT == 3) ? 4 : SRC0_COMPONENTS_COUNT;
11287 	const size_t			componentsStrideSrc1	= (SRC1_COMPONENTS_COUNT == 3) ? 4 : SRC1_COMPONENTS_COUNT;
11288 	const size_t			iterations				= input1Bytes.size() / (componentsStrideSrc0 * sizeof(deFloat16));
11289 	const deFloat16* const	input1AsFP16			= (const deFloat16*)&input1Bytes[0];
11290 	const deFloat16* const	input2AsFP16			= (const deFloat16*)&input2Bytes[0];
11291 	const deFloat16* const	outputAsFP16			= (const deFloat16*)outputAllocs[0]->getHostPtr();
11292 	std::string				error;
11293 
11294 	DE_ASSERT(input1Bytes.size() == iterations * componentsStrideSrc0 * sizeof(deFloat16));
11295 	DE_ASSERT(input2Bytes.size() == iterations * componentsStrideSrc1 * sizeof(deFloat16));
11296 
11297 	for (size_t idx = 0; idx < iterations; ++idx)
11298 	{
11299 		const deFloat16*	input1Vec	= &input1AsFP16[componentsStrideSrc0 * idx];
11300 		const deFloat16*	input2Vec	= &input2AsFP16[componentsStrideSrc1 * idx];
11301 		const deFloat16*	outputVec	= &outputAsFP16[componentsStrideDst * idx];
11302 
11303 		for (size_t compNdx = 0; compNdx < DST_COMPONENTS_COUNT; ++compNdx)
11304 		{
11305 			bool		validate	= true;
11306 			deFloat16	expected	= getShuffledComponent(idx, compNdx, input1Vec, input2Vec, SRC0_COMPONENTS_COUNT, SRC1_COMPONENTS_COUNT, validate);
11307 
11308 			if (validate && !compare16BitFloat(expected, outputVec[compNdx], error))
11309 			{
11310 				log << TestLog::Message << "At " << idx << "[" << compNdx << "]: " << error << TestLog::EndMessage;
11311 
11312 				return false;
11313 			}
11314 		}
11315 	}
11316 
11317 	return true;
11318 }
11319 
getFloat16VectorShuffleVerifyIOFunc(deUint32 dstComponentsCount,deUint32 src0ComponentsCount,deUint32 src1ComponentsCount)11320 VerifyIOFunc getFloat16VectorShuffleVerifyIOFunc (deUint32 dstComponentsCount, deUint32 src0ComponentsCount, deUint32 src1ComponentsCount)
11321 {
11322 	DE_ASSERT(dstComponentsCount <= 4);
11323 	DE_ASSERT(src0ComponentsCount <= 4);
11324 	DE_ASSERT(src1ComponentsCount <= 4);
11325 	deUint32 funcCode = 100 * dstComponentsCount + 10 * src0ComponentsCount + src1ComponentsCount;
11326 
11327 	switch (funcCode)
11328 	{
11329 		case 222:return compareFP16VectorShuffleFunc<2, 2, 2>;
11330 		case 223:return compareFP16VectorShuffleFunc<2, 2, 3>;
11331 		case 224:return compareFP16VectorShuffleFunc<2, 2, 4>;
11332 		case 232:return compareFP16VectorShuffleFunc<2, 3, 2>;
11333 		case 233:return compareFP16VectorShuffleFunc<2, 3, 3>;
11334 		case 234:return compareFP16VectorShuffleFunc<2, 3, 4>;
11335 		case 242:return compareFP16VectorShuffleFunc<2, 4, 2>;
11336 		case 243:return compareFP16VectorShuffleFunc<2, 4, 3>;
11337 		case 244:return compareFP16VectorShuffleFunc<2, 4, 4>;
11338 		case 322:return compareFP16VectorShuffleFunc<3, 2, 2>;
11339 		case 323:return compareFP16VectorShuffleFunc<3, 2, 3>;
11340 		case 324:return compareFP16VectorShuffleFunc<3, 2, 4>;
11341 		case 332:return compareFP16VectorShuffleFunc<3, 3, 2>;
11342 		case 333:return compareFP16VectorShuffleFunc<3, 3, 3>;
11343 		case 334:return compareFP16VectorShuffleFunc<3, 3, 4>;
11344 		case 342:return compareFP16VectorShuffleFunc<3, 4, 2>;
11345 		case 343:return compareFP16VectorShuffleFunc<3, 4, 3>;
11346 		case 344:return compareFP16VectorShuffleFunc<3, 4, 4>;
11347 		case 422:return compareFP16VectorShuffleFunc<4, 2, 2>;
11348 		case 423:return compareFP16VectorShuffleFunc<4, 2, 3>;
11349 		case 424:return compareFP16VectorShuffleFunc<4, 2, 4>;
11350 		case 432:return compareFP16VectorShuffleFunc<4, 3, 2>;
11351 		case 433:return compareFP16VectorShuffleFunc<4, 3, 3>;
11352 		case 434:return compareFP16VectorShuffleFunc<4, 3, 4>;
11353 		case 442:return compareFP16VectorShuffleFunc<4, 4, 2>;
11354 		case 443:return compareFP16VectorShuffleFunc<4, 4, 3>;
11355 		case 444:return compareFP16VectorShuffleFunc<4, 4, 4>;
11356 		default: TCU_THROW(InternalError, "Invalid number of components specified.");
11357 	}
11358 }
11359 
11360 template<class SpecResource>
createFloat16VectorShuffleSet(tcu::TestContext & testCtx)11361 tcu::TestCaseGroup* createFloat16VectorShuffleSet (tcu::TestContext& testCtx)
11362 {
11363 	de::MovePtr<tcu::TestCaseGroup>		testGroup			(new tcu::TestCaseGroup(testCtx, "opvectorshuffle", "OpVectorShuffle tests"));
11364 	const int							testSpecificSeed	= deStringHash(testGroup->getName());
11365 	const int							seed				= testCtx.getCommandLine().getBaseSeed() ^ testSpecificSeed;
11366 	de::Random							rnd					(seed);
11367 	const deUint32						numDataPoints		= 128;
11368 	map<string, string>					fragments;
11369 
11370 	struct TestType
11371 	{
11372 		const deUint32	typeComponents;
11373 		const char*		typeName;
11374 	};
11375 
11376 	const TestType	testTypes[]	=
11377 	{
11378 		{
11379 			2,
11380 			"v2f16",
11381 		},
11382 		{
11383 			3,
11384 			"v3f16",
11385 		},
11386 		{
11387 			4,
11388 			"v4f16",
11389 		},
11390 	};
11391 
11392 	const StringTemplate preMain
11393 	(
11394 		"    %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
11395 		"     %c_i32_cc = OpConstant %i32 ${case_count}\n"
11396 		"          %f16 = OpTypeFloat 16\n"
11397 		"        %v2f16 = OpTypeVector %f16 2\n"
11398 		"        %v3f16 = OpTypeVector %f16 3\n"
11399 		"        %v4f16 = OpTypeVector %f16 4\n"
11400 
11401 		"     %up_v2f16 = OpTypePointer Uniform %v2f16\n"
11402 		"     %ra_v2f16 = OpTypeArray %v2f16 %c_i32_ndp\n"
11403 		"   %SSBO_v2f16 = OpTypeStruct %ra_v2f16\n"
11404 		"%up_SSBO_v2f16 = OpTypePointer Uniform %SSBO_v2f16\n"
11405 
11406 		"     %up_v3f16 = OpTypePointer Uniform %v3f16\n"
11407 		"     %ra_v3f16 = OpTypeArray %v3f16 %c_i32_ndp\n"
11408 		"   %SSBO_v3f16 = OpTypeStruct %ra_v3f16\n"
11409 		"%up_SSBO_v3f16 = OpTypePointer Uniform %SSBO_v3f16\n"
11410 
11411 		"     %up_v4f16 = OpTypePointer Uniform %v4f16\n"
11412 		"     %ra_v4f16 = OpTypeArray %v4f16 %c_i32_ndp\n"
11413 		"   %SSBO_v4f16 = OpTypeStruct %ra_v4f16\n"
11414 		"%up_SSBO_v4f16 = OpTypePointer Uniform %SSBO_v4f16\n"
11415 
11416 		"        %fun_t = OpTypeFunction %${tt_dst} %${tt_src0} %${tt_src1} %i32\n"
11417 
11418 		"    %ssbo_src0 = OpVariable %up_SSBO_${tt_src0} Uniform\n"
11419 		"    %ssbo_src1 = OpVariable %up_SSBO_${tt_src1} Uniform\n"
11420 		"     %ssbo_dst = OpVariable %up_SSBO_${tt_dst} Uniform\n"
11421 	);
11422 
11423 	const StringTemplate decoration
11424 	(
11425 		"OpDecorate %ra_v2f16 ArrayStride 4\n"
11426 		"OpDecorate %ra_v3f16 ArrayStride 8\n"
11427 		"OpDecorate %ra_v4f16 ArrayStride 8\n"
11428 
11429 		"OpMemberDecorate %SSBO_v2f16 0 Offset 0\n"
11430 		"OpDecorate %SSBO_v2f16 BufferBlock\n"
11431 
11432 		"OpMemberDecorate %SSBO_v3f16 0 Offset 0\n"
11433 		"OpDecorate %SSBO_v3f16 BufferBlock\n"
11434 
11435 		"OpMemberDecorate %SSBO_v4f16 0 Offset 0\n"
11436 		"OpDecorate %SSBO_v4f16 BufferBlock\n"
11437 
11438 		"OpDecorate %ssbo_src0 DescriptorSet 0\n"
11439 		"OpDecorate %ssbo_src0 Binding 0\n"
11440 		"OpDecorate %ssbo_src1 DescriptorSet 0\n"
11441 		"OpDecorate %ssbo_src1 Binding 1\n"
11442 		"OpDecorate %ssbo_dst DescriptorSet 0\n"
11443 		"OpDecorate %ssbo_dst Binding 2\n"
11444 	);
11445 
11446 	const StringTemplate testFun
11447 	(
11448 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11449 		"    %param = OpFunctionParameter %v4f32\n"
11450 		"    %entry = OpLabel\n"
11451 
11452 		"        %i = OpVariable %fp_i32 Function\n"
11453 		"             OpStore %i %c_i32_0\n"
11454 
11455 		" %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11456 		"             OpSelectionMerge %end_if None\n"
11457 		"             OpBranchConditional %will_run %run_test %end_if\n"
11458 
11459 		" %run_test = OpLabel\n"
11460 		"             OpBranch %loop\n"
11461 
11462 		"     %loop = OpLabel\n"
11463 		"    %i_cmp = OpLoad %i32 %i\n"
11464 		"       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11465 		"             OpLoopMerge %merge %next None\n"
11466 		"             OpBranchConditional %lt %write %merge\n"
11467 
11468 		"    %write = OpLabel\n"
11469 		"      %ndx = OpLoad %i32 %i\n"
11470 		"     %src0 = OpAccessChain %up_${tt_src0} %ssbo_src0 %c_i32_0 %ndx\n"
11471 		" %val_src0 = OpLoad %${tt_src0} %src0\n"
11472 		"     %src1 = OpAccessChain %up_${tt_src1} %ssbo_src1 %c_i32_0 %ndx\n"
11473 		" %val_src1 = OpLoad %${tt_src1} %src1\n"
11474 		"  %val_dst = OpFunctionCall %${tt_dst} %sw_fun %val_src0 %val_src1 %ndx\n"
11475 		"      %dst = OpAccessChain %up_${tt_dst} %ssbo_dst %c_i32_0 %ndx\n"
11476 		"             OpStore %dst %val_dst\n"
11477 		"             OpBranch %next\n"
11478 
11479 		"     %next = OpLabel\n"
11480 		"    %i_cur = OpLoad %i32 %i\n"
11481 		"    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11482 		"             OpStore %i %i_new\n"
11483 		"             OpBranch %loop\n"
11484 
11485 		"    %merge = OpLabel\n"
11486 		"             OpBranch %end_if\n"
11487 		"   %end_if = OpLabel\n"
11488 		"             OpReturnValue %param\n"
11489 		"             OpFunctionEnd\n"
11490 		"\n"
11491 
11492 		"   %sw_fun = OpFunction %${tt_dst} None %fun_t\n"
11493 		"%sw_param0 = OpFunctionParameter %${tt_src0}\n"
11494 		"%sw_param1 = OpFunctionParameter %${tt_src1}\n"
11495 		"%sw_paramn = OpFunctionParameter %i32\n"
11496 		" %sw_entry = OpLabel\n"
11497 		"   %modulo = OpSMod %i32 %sw_paramn %c_i32_cc\n"
11498 		"             OpSelectionMerge %switch_e None\n"
11499 		"             OpSwitch %modulo %default ${case_list}\n"
11500 		"${case_bodies}"
11501 		"%default   = OpLabel\n"
11502 		"             OpUnreachable\n" // Unreachable default case for switch statement
11503 		"%switch_e  = OpLabel\n"
11504 		"             OpUnreachable\n" // Unreachable merge block for switch statement
11505 		"             OpFunctionEnd\n"
11506 	);
11507 
11508 	const StringTemplate testCaseBody
11509 	(
11510 		"%case_${case_ndx}    = OpLabel\n"
11511 		"%val_dst_${case_ndx} = OpVectorShuffle %${tt_dst} %sw_param0 %sw_param1 ${shuffle}\n"
11512 		"             OpReturnValue %val_dst_${case_ndx}\n"
11513 	);
11514 
11515 	for (deUint32 dstTypeIdx = 0; dstTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++dstTypeIdx)
11516 	{
11517 		const TestType&	dstType			= testTypes[dstTypeIdx];
11518 
11519 		for (deUint32 comp0Idx = 0; comp0Idx < DE_LENGTH_OF_ARRAY(testTypes); ++comp0Idx)
11520 		{
11521 			const TestType&	src0Type	= testTypes[comp0Idx];
11522 
11523 			for (deUint32 comp1Idx = 0; comp1Idx < DE_LENGTH_OF_ARRAY(testTypes); ++comp1Idx)
11524 			{
11525 				const TestType&			src1Type			= testTypes[comp1Idx];
11526 				const deUint32			input0Stride		= (src0Type.typeComponents == 3) ? 4 : src0Type.typeComponents;
11527 				const deUint32			input1Stride		= (src1Type.typeComponents == 3) ? 4 : src1Type.typeComponents;
11528 				const deUint32			outputStride		= (dstType.typeComponents == 3) ? 4 : dstType.typeComponents;
11529 				const vector<deFloat16>	float16Input0Data	= getFloat16s(rnd, input0Stride * numDataPoints);
11530 				const vector<deFloat16>	float16Input1Data	= getFloat16s(rnd, input1Stride * numDataPoints);
11531 				const vector<deFloat16>	float16OutputDummy	(outputStride * numDataPoints, 0);
11532 				const string			testName			= de::toString(dstType.typeComponents) + de::toString(src0Type.typeComponents) + de::toString(src1Type.typeComponents);
11533 				deUint32				caseCount			= 0;
11534 				SpecResource			specResource;
11535 				map<string, string>		specs;
11536 				vector<string>			extensions;
11537 				VulkanFeatures			features;
11538 				string					caseBodies;
11539 				string					caseList;
11540 
11541 				// Generate case
11542 				{
11543 					vector<string>	componentList;
11544 
11545 					// Generate component possible indices for OpVectorShuffle for components 0 and 1 in output vector
11546 					{
11547 						deUint32		caseNo		= 0;
11548 
11549 						for (deUint32 comp0IdxLocal = 0; comp0IdxLocal < src0Type.typeComponents; ++comp0IdxLocal)
11550 							componentList.push_back(de::toString(caseNo++));
11551 						for (deUint32 comp1IdxLocal = 0; comp1IdxLocal < src1Type.typeComponents; ++comp1IdxLocal)
11552 							componentList.push_back(de::toString(caseNo++));
11553 						componentList.push_back("0xFFFFFFFF");
11554 					}
11555 
11556 					for (deUint32 comp0IdxLocal = 0; comp0IdxLocal < componentList.size(); ++comp0IdxLocal)
11557 					{
11558 						for (deUint32 comp1IdxLocal = 0; comp1IdxLocal < componentList.size(); ++comp1IdxLocal)
11559 						{
11560 							map<string, string>	specCase;
11561 							string				shuffle		= componentList[comp0IdxLocal] + " " + componentList[comp1IdxLocal];
11562 
11563 							for (deUint32 compIdx = 2; compIdx < dstType.typeComponents; ++compIdx)
11564 								shuffle += " " + de::toString(compIdx - 2);
11565 
11566 							specCase["case_ndx"]	= de::toString(caseCount);
11567 							specCase["shuffle"]		= shuffle;
11568 							specCase["tt_dst"]		= dstType.typeName;
11569 
11570 							caseBodies	+= testCaseBody.specialize(specCase);
11571 							caseList	+= de::toString(caseCount) + " %case_" + de::toString(caseCount) + " ";
11572 
11573 							caseCount++;
11574 						}
11575 					}
11576 				}
11577 
11578 				specs["num_data_points"]	= de::toString(numDataPoints);
11579 				specs["tt_dst"]				= dstType.typeName;
11580 				specs["tt_src0"]			= src0Type.typeName;
11581 				specs["tt_src1"]			= src1Type.typeName;
11582 				specs["case_bodies"]		= caseBodies;
11583 				specs["case_list"]			= caseList;
11584 				specs["case_count"]			= de::toString(caseCount);
11585 
11586 				fragments["extension"]		= "OpExtension \"SPV_KHR_16bit_storage\"";
11587 				fragments["capability"]		= "OpCapability StorageUniformBufferBlock16\n";
11588 				fragments["decoration"]		= decoration.specialize(specs);
11589 				fragments["pre_main"]		= preMain.specialize(specs);
11590 				fragments["testfun"]		= testFun.specialize(specs);
11591 
11592 				specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Input0Data)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11593 				specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Input1Data)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11594 				specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11595 				specResource.verifyIO = getFloat16VectorShuffleVerifyIOFunc(dstType.typeComponents, src0Type.typeComponents, src1Type.typeComponents);
11596 
11597 				extensions.push_back("VK_KHR_16bit_storage");
11598 				extensions.push_back("VK_KHR_shader_float16_int8");
11599 
11600 				features.extFloat16Int8		= EXTFLOAT16INT8FEATURES_FLOAT16;
11601 				features.ext16BitStorage	= EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11602 
11603 				finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11604 			}
11605 		}
11606 	}
11607 
11608 	return testGroup.release();
11609 }
11610 
compareFP16CompositeFunc(const std::vector<Resource> & inputs,const vector<AllocationSp> & outputAllocs,const std::vector<Resource> &,TestLog & log)11611 bool compareFP16CompositeFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11612 {
11613 	if (inputs.size() != 1 || outputAllocs.size() != 1)
11614 		return false;
11615 
11616 	vector<deUint8>	input1Bytes;
11617 
11618 	inputs[0].getBytes(input1Bytes);
11619 
11620 	DE_ASSERT(input1Bytes.size() > 0);
11621 	DE_ASSERT(input1Bytes.size() % sizeof(deFloat16) == 0);
11622 
11623 	const size_t			iterations		= input1Bytes.size() / sizeof(deFloat16);
11624 	const deFloat16* const	input1AsFP16	= (const deFloat16*)&input1Bytes[0];
11625 	const deFloat16* const	outputAsFP16	= (const deFloat16*)outputAllocs[0]->getHostPtr();
11626 	const deFloat16			exceptionValue	= tcu::Float16(-1.0).bits();
11627 	std::string				error;
11628 
11629 	for (size_t idx = 0; idx < iterations; ++idx)
11630 	{
11631 		if (input1AsFP16[idx] == exceptionValue)
11632 			continue;
11633 
11634 		if (!compare16BitFloat(input1AsFP16[idx], outputAsFP16[idx], error))
11635 		{
11636 			log << TestLog::Message << "At " << idx << ":" << error << TestLog::EndMessage;
11637 
11638 			return false;
11639 		}
11640 	}
11641 
11642 	return true;
11643 }
11644 
11645 template<class SpecResource>
createFloat16CompositeConstructSet(tcu::TestContext & testCtx)11646 tcu::TestCaseGroup* createFloat16CompositeConstructSet (tcu::TestContext& testCtx)
11647 {
11648 	de::MovePtr<tcu::TestCaseGroup>		testGroup				(new tcu::TestCaseGroup(testCtx, "opcompositeconstruct", "OpCompositeConstruct tests"));
11649 	const deUint32						numElements				= 8;
11650 	const string						testName				= "struct";
11651 	const deUint32						structItemsCount		= 88;
11652 	const deUint32						exceptionIndices[]		= { 1, 7, 15, 17, 25, 33, 51, 55, 59, 63, 67, 71, 84, 85, 86, 87 };
11653 	const deFloat16						exceptionValue			= tcu::Float16(-1.0).bits();
11654 	const deUint32						fieldModifier			= 2;
11655 	const deUint32						fieldModifiedMulIndex	= 60;
11656 	const deUint32						fieldModifiedAddIndex	= 66;
11657 
11658 	const StringTemplate preMain
11659 	(
11660 		"    %c_i32_ndp = OpConstant %i32 ${num_elements}\n"
11661 		"          %f16 = OpTypeFloat 16\n"
11662 		"        %v2f16 = OpTypeVector %f16 2\n"
11663 		"        %v3f16 = OpTypeVector %f16 3\n"
11664 		"        %v4f16 = OpTypeVector %f16 4\n"
11665 		"    %c_f16_mod = OpConstant %f16 ${field_modifier}\n"
11666 
11667 		"${consts}"
11668 
11669 		"      %c_u32_5 = OpConstant %u32 5\n"
11670 
11671 		" %f16arr3      = OpTypeArray %f16 %c_u32_3\n"
11672 		" %v2f16arr3    = OpTypeArray %v2f16 %c_u32_3\n"
11673 		" %v2f16arr5    = OpTypeArray %v2f16 %c_u32_5\n"
11674 		" %v3f16arr5    = OpTypeArray %v3f16 %c_u32_5\n"
11675 		" %v4f16arr3    = OpTypeArray %v4f16 %c_u32_3\n"
11676 		" %struct16     = OpTypeStruct %f16 %v2f16arr3\n"
11677 		" %struct16arr3 = OpTypeArray %struct16 %c_u32_3\n"
11678 		" %st_test      = OpTypeStruct %f16 %v2f16 %v3f16 %v4f16 %f16arr3 %struct16arr3 %v2f16arr5 %f16 %v3f16arr5 %v4f16arr3\n"
11679 
11680 		"        %up_st = OpTypePointer Uniform %st_test\n"
11681 		"        %ra_st = OpTypeArray %st_test %c_i32_ndp\n"
11682 		"      %SSBO_st = OpTypeStruct %ra_st\n"
11683 		"   %up_SSBO_st = OpTypePointer Uniform %SSBO_st\n"
11684 
11685 		"     %ssbo_dst = OpVariable %up_SSBO_st Uniform\n"
11686 	);
11687 
11688 	const StringTemplate decoration
11689 	(
11690 		"OpDecorate %SSBO_st BufferBlock\n"
11691 		"OpDecorate %ra_st ArrayStride ${struct_item_size}\n"
11692 		"OpDecorate %ssbo_dst DescriptorSet 0\n"
11693 		"OpDecorate %ssbo_dst Binding 1\n"
11694 
11695 		"OpMemberDecorate %SSBO_st 0 Offset 0\n"
11696 
11697 		"OpDecorate %v2f16arr3 ArrayStride 4\n"
11698 		"OpMemberDecorate %struct16 0 Offset 0\n"
11699 		"OpMemberDecorate %struct16 1 Offset 4\n"
11700 		"OpDecorate %struct16arr3 ArrayStride 16\n"
11701 		"OpDecorate %f16arr3 ArrayStride 2\n"
11702 		"OpDecorate %v2f16arr5 ArrayStride 4\n"
11703 		"OpDecorate %v3f16arr5 ArrayStride 8\n"
11704 		"OpDecorate %v4f16arr3 ArrayStride 8\n"
11705 
11706 		"OpMemberDecorate %st_test 0 Offset 0\n"
11707 		"OpMemberDecorate %st_test 1 Offset 4\n"
11708 		"OpMemberDecorate %st_test 2 Offset 8\n"
11709 		"OpMemberDecorate %st_test 3 Offset 16\n"
11710 		"OpMemberDecorate %st_test 4 Offset 24\n"
11711 		"OpMemberDecorate %st_test 5 Offset 32\n"
11712 		"OpMemberDecorate %st_test 6 Offset 80\n"
11713 		"OpMemberDecorate %st_test 7 Offset 100\n"
11714 		"OpMemberDecorate %st_test 8 Offset 104\n"
11715 		"OpMemberDecorate %st_test 9 Offset 144\n"
11716 	);
11717 
11718 	const StringTemplate testFun
11719 	(
11720 		" %test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11721 		"     %param = OpFunctionParameter %v4f32\n"
11722 		"     %entry = OpLabel\n"
11723 
11724 		"         %i = OpVariable %fp_i32 Function\n"
11725 		"              OpStore %i %c_i32_0\n"
11726 
11727 		"  %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11728 		"              OpSelectionMerge %end_if None\n"
11729 		"              OpBranchConditional %will_run %run_test %end_if\n"
11730 
11731 		"  %run_test = OpLabel\n"
11732 		"              OpBranch %loop\n"
11733 
11734 		"      %loop = OpLabel\n"
11735 		"     %i_cmp = OpLoad %i32 %i\n"
11736 		"        %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11737 		"              OpLoopMerge %merge %next None\n"
11738 		"              OpBranchConditional %lt %write %merge\n"
11739 
11740 		"     %write = OpLabel\n"
11741 		"       %ndx = OpLoad %i32 %i\n"
11742 
11743 		"      %fld1 = OpCompositeConstruct %v2f16 %c_f16_2 %c_f16_3\n"
11744 		"      %fld2 = OpCompositeConstruct %v3f16 %c_f16_4 %c_f16_5 %c_f16_6\n"
11745 		"      %fld3 = OpCompositeConstruct %v4f16 %c_f16_8 %c_f16_9 %c_f16_10 %c_f16_11\n"
11746 
11747 		"      %fld4 = OpCompositeConstruct %f16arr3 %c_f16_12 %c_f16_13 %c_f16_14\n"
11748 
11749 		"%fld5_0_1_0 = OpCompositeConstruct %v2f16 %c_f16_18 %c_f16_19\n"
11750 		"%fld5_0_1_1 = OpCompositeConstruct %v2f16 %c_f16_20 %c_f16_21\n"
11751 		"%fld5_0_1_2 = OpCompositeConstruct %v2f16 %c_f16_22 %c_f16_23\n"
11752 		"  %fld5_0_1 = OpCompositeConstruct %v2f16arr3 %fld5_0_1_0 %fld5_0_1_1 %fld5_0_1_2\n"
11753 		"    %fld5_0 = OpCompositeConstruct %struct16 %c_f16_16 %fld5_0_1\n"
11754 
11755 		"%fld5_1_1_0 = OpCompositeConstruct %v2f16 %c_f16_26 %c_f16_27\n"
11756 		"%fld5_1_1_1 = OpCompositeConstruct %v2f16 %c_f16_28 %c_f16_29\n"
11757 		"%fld5_1_1_2 = OpCompositeConstruct %v2f16 %c_f16_30 %c_f16_31\n"
11758 		"  %fld5_1_1 = OpCompositeConstruct %v2f16arr3 %fld5_1_1_0 %fld5_1_1_1 %fld5_1_1_2\n"
11759 		"    %fld5_1 = OpCompositeConstruct %struct16 %c_f16_24 %fld5_1_1\n"
11760 
11761 		"%fld5_2_1_0 = OpCompositeConstruct %v2f16 %c_f16_34 %c_f16_35\n"
11762 		"%fld5_2_1_1 = OpCompositeConstruct %v2f16 %c_f16_36 %c_f16_37\n"
11763 		"%fld5_2_1_2 = OpCompositeConstruct %v2f16 %c_f16_38 %c_f16_39\n"
11764 		"  %fld5_2_1 = OpCompositeConstruct %v2f16arr3 %fld5_2_1_0 %fld5_2_1_1 %fld5_2_1_2\n"
11765 		"    %fld5_2 = OpCompositeConstruct %struct16 %c_f16_32 %fld5_2_1\n"
11766 
11767 		"      %fld5 = OpCompositeConstruct %struct16arr3 %fld5_0 %fld5_1 %fld5_2\n"
11768 
11769 		"    %fld6_0 = OpCompositeConstruct %v2f16 %c_f16_40 %c_f16_41\n"
11770 		"    %fld6_1 = OpCompositeConstruct %v2f16 %c_f16_42 %c_f16_43\n"
11771 		"    %fld6_2 = OpCompositeConstruct %v2f16 %c_f16_44 %c_f16_45\n"
11772 		"    %fld6_3 = OpCompositeConstruct %v2f16 %c_f16_46 %c_f16_47\n"
11773 		"    %fld6_4 = OpCompositeConstruct %v2f16 %c_f16_48 %c_f16_49\n"
11774 		"      %fld6 = OpCompositeConstruct %v2f16arr5 %fld6_0 %fld6_1 %fld6_2 %fld6_3 %fld6_4\n"
11775 
11776 		"      %fndx = OpConvertSToF %f16 %ndx\n"
11777 		"  %fld8_2a0 = OpFMul %f16 %fndx %c_f16_mod\n"
11778 		"  %fld8_3b1 = OpFAdd %f16 %fndx %c_f16_mod\n"
11779 
11780 		"   %fld8_2a = OpCompositeConstruct %v2f16 %fld8_2a0 %c_f16_61\n"
11781 		"   %fld8_3b = OpCompositeConstruct %v2f16 %c_f16_65 %fld8_3b1\n"
11782 		"    %fld8_0 = OpCompositeConstruct %v3f16 %c_f16_52 %c_f16_53 %c_f16_54\n"
11783 		"    %fld8_1 = OpCompositeConstruct %v3f16 %c_f16_56 %c_f16_57 %c_f16_58\n"
11784 		"    %fld8_2 = OpCompositeConstruct %v3f16 %fld8_2a %c_f16_62\n"
11785 		"    %fld8_3 = OpCompositeConstruct %v3f16 %c_f16_64 %fld8_3b\n"
11786 		"    %fld8_4 = OpCompositeConstruct %v3f16 %c_f16_68 %c_f16_69 %c_f16_70\n"
11787 		"      %fld8 = OpCompositeConstruct %v3f16arr5 %fld8_0 %fld8_1 %fld8_2 %fld8_3 %fld8_4\n"
11788 
11789 		"    %fld9_0 = OpCompositeConstruct %v4f16 %c_f16_72 %c_f16_73 %c_f16_74 %c_f16_75\n"
11790 		"    %fld9_1 = OpCompositeConstruct %v4f16 %c_f16_76 %c_f16_77 %c_f16_78 %c_f16_79\n"
11791 		"    %fld9_2 = OpCompositeConstruct %v4f16 %c_f16_80 %c_f16_81 %c_f16_82 %c_f16_83\n"
11792 		"      %fld9 = OpCompositeConstruct %v4f16arr3 %fld9_0 %fld9_1 %fld9_2\n"
11793 
11794 		"    %st_val = OpCompositeConstruct %st_test %c_f16_0 %fld1 %fld2 %fld3 %fld4 %fld5 %fld6 %c_f16_50 %fld8 %fld9\n"
11795 		"       %dst = OpAccessChain %up_st %ssbo_dst %c_i32_0 %ndx\n"
11796 		"              OpStore %dst %st_val\n"
11797 
11798 		"              OpBranch %next\n"
11799 
11800 		"      %next = OpLabel\n"
11801 		"     %i_cur = OpLoad %i32 %i\n"
11802 		"     %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11803 		"              OpStore %i %i_new\n"
11804 		"              OpBranch %loop\n"
11805 
11806 		"     %merge = OpLabel\n"
11807 		"              OpBranch %end_if\n"
11808 		"    %end_if = OpLabel\n"
11809 		"              OpReturnValue %param\n"
11810 		"              OpFunctionEnd\n"
11811 	);
11812 
11813 	{
11814 		SpecResource		specResource;
11815 		map<string, string>	specs;
11816 		VulkanFeatures		features;
11817 		map<string, string>	fragments;
11818 		vector<string>		extensions;
11819 		vector<deFloat16>	expectedOutput;
11820 		string				consts;
11821 
11822 		for (deUint32 elementNdx = 0; elementNdx < numElements; ++elementNdx)
11823 		{
11824 			vector<deFloat16>	expectedIterationOutput;
11825 
11826 			for (deUint32 structItemNdx = 0; structItemNdx < structItemsCount; ++structItemNdx)
11827 				expectedIterationOutput.push_back(tcu::Float16(float(structItemNdx)).bits());
11828 
11829 			for (deUint32 structItemNdx = 0; structItemNdx < DE_LENGTH_OF_ARRAY(exceptionIndices); ++structItemNdx)
11830 				expectedIterationOutput[exceptionIndices[structItemNdx]] = exceptionValue;
11831 
11832 			expectedIterationOutput[fieldModifiedMulIndex] = tcu::Float16(float(elementNdx * fieldModifier)).bits();
11833 			expectedIterationOutput[fieldModifiedAddIndex] = tcu::Float16(float(elementNdx + fieldModifier)).bits();
11834 
11835 			expectedOutput.insert(expectedOutput.end(), expectedIterationOutput.begin(), expectedIterationOutput.end());
11836 		}
11837 
11838 		for (deUint32 i = 0; i < structItemsCount; ++i)
11839 			consts += "     %c_f16_" + de::toString(i) + " = OpConstant %f16 "  + de::toString(i) + "\n";
11840 
11841 		specs["num_elements"]		= de::toString(numElements);
11842 		specs["struct_item_size"]	= de::toString(structItemsCount * sizeof(deFloat16));
11843 		specs["field_modifier"]		= de::toString(fieldModifier);
11844 		specs["consts"]				= consts;
11845 
11846 		fragments["extension"]		= "OpExtension \"SPV_KHR_16bit_storage\"";
11847 		fragments["capability"]		= "OpCapability StorageUniformBufferBlock16\n";
11848 		fragments["decoration"]		= decoration.specialize(specs);
11849 		fragments["pre_main"]		= preMain.specialize(specs);
11850 		fragments["testfun"]		= testFun.specialize(specs);
11851 
11852 		specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(expectedOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11853 		specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(expectedOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11854 		specResource.verifyIO = compareFP16CompositeFunc;
11855 
11856 		extensions.push_back("VK_KHR_16bit_storage");
11857 		extensions.push_back("VK_KHR_shader_float16_int8");
11858 
11859 		features.extFloat16Int8		= EXTFLOAT16INT8FEATURES_FLOAT16;
11860 		features.ext16BitStorage	= EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11861 
11862 		finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11863 	}
11864 
11865 	return testGroup.release();
11866 }
11867 
11868 template<class SpecResource>
createFloat16CompositeInsertExtractSet(tcu::TestContext & testCtx,const char * op)11869 tcu::TestCaseGroup* createFloat16CompositeInsertExtractSet (tcu::TestContext& testCtx, const char* op)
11870 {
11871 	de::MovePtr<tcu::TestCaseGroup>		testGroup		(new tcu::TestCaseGroup(testCtx, de::toLower(op).c_str(), op));
11872 	const deFloat16						exceptionValue	= tcu::Float16(-1.0).bits();
11873 	const string						opName			(op);
11874 	const deUint32						opIndex			= (opName == "OpCompositeInsert") ? 0
11875 														: (opName == "OpCompositeExtract") ? 1
11876 														: -1;
11877 
11878 	const StringTemplate preMain
11879 	(
11880 		"   %c_i32_ndp = OpConstant %i32 ${num_elements}\n"
11881 		"         %f16 = OpTypeFloat 16\n"
11882 		"       %v2f16 = OpTypeVector %f16 2\n"
11883 		"       %v3f16 = OpTypeVector %f16 3\n"
11884 		"       %v4f16 = OpTypeVector %f16 4\n"
11885 		"    %c_f16_na = OpConstant %f16 -1.0\n"
11886 		"     %c_u32_5 = OpConstant %u32 5\n"
11887 
11888 		"%f16arr3      = OpTypeArray %f16 %c_u32_3\n"
11889 		"%v2f16arr3    = OpTypeArray %v2f16 %c_u32_3\n"
11890 		"%v2f16arr5    = OpTypeArray %v2f16 %c_u32_5\n"
11891 		"%v3f16arr5    = OpTypeArray %v3f16 %c_u32_5\n"
11892 		"%v4f16arr3    = OpTypeArray %v4f16 %c_u32_3\n"
11893 		"%struct16     = OpTypeStruct %f16 %v2f16arr3\n"
11894 		"%struct16arr3 = OpTypeArray %struct16 %c_u32_3\n"
11895 		"%st_test      = OpTypeStruct %${field_type}\n"
11896 
11897 		"      %up_f16 = OpTypePointer Uniform %f16\n"
11898 		"       %up_st = OpTypePointer Uniform %st_test\n"
11899 		"      %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
11900 		"       %ra_st = OpTypeArray %st_test %c_i32_1\n"
11901 
11902 		"${op_premain_decls}"
11903 
11904 		" %up_SSBO_src = OpTypePointer Uniform %SSBO_src\n"
11905 		" %up_SSBO_dst = OpTypePointer Uniform %SSBO_dst\n"
11906 
11907 		"    %ssbo_src = OpVariable %up_SSBO_src Uniform\n"
11908 		"    %ssbo_dst = OpVariable %up_SSBO_dst Uniform\n"
11909 	);
11910 
11911 	const StringTemplate decoration
11912 	(
11913 		"OpDecorate %SSBO_src BufferBlock\n"
11914 		"OpDecorate %SSBO_dst BufferBlock\n"
11915 		"OpDecorate %ra_f16 ArrayStride 2\n"
11916 		"OpDecorate %ra_st ArrayStride ${struct_item_size}\n"
11917 		"OpDecorate %ssbo_src DescriptorSet 0\n"
11918 		"OpDecorate %ssbo_src Binding 0\n"
11919 		"OpDecorate %ssbo_dst DescriptorSet 0\n"
11920 		"OpDecorate %ssbo_dst Binding 1\n"
11921 
11922 		"OpMemberDecorate %SSBO_src 0 Offset 0\n"
11923 		"OpMemberDecorate %SSBO_dst 0 Offset 0\n"
11924 
11925 		"OpDecorate %v2f16arr3 ArrayStride 4\n"
11926 		"OpMemberDecorate %struct16 0 Offset 0\n"
11927 		"OpMemberDecorate %struct16 1 Offset 4\n"
11928 		"OpDecorate %struct16arr3 ArrayStride 16\n"
11929 		"OpDecorate %f16arr3 ArrayStride 2\n"
11930 		"OpDecorate %v2f16arr5 ArrayStride 4\n"
11931 		"OpDecorate %v3f16arr5 ArrayStride 8\n"
11932 		"OpDecorate %v4f16arr3 ArrayStride 8\n"
11933 
11934 		"OpMemberDecorate %st_test 0 Offset 0\n"
11935 	);
11936 
11937 	const StringTemplate testFun
11938 	(
11939 		" %test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11940 		"     %param = OpFunctionParameter %v4f32\n"
11941 		"     %entry = OpLabel\n"
11942 
11943 		"         %i = OpVariable %fp_i32 Function\n"
11944 		"              OpStore %i %c_i32_0\n"
11945 
11946 		"  %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11947 		"              OpSelectionMerge %end_if None\n"
11948 		"              OpBranchConditional %will_run %run_test %end_if\n"
11949 
11950 		"  %run_test = OpLabel\n"
11951 		"              OpBranch %loop\n"
11952 
11953 		"      %loop = OpLabel\n"
11954 		"     %i_cmp = OpLoad %i32 %i\n"
11955 		"        %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11956 		"              OpLoopMerge %merge %next None\n"
11957 		"              OpBranchConditional %lt %write %merge\n"
11958 
11959 		"     %write = OpLabel\n"
11960 		"       %ndx = OpLoad %i32 %i\n"
11961 
11962 		"${op_sw_fun_call}"
11963 
11964 		"              OpStore %dst %val_dst\n"
11965 		"              OpBranch %next\n"
11966 
11967 		"      %next = OpLabel\n"
11968 		"     %i_cur = OpLoad %i32 %i\n"
11969 		"     %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11970 		"              OpStore %i %i_new\n"
11971 		"              OpBranch %loop\n"
11972 
11973 		"     %merge = OpLabel\n"
11974 		"              OpBranch %end_if\n"
11975 		"    %end_if = OpLabel\n"
11976 		"              OpReturnValue %param\n"
11977 		"              OpFunctionEnd\n"
11978 
11979 		"${op_sw_fun_header}"
11980 		" %sw_param = OpFunctionParameter %st_test\n"
11981 		"%sw_paramn = OpFunctionParameter %i32\n"
11982 		" %sw_entry = OpLabel\n"
11983 		"             OpSelectionMerge %switch_e None\n"
11984 		"             OpSwitch %sw_paramn %default ${case_list}\n"
11985 
11986 		"${case_bodies}"
11987 
11988 		"%default   = OpLabel\n"
11989 		"             OpReturnValue ${op_case_default_value}\n"
11990 		"%switch_e  = OpLabel\n"
11991 		"             OpUnreachable\n" // Unreachable merge block for switch statement
11992 		"             OpFunctionEnd\n"
11993 	);
11994 
11995 	const StringTemplate testCaseBody
11996 	(
11997 		"%case_${case_ndx}    = OpLabel\n"
11998 		"%val_ret_${case_ndx} = ${op_name} ${op_args_part} ${access_path}\n"
11999 		"             OpReturnValue %val_ret_${case_ndx}\n"
12000 	);
12001 
12002 	struct OpParts
12003 	{
12004 		const char*	premainDecls;
12005 		const char*	swFunCall;
12006 		const char*	swFunHeader;
12007 		const char*	caseDefaultValue;
12008 		const char*	argsPartial;
12009 	};
12010 
12011 	OpParts								opPartsArray[]			=
12012 	{
12013 		// OpCompositeInsert
12014 		{
12015 			"       %fun_t = OpTypeFunction %st_test %f16 %st_test %i32\n"
12016 			"    %SSBO_src = OpTypeStruct %ra_f16\n"
12017 			"    %SSBO_dst = OpTypeStruct %ra_st\n",
12018 
12019 			"       %src = OpAccessChain %up_f16 %ssbo_src %c_i32_0 %ndx\n"
12020 			"       %dst = OpAccessChain %up_st %ssbo_dst %c_i32_0 %c_i32_0\n"
12021 			"   %val_new = OpLoad %f16 %src\n"
12022 			"   %val_old = OpLoad %st_test %dst\n"
12023 			"   %val_dst = OpFunctionCall %st_test %sw_fun %val_new %val_old %ndx\n",
12024 
12025 			"   %sw_fun = OpFunction %st_test None %fun_t\n"
12026 			"%sw_paramv = OpFunctionParameter %f16\n",
12027 
12028 			"%sw_param",
12029 
12030 			"%st_test %sw_paramv %sw_param",
12031 		},
12032 		// OpCompositeExtract
12033 		{
12034 			"       %fun_t = OpTypeFunction %f16 %st_test %i32\n"
12035 			"    %SSBO_src = OpTypeStruct %ra_st\n"
12036 			"    %SSBO_dst = OpTypeStruct %ra_f16\n",
12037 
12038 			"       %src = OpAccessChain %up_st %ssbo_src %c_i32_0 %c_i32_0\n"
12039 			"       %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
12040 			"   %val_src = OpLoad %st_test %src\n"
12041 			"   %val_dst = OpFunctionCall %f16 %sw_fun %val_src %ndx\n",
12042 
12043 			"   %sw_fun = OpFunction %f16 None %fun_t\n",
12044 
12045 			"%c_f16_na",
12046 
12047 			"%f16 %sw_param",
12048 		},
12049 	};
12050 
12051 	DE_ASSERT(opIndex >= 0 && opIndex < DE_LENGTH_OF_ARRAY(opPartsArray));
12052 
12053 	const char*	accessPathF16[] =
12054 	{
12055 		"0",			// %f16
12056 		DE_NULL,
12057 	};
12058 	const char*	accessPathV2F16[] =
12059 	{
12060 		"0 0",			// %v2f16
12061 		"0 1",
12062 	};
12063 	const char*	accessPathV3F16[] =
12064 	{
12065 		"0 0",			// %v3f16
12066 		"0 1",
12067 		"0 2",
12068 		DE_NULL,
12069 	};
12070 	const char*	accessPathV4F16[] =
12071 	{
12072 		"0 0",			// %v4f16"
12073 		"0 1",
12074 		"0 2",
12075 		"0 3",
12076 	};
12077 	const char*	accessPathF16Arr3[] =
12078 	{
12079 		"0 0",			// %f16arr3
12080 		"0 1",
12081 		"0 2",
12082 		DE_NULL,
12083 	};
12084 	const char*	accessPathStruct16Arr3[] =
12085 	{
12086 		"0 0 0",		// %struct16arr3
12087 		DE_NULL,
12088 		"0 0 1 0 0",
12089 		"0 0 1 0 1",
12090 		"0 0 1 1 0",
12091 		"0 0 1 1 1",
12092 		"0 0 1 2 0",
12093 		"0 0 1 2 1",
12094 		"0 1 0",
12095 		DE_NULL,
12096 		"0 1 1 0 0",
12097 		"0 1 1 0 1",
12098 		"0 1 1 1 0",
12099 		"0 1 1 1 1",
12100 		"0 1 1 2 0",
12101 		"0 1 1 2 1",
12102 		"0 2 0",
12103 		DE_NULL,
12104 		"0 2 1 0 0",
12105 		"0 2 1 0 1",
12106 		"0 2 1 1 0",
12107 		"0 2 1 1 1",
12108 		"0 2 1 2 0",
12109 		"0 2 1 2 1",
12110 	};
12111 	const char*	accessPathV2F16Arr5[] =
12112 	{
12113 		"0 0 0",		// %v2f16arr5
12114 		"0 0 1",
12115 		"0 1 0",
12116 		"0 1 1",
12117 		"0 2 0",
12118 		"0 2 1",
12119 		"0 3 0",
12120 		"0 3 1",
12121 		"0 4 0",
12122 		"0 4 1",
12123 	};
12124 	const char*	accessPathV3F16Arr5[] =
12125 	{
12126 		"0 0 0",		// %v3f16arr5
12127 		"0 0 1",
12128 		"0 0 2",
12129 		DE_NULL,
12130 		"0 1 0",
12131 		"0 1 1",
12132 		"0 1 2",
12133 		DE_NULL,
12134 		"0 2 0",
12135 		"0 2 1",
12136 		"0 2 2",
12137 		DE_NULL,
12138 		"0 3 0",
12139 		"0 3 1",
12140 		"0 3 2",
12141 		DE_NULL,
12142 		"0 4 0",
12143 		"0 4 1",
12144 		"0 4 2",
12145 		DE_NULL,
12146 	};
12147 	const char*	accessPathV4F16Arr3[] =
12148 	{
12149 		"0 0 0",		// %v4f16arr3
12150 		"0 0 1",
12151 		"0 0 2",
12152 		"0 0 3",
12153 		"0 1 0",
12154 		"0 1 1",
12155 		"0 1 2",
12156 		"0 1 3",
12157 		"0 2 0",
12158 		"0 2 1",
12159 		"0 2 2",
12160 		"0 2 3",
12161 		DE_NULL,
12162 		DE_NULL,
12163 		DE_NULL,
12164 		DE_NULL,
12165 	};
12166 
12167 	struct TypeTestParameters
12168 	{
12169 		const char*		name;
12170 		size_t			accessPathLength;
12171 		const char**	accessPath;
12172 	};
12173 
12174 	const TypeTestParameters typeTestParameters[] =
12175 	{
12176 		{	"f16",			DE_LENGTH_OF_ARRAY(accessPathF16),			accessPathF16			},
12177 		{	"v2f16",		DE_LENGTH_OF_ARRAY(accessPathV2F16),		accessPathV2F16			},
12178 		{	"v3f16",		DE_LENGTH_OF_ARRAY(accessPathV3F16),		accessPathV3F16			},
12179 		{	"v4f16",		DE_LENGTH_OF_ARRAY(accessPathV4F16),		accessPathV4F16			},
12180 		{	"f16arr3",		DE_LENGTH_OF_ARRAY(accessPathF16Arr3),		accessPathF16Arr3		},
12181 		{	"v2f16arr5",	DE_LENGTH_OF_ARRAY(accessPathV2F16Arr5),	accessPathV2F16Arr5		},
12182 		{	"v3f16arr5",	DE_LENGTH_OF_ARRAY(accessPathV3F16Arr5),	accessPathV3F16Arr5		},
12183 		{	"v4f16arr3",	DE_LENGTH_OF_ARRAY(accessPathV4F16Arr3),	accessPathV4F16Arr3		},
12184 		{	"struct16arr3",	DE_LENGTH_OF_ARRAY(accessPathStruct16Arr3),	accessPathStruct16Arr3	},
12185 	};
12186 
12187 	for (size_t typeTestNdx = 0; typeTestNdx < DE_LENGTH_OF_ARRAY(typeTestParameters); ++typeTestNdx)
12188 	{
12189 		const OpParts		opParts				= opPartsArray[opIndex];
12190 		const string		testName			= typeTestParameters[typeTestNdx].name;
12191 		const size_t		structItemsCount	= typeTestParameters[typeTestNdx].accessPathLength;
12192 		const char**		accessPath			= typeTestParameters[typeTestNdx].accessPath;
12193 		SpecResource		specResource;
12194 		map<string, string>	specs;
12195 		VulkanFeatures		features;
12196 		map<string, string>	fragments;
12197 		vector<string>		extensions;
12198 		vector<deFloat16>	inputFP16;
12199 		vector<deFloat16>	dummyFP16Output;
12200 
12201 		// Generate values for input
12202 		inputFP16.reserve(structItemsCount);
12203 		for (deUint32 structItemNdx = 0; structItemNdx < structItemsCount; ++structItemNdx)
12204 			inputFP16.push_back((accessPath[structItemNdx] == DE_NULL) ? exceptionValue : tcu::Float16(float(structItemNdx)).bits());
12205 
12206 		dummyFP16Output.resize(structItemsCount);
12207 
12208 		// Generate cases for OpSwitch
12209 		{
12210 			string	caseBodies;
12211 			string	caseList;
12212 
12213 			for (deUint32 caseNdx = 0; caseNdx < structItemsCount; ++caseNdx)
12214 				if (accessPath[caseNdx] != DE_NULL)
12215 				{
12216 					map<string, string>	specCase;
12217 
12218 					specCase["case_ndx"]		= de::toString(caseNdx);
12219 					specCase["access_path"]		= accessPath[caseNdx];
12220 					specCase["op_args_part"]	= opParts.argsPartial;
12221 					specCase["op_name"]			= opName;
12222 
12223 					caseBodies	+= testCaseBody.specialize(specCase);
12224 					caseList	+= de::toString(caseNdx) + " %case_" + de::toString(caseNdx) + " ";
12225 				}
12226 
12227 			specs["case_bodies"]	= caseBodies;
12228 			specs["case_list"]		= caseList;
12229 		}
12230 
12231 		specs["num_elements"]			= de::toString(structItemsCount);
12232 		specs["field_type"]				= typeTestParameters[typeTestNdx].name;
12233 		specs["struct_item_size"]		= de::toString(structItemsCount * sizeof(deFloat16));
12234 		specs["op_premain_decls"]		= opParts.premainDecls;
12235 		specs["op_sw_fun_call"]			= opParts.swFunCall;
12236 		specs["op_sw_fun_header"]		= opParts.swFunHeader;
12237 		specs["op_case_default_value"]	= opParts.caseDefaultValue;
12238 
12239 		fragments["extension"]		= "OpExtension \"SPV_KHR_16bit_storage\"";
12240 		fragments["capability"]		= "OpCapability StorageUniformBufferBlock16\n";
12241 		fragments["decoration"]		= decoration.specialize(specs);
12242 		fragments["pre_main"]		= preMain.specialize(specs);
12243 		fragments["testfun"]		= testFun.specialize(specs);
12244 
12245 		specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(inputFP16)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
12246 		specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(dummyFP16Output)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
12247 		specResource.verifyIO = compareFP16CompositeFunc;
12248 
12249 		extensions.push_back("VK_KHR_16bit_storage");
12250 		extensions.push_back("VK_KHR_shader_float16_int8");
12251 
12252 		features.extFloat16Int8		= EXTFLOAT16INT8FEATURES_FLOAT16;
12253 		features.ext16BitStorage	= EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
12254 
12255 		finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
12256 	}
12257 
12258 	return testGroup.release();
12259 }
12260 
12261 struct fp16PerComponent
12262 {
fp16PerComponentvkt::SpirVAssembly::fp16PerComponent12263 	fp16PerComponent()
12264 		: flavor(0)
12265 		, floatFormat16	(-14, 15, 10, true)
12266 		, outCompCount(0)
12267 		, argCompCount(3, 0)
12268 	{
12269 	}
12270 
callOncePerComponentvkt::SpirVAssembly::fp16PerComponent12271 	bool			callOncePerComponent	()									{ return true; }
getComponentValidityvkt::SpirVAssembly::fp16PerComponent12272 	deUint32		getComponentValidity	()									{ return static_cast<deUint32>(-1); }
12273 
getULPsvkt::SpirVAssembly::fp16PerComponent12274 	virtual double	getULPs					(vector<const deFloat16*>&)			{ return 1.0; }
getMinvkt::SpirVAssembly::fp16PerComponent12275 	virtual double	getMin					(double value, double ulps)			{ return value - floatFormat16.ulp(deAbs(value), ulps); }
getMaxvkt::SpirVAssembly::fp16PerComponent12276 	virtual double	getMax					(double value, double ulps)			{ return value + floatFormat16.ulp(deAbs(value), ulps); }
12277 
getFlavorCountvkt::SpirVAssembly::fp16PerComponent12278 	virtual size_t	getFlavorCount			()									{ return flavorNames.empty() ? 1 : flavorNames.size(); }
setFlavorvkt::SpirVAssembly::fp16PerComponent12279 	virtual void	setFlavor				(size_t flavorNo)					{ DE_ASSERT(flavorNo < getFlavorCount()); flavor = flavorNo; }
getFlavorvkt::SpirVAssembly::fp16PerComponent12280 	virtual size_t	getFlavor				()									{ return flavor; }
getCurrentFlavorNamevkt::SpirVAssembly::fp16PerComponent12281 	virtual string	getCurrentFlavorName	()									{ return flavorNames.empty() ? string("") : flavorNames[getFlavor()]; }
12282 
setOutCompCountvkt::SpirVAssembly::fp16PerComponent12283 	virtual void	setOutCompCount			(size_t compCount)					{ outCompCount = compCount; }
getOutCompCountvkt::SpirVAssembly::fp16PerComponent12284 	virtual size_t	getOutCompCount			()									{ return outCompCount; }
12285 
setArgCompCountvkt::SpirVAssembly::fp16PerComponent12286 	virtual void	setArgCompCount			(size_t argNo, size_t compCount)	{ argCompCount[argNo] = compCount; }
getArgCompCountvkt::SpirVAssembly::fp16PerComponent12287 	virtual size_t	getArgCompCount			(size_t argNo)						{ return argCompCount[argNo]; }
12288 
12289 protected:
12290 	size_t				flavor;
12291 	tcu::FloatFormat	floatFormat16;
12292 	size_t				outCompCount;
12293 	vector<size_t>		argCompCount;
12294 	vector<string>		flavorNames;
12295 };
12296 
12297 struct fp16OpFNegate : public fp16PerComponent
12298 {
12299 	template <class fp16type>
calcvkt::SpirVAssembly::fp16OpFNegate12300 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12301 	{
12302 		const fp16type	x		(*in[0]);
12303 		const double	d		(x.asDouble());
12304 		const double	result	(0.0 - d);
12305 
12306 		out[0] = fp16type(result).bits();
12307 		min[0] = getMin(result, getULPs(in));
12308 		max[0] = getMax(result, getULPs(in));
12309 
12310 		return true;
12311 	}
12312 };
12313 
12314 struct fp16Round : public fp16PerComponent
12315 {
fp16Roundvkt::SpirVAssembly::fp16Round12316 	fp16Round() : fp16PerComponent()
12317 	{
12318 		flavorNames.push_back("Floor(x+0.5)");
12319 		flavorNames.push_back("Floor(x-0.5)");
12320 		flavorNames.push_back("RoundEven");
12321 	}
12322 
12323 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Round12324 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12325 	{
12326 		const fp16type	x		(*in[0]);
12327 		const double	d		(x.asDouble());
12328 		double			result	(0.0);
12329 
12330 		switch (flavor)
12331 		{
12332 			case 0:		result = deRound(d);		break;
12333 			case 1:		result = deFloor(d - 0.5);	break;
12334 			case 2:		result = deRoundEven(d);	break;
12335 			default:	TCU_THROW(InternalError, "Invalid flavor specified");
12336 		}
12337 
12338 		out[0] = fp16type(result).bits();
12339 		min[0] = getMin(result, getULPs(in));
12340 		max[0] = getMax(result, getULPs(in));
12341 
12342 		return true;
12343 	}
12344 };
12345 
12346 struct fp16RoundEven : public fp16PerComponent
12347 {
12348 	template<class fp16type>
calcvkt::SpirVAssembly::fp16RoundEven12349 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12350 	{
12351 		const fp16type	x		(*in[0]);
12352 		const double	d		(x.asDouble());
12353 		const double	result	(deRoundEven(d));
12354 
12355 		out[0] = fp16type(result).bits();
12356 		min[0] = getMin(result, getULPs(in));
12357 		max[0] = getMax(result, getULPs(in));
12358 
12359 		return true;
12360 	}
12361 };
12362 
12363 struct fp16Trunc : public fp16PerComponent
12364 {
12365 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Trunc12366 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12367 	{
12368 		const fp16type	x		(*in[0]);
12369 		const double	d		(x.asDouble());
12370 		const double	result	(deTrunc(d));
12371 
12372 		out[0] = fp16type(result).bits();
12373 		min[0] = getMin(result, getULPs(in));
12374 		max[0] = getMax(result, getULPs(in));
12375 
12376 		return true;
12377 	}
12378 };
12379 
12380 struct fp16FAbs : public fp16PerComponent
12381 {
12382 	template<class fp16type>
calcvkt::SpirVAssembly::fp16FAbs12383 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12384 	{
12385 		const fp16type	x		(*in[0]);
12386 		const double	d		(x.asDouble());
12387 		const double	result	(deAbs(d));
12388 
12389 		out[0] = fp16type(result).bits();
12390 		min[0] = getMin(result, getULPs(in));
12391 		max[0] = getMax(result, getULPs(in));
12392 
12393 		return true;
12394 	}
12395 };
12396 
12397 struct fp16FSign : public fp16PerComponent
12398 {
12399 	template<class fp16type>
calcvkt::SpirVAssembly::fp16FSign12400 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12401 	{
12402 		const fp16type	x		(*in[0]);
12403 		const double	d		(x.asDouble());
12404 		const double	result	(deSign(d));
12405 
12406 		if (x.isNaN())
12407 			return false;
12408 
12409 		out[0] = fp16type(result).bits();
12410 		min[0] = getMin(result, getULPs(in));
12411 		max[0] = getMax(result, getULPs(in));
12412 
12413 		return true;
12414 	}
12415 };
12416 
12417 struct fp16Floor : public fp16PerComponent
12418 {
12419 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Floor12420 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12421 	{
12422 		const fp16type	x		(*in[0]);
12423 		const double	d		(x.asDouble());
12424 		const double	result	(deFloor(d));
12425 
12426 		out[0] = fp16type(result).bits();
12427 		min[0] = getMin(result, getULPs(in));
12428 		max[0] = getMax(result, getULPs(in));
12429 
12430 		return true;
12431 	}
12432 };
12433 
12434 struct fp16Ceil : public fp16PerComponent
12435 {
12436 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Ceil12437 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12438 	{
12439 		const fp16type	x		(*in[0]);
12440 		const double	d		(x.asDouble());
12441 		const double	result	(deCeil(d));
12442 
12443 		out[0] = fp16type(result).bits();
12444 		min[0] = getMin(result, getULPs(in));
12445 		max[0] = getMax(result, getULPs(in));
12446 
12447 		return true;
12448 	}
12449 };
12450 
12451 struct fp16Fract : public fp16PerComponent
12452 {
12453 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Fract12454 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12455 	{
12456 		const fp16type	x		(*in[0]);
12457 		const double	d		(x.asDouble());
12458 		const double	result	(deFrac(d));
12459 
12460 		out[0] = fp16type(result).bits();
12461 		min[0] = getMin(result, getULPs(in));
12462 		max[0] = getMax(result, getULPs(in));
12463 
12464 		return true;
12465 	}
12466 };
12467 
12468 struct fp16Radians : public fp16PerComponent
12469 {
getULPsvkt::SpirVAssembly::fp16Radians12470 	virtual double getULPs (vector<const deFloat16*>& in)
12471 	{
12472 		DE_UNREF(in);
12473 
12474 		return 2.5;
12475 	}
12476 
12477 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Radians12478 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12479 	{
12480 		const fp16type	x		(*in[0]);
12481 		const float		d		(x.asFloat());
12482 		const float		result	(deFloatRadians(d));
12483 
12484 		out[0] = fp16type(result).bits();
12485 		min[0] = getMin(result, getULPs(in));
12486 		max[0] = getMax(result, getULPs(in));
12487 
12488 		return true;
12489 	}
12490 };
12491 
12492 struct fp16Degrees : public fp16PerComponent
12493 {
getULPsvkt::SpirVAssembly::fp16Degrees12494 	virtual double getULPs (vector<const deFloat16*>& in)
12495 	{
12496 		DE_UNREF(in);
12497 
12498 		return 2.5;
12499 	}
12500 
12501 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Degrees12502 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12503 	{
12504 		const fp16type	x		(*in[0]);
12505 		const float		d		(x.asFloat());
12506 		const float		result	(deFloatDegrees(d));
12507 
12508 		out[0] = fp16type(result).bits();
12509 		min[0] = getMin(result, getULPs(in));
12510 		max[0] = getMax(result, getULPs(in));
12511 
12512 		return true;
12513 	}
12514 };
12515 
12516 struct fp16Sin : public fp16PerComponent
12517 {
12518 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Sin12519 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12520 	{
12521 		const fp16type	x			(*in[0]);
12522 		const double	d			(x.asDouble());
12523 		const double	result		(deSin(d));
12524 		const double	unspecUlp	(16.0);
12525 		const double	err			(de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE) ? deLdExp(1.0, -7) : floatFormat16.ulp(deAbs(result), unspecUlp));
12526 
12527 		if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12528 			return false;
12529 
12530 		out[0] = fp16type(result).bits();
12531 		min[0] = result - err;
12532 		max[0] = result + err;
12533 
12534 		return true;
12535 	}
12536 };
12537 
12538 struct fp16Cos : public fp16PerComponent
12539 {
12540 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Cos12541 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12542 	{
12543 		const fp16type	x			(*in[0]);
12544 		const double	d			(x.asDouble());
12545 		const double	result		(deCos(d));
12546 		const double	unspecUlp	(16.0);
12547 		const double	err			(de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE) ? deLdExp(1.0, -7) : floatFormat16.ulp(deAbs(result), unspecUlp));
12548 
12549 		if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12550 			return false;
12551 
12552 		out[0] = fp16type(result).bits();
12553 		min[0] = result - err;
12554 		max[0] = result + err;
12555 
12556 		return true;
12557 	}
12558 };
12559 
12560 struct fp16Tan : public fp16PerComponent
12561 {
12562 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Tan12563 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12564 	{
12565 		const fp16type	x		(*in[0]);
12566 		const double	d		(x.asDouble());
12567 		const double	result	(deTan(d));
12568 
12569 		if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12570 			return false;
12571 
12572 		out[0] = fp16type(result).bits();
12573 		{
12574 			const double	err			= deLdExp(1.0, -7);
12575 			const double	s1			= deSin(d) + err;
12576 			const double	s2			= deSin(d) - err;
12577 			const double	c1			= deCos(d) + err;
12578 			const double	c2			= deCos(d) - err;
12579 			const double	edgeVals[]	= {s1/c1, s1/c2, s2/c1, s2/c2};
12580 			double			edgeLeft	= out[0];
12581 			double			edgeRight	= out[0];
12582 
12583 			if (deSign(c1 * c2) < 0.0)
12584 			{
12585 				edgeLeft	= -std::numeric_limits<double>::infinity();
12586 				edgeRight	= +std::numeric_limits<double>::infinity();
12587 			}
12588 			else
12589 			{
12590 				edgeLeft	= *std::min_element(&edgeVals[0], &edgeVals[DE_LENGTH_OF_ARRAY(edgeVals)]);
12591 				edgeRight	= *std::max_element(&edgeVals[0], &edgeVals[DE_LENGTH_OF_ARRAY(edgeVals)]);
12592 			}
12593 
12594 			min[0] = edgeLeft;
12595 			max[0] = edgeRight;
12596 		}
12597 
12598 		return true;
12599 	}
12600 };
12601 
12602 struct fp16Asin : public fp16PerComponent
12603 {
12604 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Asin12605 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12606 	{
12607 		const fp16type	x		(*in[0]);
12608 		const double	d		(x.asDouble());
12609 		const double	result	(deAsin(d));
12610 		const double	error	(deAtan2(d, sqrt(1.0 - d * d)));
12611 
12612 		if (!x.isNaN() && deAbs(d) > 1.0)
12613 			return false;
12614 
12615 		out[0] = fp16type(result).bits();
12616 		min[0] = result - floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12617 		max[0] = result + floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12618 
12619 		return true;
12620 	}
12621 };
12622 
12623 struct fp16Acos : public fp16PerComponent
12624 {
12625 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Acos12626 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12627 	{
12628 		const fp16type	x		(*in[0]);
12629 		const double	d		(x.asDouble());
12630 		const double	result	(deAcos(d));
12631 		const double	error	(deAtan2(sqrt(1.0 - d * d), d));
12632 
12633 		if (!x.isNaN() && deAbs(d) > 1.0)
12634 			return false;
12635 
12636 		out[0] = fp16type(result).bits();
12637 		min[0] = result - floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12638 		max[0] = result + floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12639 
12640 		return true;
12641 	}
12642 };
12643 
12644 struct fp16Atan : public fp16PerComponent
12645 {
getULPsvkt::SpirVAssembly::fp16Atan12646 	virtual double getULPs(vector<const deFloat16*>& in)
12647 	{
12648 		DE_UNREF(in);
12649 
12650 		return 2 * 5.0; // This is not a precision test. Value is not from spec
12651 	}
12652 
12653 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Atan12654 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12655 	{
12656 		const fp16type	x		(*in[0]);
12657 		const double	d		(x.asDouble());
12658 		const double	result	(deAtanOver(d));
12659 
12660 		out[0] = fp16type(result).bits();
12661 		min[0] = getMin(result, getULPs(in));
12662 		max[0] = getMax(result, getULPs(in));
12663 
12664 		return true;
12665 	}
12666 };
12667 
12668 struct fp16Sinh : public fp16PerComponent
12669 {
fp16Sinhvkt::SpirVAssembly::fp16Sinh12670 	fp16Sinh() : fp16PerComponent()
12671 	{
12672 		flavorNames.push_back("Double");
12673 		flavorNames.push_back("ExpFP16");
12674 	}
12675 
12676 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Sinh12677 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12678 	{
12679 		const fp16type	x		(*in[0]);
12680 		const double	d		(x.asDouble());
12681 		const double	ulps	(64 * (1.0 + 2 * deAbs(d))); // This is not a precision test. Value is not from spec
12682 		double			result	(0.0);
12683 		double			error	(0.0);
12684 
12685 		if (getFlavor() == 0)
12686 		{
12687 			result	= deSinh(d);
12688 			error	= floatFormat16.ulp(deAbs(result), ulps);
12689 		}
12690 		else if (getFlavor() == 1)
12691 		{
12692 			const fp16type	epx	(deExp(d));
12693 			const fp16type	enx	(deExp(-d));
12694 			const fp16type	esx	(epx.asDouble() - enx.asDouble());
12695 			const fp16type	sx2	(esx.asDouble() / 2.0);
12696 
12697 			result	= sx2.asDouble();
12698 			error	= deAbs(floatFormat16.ulp(epx.asDouble(), ulps)) + deAbs(floatFormat16.ulp(enx.asDouble(), ulps));
12699 		}
12700 		else
12701 		{
12702 			TCU_THROW(InternalError, "Unknown flavor");
12703 		}
12704 
12705 		out[0] = fp16type(result).bits();
12706 		min[0] = result - error;
12707 		max[0] = result + error;
12708 
12709 		return true;
12710 	}
12711 };
12712 
12713 struct fp16Cosh : public fp16PerComponent
12714 {
fp16Coshvkt::SpirVAssembly::fp16Cosh12715 	fp16Cosh() : fp16PerComponent()
12716 	{
12717 		flavorNames.push_back("Double");
12718 		flavorNames.push_back("ExpFP16");
12719 	}
12720 
12721 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Cosh12722 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12723 	{
12724 		const fp16type	x		(*in[0]);
12725 		const double	d		(x.asDouble());
12726 		const double	ulps	(64 * (1.0 + 2 * deAbs(d))); // This is not a precision test. Value is not from spec
12727 		double			result	(0.0);
12728 
12729 		if (getFlavor() == 0)
12730 		{
12731 			result = deCosh(d);
12732 		}
12733 		else if (getFlavor() == 1)
12734 		{
12735 			const fp16type	epx	(deExp(d));
12736 			const fp16type	enx	(deExp(-d));
12737 			const fp16type	esx	(epx.asDouble() + enx.asDouble());
12738 			const fp16type	sx2	(esx.asDouble() / 2.0);
12739 
12740 			result = sx2.asDouble();
12741 		}
12742 		else
12743 		{
12744 			TCU_THROW(InternalError, "Unknown flavor");
12745 		}
12746 
12747 		out[0] = fp16type(result).bits();
12748 		min[0] = result - floatFormat16.ulp(deAbs(result), ulps);
12749 		max[0] = result + floatFormat16.ulp(deAbs(result), ulps);
12750 
12751 		return true;
12752 	}
12753 };
12754 
12755 struct fp16Tanh : public fp16PerComponent
12756 {
fp16Tanhvkt::SpirVAssembly::fp16Tanh12757 	fp16Tanh() : fp16PerComponent()
12758 	{
12759 		flavorNames.push_back("Tanh");
12760 		flavorNames.push_back("SinhCosh");
12761 		flavorNames.push_back("SinhCoshFP16");
12762 		flavorNames.push_back("PolyFP16");
12763 	}
12764 
getULPsvkt::SpirVAssembly::fp16Tanh12765 	virtual double getULPs (vector<const deFloat16*>& in)
12766 	{
12767 		const tcu::Float16	x	(*in[0]);
12768 		const double		d	(x.asDouble());
12769 
12770 		return 2 * (1.0 + 2 * deAbs(d)); // This is not a precision test. Value is not from spec
12771 	}
12772 
12773 	template<class fp16type>
calcPolyvkt::SpirVAssembly::fp16Tanh12774 	inline double calcPoly (const fp16type& espx, const fp16type& esnx, const fp16type& ecpx, const fp16type& ecnx)
12775 	{
12776 		const fp16type	esx	(espx.asDouble() - esnx.asDouble());
12777 		const fp16type	sx2	(esx.asDouble() / 2.0);
12778 		const fp16type	ecx	(ecpx.asDouble() + ecnx.asDouble());
12779 		const fp16type	cx2	(ecx.asDouble() / 2.0);
12780 		const fp16type	tg	(sx2.asDouble() / cx2.asDouble());
12781 		const double	rez	(tg.asDouble());
12782 
12783 		return rez;
12784 	}
12785 
12786 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Tanh12787 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12788 	{
12789 		const fp16type	x		(*in[0]);
12790 		const double	d		(x.asDouble());
12791 		double			result	(0.0);
12792 
12793 		if (getFlavor() == 0)
12794 		{
12795 			result	= deTanh(d);
12796 			min[0]	= getMin(result, getULPs(in));
12797 			max[0]	= getMax(result, getULPs(in));
12798 		}
12799 		else if (getFlavor() == 1)
12800 		{
12801 			result	= deSinh(d) / deCosh(d);
12802 			min[0]	= getMin(result, getULPs(in));
12803 			max[0]	= getMax(result, getULPs(in));
12804 		}
12805 		else if (getFlavor() == 2)
12806 		{
12807 			const fp16type	s	(deSinh(d));
12808 			const fp16type	c	(deCosh(d));
12809 
12810 			result	= s.asDouble() / c.asDouble();
12811 			min[0]	= getMin(result, getULPs(in));
12812 			max[0]	= getMax(result, getULPs(in));
12813 		}
12814 		else if (getFlavor() == 3)
12815 		{
12816 			const double	ulps	(getULPs(in));
12817 			const double	epxm	(deExp( d));
12818 			const double	enxm	(deExp(-d));
12819 			const double	epxmerr	= floatFormat16.ulp(epxm, ulps);
12820 			const double	enxmerr	= floatFormat16.ulp(enxm, ulps);
12821 			const fp16type	epx[]	= { fp16type(epxm - epxmerr), fp16type(epxm + epxmerr) };
12822 			const fp16type	enx[]	= { fp16type(enxm - enxmerr), fp16type(enxm + enxmerr) };
12823 			const fp16type	epxm16	(epxm);
12824 			const fp16type	enxm16	(enxm);
12825 			vector<double>	tgs;
12826 
12827 			for (size_t spNdx = 0; spNdx < DE_LENGTH_OF_ARRAY(epx); ++spNdx)
12828 			for (size_t snNdx = 0; snNdx < DE_LENGTH_OF_ARRAY(enx); ++snNdx)
12829 			for (size_t cpNdx = 0; cpNdx < DE_LENGTH_OF_ARRAY(epx); ++cpNdx)
12830 			for (size_t cnNdx = 0; cnNdx < DE_LENGTH_OF_ARRAY(enx); ++cnNdx)
12831 			{
12832 				const double tgh = calcPoly(epx[spNdx], enx[snNdx], epx[cpNdx], enx[cnNdx]);
12833 
12834 				tgs.push_back(tgh);
12835 			}
12836 
12837 			result = calcPoly(epxm16, enxm16, epxm16, enxm16);
12838 			min[0] = *std::min_element(tgs.begin(), tgs.end());
12839 			max[0] = *std::max_element(tgs.begin(), tgs.end());
12840 		}
12841 		else
12842 		{
12843 			TCU_THROW(InternalError, "Unknown flavor");
12844 		}
12845 
12846 		out[0] = fp16type(result).bits();
12847 
12848 		return true;
12849 	}
12850 };
12851 
12852 struct fp16Asinh : public fp16PerComponent
12853 {
fp16Asinhvkt::SpirVAssembly::fp16Asinh12854 	fp16Asinh() : fp16PerComponent()
12855 	{
12856 		flavorNames.push_back("Double");
12857 		flavorNames.push_back("PolyFP16Wiki");
12858 		flavorNames.push_back("PolyFP16Abs");
12859 	}
12860 
getULPsvkt::SpirVAssembly::fp16Asinh12861 	virtual double getULPs (vector<const deFloat16*>& in)
12862 	{
12863 		DE_UNREF(in);
12864 
12865 		return 256.0; // This is not a precision test. Value is not from spec
12866 	}
12867 
12868 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Asinh12869 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12870 	{
12871 		const fp16type	x		(*in[0]);
12872 		const double	d		(x.asDouble());
12873 		double			result	(0.0);
12874 
12875 		if (getFlavor() == 0)
12876 		{
12877 			result = deAsinh(d);
12878 		}
12879 		else if (getFlavor() == 1)
12880 		{
12881 			const fp16type	x2		(d * d);
12882 			const fp16type	x2p1	(x2.asDouble() + 1.0);
12883 			const fp16type	sq		(deSqrt(x2p1.asDouble()));
12884 			const fp16type	sxsq	(d + sq.asDouble());
12885 			const fp16type	lsxsq	(deLog(sxsq.asDouble()));
12886 
12887 			if (lsxsq.isInf())
12888 				return false;
12889 
12890 			result = lsxsq.asDouble();
12891 		}
12892 		else if (getFlavor() == 2)
12893 		{
12894 			const fp16type	x2		(d * d);
12895 			const fp16type	x2p1	(x2.asDouble() + 1.0);
12896 			const fp16type	sq		(deSqrt(x2p1.asDouble()));
12897 			const fp16type	sxsq	(deAbs(d) + sq.asDouble());
12898 			const fp16type	lsxsq	(deLog(sxsq.asDouble()));
12899 
12900 			result = deSign(d) * lsxsq.asDouble();
12901 		}
12902 		else
12903 		{
12904 			TCU_THROW(InternalError, "Unknown flavor");
12905 		}
12906 
12907 		out[0] = fp16type(result).bits();
12908 		min[0] = getMin(result, getULPs(in));
12909 		max[0] = getMax(result, getULPs(in));
12910 
12911 		return true;
12912 	}
12913 };
12914 
12915 struct fp16Acosh : public fp16PerComponent
12916 {
fp16Acoshvkt::SpirVAssembly::fp16Acosh12917 	fp16Acosh() : fp16PerComponent()
12918 	{
12919 		flavorNames.push_back("Double");
12920 		flavorNames.push_back("PolyFP16");
12921 	}
12922 
getULPsvkt::SpirVAssembly::fp16Acosh12923 	virtual double getULPs (vector<const deFloat16*>& in)
12924 	{
12925 		DE_UNREF(in);
12926 
12927 		return 16.0; // This is not a precision test. Value is not from spec
12928 	}
12929 
12930 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Acosh12931 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12932 	{
12933 		const fp16type	x		(*in[0]);
12934 		const double	d		(x.asDouble());
12935 		double			result	(0.0);
12936 
12937 		if (!x.isNaN() && d < 1.0)
12938 			return false;
12939 
12940 		if (getFlavor() == 0)
12941 		{
12942 			result = deAcosh(d);
12943 		}
12944 		else if (getFlavor() == 1)
12945 		{
12946 			const fp16type	x2		(d * d);
12947 			const fp16type	x2m1	(x2.asDouble() - 1.0);
12948 			const fp16type	sq		(deSqrt(x2m1.asDouble()));
12949 			const fp16type	sxsq	(d + sq.asDouble());
12950 			const fp16type	lsxsq	(deLog(sxsq.asDouble()));
12951 
12952 			result = lsxsq.asDouble();
12953 		}
12954 		else
12955 		{
12956 			TCU_THROW(InternalError, "Unknown flavor");
12957 		}
12958 
12959 		out[0] = fp16type(result).bits();
12960 		min[0] = getMin(result, getULPs(in));
12961 		max[0] = getMax(result, getULPs(in));
12962 
12963 		return true;
12964 	}
12965 };
12966 
12967 struct fp16Atanh : public fp16PerComponent
12968 {
fp16Atanhvkt::SpirVAssembly::fp16Atanh12969 	fp16Atanh() : fp16PerComponent()
12970 	{
12971 		flavorNames.push_back("Double");
12972 		flavorNames.push_back("PolyFP16");
12973 	}
12974 
12975 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Atanh12976 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12977 	{
12978 		const fp16type	x		(*in[0]);
12979 		const double	d		(x.asDouble());
12980 		double			result	(0.0);
12981 
12982 		if (deAbs(d) >= 1.0)
12983 			return false;
12984 
12985 		if (getFlavor() == 0)
12986 		{
12987 			const double	ulps	(16.0);	// This is not a precision test. Value is not from spec
12988 
12989 			result = deAtanh(d);
12990 			min[0] = getMin(result, ulps);
12991 			max[0] = getMax(result, ulps);
12992 		}
12993 		else if (getFlavor() == 1)
12994 		{
12995 			const fp16type	x1a		(1.0 + d);
12996 			const fp16type	x1b		(1.0 - d);
12997 			const fp16type	x1d		(x1a.asDouble() / x1b.asDouble());
12998 			const fp16type	lx1d	(deLog(x1d.asDouble()));
12999 			const fp16type	lx1d2	(0.5 * lx1d.asDouble());
13000 			const double	error	(2 * (de::inRange(deAbs(x1d.asDouble()), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(x1d.asDouble()), 3.0)));
13001 
13002 			result = lx1d2.asDouble();
13003 			min[0] = result - error;
13004 			max[0] = result + error;
13005 		}
13006 		else
13007 		{
13008 			TCU_THROW(InternalError, "Unknown flavor");
13009 		}
13010 
13011 		out[0] = fp16type(result).bits();
13012 
13013 		return true;
13014 	}
13015 };
13016 
13017 struct fp16Exp : public fp16PerComponent
13018 {
13019 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Exp13020 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13021 	{
13022 		const fp16type	x		(*in[0]);
13023 		const double	d		(x.asDouble());
13024 		const double	ulps	(10.0 * (1.0 + 2.0 * deAbs(d)));
13025 		const double	result	(deExp(d));
13026 
13027 		out[0] = fp16type(result).bits();
13028 		min[0] = getMin(result, ulps);
13029 		max[0] = getMax(result, ulps);
13030 
13031 		return true;
13032 	}
13033 };
13034 
13035 struct fp16Log : public fp16PerComponent
13036 {
13037 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Log13038 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13039 	{
13040 		const fp16type	x		(*in[0]);
13041 		const double	d		(x.asDouble());
13042 		const double	result	(deLog(d));
13043 		const double	error	(de::inRange(deAbs(d), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(result), 3.0));
13044 
13045 		if (d <= 0.0)
13046 			return false;
13047 
13048 		out[0] = fp16type(result).bits();
13049 		min[0] = result - error;
13050 		max[0] = result + error;
13051 
13052 		return true;
13053 	}
13054 };
13055 
13056 struct fp16Exp2 : public fp16PerComponent
13057 {
13058 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Exp213059 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13060 	{
13061 		const fp16type	x		(*in[0]);
13062 		const double	d		(x.asDouble());
13063 		const double	result	(deExp2(d));
13064 		const double	ulps	(1.0 + 2.0 * deAbs(fp16type(in[0][0]).asDouble()));
13065 
13066 		out[0] = fp16type(result).bits();
13067 		min[0] = getMin(result, ulps);
13068 		max[0] = getMax(result, ulps);
13069 
13070 		return true;
13071 	}
13072 };
13073 
13074 struct fp16Log2 : public fp16PerComponent
13075 {
13076 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Log213077 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13078 	{
13079 		const fp16type	x		(*in[0]);
13080 		const double	d		(x.asDouble());
13081 		const double	result	(deLog2(d));
13082 		const double	error	(de::inRange(deAbs(d), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(result), 3.0));
13083 
13084 		if (d <= 0.0)
13085 			return false;
13086 
13087 		out[0] = fp16type(result).bits();
13088 		min[0] = result - error;
13089 		max[0] = result + error;
13090 
13091 		return true;
13092 	}
13093 };
13094 
13095 struct fp16Sqrt : public fp16PerComponent
13096 {
getULPsvkt::SpirVAssembly::fp16Sqrt13097 	virtual double getULPs (vector<const deFloat16*>& in)
13098 	{
13099 		DE_UNREF(in);
13100 
13101 		return 6.0;
13102 	}
13103 
13104 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Sqrt13105 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13106 	{
13107 		const fp16type	x		(*in[0]);
13108 		const double	d		(x.asDouble());
13109 		const double	result	(deSqrt(d));
13110 
13111 		if (!x.isNaN() && d < 0.0)
13112 			return false;
13113 
13114 		out[0] = fp16type(result).bits();
13115 		min[0] = getMin(result, getULPs(in));
13116 		max[0] = getMax(result, getULPs(in));
13117 
13118 		return true;
13119 	}
13120 };
13121 
13122 struct fp16InverseSqrt : public fp16PerComponent
13123 {
getULPsvkt::SpirVAssembly::fp16InverseSqrt13124 	virtual double getULPs (vector<const deFloat16*>& in)
13125 	{
13126 		DE_UNREF(in);
13127 
13128 		return 2.0;
13129 	}
13130 
13131 	template<class fp16type>
calcvkt::SpirVAssembly::fp16InverseSqrt13132 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13133 	{
13134 		const fp16type	x		(*in[0]);
13135 		const double	d		(x.asDouble());
13136 		const double	result	(1.0/deSqrt(d));
13137 
13138 		if (!x.isNaN() && d <= 0.0)
13139 			return false;
13140 
13141 		out[0] = fp16type(result).bits();
13142 		min[0] = getMin(result, getULPs(in));
13143 		max[0] = getMax(result, getULPs(in));
13144 
13145 		return true;
13146 	}
13147 };
13148 
13149 struct fp16ModfFrac : public fp16PerComponent
13150 {
13151 	template<class fp16type>
calcvkt::SpirVAssembly::fp16ModfFrac13152 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13153 	{
13154 		const fp16type	x		(*in[0]);
13155 		const double	d		(x.asDouble());
13156 		double			i		(0.0);
13157 		const double	result	(deModf(d, &i));
13158 
13159 		if (x.isInf() || x.isNaN())
13160 			return false;
13161 
13162 		out[0] = fp16type(result).bits();
13163 		min[0] = getMin(result, getULPs(in));
13164 		max[0] = getMax(result, getULPs(in));
13165 
13166 		return true;
13167 	}
13168 };
13169 
13170 struct fp16ModfInt : public fp16PerComponent
13171 {
13172 	template<class fp16type>
calcvkt::SpirVAssembly::fp16ModfInt13173 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13174 	{
13175 		const fp16type	x		(*in[0]);
13176 		const double	d		(x.asDouble());
13177 		double			i		(0.0);
13178 		const double	dummy	(deModf(d, &i));
13179 		const double	result	(i);
13180 
13181 		DE_UNREF(dummy);
13182 
13183 		if (x.isInf() || x.isNaN())
13184 			return false;
13185 
13186 		out[0] = fp16type(result).bits();
13187 		min[0] = getMin(result, getULPs(in));
13188 		max[0] = getMax(result, getULPs(in));
13189 
13190 		return true;
13191 	}
13192 };
13193 
13194 struct fp16FrexpS : public fp16PerComponent
13195 {
13196 	template<class fp16type>
calcvkt::SpirVAssembly::fp16FrexpS13197 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13198 	{
13199 		const fp16type	x		(*in[0]);
13200 		const double	d		(x.asDouble());
13201 		int				e		(0);
13202 		const double	result	(deFrExp(d, &e));
13203 
13204 		if (x.isNaN() || x.isInf())
13205 			return false;
13206 
13207 		out[0] = fp16type(result).bits();
13208 		min[0] = getMin(result, getULPs(in));
13209 		max[0] = getMax(result, getULPs(in));
13210 
13211 		return true;
13212 	}
13213 };
13214 
13215 struct fp16FrexpE : public fp16PerComponent
13216 {
13217 	template<class fp16type>
calcvkt::SpirVAssembly::fp16FrexpE13218 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13219 	{
13220 		const fp16type	x		(*in[0]);
13221 		const double	d		(x.asDouble());
13222 		int				e		(0);
13223 		const double	dummy	(deFrExp(d, &e));
13224 		const double	result	(static_cast<double>(e));
13225 
13226 		DE_UNREF(dummy);
13227 
13228 		if (x.isNaN() || x.isInf())
13229 			return false;
13230 
13231 		out[0] = fp16type(result).bits();
13232 		min[0] = getMin(result, getULPs(in));
13233 		max[0] = getMax(result, getULPs(in));
13234 
13235 		return true;
13236 	}
13237 };
13238 
13239 struct fp16OpFAdd : public fp16PerComponent
13240 {
13241 	template<class fp16type>
calcvkt::SpirVAssembly::fp16OpFAdd13242 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13243 	{
13244 		const fp16type	x		(*in[0]);
13245 		const fp16type	y		(*in[1]);
13246 		const double	xd		(x.asDouble());
13247 		const double	yd		(y.asDouble());
13248 		const double	result	(xd + yd);
13249 
13250 		out[0] = fp16type(result).bits();
13251 		min[0] = getMin(result, getULPs(in));
13252 		max[0] = getMax(result, getULPs(in));
13253 
13254 		return true;
13255 	}
13256 };
13257 
13258 struct fp16OpFSub : public fp16PerComponent
13259 {
13260 	template<class fp16type>
calcvkt::SpirVAssembly::fp16OpFSub13261 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13262 	{
13263 		const fp16type	x		(*in[0]);
13264 		const fp16type	y		(*in[1]);
13265 		const double	xd		(x.asDouble());
13266 		const double	yd		(y.asDouble());
13267 		const double	result	(xd - yd);
13268 
13269 		out[0] = fp16type(result).bits();
13270 		min[0] = getMin(result, getULPs(in));
13271 		max[0] = getMax(result, getULPs(in));
13272 
13273 		return true;
13274 	}
13275 };
13276 
13277 struct fp16OpFMul : public fp16PerComponent
13278 {
13279 	template<class fp16type>
calcvkt::SpirVAssembly::fp16OpFMul13280 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13281 	{
13282 		const fp16type	x		(*in[0]);
13283 		const fp16type	y		(*in[1]);
13284 		const double	xd		(x.asDouble());
13285 		const double	yd		(y.asDouble());
13286 		const double	result	(xd * yd);
13287 
13288 		out[0] = fp16type(result).bits();
13289 		min[0] = getMin(result, getULPs(in));
13290 		max[0] = getMax(result, getULPs(in));
13291 
13292 		return true;
13293 	}
13294 };
13295 
13296 struct fp16OpFDiv : public fp16PerComponent
13297 {
fp16OpFDivvkt::SpirVAssembly::fp16OpFDiv13298 	fp16OpFDiv() : fp16PerComponent()
13299 	{
13300 		flavorNames.push_back("DirectDiv");
13301 		flavorNames.push_back("InverseDiv");
13302 	}
13303 
13304 	template<class fp16type>
calcvkt::SpirVAssembly::fp16OpFDiv13305 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13306 	{
13307 		const fp16type	x			(*in[0]);
13308 		const fp16type	y			(*in[1]);
13309 		const double	xd			(x.asDouble());
13310 		const double	yd			(y.asDouble());
13311 		const double	unspecUlp	(16.0);
13312 		const double	ulpCnt		(de::inRange(deAbs(yd), deLdExp(1, -14), deLdExp(1, 14)) ? 2.5 : unspecUlp);
13313 		double			result		(0.0);
13314 
13315 		if (y.isZero())
13316 			return false;
13317 
13318 		if (getFlavor() == 0)
13319 		{
13320 			result = (xd / yd);
13321 		}
13322 		else if (getFlavor() == 1)
13323 		{
13324 			const double	invyd	(1.0 / yd);
13325 			const fp16type	invy	(invyd);
13326 
13327 			result = (xd * invy.asDouble());
13328 		}
13329 		else
13330 		{
13331 			TCU_THROW(InternalError, "Unknown flavor");
13332 		}
13333 
13334 		out[0] = fp16type(result).bits();
13335 		min[0] = getMin(result, ulpCnt);
13336 		max[0] = getMax(result, ulpCnt);
13337 
13338 		return true;
13339 	}
13340 };
13341 
13342 struct fp16Atan2 : public fp16PerComponent
13343 {
fp16Atan2vkt::SpirVAssembly::fp16Atan213344 	fp16Atan2() : fp16PerComponent()
13345 	{
13346 		flavorNames.push_back("DoubleCalc");
13347 		flavorNames.push_back("DoubleCalc_PI");
13348 	}
13349 
getULPsvkt::SpirVAssembly::fp16Atan213350 	virtual double getULPs(vector<const deFloat16*>& in)
13351 	{
13352 		DE_UNREF(in);
13353 
13354 		return 2 * 5.0; // This is not a precision test. Value is not from spec
13355 	}
13356 
13357 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Atan213358 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13359 	{
13360 		const fp16type	x		(*in[0]);
13361 		const fp16type	y		(*in[1]);
13362 		const double	xd		(x.asDouble());
13363 		const double	yd		(y.asDouble());
13364 		double			result	(0.0);
13365 
13366 		if (x.isZero() && y.isZero())
13367 			return false;
13368 
13369 		if (getFlavor() == 0)
13370 		{
13371 			result	= deAtan2(xd, yd);
13372 		}
13373 		else if (getFlavor() == 1)
13374 		{
13375 			const double	ulps	(2.0 * 5.0); // This is not a precision test. Value is not from spec
13376 			const double	eps		(floatFormat16.ulp(DE_PI_DOUBLE, ulps));
13377 
13378 			result	= deAtan2(xd, yd);
13379 
13380 			if (de::inRange(deAbs(result), DE_PI_DOUBLE - eps, DE_PI_DOUBLE + eps))
13381 				result	= -result;
13382 		}
13383 		else
13384 		{
13385 			TCU_THROW(InternalError, "Unknown flavor");
13386 		}
13387 
13388 		out[0] = fp16type(result).bits();
13389 		min[0] = getMin(result, getULPs(in));
13390 		max[0] = getMax(result, getULPs(in));
13391 
13392 		return true;
13393 	}
13394 };
13395 
13396 struct fp16Pow : public fp16PerComponent
13397 {
fp16Powvkt::SpirVAssembly::fp16Pow13398 	fp16Pow() : fp16PerComponent()
13399 	{
13400 		flavorNames.push_back("Pow");
13401 		flavorNames.push_back("PowLog2");
13402 		flavorNames.push_back("PowLog2FP16");
13403 	}
13404 
13405 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Pow13406 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13407 	{
13408 		const fp16type	x		(*in[0]);
13409 		const fp16type	y		(*in[1]);
13410 		const double	xd		(x.asDouble());
13411 		const double	yd		(y.asDouble());
13412 		const double	logxeps	(de::inRange(deAbs(xd), 0.5, 2.0) ? deLdExp(1.0, -7) : floatFormat16.ulp(deLog2(xd), 3.0));
13413 		const double	ulps1	(1.0 + 4.0 * deAbs(yd * (deLog2(xd) - logxeps)));
13414 		const double	ulps2	(1.0 + 4.0 * deAbs(yd * (deLog2(xd) + logxeps)));
13415 		const double	ulps	(deMax(deAbs(ulps1), deAbs(ulps2)));
13416 		double			result	(0.0);
13417 
13418 		if (xd < 0.0)
13419 			return false;
13420 
13421 		if (x.isZero() && yd <= 0.0)
13422 			return false;
13423 
13424 		if (getFlavor() == 0)
13425 		{
13426 			result = dePow(xd, yd);
13427 		}
13428 		else if (getFlavor() == 1)
13429 		{
13430 			const double	l2d	(deLog2(xd));
13431 			const double	e2d	(deExp2(yd * l2d));
13432 
13433 			result = e2d;
13434 		}
13435 		else if (getFlavor() == 2)
13436 		{
13437 			const double	l2d	(deLog2(xd));
13438 			const fp16type	l2	(l2d);
13439 			const double	e2d	(deExp2(yd * l2.asDouble()));
13440 			const fp16type	e2	(e2d);
13441 
13442 			result = e2.asDouble();
13443 		}
13444 		else
13445 		{
13446 			TCU_THROW(InternalError, "Unknown flavor");
13447 		}
13448 
13449 		out[0] = fp16type(result).bits();
13450 		min[0] = getMin(result, ulps);
13451 		max[0] = getMax(result, ulps);
13452 
13453 		return true;
13454 	}
13455 };
13456 
13457 struct fp16FMin : public fp16PerComponent
13458 {
13459 	template<class fp16type>
calcvkt::SpirVAssembly::fp16FMin13460 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13461 	{
13462 		const fp16type	x		(*in[0]);
13463 		const fp16type	y		(*in[1]);
13464 		const double	xd		(x.asDouble());
13465 		const double	yd		(y.asDouble());
13466 		const double	result	(deMin(xd, yd));
13467 
13468 		if (x.isNaN() || y.isNaN())
13469 			return false;
13470 
13471 		out[0] = fp16type(result).bits();
13472 		min[0] = getMin(result, getULPs(in));
13473 		max[0] = getMax(result, getULPs(in));
13474 
13475 		return true;
13476 	}
13477 };
13478 
13479 struct fp16FMax : public fp16PerComponent
13480 {
13481 	template<class fp16type>
calcvkt::SpirVAssembly::fp16FMax13482 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13483 	{
13484 		const fp16type	x		(*in[0]);
13485 		const fp16type	y		(*in[1]);
13486 		const double	xd		(x.asDouble());
13487 		const double	yd		(y.asDouble());
13488 		const double	result	(deMax(xd, yd));
13489 
13490 		if (x.isNaN() || y.isNaN())
13491 			return false;
13492 
13493 		out[0] = fp16type(result).bits();
13494 		min[0] = getMin(result, getULPs(in));
13495 		max[0] = getMax(result, getULPs(in));
13496 
13497 		return true;
13498 	}
13499 };
13500 
13501 struct fp16Step : public fp16PerComponent
13502 {
13503 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Step13504 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13505 	{
13506 		const fp16type	edge	(*in[0]);
13507 		const fp16type	x		(*in[1]);
13508 		const double	edged	(edge.asDouble());
13509 		const double	xd		(x.asDouble());
13510 		const double	result	(deStep(edged, xd));
13511 
13512 		out[0] = fp16type(result).bits();
13513 		min[0] = getMin(result, getULPs(in));
13514 		max[0] = getMax(result, getULPs(in));
13515 
13516 		return true;
13517 	}
13518 };
13519 
13520 struct fp16Ldexp : public fp16PerComponent
13521 {
13522 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Ldexp13523 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13524 	{
13525 		const fp16type	x		(*in[0]);
13526 		const fp16type	y		(*in[1]);
13527 		const double	xd		(x.asDouble());
13528 		const int		yd		(static_cast<int>(deTrunc(y.asDouble())));
13529 		const double	result	(deLdExp(xd, yd));
13530 
13531 		if (y.isNaN() || y.isInf() || y.isDenorm() || yd < -14 || yd > 15)
13532 			return false;
13533 
13534 		// Spec: "If this product is too large to be represented in the floating-point type, the result is undefined."
13535 		if (fp16type(result).isInf())
13536 			return false;
13537 
13538 		out[0] = fp16type(result).bits();
13539 		min[0] = getMin(result, getULPs(in));
13540 		max[0] = getMax(result, getULPs(in));
13541 
13542 		return true;
13543 	}
13544 };
13545 
13546 struct fp16FClamp : public fp16PerComponent
13547 {
13548 	template<class fp16type>
calcvkt::SpirVAssembly::fp16FClamp13549 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13550 	{
13551 		const fp16type	x		(*in[0]);
13552 		const fp16type	minVal	(*in[1]);
13553 		const fp16type	maxVal	(*in[2]);
13554 		const double	xd		(x.asDouble());
13555 		const double	minVald	(minVal.asDouble());
13556 		const double	maxVald	(maxVal.asDouble());
13557 		const double	result	(deClamp(xd, minVald, maxVald));
13558 
13559 		if (minVal.isNaN() || maxVal.isNaN() || minVald > maxVald)
13560 			return false;
13561 
13562 		out[0] = fp16type(result).bits();
13563 		min[0] = getMin(result, getULPs(in));
13564 		max[0] = getMax(result, getULPs(in));
13565 
13566 		return true;
13567 	}
13568 };
13569 
13570 struct fp16FMix : public fp16PerComponent
13571 {
fp16FMixvkt::SpirVAssembly::fp16FMix13572 	fp16FMix() : fp16PerComponent()
13573 	{
13574 		flavorNames.push_back("DoubleCalc");
13575 		flavorNames.push_back("EmulatingFP16");
13576 		flavorNames.push_back("EmulatingFP16YminusX");
13577 	}
13578 
13579 	template<class fp16type>
calcvkt::SpirVAssembly::fp16FMix13580 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13581 	{
13582 		const fp16type	x		(*in[0]);
13583 		const fp16type	y		(*in[1]);
13584 		const fp16type	a		(*in[2]);
13585 		const double	ulps	(8.0); // This is not a precision test. Value is not from spec
13586 		double			result	(0.0);
13587 
13588 		if (getFlavor() == 0)
13589 		{
13590 			const double	xd		(x.asDouble());
13591 			const double	yd		(y.asDouble());
13592 			const double	ad		(a.asDouble());
13593 			const double	xeps	(floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13594 			const double	yeps	(floatFormat16.ulp(deAbs(yd * ad), ulps));
13595 			const double	eps		(xeps + yeps);
13596 
13597 			result = deMix(xd, yd, ad);
13598 			min[0] = result - eps;
13599 			max[0] = result + eps;
13600 		}
13601 		else if (getFlavor() == 1)
13602 		{
13603 			const double	xd		(x.asDouble());
13604 			const double	yd		(y.asDouble());
13605 			const double	ad		(a.asDouble());
13606 			const fp16type	am		(1.0 - ad);
13607 			const double	amd		(am.asDouble());
13608 			const fp16type	xam		(xd * amd);
13609 			const double	xamd	(xam.asDouble());
13610 			const fp16type	ya		(yd * ad);
13611 			const double	yad		(ya.asDouble());
13612 			const double	xeps	(floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13613 			const double	yeps	(floatFormat16.ulp(deAbs(yd * ad), ulps));
13614 			const double	eps		(xeps + yeps);
13615 
13616 			result = xamd + yad;
13617 			min[0] = result - eps;
13618 			max[0] = result + eps;
13619 		}
13620 		else if (getFlavor() == 2)
13621 		{
13622 			const double	xd		(x.asDouble());
13623 			const double	yd		(y.asDouble());
13624 			const double	ad		(a.asDouble());
13625 			const fp16type	ymx		(yd - xd);
13626 			const double	ymxd	(ymx.asDouble());
13627 			const fp16type	ymxa	(ymxd * ad);
13628 			const double	ymxad	(ymxa.asDouble());
13629 			const double	xeps	(floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13630 			const double	yeps	(floatFormat16.ulp(deAbs(yd * ad), ulps));
13631 			const double	eps		(xeps + yeps);
13632 
13633 			result = xd + ymxad;
13634 			min[0] = result - eps;
13635 			max[0] = result + eps;
13636 		}
13637 		else
13638 		{
13639 			TCU_THROW(InternalError, "Unknown flavor");
13640 		}
13641 
13642 		out[0] = fp16type(result).bits();
13643 
13644 		return true;
13645 	}
13646 };
13647 
13648 struct fp16SmoothStep : public fp16PerComponent
13649 {
fp16SmoothStepvkt::SpirVAssembly::fp16SmoothStep13650 	fp16SmoothStep() : fp16PerComponent()
13651 	{
13652 		flavorNames.push_back("FloatCalc");
13653 		flavorNames.push_back("EmulatingFP16");
13654 		flavorNames.push_back("EmulatingFP16WClamp");
13655 	}
13656 
getULPsvkt::SpirVAssembly::fp16SmoothStep13657 	virtual double getULPs(vector<const deFloat16*>& in)
13658 	{
13659 		DE_UNREF(in);
13660 
13661 		return 4.0; // This is not a precision test. Value is not from spec
13662 	}
13663 
13664 	template<class fp16type>
calcvkt::SpirVAssembly::fp16SmoothStep13665 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13666 	{
13667 		const fp16type	edge0	(*in[0]);
13668 		const fp16type	edge1	(*in[1]);
13669 		const fp16type	x		(*in[2]);
13670 		double			result	(0.0);
13671 
13672 		if (edge0.isNaN() || edge1.isNaN() || x.isNaN() || edge0.asDouble() >= edge1.asDouble())
13673 			return false;
13674 
13675 		if (edge0.isInf() || edge1.isInf() || x.isInf())
13676 			return false;
13677 
13678 		if (getFlavor() == 0)
13679 		{
13680 			const float	edge0d	(edge0.asFloat());
13681 			const float	edge1d	(edge1.asFloat());
13682 			const float	xd		(x.asFloat());
13683 			const float	sstep	(deFloatSmoothStep(edge0d, edge1d, xd));
13684 
13685 			result = sstep;
13686 		}
13687 		else if (getFlavor() == 1)
13688 		{
13689 			const double	edge0d	(edge0.asDouble());
13690 			const double	edge1d	(edge1.asDouble());
13691 			const double	xd		(x.asDouble());
13692 
13693 			if (xd <= edge0d)
13694 				result = 0.0;
13695 			else if (xd >= edge1d)
13696 				result = 1.0;
13697 			else
13698 			{
13699 				const fp16type	a	(xd - edge0d);
13700 				const fp16type	b	(edge1d - edge0d);
13701 				const fp16type	t	(a.asDouble() / b.asDouble());
13702 				const fp16type	t2	(2.0 * t.asDouble());
13703 				const fp16type	t3	(3.0 - t2.asDouble());
13704 				const fp16type	t4	(t.asDouble() * t3.asDouble());
13705 				const fp16type	t5	(t.asDouble() * t4.asDouble());
13706 
13707 				result = t5.asDouble();
13708 			}
13709 		}
13710 		else if (getFlavor() == 2)
13711 		{
13712 			const double	edge0d	(edge0.asDouble());
13713 			const double	edge1d	(edge1.asDouble());
13714 			const double	xd		(x.asDouble());
13715 			const fp16type	a	(xd - edge0d);
13716 			const fp16type	b	(edge1d - edge0d);
13717 			const fp16type	bi	(1.0 / b.asDouble());
13718 			const fp16type	t0	(a.asDouble() * bi.asDouble());
13719 			const double	tc	(deClamp(t0.asDouble(), 0.0, 1.0));
13720 			const fp16type	t	(tc);
13721 			const fp16type	t2	(2.0 * t.asDouble());
13722 			const fp16type	t3	(3.0 - t2.asDouble());
13723 			const fp16type	t4	(t.asDouble() * t3.asDouble());
13724 			const fp16type	t5	(t.asDouble() * t4.asDouble());
13725 
13726 			result = t5.asDouble();
13727 		}
13728 		else
13729 		{
13730 			TCU_THROW(InternalError, "Unknown flavor");
13731 		}
13732 
13733 		out[0] = fp16type(result).bits();
13734 		min[0] = getMin(result, getULPs(in));
13735 		max[0] = getMax(result, getULPs(in));
13736 
13737 		return true;
13738 	}
13739 };
13740 
13741 struct fp16Fma : public fp16PerComponent
13742 {
fp16Fmavkt::SpirVAssembly::fp16Fma13743 	fp16Fma()
13744 	{
13745 		flavorNames.push_back("DoubleCalc");
13746 		flavorNames.push_back("EmulatingFP16");
13747 	}
13748 
getULPsvkt::SpirVAssembly::fp16Fma13749 	virtual double getULPs(vector<const deFloat16*>& in)
13750 	{
13751 		DE_UNREF(in);
13752 
13753 		return 16.0;
13754 	}
13755 
13756 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Fma13757 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13758 	{
13759 		DE_ASSERT(in.size() == 3);
13760 		DE_ASSERT(getArgCompCount(0) == getOutCompCount());
13761 		DE_ASSERT(getArgCompCount(1) == getOutCompCount());
13762 		DE_ASSERT(getArgCompCount(2) == getOutCompCount());
13763 		DE_ASSERT(getOutCompCount() > 0);
13764 
13765 		const fp16type	a		(*in[0]);
13766 		const fp16type	b		(*in[1]);
13767 		const fp16type	c		(*in[2]);
13768 		double			result	(0.0);
13769 
13770 		if (getFlavor() == 0)
13771 		{
13772 			const double	ad	(a.asDouble());
13773 			const double	bd	(b.asDouble());
13774 			const double	cd	(c.asDouble());
13775 
13776 			result	= deMadd(ad, bd, cd);
13777 		}
13778 		else if (getFlavor() == 1)
13779 		{
13780 			const double	ad	(a.asDouble());
13781 			const double	bd	(b.asDouble());
13782 			const double	cd	(c.asDouble());
13783 			const fp16type	ab	(ad * bd);
13784 			const fp16type	r	(ab.asDouble() + cd);
13785 
13786 			result	= r.asDouble();
13787 		}
13788 		else
13789 		{
13790 			TCU_THROW(InternalError, "Unknown flavor");
13791 		}
13792 
13793 		out[0] = fp16type(result).bits();
13794 		min[0] = getMin(result, getULPs(in));
13795 		max[0] = getMax(result, getULPs(in));
13796 
13797 		return true;
13798 	}
13799 };
13800 
13801 
13802 struct fp16AllComponents : public fp16PerComponent
13803 {
callOncePerComponentvkt::SpirVAssembly::fp16AllComponents13804 	bool		callOncePerComponent	()	{ return false; }
13805 };
13806 
13807 struct fp16Length : public fp16AllComponents
13808 {
fp16Lengthvkt::SpirVAssembly::fp16Length13809 	fp16Length() : fp16AllComponents()
13810 	{
13811 		flavorNames.push_back("EmulatingFP16");
13812 		flavorNames.push_back("DoubleCalc");
13813 	}
13814 
getULPsvkt::SpirVAssembly::fp16Length13815 	virtual double getULPs(vector<const deFloat16*>& in)
13816 	{
13817 		DE_UNREF(in);
13818 
13819 		return 4.0;
13820 	}
13821 
13822 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Length13823 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13824 	{
13825 		DE_ASSERT(getOutCompCount() == 1);
13826 		DE_ASSERT(in.size() == 1);
13827 
13828 		double	result	(0.0);
13829 
13830 		if (getFlavor() == 0)
13831 		{
13832 			fp16type	r	(0.0);
13833 
13834 			for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13835 			{
13836 				const fp16type	x	(in[0][componentNdx]);
13837 				const fp16type	q	(x.asDouble() * x.asDouble());
13838 
13839 				r = fp16type(r.asDouble() + q.asDouble());
13840 			}
13841 
13842 			result = deSqrt(r.asDouble());
13843 
13844 			out[0] = fp16type(result).bits();
13845 		}
13846 		else if (getFlavor() == 1)
13847 		{
13848 			double	r	(0.0);
13849 
13850 			for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13851 			{
13852 				const fp16type	x	(in[0][componentNdx]);
13853 				const double	q	(x.asDouble() * x.asDouble());
13854 
13855 				r += q;
13856 			}
13857 
13858 			result = deSqrt(r);
13859 
13860 			out[0] = fp16type(result).bits();
13861 		}
13862 		else
13863 		{
13864 			TCU_THROW(InternalError, "Unknown flavor");
13865 		}
13866 
13867 		min[0] = getMin(result, getULPs(in));
13868 		max[0] = getMax(result, getULPs(in));
13869 
13870 		return true;
13871 	}
13872 };
13873 
13874 struct fp16Distance : public fp16AllComponents
13875 {
fp16Distancevkt::SpirVAssembly::fp16Distance13876 	fp16Distance() : fp16AllComponents()
13877 	{
13878 		flavorNames.push_back("EmulatingFP16");
13879 		flavorNames.push_back("DoubleCalc");
13880 	}
13881 
getULPsvkt::SpirVAssembly::fp16Distance13882 	virtual double getULPs(vector<const deFloat16*>& in)
13883 	{
13884 		DE_UNREF(in);
13885 
13886 		return 4.0;
13887 	}
13888 
13889 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Distance13890 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13891 	{
13892 		DE_ASSERT(getOutCompCount() == 1);
13893 		DE_ASSERT(in.size() == 2);
13894 		DE_ASSERT(getArgCompCount(0) == getArgCompCount(1));
13895 
13896 		double	result	(0.0);
13897 
13898 		if (getFlavor() == 0)
13899 		{
13900 			fp16type	r	(0.0);
13901 
13902 			for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13903 			{
13904 				const fp16type	x	(in[0][componentNdx]);
13905 				const fp16type	y	(in[1][componentNdx]);
13906 				const fp16type	d	(x.asDouble() - y.asDouble());
13907 				const fp16type	q	(d.asDouble() * d.asDouble());
13908 
13909 				r = fp16type(r.asDouble() + q.asDouble());
13910 			}
13911 
13912 			result = deSqrt(r.asDouble());
13913 		}
13914 		else if (getFlavor() == 1)
13915 		{
13916 			double	r	(0.0);
13917 
13918 			for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13919 			{
13920 				const fp16type	x	(in[0][componentNdx]);
13921 				const fp16type	y	(in[1][componentNdx]);
13922 				const double	d	(x.asDouble() - y.asDouble());
13923 				const double	q	(d * d);
13924 
13925 				r += q;
13926 			}
13927 
13928 			result = deSqrt(r);
13929 		}
13930 		else
13931 		{
13932 			TCU_THROW(InternalError, "Unknown flavor");
13933 		}
13934 
13935 		out[0] = fp16type(result).bits();
13936 		min[0] = getMin(result, getULPs(in));
13937 		max[0] = getMax(result, getULPs(in));
13938 
13939 		return true;
13940 	}
13941 };
13942 
13943 struct fp16Cross : public fp16AllComponents
13944 {
fp16Crossvkt::SpirVAssembly::fp16Cross13945 	fp16Cross() : fp16AllComponents()
13946 	{
13947 		flavorNames.push_back("EmulatingFP16");
13948 		flavorNames.push_back("DoubleCalc");
13949 	}
13950 
getULPsvkt::SpirVAssembly::fp16Cross13951 	virtual double getULPs(vector<const deFloat16*>& in)
13952 	{
13953 		DE_UNREF(in);
13954 
13955 		return 4.0;
13956 	}
13957 
13958 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Cross13959 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13960 	{
13961 		DE_ASSERT(getOutCompCount() == 3);
13962 		DE_ASSERT(in.size() == 2);
13963 		DE_ASSERT(getArgCompCount(0) == 3);
13964 		DE_ASSERT(getArgCompCount(1) == 3);
13965 
13966 		if (getFlavor() == 0)
13967 		{
13968 			const fp16type	x0		(in[0][0]);
13969 			const fp16type	x1		(in[0][1]);
13970 			const fp16type	x2		(in[0][2]);
13971 			const fp16type	y0		(in[1][0]);
13972 			const fp16type	y1		(in[1][1]);
13973 			const fp16type	y2		(in[1][2]);
13974 			const fp16type	x1y2	(x1.asDouble() * y2.asDouble());
13975 			const fp16type	y1x2	(y1.asDouble() * x2.asDouble());
13976 			const fp16type	x2y0	(x2.asDouble() * y0.asDouble());
13977 			const fp16type	y2x0	(y2.asDouble() * x0.asDouble());
13978 			const fp16type	x0y1	(x0.asDouble() * y1.asDouble());
13979 			const fp16type	y0x1	(y0.asDouble() * x1.asDouble());
13980 
13981 			out[0] = fp16type(x1y2.asDouble() - y1x2.asDouble()).bits();
13982 			out[1] = fp16type(x2y0.asDouble() - y2x0.asDouble()).bits();
13983 			out[2] = fp16type(x0y1.asDouble() - y0x1.asDouble()).bits();
13984 		}
13985 		else if (getFlavor() == 1)
13986 		{
13987 			const fp16type	x0		(in[0][0]);
13988 			const fp16type	x1		(in[0][1]);
13989 			const fp16type	x2		(in[0][2]);
13990 			const fp16type	y0		(in[1][0]);
13991 			const fp16type	y1		(in[1][1]);
13992 			const fp16type	y2		(in[1][2]);
13993 			const double	x1y2	(x1.asDouble() * y2.asDouble());
13994 			const double	y1x2	(y1.asDouble() * x2.asDouble());
13995 			const double	x2y0	(x2.asDouble() * y0.asDouble());
13996 			const double	y2x0	(y2.asDouble() * x0.asDouble());
13997 			const double	x0y1	(x0.asDouble() * y1.asDouble());
13998 			const double	y0x1	(y0.asDouble() * x1.asDouble());
13999 
14000 			out[0] = fp16type(x1y2 - y1x2).bits();
14001 			out[1] = fp16type(x2y0 - y2x0).bits();
14002 			out[2] = fp16type(x0y1 - y0x1).bits();
14003 		}
14004 		else
14005 		{
14006 			TCU_THROW(InternalError, "Unknown flavor");
14007 		}
14008 
14009 		for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14010 			min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14011 		for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14012 			max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14013 
14014 		return true;
14015 	}
14016 };
14017 
14018 struct fp16Normalize : public fp16AllComponents
14019 {
fp16Normalizevkt::SpirVAssembly::fp16Normalize14020 	fp16Normalize() : fp16AllComponents()
14021 	{
14022 		flavorNames.push_back("EmulatingFP16");
14023 		flavorNames.push_back("DoubleCalc");
14024 
14025 		// flavorNames will be extended later
14026 	}
14027 
setArgCompCountvkt::SpirVAssembly::fp16Normalize14028 	virtual void	setArgCompCount			(size_t argNo, size_t compCount)
14029 	{
14030 		DE_ASSERT(argCompCount[argNo] == 0); // Once only
14031 
14032 		if (argNo == 0 && argCompCount[argNo] == 0)
14033 		{
14034 			const size_t		maxPermutationsCount	= 24u; // Equal to 4!
14035 			std::vector<int>	indices;
14036 
14037 			for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14038 				indices.push_back(static_cast<int>(componentNdx));
14039 
14040 			m_permutations.reserve(maxPermutationsCount);
14041 
14042 			permutationsFlavorStart = flavorNames.size();
14043 
14044 			do
14045 			{
14046 				tcu::UVec4	permutation;
14047 				std::string	name		= "Permutted_";
14048 
14049 				for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14050 				{
14051 					permutation[static_cast<int>(componentNdx)] = indices[componentNdx];
14052 					name += de::toString(indices[componentNdx]);
14053 				}
14054 
14055 				m_permutations.push_back(permutation);
14056 				flavorNames.push_back(name);
14057 
14058 			} while(std::next_permutation(indices.begin(), indices.end()));
14059 
14060 			permutationsFlavorEnd = flavorNames.size();
14061 		}
14062 
14063 		fp16AllComponents::setArgCompCount(argNo, compCount);
14064 	}
getULPsvkt::SpirVAssembly::fp16Normalize14065 	virtual double getULPs(vector<const deFloat16*>& in)
14066 	{
14067 		DE_UNREF(in);
14068 
14069 		return 8.0;
14070 	}
14071 
14072 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Normalize14073 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14074 	{
14075 		DE_ASSERT(in.size() == 1);
14076 		DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14077 
14078 		if (getFlavor() == 0)
14079 		{
14080 			fp16type	r(0.0);
14081 
14082 			for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14083 			{
14084 				const fp16type	x	(in[0][componentNdx]);
14085 				const fp16type	q	(x.asDouble() * x.asDouble());
14086 
14087 				r = fp16type(r.asDouble() + q.asDouble());
14088 			}
14089 
14090 			r = fp16type(deSqrt(r.asDouble()));
14091 
14092 			if (r.isZero())
14093 				return false;
14094 
14095 			for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14096 			{
14097 				const fp16type	x	(in[0][componentNdx]);
14098 
14099 				out[componentNdx] = fp16type(x.asDouble() / r.asDouble()).bits();
14100 			}
14101 		}
14102 		else if (getFlavor() == 1)
14103 		{
14104 			double	r(0.0);
14105 
14106 			for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14107 			{
14108 				const fp16type	x	(in[0][componentNdx]);
14109 				const double	q	(x.asDouble() * x.asDouble());
14110 
14111 				r += q;
14112 			}
14113 
14114 			r = deSqrt(r);
14115 
14116 			if (r == 0)
14117 				return false;
14118 
14119 			for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14120 			{
14121 				const fp16type	x	(in[0][componentNdx]);
14122 
14123 				out[componentNdx] = fp16type(x.asDouble() / r).bits();
14124 			}
14125 		}
14126 		else if (de::inBounds<size_t>(getFlavor(), permutationsFlavorStart, permutationsFlavorEnd))
14127 		{
14128 			const int			compCount		(static_cast<int>(getArgCompCount(0)));
14129 			const size_t		permutationNdx	(getFlavor() - permutationsFlavorStart);
14130 			const tcu::UVec4&	permutation		(m_permutations[permutationNdx]);
14131 			fp16type			r				(0.0);
14132 
14133 			for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14134 			{
14135 				const size_t	componentNdx	(permutation[permComponentNdx]);
14136 				const fp16type	x				(in[0][componentNdx]);
14137 				const fp16type	q				(x.asDouble() * x.asDouble());
14138 
14139 				r = fp16type(r.asDouble() + q.asDouble());
14140 			}
14141 
14142 			r = fp16type(deSqrt(r.asDouble()));
14143 
14144 			if (r.isZero())
14145 				return false;
14146 
14147 			for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14148 			{
14149 				const size_t	componentNdx	(permutation[permComponentNdx]);
14150 				const fp16type	x				(in[0][componentNdx]);
14151 
14152 				out[componentNdx] = fp16type(x.asDouble() / r.asDouble()).bits();
14153 			}
14154 		}
14155 		else
14156 		{
14157 			TCU_THROW(InternalError, "Unknown flavor");
14158 		}
14159 
14160 		for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14161 			min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14162 		for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14163 			max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14164 
14165 		return true;
14166 	}
14167 
14168 private:
14169 	std::vector<tcu::UVec4> m_permutations;
14170 	size_t					permutationsFlavorStart;
14171 	size_t					permutationsFlavorEnd;
14172 };
14173 
14174 struct fp16FaceForward : public fp16AllComponents
14175 {
getULPsvkt::SpirVAssembly::fp16FaceForward14176 	virtual double getULPs(vector<const deFloat16*>& in)
14177 	{
14178 		DE_UNREF(in);
14179 
14180 		return 4.0;
14181 	}
14182 
14183 	template<class fp16type>
calcvkt::SpirVAssembly::fp16FaceForward14184 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14185 	{
14186 		DE_ASSERT(in.size() == 3);
14187 		DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14188 		DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14189 		DE_ASSERT(getArgCompCount(2) == getOutCompCount());
14190 
14191 		fp16type	dp(0.0);
14192 
14193 		for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14194 		{
14195 			const fp16type	x	(in[1][componentNdx]);
14196 			const fp16type	y	(in[2][componentNdx]);
14197 			const double	xd	(x.asDouble());
14198 			const double	yd	(y.asDouble());
14199 			const fp16type	q	(xd * yd);
14200 
14201 			dp = fp16type(dp.asDouble() + q.asDouble());
14202 		}
14203 
14204 		if (dp.isNaN() || dp.isZero())
14205 			return false;
14206 
14207 		for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14208 		{
14209 			const fp16type	n	(in[0][componentNdx]);
14210 
14211 			out[componentNdx] = (dp.signBit() == 1) ? n.bits() : fp16type(-n.asDouble()).bits();
14212 		}
14213 
14214 		for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14215 			min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14216 		for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14217 			max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14218 
14219 		return true;
14220 	}
14221 };
14222 
14223 struct fp16Reflect : public fp16AllComponents
14224 {
fp16Reflectvkt::SpirVAssembly::fp16Reflect14225 	fp16Reflect() : fp16AllComponents()
14226 	{
14227 		flavorNames.push_back("EmulatingFP16");
14228 		flavorNames.push_back("EmulatingFP16+KeepZeroSign");
14229 		flavorNames.push_back("FloatCalc");
14230 		flavorNames.push_back("FloatCalc+KeepZeroSign");
14231 		flavorNames.push_back("EmulatingFP16+2Nfirst");
14232 		flavorNames.push_back("EmulatingFP16+2Ifirst");
14233 	}
14234 
getULPsvkt::SpirVAssembly::fp16Reflect14235 	virtual double getULPs(vector<const deFloat16*>& in)
14236 	{
14237 		DE_UNREF(in);
14238 
14239 		return 256.0; // This is not a precision test. Value is not from spec
14240 	}
14241 
14242 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Reflect14243 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14244 	{
14245 		DE_ASSERT(in.size() == 2);
14246 		DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14247 		DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14248 
14249 		if (getFlavor() < 4)
14250 		{
14251 			const bool	keepZeroSign	((flavor & 1) != 0 ? true : false);
14252 			const bool	floatCalc		((flavor & 2) != 0 ? true : false);
14253 
14254 			if (floatCalc)
14255 			{
14256 				float	dp(0.0f);
14257 
14258 				for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14259 				{
14260 					const fp16type	i	(in[0][componentNdx]);
14261 					const fp16type	n	(in[1][componentNdx]);
14262 					const float		id	(i.asFloat());
14263 					const float		nd	(n.asFloat());
14264 					const float		qd	(id * nd);
14265 
14266 					if (keepZeroSign)
14267 						dp = (componentNdx == 0) ? qd : dp + qd;
14268 					else
14269 						dp = dp + qd;
14270 				}
14271 
14272 				for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14273 				{
14274 					const fp16type	i		(in[0][componentNdx]);
14275 					const fp16type	n		(in[1][componentNdx]);
14276 					const float		dpnd	(dp * n.asFloat());
14277 					const float		dpn2d	(2.0f * dpnd);
14278 					const float		idpn2d	(i.asFloat() - dpn2d);
14279 					const fp16type	result	(idpn2d);
14280 
14281 					out[componentNdx] = result.bits();
14282 				}
14283 			}
14284 			else
14285 			{
14286 				fp16type	dp(0.0);
14287 
14288 				for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14289 				{
14290 					const fp16type	i	(in[0][componentNdx]);
14291 					const fp16type	n	(in[1][componentNdx]);
14292 					const double	id	(i.asDouble());
14293 					const double	nd	(n.asDouble());
14294 					const fp16type	q	(id * nd);
14295 
14296 					if (keepZeroSign)
14297 						dp = (componentNdx == 0) ? q : fp16type(dp.asDouble() + q.asDouble());
14298 					else
14299 						dp = fp16type(dp.asDouble() + q.asDouble());
14300 				}
14301 
14302 				if (dp.isNaN())
14303 					return false;
14304 
14305 				for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14306 				{
14307 					const fp16type	i		(in[0][componentNdx]);
14308 					const fp16type	n		(in[1][componentNdx]);
14309 					const fp16type	dpn		(dp.asDouble() * n.asDouble());
14310 					const fp16type	dpn2	(2 * dpn.asDouble());
14311 					const fp16type	idpn2	(i.asDouble() - dpn2.asDouble());
14312 
14313 					out[componentNdx] = idpn2.bits();
14314 				}
14315 			}
14316 		}
14317 		else if (getFlavor() == 4)
14318 		{
14319 			fp16type	dp(0.0);
14320 
14321 			for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14322 			{
14323 				const fp16type	i	(in[0][componentNdx]);
14324 				const fp16type	n	(in[1][componentNdx]);
14325 				const double	id	(i.asDouble());
14326 				const double	nd	(n.asDouble());
14327 				const fp16type	q	(id * nd);
14328 
14329 				dp = fp16type(dp.asDouble() + q.asDouble());
14330 			}
14331 
14332 			if (dp.isNaN())
14333 				return false;
14334 
14335 			for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14336 			{
14337 				const fp16type	i		(in[0][componentNdx]);
14338 				const fp16type	n		(in[1][componentNdx]);
14339 				const fp16type	n2		(2 * n.asDouble());
14340 				const fp16type	dpn2	(dp.asDouble() * n2.asDouble());
14341 				const fp16type	idpn2	(i.asDouble() - dpn2.asDouble());
14342 
14343 				out[componentNdx] = idpn2.bits();
14344 			}
14345 		}
14346 		else if (getFlavor() == 5)
14347 		{
14348 			fp16type	dp2(0.0);
14349 
14350 			for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14351 			{
14352 				const fp16type	i	(in[0][componentNdx]);
14353 				const fp16type	n	(in[1][componentNdx]);
14354 				const fp16type	i2	(2.0 * i.asDouble());
14355 				const double	i2d	(i2.asDouble());
14356 				const double	nd	(n.asDouble());
14357 				const fp16type	q	(i2d * nd);
14358 
14359 				dp2 = fp16type(dp2.asDouble() + q.asDouble());
14360 			}
14361 
14362 			if (dp2.isNaN())
14363 				return false;
14364 
14365 			for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14366 			{
14367 				const fp16type	i		(in[0][componentNdx]);
14368 				const fp16type	n		(in[1][componentNdx]);
14369 				const fp16type	dpn2	(dp2.asDouble() * n.asDouble());
14370 				const fp16type	idpn2	(i.asDouble() - dpn2.asDouble());
14371 
14372 				out[componentNdx] = idpn2.bits();
14373 			}
14374 		}
14375 		else
14376 		{
14377 			TCU_THROW(InternalError, "Unknown flavor");
14378 		}
14379 
14380 		for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14381 			min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14382 		for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14383 			max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14384 
14385 		return true;
14386 	}
14387 };
14388 
14389 struct fp16Refract : public fp16AllComponents
14390 {
fp16Refractvkt::SpirVAssembly::fp16Refract14391 	fp16Refract() : fp16AllComponents()
14392 	{
14393 		flavorNames.push_back("EmulatingFP16");
14394 		flavorNames.push_back("EmulatingFP16+KeepZeroSign");
14395 		flavorNames.push_back("FloatCalc");
14396 		flavorNames.push_back("FloatCalc+KeepZeroSign");
14397 	}
14398 
getULPsvkt::SpirVAssembly::fp16Refract14399 	virtual double getULPs(vector<const deFloat16*>& in)
14400 	{
14401 		DE_UNREF(in);
14402 
14403 		return 8192.0; // This is not a precision test. Value is not from spec
14404 	}
14405 
14406 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Refract14407 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14408 	{
14409 		DE_ASSERT(in.size() == 3);
14410 		DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14411 		DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14412 		DE_ASSERT(getArgCompCount(2) == 1);
14413 
14414 		const bool		keepZeroSign	((flavor & 1) != 0 ? true : false);
14415 		const bool		doubleCalc		((flavor & 2) != 0 ? true : false);
14416 		const fp16type	eta				(*in[2]);
14417 
14418 		if (doubleCalc)
14419 		{
14420 			double	dp	(0.0);
14421 
14422 			for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14423 			{
14424 				const fp16type	i	(in[0][componentNdx]);
14425 				const fp16type	n	(in[1][componentNdx]);
14426 				const double	id	(i.asDouble());
14427 				const double	nd	(n.asDouble());
14428 				const double	qd	(id * nd);
14429 
14430 				if (keepZeroSign)
14431 					dp = (componentNdx == 0) ? qd : dp + qd;
14432 				else
14433 					dp = dp + qd;
14434 			}
14435 
14436 			const double	eta2	(eta.asDouble() * eta.asDouble());
14437 			const double	dp2		(dp * dp);
14438 			const double	dp1		(1.0 - dp2);
14439 			const double	dpe		(eta2 * dp1);
14440 			const double	k		(1.0 - dpe);
14441 
14442 			if (k < 0.0)
14443 			{
14444 				const fp16type	zero	(0.0);
14445 
14446 				for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14447 					out[componentNdx] = zero.bits();
14448 			}
14449 			else
14450 			{
14451 				const double	sk	(deSqrt(k));
14452 
14453 				for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14454 				{
14455 					const fp16type	i		(in[0][componentNdx]);
14456 					const fp16type	n		(in[1][componentNdx]);
14457 					const double	etai	(i.asDouble() * eta.asDouble());
14458 					const double	etadp	(eta.asDouble() * dp);
14459 					const double	etadpk	(etadp + sk);
14460 					const double	etadpkn	(etadpk * n.asDouble());
14461 					const double	full	(etai - etadpkn);
14462 					const fp16type	result	(full);
14463 
14464 					if (result.isInf())
14465 						return false;
14466 
14467 					out[componentNdx] = result.bits();
14468 				}
14469 			}
14470 		}
14471 		else
14472 		{
14473 			fp16type	dp	(0.0);
14474 
14475 			for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14476 			{
14477 				const fp16type	i	(in[0][componentNdx]);
14478 				const fp16type	n	(in[1][componentNdx]);
14479 				const double	id	(i.asDouble());
14480 				const double	nd	(n.asDouble());
14481 				const fp16type	q	(id * nd);
14482 
14483 				if (keepZeroSign)
14484 					dp = (componentNdx == 0) ? q : fp16type(dp.asDouble() + q.asDouble());
14485 				else
14486 					dp = fp16type(dp.asDouble() + q.asDouble());
14487 			}
14488 
14489 			if (dp.isNaN())
14490 				return false;
14491 
14492 			const fp16type	eta2(eta.asDouble() * eta.asDouble());
14493 			const fp16type	dp2	(dp.asDouble() * dp.asDouble());
14494 			const fp16type	dp1	(1.0 - dp2.asDouble());
14495 			const fp16type	dpe	(eta2.asDouble() * dp1.asDouble());
14496 			const fp16type	k	(1.0 - dpe.asDouble());
14497 
14498 			if (k.asDouble() < 0.0)
14499 			{
14500 				const fp16type	zero	(0.0);
14501 
14502 				for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14503 					out[componentNdx] = zero.bits();
14504 			}
14505 			else
14506 			{
14507 				const fp16type	sk	(deSqrt(k.asDouble()));
14508 
14509 				for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14510 				{
14511 					const fp16type	i		(in[0][componentNdx]);
14512 					const fp16type	n		(in[1][componentNdx]);
14513 					const fp16type	etai	(i.asDouble() * eta.asDouble());
14514 					const fp16type	etadp	(eta.asDouble() * dp.asDouble());
14515 					const fp16type	etadpk	(etadp.asDouble() + sk.asDouble());
14516 					const fp16type	etadpkn	(etadpk.asDouble() * n.asDouble());
14517 					const fp16type	full	(etai.asDouble() - etadpkn.asDouble());
14518 
14519 					if (full.isNaN() || full.isInf())
14520 						return false;
14521 
14522 					out[componentNdx] = full.bits();
14523 				}
14524 			}
14525 		}
14526 
14527 		for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14528 			min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14529 		for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14530 			max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14531 
14532 		return true;
14533 	}
14534 };
14535 
14536 struct fp16Dot : public fp16AllComponents
14537 {
fp16Dotvkt::SpirVAssembly::fp16Dot14538 	fp16Dot() : fp16AllComponents()
14539 	{
14540 		flavorNames.push_back("EmulatingFP16");
14541 		flavorNames.push_back("FloatCalc");
14542 		flavorNames.push_back("DoubleCalc");
14543 
14544 		// flavorNames will be extended later
14545 	}
14546 
setArgCompCountvkt::SpirVAssembly::fp16Dot14547 	virtual void	setArgCompCount			(size_t argNo, size_t compCount)
14548 	{
14549 		DE_ASSERT(argCompCount[argNo] == 0); // Once only
14550 
14551 		if (argNo == 0 && argCompCount[argNo] == 0)
14552 		{
14553 			const size_t		maxPermutationsCount	= 24u; // Equal to 4!
14554 			std::vector<int>	indices;
14555 
14556 			for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14557 				indices.push_back(static_cast<int>(componentNdx));
14558 
14559 			m_permutations.reserve(maxPermutationsCount);
14560 
14561 			permutationsFlavorStart = flavorNames.size();
14562 
14563 			do
14564 			{
14565 				tcu::UVec4	permutation;
14566 				std::string	name		= "Permutted_";
14567 
14568 				for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14569 				{
14570 					permutation[static_cast<int>(componentNdx)] = indices[componentNdx];
14571 					name += de::toString(indices[componentNdx]);
14572 				}
14573 
14574 				m_permutations.push_back(permutation);
14575 				flavorNames.push_back(name);
14576 
14577 			} while(std::next_permutation(indices.begin(), indices.end()));
14578 
14579 			permutationsFlavorEnd = flavorNames.size();
14580 		}
14581 
14582 		fp16AllComponents::setArgCompCount(argNo, compCount);
14583 	}
14584 
getULPsvkt::SpirVAssembly::fp16Dot14585 	virtual double	getULPs(vector<const deFloat16*>& in)
14586 	{
14587 		DE_UNREF(in);
14588 
14589 		return 16.0; // This is not a precision test. Value is not from spec
14590 	}
14591 
14592 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Dot14593 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14594 	{
14595 		DE_ASSERT(in.size() == 2);
14596 		DE_ASSERT(getArgCompCount(0) == getArgCompCount(1));
14597 		DE_ASSERT(getOutCompCount() == 1);
14598 
14599 		double	result	(0.0);
14600 		double	eps		(0.0);
14601 
14602 		if (getFlavor() == 0)
14603 		{
14604 			fp16type	dp	(0.0);
14605 
14606 			for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14607 			{
14608 				const fp16type	x	(in[0][componentNdx]);
14609 				const fp16type	y	(in[1][componentNdx]);
14610 				const fp16type	q	(x.asDouble() * y.asDouble());
14611 
14612 				dp = fp16type(dp.asDouble() + q.asDouble());
14613 				eps += floatFormat16.ulp(q.asDouble(), 2.0);
14614 			}
14615 
14616 			result = dp.asDouble();
14617 		}
14618 		else if (getFlavor() == 1)
14619 		{
14620 			float	dp	(0.0);
14621 
14622 			for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14623 			{
14624 				const fp16type	x	(in[0][componentNdx]);
14625 				const fp16type	y	(in[1][componentNdx]);
14626 				const float		q	(x.asFloat() * y.asFloat());
14627 
14628 				dp += q;
14629 				eps += floatFormat16.ulp(static_cast<double>(q), 2.0);
14630 			}
14631 
14632 			result = dp;
14633 		}
14634 		else if (getFlavor() == 2)
14635 		{
14636 			double	dp	(0.0);
14637 
14638 			for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14639 			{
14640 				const fp16type	x	(in[0][componentNdx]);
14641 				const fp16type	y	(in[1][componentNdx]);
14642 				const double	q	(x.asDouble() * y.asDouble());
14643 
14644 				dp += q;
14645 				eps += floatFormat16.ulp(q, 2.0);
14646 			}
14647 
14648 			result = dp;
14649 		}
14650 		else if (de::inBounds<size_t>(getFlavor(), permutationsFlavorStart, permutationsFlavorEnd))
14651 		{
14652 			const int			compCount		(static_cast<int>(getArgCompCount(1)));
14653 			const size_t		permutationNdx	(getFlavor() - permutationsFlavorStart);
14654 			const tcu::UVec4&	permutation		(m_permutations[permutationNdx]);
14655 			fp16type			dp				(0.0);
14656 
14657 			for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14658 			{
14659 				const size_t		componentNdx	(permutation[permComponentNdx]);
14660 				const fp16type		x				(in[0][componentNdx]);
14661 				const fp16type		y				(in[1][componentNdx]);
14662 				const fp16type		q				(x.asDouble() * y.asDouble());
14663 
14664 				dp = fp16type(dp.asDouble() + q.asDouble());
14665 				eps += floatFormat16.ulp(q.asDouble(), 2.0);
14666 			}
14667 
14668 			result = dp.asDouble();
14669 		}
14670 		else
14671 		{
14672 			TCU_THROW(InternalError, "Unknown flavor");
14673 		}
14674 
14675 		out[0] = fp16type(result).bits();
14676 		min[0] = result - eps;
14677 		max[0] = result + eps;
14678 
14679 		return true;
14680 	}
14681 
14682 private:
14683 	std::vector<tcu::UVec4> m_permutations;
14684 	size_t					permutationsFlavorStart;
14685 	size_t					permutationsFlavorEnd;
14686 };
14687 
14688 struct fp16VectorTimesScalar : public fp16AllComponents
14689 {
getULPsvkt::SpirVAssembly::fp16VectorTimesScalar14690 	virtual double getULPs(vector<const deFloat16*>& in)
14691 	{
14692 		DE_UNREF(in);
14693 
14694 		return 2.0;
14695 	}
14696 
14697 	template<class fp16type>
calcvkt::SpirVAssembly::fp16VectorTimesScalar14698 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14699 	{
14700 		DE_ASSERT(in.size() == 2);
14701 		DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14702 		DE_ASSERT(getArgCompCount(1) == 1);
14703 
14704 		fp16type	s	(*in[1]);
14705 
14706 		for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14707 		{
14708 			const fp16type	x	   (in[0][componentNdx]);
14709 			const double    result (s.asDouble() * x.asDouble());
14710 			const fp16type	m	   (result);
14711 
14712 			out[componentNdx] = m.bits();
14713 			min[componentNdx] = getMin(result, getULPs(in));
14714 			max[componentNdx] = getMax(result, getULPs(in));
14715 		}
14716 
14717 		return true;
14718 	}
14719 };
14720 
14721 struct fp16MatrixBase : public fp16AllComponents
14722 {
getComponentValidityvkt::SpirVAssembly::fp16MatrixBase14723 	deUint32		getComponentValidity			()
14724 	{
14725 		return static_cast<deUint32>(-1);
14726 	}
14727 
getNdxvkt::SpirVAssembly::fp16MatrixBase14728 	inline size_t	getNdx							(const size_t rowCount, const size_t col, const size_t row)
14729 	{
14730 		const size_t minComponentCount	= 0;
14731 		const size_t maxComponentCount	= 3;
14732 		const size_t alignedRowsCount	= (rowCount == 3) ? 4 : rowCount;
14733 
14734 		DE_ASSERT(de::inRange(rowCount, minComponentCount + 1, maxComponentCount + 1));
14735 		DE_ASSERT(de::inRange(col, minComponentCount, maxComponentCount));
14736 		DE_ASSERT(de::inBounds(row, minComponentCount, rowCount));
14737 		DE_UNREF(minComponentCount);
14738 		DE_UNREF(maxComponentCount);
14739 
14740 		return col * alignedRowsCount + row;
14741 	}
14742 
getComponentMatrixValidityMaskvkt::SpirVAssembly::fp16MatrixBase14743 	deUint32		getComponentMatrixValidityMask	(size_t cols, size_t rows)
14744 	{
14745 		deUint32	result	= 0u;
14746 
14747 		for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14748 			for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14749 			{
14750 				const size_t bitNdx = getNdx(rows, colNdx, rowNdx);
14751 
14752 				DE_ASSERT(bitNdx < sizeof(result) * 8);
14753 
14754 				result |= (1<<bitNdx);
14755 			}
14756 
14757 		return result;
14758 	}
14759 };
14760 
14761 template<size_t cols, size_t rows>
14762 struct fp16Transpose : public fp16MatrixBase
14763 {
getULPsvkt::SpirVAssembly::fp16Transpose14764 	virtual double getULPs(vector<const deFloat16*>& in)
14765 	{
14766 		DE_UNREF(in);
14767 
14768 		return 1.0;
14769 	}
14770 
getComponentValidityvkt::SpirVAssembly::fp16Transpose14771 	deUint32	getComponentValidity	()
14772 	{
14773 		return getComponentMatrixValidityMask(rows, cols);
14774 	}
14775 
14776 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Transpose14777 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14778 	{
14779 		DE_ASSERT(in.size() == 1);
14780 
14781 		const size_t		alignedCols	= (cols == 3) ? 4 : cols;
14782 		const size_t		alignedRows	= (rows == 3) ? 4 : rows;
14783 		vector<deFloat16>	output		(alignedCols * alignedRows, 0);
14784 
14785 		DE_ASSERT(output.size() == alignedCols * alignedRows);
14786 
14787 		for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14788 			for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14789 				output[rowNdx * alignedCols + colNdx] = in[0][colNdx * alignedRows + rowNdx];
14790 
14791 		deMemcpy(out, &output[0], sizeof(deFloat16) * output.size());
14792 		deMemcpy(min, &output[0], sizeof(deFloat16) * output.size());
14793 		deMemcpy(max, &output[0], sizeof(deFloat16) * output.size());
14794 
14795 		return true;
14796 	}
14797 };
14798 
14799 template<size_t cols, size_t rows>
14800 struct fp16MatrixTimesScalar : public fp16MatrixBase
14801 {
getULPsvkt::SpirVAssembly::fp16MatrixTimesScalar14802 	virtual double getULPs(vector<const deFloat16*>& in)
14803 	{
14804 		DE_UNREF(in);
14805 
14806 		return 4.0;
14807 	}
14808 
getComponentValidityvkt::SpirVAssembly::fp16MatrixTimesScalar14809 	deUint32	getComponentValidity	()
14810 	{
14811 		return getComponentMatrixValidityMask(cols, rows);
14812 	}
14813 
14814 	template<class fp16type>
calcvkt::SpirVAssembly::fp16MatrixTimesScalar14815 	bool calc(vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14816 	{
14817 		DE_ASSERT(in.size() == 2);
14818 		DE_ASSERT(getArgCompCount(1) == 1);
14819 
14820 		const fp16type	y			(in[1][0]);
14821 		const float		scalar		(y.asFloat());
14822 		const size_t	alignedCols	= (cols == 3) ? 4 : cols;
14823 		const size_t	alignedRows	= (rows == 3) ? 4 : rows;
14824 
14825 		DE_ASSERT(getArgCompCount(0) == alignedCols * alignedRows);
14826 		DE_ASSERT(getOutCompCount() == alignedCols * alignedRows);
14827 		DE_UNREF(alignedCols);
14828 
14829 		for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14830 			for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14831 			{
14832 				const size_t	ndx	(colNdx * alignedRows + rowNdx);
14833 				const fp16type	x	(in[0][ndx]);
14834 				const double	result	(scalar * x.asFloat());
14835 
14836 				out[ndx] = fp16type(result).bits();
14837 				min[ndx] = getMin(result, getULPs(in));
14838 				max[ndx] = getMax(result, getULPs(in));
14839 			}
14840 
14841 		return true;
14842 	}
14843 };
14844 
14845 template<size_t cols, size_t rows>
14846 struct fp16VectorTimesMatrix : public fp16MatrixBase
14847 {
fp16VectorTimesMatrixvkt::SpirVAssembly::fp16VectorTimesMatrix14848 	fp16VectorTimesMatrix() : fp16MatrixBase()
14849 	{
14850 		flavorNames.push_back("EmulatingFP16");
14851 		flavorNames.push_back("FloatCalc");
14852 	}
14853 
getULPsvkt::SpirVAssembly::fp16VectorTimesMatrix14854 	virtual double getULPs (vector<const deFloat16*>& in)
14855 	{
14856 		DE_UNREF(in);
14857 
14858 		return (8.0 * cols);
14859 	}
14860 
getComponentValidityvkt::SpirVAssembly::fp16VectorTimesMatrix14861 	deUint32 getComponentValidity ()
14862 	{
14863 		return getComponentMatrixValidityMask(cols, 1);
14864 	}
14865 
14866 	template<class fp16type>
calcvkt::SpirVAssembly::fp16VectorTimesMatrix14867 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14868 	{
14869 		DE_ASSERT(in.size() == 2);
14870 
14871 		const size_t	alignedCols	= (cols == 3) ? 4 : cols;
14872 		const size_t	alignedRows	= (rows == 3) ? 4 : rows;
14873 
14874 		DE_ASSERT(getOutCompCount() == cols);
14875 		DE_ASSERT(getArgCompCount(0) == rows);
14876 		DE_ASSERT(getArgCompCount(1) == alignedCols * alignedRows);
14877 		DE_UNREF(alignedCols);
14878 
14879 		if (getFlavor() == 0)
14880 		{
14881 			for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14882 			{
14883 				fp16type	s	(fp16type::zero(1));
14884 
14885 				for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14886 				{
14887 					const fp16type	v	(in[0][rowNdx]);
14888 					const float		vf	(v.asFloat());
14889 					const size_t	ndx	(colNdx * alignedRows + rowNdx);
14890 					const fp16type	x	(in[1][ndx]);
14891 					const float		xf	(x.asFloat());
14892 					const fp16type	m	(vf * xf);
14893 
14894 					s = fp16type(s.asFloat() + m.asFloat());
14895 				}
14896 
14897 				out[colNdx] = s.bits();
14898 				min[colNdx] = getMin(s.asDouble(), getULPs(in));
14899 				max[colNdx] = getMax(s.asDouble(), getULPs(in));
14900 			}
14901 		}
14902 		else if (getFlavor() == 1)
14903 		{
14904 			for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14905 			{
14906 				float	s	(0.0f);
14907 
14908 				for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14909 				{
14910 					const fp16type	v	(in[0][rowNdx]);
14911 					const float		vf	(v.asFloat());
14912 					const size_t	ndx	(colNdx * alignedRows + rowNdx);
14913 					const fp16type	x	(in[1][ndx]);
14914 					const float		xf	(x.asFloat());
14915 					const float		m	(vf * xf);
14916 
14917 					s += m;
14918 				}
14919 
14920 				out[colNdx] = fp16type(s).bits();
14921 				min[colNdx] = getMin(static_cast<double>(s), getULPs(in));
14922 				max[colNdx] = getMax(static_cast<double>(s), getULPs(in));
14923 			}
14924 		}
14925 		else
14926 		{
14927 			TCU_THROW(InternalError, "Unknown flavor");
14928 		}
14929 
14930 		return true;
14931 	}
14932 };
14933 
14934 template<size_t cols, size_t rows>
14935 struct fp16MatrixTimesVector : public fp16MatrixBase
14936 {
fp16MatrixTimesVectorvkt::SpirVAssembly::fp16MatrixTimesVector14937 	fp16MatrixTimesVector() : fp16MatrixBase()
14938 	{
14939 		flavorNames.push_back("EmulatingFP16");
14940 		flavorNames.push_back("FloatCalc");
14941 	}
14942 
getULPsvkt::SpirVAssembly::fp16MatrixTimesVector14943 	virtual double getULPs (vector<const deFloat16*>& in)
14944 	{
14945 		DE_UNREF(in);
14946 
14947 		return (8.0 * rows);
14948 	}
14949 
getComponentValidityvkt::SpirVAssembly::fp16MatrixTimesVector14950 	deUint32 getComponentValidity ()
14951 	{
14952 		return getComponentMatrixValidityMask(rows, 1);
14953 	}
14954 
14955 	template<class fp16type>
calcvkt::SpirVAssembly::fp16MatrixTimesVector14956 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14957 	{
14958 		DE_ASSERT(in.size() == 2);
14959 
14960 		const size_t	alignedCols	= (cols == 3) ? 4 : cols;
14961 		const size_t	alignedRows	= (rows == 3) ? 4 : rows;
14962 
14963 		DE_ASSERT(getOutCompCount() == rows);
14964 		DE_ASSERT(getArgCompCount(0) == alignedCols * alignedRows);
14965 		DE_ASSERT(getArgCompCount(1) == cols);
14966 		DE_UNREF(alignedCols);
14967 
14968 		if (getFlavor() == 0)
14969 		{
14970 			for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14971 			{
14972 				fp16type	s	(fp16type::zero(1));
14973 
14974 				for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14975 				{
14976 					const size_t	ndx	(colNdx * alignedRows + rowNdx);
14977 					const fp16type	x	(in[0][ndx]);
14978 					const float		xf	(x.asFloat());
14979 					const fp16type	v	(in[1][colNdx]);
14980 					const float		vf	(v.asFloat());
14981 					const fp16type	m	(vf * xf);
14982 
14983 					s = fp16type(s.asFloat() + m.asFloat());
14984 				}
14985 
14986 				out[rowNdx] = s.bits();
14987 				min[rowNdx] = getMin(s.asDouble(), getULPs(in));
14988 				max[rowNdx] = getMax(s.asDouble(), getULPs(in));
14989 			}
14990 		}
14991 		else if (getFlavor() == 1)
14992 		{
14993 			for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14994 			{
14995 				float	s	(0.0f);
14996 
14997 				for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14998 				{
14999 					const size_t	ndx	(colNdx * alignedRows + rowNdx);
15000 					const fp16type	x	(in[0][ndx]);
15001 					const float		xf	(x.asFloat());
15002 					const fp16type	v	(in[1][colNdx]);
15003 					const float		vf	(v.asFloat());
15004 					const float		m	(vf * xf);
15005 
15006 					s += m;
15007 				}
15008 
15009 				out[rowNdx] = fp16type(s).bits();
15010 				min[rowNdx] = getMin(static_cast<double>(s), getULPs(in));
15011 				max[rowNdx] = getMax(static_cast<double>(s), getULPs(in));
15012 			}
15013 		}
15014 		else
15015 		{
15016 			TCU_THROW(InternalError, "Unknown flavor");
15017 		}
15018 
15019 		return true;
15020 	}
15021 };
15022 
15023 template<size_t colsL, size_t rowsL, size_t colsR, size_t rowsR>
15024 struct fp16MatrixTimesMatrix : public fp16MatrixBase
15025 {
fp16MatrixTimesMatrixvkt::SpirVAssembly::fp16MatrixTimesMatrix15026 	fp16MatrixTimesMatrix() : fp16MatrixBase()
15027 	{
15028 		flavorNames.push_back("EmulatingFP16");
15029 		flavorNames.push_back("FloatCalc");
15030 	}
15031 
getULPsvkt::SpirVAssembly::fp16MatrixTimesMatrix15032 	virtual double getULPs (vector<const deFloat16*>& in)
15033 	{
15034 		DE_UNREF(in);
15035 
15036 		return 32.0;
15037 	}
15038 
getComponentValidityvkt::SpirVAssembly::fp16MatrixTimesMatrix15039 	deUint32 getComponentValidity ()
15040 	{
15041 		return getComponentMatrixValidityMask(colsR, rowsL);
15042 	}
15043 
15044 	template<class fp16type>
calcvkt::SpirVAssembly::fp16MatrixTimesMatrix15045 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15046 	{
15047 		DE_STATIC_ASSERT(colsL == rowsR);
15048 
15049 		DE_ASSERT(in.size() == 2);
15050 
15051 		const size_t	alignedColsL	= (colsL == 3) ? 4 : colsL;
15052 		const size_t	alignedRowsL	= (rowsL == 3) ? 4 : rowsL;
15053 		const size_t	alignedColsR	= (colsR == 3) ? 4 : colsR;
15054 		const size_t	alignedRowsR	= (rowsR == 3) ? 4 : rowsR;
15055 
15056 		DE_ASSERT(getOutCompCount() == alignedColsR * alignedRowsL);
15057 		DE_ASSERT(getArgCompCount(0) == alignedColsL * alignedRowsL);
15058 		DE_ASSERT(getArgCompCount(1) == alignedColsR * alignedRowsR);
15059 		DE_UNREF(alignedColsL);
15060 		DE_UNREF(alignedColsR);
15061 
15062 		if (getFlavor() == 0)
15063 		{
15064 			for (size_t rowNdx = 0; rowNdx < rowsL; ++rowNdx)
15065 			{
15066 				for (size_t colNdx = 0; colNdx < colsR; ++colNdx)
15067 				{
15068 					const size_t	ndx	(colNdx * alignedRowsL + rowNdx);
15069 					fp16type		s	(fp16type::zero(1));
15070 
15071 					for (size_t commonNdx = 0; commonNdx < colsL; ++commonNdx)
15072 					{
15073 						const size_t	ndxl	(commonNdx * alignedRowsL + rowNdx);
15074 						const fp16type	l		(in[0][ndxl]);
15075 						const float		lf		(l.asFloat());
15076 						const size_t	ndxr	(colNdx * alignedRowsR + commonNdx);
15077 						const fp16type	r		(in[1][ndxr]);
15078 						const float		rf		(r.asFloat());
15079 						const fp16type	m		(lf * rf);
15080 
15081 						s = fp16type(s.asFloat() + m.asFloat());
15082 					}
15083 
15084 					out[ndx] = s.bits();
15085 					min[ndx] = getMin(s.asDouble(), getULPs(in));
15086 					max[ndx] = getMax(s.asDouble(), getULPs(in));
15087 				}
15088 			}
15089 		}
15090 		else if (getFlavor() == 1)
15091 		{
15092 			for (size_t rowNdx = 0; rowNdx < rowsL; ++rowNdx)
15093 			{
15094 				for (size_t colNdx = 0; colNdx < colsR; ++colNdx)
15095 				{
15096 					const size_t	ndx	(colNdx * alignedRowsL + rowNdx);
15097 					float			s	(0.0f);
15098 
15099 					for (size_t commonNdx = 0; commonNdx < colsL; ++commonNdx)
15100 					{
15101 						const size_t	ndxl	(commonNdx * alignedRowsL + rowNdx);
15102 						const fp16type	l		(in[0][ndxl]);
15103 						const float		lf		(l.asFloat());
15104 						const size_t	ndxr	(colNdx * alignedRowsR + commonNdx);
15105 						const fp16type	r		(in[1][ndxr]);
15106 						const float		rf		(r.asFloat());
15107 						const float		m		(lf * rf);
15108 
15109 						s += m;
15110 					}
15111 
15112 					out[ndx] = fp16type(s).bits();
15113 					min[ndx] = getMin(static_cast<double>(s), getULPs(in));
15114 					max[ndx] = getMax(static_cast<double>(s), getULPs(in));
15115 				}
15116 			}
15117 		}
15118 		else
15119 		{
15120 			TCU_THROW(InternalError, "Unknown flavor");
15121 		}
15122 
15123 		return true;
15124 	}
15125 };
15126 
15127 template<size_t cols, size_t rows>
15128 struct fp16OuterProduct : public fp16MatrixBase
15129 {
getULPsvkt::SpirVAssembly::fp16OuterProduct15130 	virtual double getULPs (vector<const deFloat16*>& in)
15131 	{
15132 		DE_UNREF(in);
15133 
15134 		return 2.0;
15135 	}
15136 
getComponentValidityvkt::SpirVAssembly::fp16OuterProduct15137 	deUint32 getComponentValidity ()
15138 	{
15139 		return getComponentMatrixValidityMask(cols, rows);
15140 	}
15141 
15142 	template<class fp16type>
calcvkt::SpirVAssembly::fp16OuterProduct15143 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15144 	{
15145 		DE_ASSERT(in.size() == 2);
15146 
15147 		const size_t	alignedCols	= (cols == 3) ? 4 : cols;
15148 		const size_t	alignedRows	= (rows == 3) ? 4 : rows;
15149 
15150 		DE_ASSERT(getArgCompCount(0) == rows);
15151 		DE_ASSERT(getArgCompCount(1) == cols);
15152 		DE_ASSERT(getOutCompCount() == alignedCols * alignedRows);
15153 		DE_UNREF(alignedCols);
15154 
15155 		for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15156 		{
15157 			for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15158 			{
15159 				const size_t	ndx	(colNdx * alignedRows + rowNdx);
15160 				const fp16type	x	(in[0][rowNdx]);
15161 				const float		xf	(x.asFloat());
15162 				const fp16type	y	(in[1][colNdx]);
15163 				const float		yf	(y.asFloat());
15164 				const fp16type	m	(xf * yf);
15165 
15166 				out[ndx] = m.bits();
15167 				min[ndx] = getMin(m.asDouble(), getULPs(in));
15168 				max[ndx] = getMax(m.asDouble(), getULPs(in));
15169 			}
15170 		}
15171 
15172 		return true;
15173 	}
15174 };
15175 
15176 template<size_t size>
15177 struct fp16Determinant;
15178 
15179 template<>
15180 struct fp16Determinant<2> : public fp16MatrixBase
15181 {
getULPsvkt::SpirVAssembly::fp16Determinant15182 	virtual double getULPs (vector<const deFloat16*>& in)
15183 	{
15184 		DE_UNREF(in);
15185 
15186 		return 128.0; // This is not a precision test. Value is not from spec
15187 	}
15188 
getComponentValidityvkt::SpirVAssembly::fp16Determinant15189 	deUint32 getComponentValidity ()
15190 	{
15191 		return 1;
15192 	}
15193 
15194 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Determinant15195 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15196 	{
15197 		const size_t	cols		= 2;
15198 		const size_t	rows		= 2;
15199 		const size_t	alignedCols	= (cols == 3) ? 4 : cols;
15200 		const size_t	alignedRows	= (rows == 3) ? 4 : rows;
15201 
15202 		DE_ASSERT(in.size() == 1);
15203 		DE_ASSERT(getOutCompCount() == 1);
15204 		DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15205 		DE_UNREF(alignedCols);
15206 		DE_UNREF(alignedRows);
15207 
15208 		// [ a b ]
15209 		// [ c d ]
15210 		const float		a		(fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15211 		const float		b		(fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15212 		const float		c		(fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15213 		const float		d		(fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15214 		const float		ad		(a * d);
15215 		const fp16type	adf16	(ad);
15216 		const float		bc		(b * c);
15217 		const fp16type	bcf16	(bc);
15218 		const float		r		(adf16.asFloat() - bcf16.asFloat());
15219 		const fp16type	rf16	(r);
15220 
15221 		out[0] = rf16.bits();
15222 		min[0] = getMin(r, getULPs(in));
15223 		max[0] = getMax(r, getULPs(in));
15224 
15225 		return true;
15226 	}
15227 };
15228 
15229 template<>
15230 struct fp16Determinant<3> : public fp16MatrixBase
15231 {
getULPsvkt::SpirVAssembly::fp16Determinant15232 	virtual double getULPs (vector<const deFloat16*>& in)
15233 	{
15234 		DE_UNREF(in);
15235 
15236 		return 128.0; // This is not a precision test. Value is not from spec
15237 	}
15238 
getComponentValidityvkt::SpirVAssembly::fp16Determinant15239 	deUint32 getComponentValidity ()
15240 	{
15241 		return 1;
15242 	}
15243 
15244 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Determinant15245 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15246 	{
15247 		const size_t	cols		= 3;
15248 		const size_t	rows		= 3;
15249 		const size_t	alignedCols	= (cols == 3) ? 4 : cols;
15250 		const size_t	alignedRows	= (rows == 3) ? 4 : rows;
15251 
15252 		DE_ASSERT(in.size() == 1);
15253 		DE_ASSERT(getOutCompCount() == 1);
15254 		DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15255 		DE_UNREF(alignedCols);
15256 		DE_UNREF(alignedRows);
15257 
15258 		// [ a b c ]
15259 		// [ d e f ]
15260 		// [ g h i ]
15261 		const float		a		(fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15262 		const float		b		(fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15263 		const float		c		(fp16type(in[0][getNdx(rows, 2, 0)]).asFloat());
15264 		const float		d		(fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15265 		const float		e		(fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15266 		const float		f		(fp16type(in[0][getNdx(rows, 2, 1)]).asFloat());
15267 		const float		g		(fp16type(in[0][getNdx(rows, 0, 2)]).asFloat());
15268 		const float		h		(fp16type(in[0][getNdx(rows, 1, 2)]).asFloat());
15269 		const float		i		(fp16type(in[0][getNdx(rows, 2, 2)]).asFloat());
15270 		const fp16type	aei		(a * e * i);
15271 		const fp16type	bfg		(b * f * g);
15272 		const fp16type	cdh		(c * d * h);
15273 		const fp16type	ceg		(c * e * g);
15274 		const fp16type	bdi		(b * d * i);
15275 		const fp16type	afh		(a * f * h);
15276 		const float		r		(aei.asFloat() + bfg.asFloat() + cdh.asFloat() - ceg.asFloat() - bdi.asFloat() - afh.asFloat());
15277 		const fp16type	rf16	(r);
15278 
15279 		out[0] = rf16.bits();
15280 		min[0] = getMin(r, getULPs(in));
15281 		max[0] = getMax(r, getULPs(in));
15282 
15283 		return true;
15284 	}
15285 };
15286 
15287 template<>
15288 struct fp16Determinant<4> : public fp16MatrixBase
15289 {
getULPsvkt::SpirVAssembly::fp16Determinant15290 	virtual double getULPs (vector<const deFloat16*>& in)
15291 	{
15292 		DE_UNREF(in);
15293 
15294 		return 128.0; // This is not a precision test. Value is not from spec
15295 	}
15296 
getComponentValidityvkt::SpirVAssembly::fp16Determinant15297 	deUint32 getComponentValidity ()
15298 	{
15299 		return 1;
15300 	}
15301 
15302 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Determinant15303 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15304 	{
15305 		const size_t	rows		= 4;
15306 		const size_t	cols		= 4;
15307 		const size_t	alignedCols	= (cols == 3) ? 4 : cols;
15308 		const size_t	alignedRows	= (rows == 3) ? 4 : rows;
15309 
15310 		DE_ASSERT(in.size() == 1);
15311 		DE_ASSERT(getOutCompCount() == 1);
15312 		DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15313 		DE_UNREF(alignedCols);
15314 		DE_UNREF(alignedRows);
15315 
15316 		// [ a b c d ]
15317 		// [ e f g h ]
15318 		// [ i j k l ]
15319 		// [ m n o p ]
15320 		const float		a		(fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15321 		const float		b		(fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15322 		const float		c		(fp16type(in[0][getNdx(rows, 2, 0)]).asFloat());
15323 		const float		d		(fp16type(in[0][getNdx(rows, 3, 0)]).asFloat());
15324 		const float		e		(fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15325 		const float		f		(fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15326 		const float		g		(fp16type(in[0][getNdx(rows, 2, 1)]).asFloat());
15327 		const float		h		(fp16type(in[0][getNdx(rows, 3, 1)]).asFloat());
15328 		const float		i		(fp16type(in[0][getNdx(rows, 0, 2)]).asFloat());
15329 		const float		j		(fp16type(in[0][getNdx(rows, 1, 2)]).asFloat());
15330 		const float		k		(fp16type(in[0][getNdx(rows, 2, 2)]).asFloat());
15331 		const float		l		(fp16type(in[0][getNdx(rows, 3, 2)]).asFloat());
15332 		const float		m		(fp16type(in[0][getNdx(rows, 0, 3)]).asFloat());
15333 		const float		n		(fp16type(in[0][getNdx(rows, 1, 3)]).asFloat());
15334 		const float		o		(fp16type(in[0][getNdx(rows, 2, 3)]).asFloat());
15335 		const float		p		(fp16type(in[0][getNdx(rows, 3, 3)]).asFloat());
15336 
15337 		// [ f g h ]
15338 		// [ j k l ]
15339 		// [ n o p ]
15340 		const fp16type	fkp		(f * k * p);
15341 		const fp16type	gln		(g * l * n);
15342 		const fp16type	hjo		(h * j * o);
15343 		const fp16type	hkn		(h * k * n);
15344 		const fp16type	gjp		(g * j * p);
15345 		const fp16type	flo		(f * l * o);
15346 		const fp16type	detA	(a * (fkp.asFloat() + gln.asFloat() + hjo.asFloat() - hkn.asFloat() - gjp.asFloat() - flo.asFloat()));
15347 
15348 		// [ e g h ]
15349 		// [ i k l ]
15350 		// [ m o p ]
15351 		const fp16type	ekp		(e * k * p);
15352 		const fp16type	glm		(g * l * m);
15353 		const fp16type	hio		(h * i * o);
15354 		const fp16type	hkm		(h * k * m);
15355 		const fp16type	gip		(g * i * p);
15356 		const fp16type	elo		(e * l * o);
15357 		const fp16type	detB	(b * (ekp.asFloat() + glm.asFloat() + hio.asFloat() - hkm.asFloat() - gip.asFloat() - elo.asFloat()));
15358 
15359 		// [ e f h ]
15360 		// [ i j l ]
15361 		// [ m n p ]
15362 		const fp16type	ejp		(e * j * p);
15363 		const fp16type	flm		(f * l * m);
15364 		const fp16type	hin		(h * i * n);
15365 		const fp16type	hjm		(h * j * m);
15366 		const fp16type	fip		(f * i * p);
15367 		const fp16type	eln		(e * l * n);
15368 		const fp16type	detC	(c * (ejp.asFloat() + flm.asFloat() + hin.asFloat() - hjm.asFloat() - fip.asFloat() - eln.asFloat()));
15369 
15370 		// [ e f g ]
15371 		// [ i j k ]
15372 		// [ m n o ]
15373 		const fp16type	ejo		(e * j * o);
15374 		const fp16type	fkm		(f * k * m);
15375 		const fp16type	gin		(g * i * n);
15376 		const fp16type	gjm		(g * j * m);
15377 		const fp16type	fio		(f * i * o);
15378 		const fp16type	ekn		(e * k * n);
15379 		const fp16type	detD	(d * (ejo.asFloat() + fkm.asFloat() + gin.asFloat() - gjm.asFloat() - fio.asFloat() - ekn.asFloat()));
15380 
15381 		const float		r		(detA.asFloat() - detB.asFloat() + detC.asFloat() - detD.asFloat());
15382 		const fp16type	rf16	(r);
15383 
15384 		out[0] = rf16.bits();
15385 		min[0] = getMin(r, getULPs(in));
15386 		max[0] = getMax(r, getULPs(in));
15387 
15388 		return true;
15389 	}
15390 };
15391 
15392 template<size_t size>
15393 struct fp16Inverse;
15394 
15395 template<>
15396 struct fp16Inverse<2> : public fp16MatrixBase
15397 {
getULPsvkt::SpirVAssembly::fp16Inverse15398 	virtual double getULPs (vector<const deFloat16*>& in)
15399 	{
15400 		DE_UNREF(in);
15401 
15402 		return 128.0; // This is not a precision test. Value is not from spec
15403 	}
15404 
getComponentValidityvkt::SpirVAssembly::fp16Inverse15405 	deUint32 getComponentValidity ()
15406 	{
15407 		return getComponentMatrixValidityMask(2, 2);
15408 	}
15409 
15410 	template<class fp16type>
calcvkt::SpirVAssembly::fp16Inverse15411 	bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15412 	{
15413 		const size_t	cols		= 2;
15414 		const size_t	rows		= 2;
15415 		const size_t	alignedCols	= (cols == 3) ? 4 : cols;
15416 		const size_t	alignedRows	= (rows == 3) ? 4 : rows;
15417 
15418 		DE_ASSERT(in.size() == 1);
15419 		DE_ASSERT(getOutCompCount() == alignedRows * alignedCols);
15420 		DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15421 		DE_UNREF(alignedCols);
15422 
15423 		// [ a b ]
15424 		// [ c d ]
15425 		const float		a		(fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15426 		const float		b		(fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15427 		const float		c		(fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15428 		const float		d		(fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15429 		const float		ad		(a * d);
15430 		const fp16type	adf16	(ad);
15431 		const float		bc		(b * c);
15432 		const fp16type	bcf16	(bc);
15433 		const float		det		(adf16.asFloat() - bcf16.asFloat());
15434 		const fp16type	det16	(det);
15435 
15436 		out[0] = fp16type( d / det16.asFloat()).bits();
15437 		out[1] = fp16type(-c / det16.asFloat()).bits();
15438 		out[2] = fp16type(-b / det16.asFloat()).bits();
15439 		out[3] = fp16type( a / det16.asFloat()).bits();
15440 
15441 		for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15442 			for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15443 			{
15444 				const size_t	ndx	(colNdx * alignedRows + rowNdx);
15445 				const fp16type	s	(out[ndx]);
15446 
15447 				min[ndx] = getMin(s.asDouble(), getULPs(in));
15448 				max[ndx] = getMax(s.asDouble(), getULPs(in));
15449 			}
15450 
15451 		return true;
15452 	}
15453 };
15454 
fp16ToString(deFloat16 val)15455 inline std::string fp16ToString(deFloat16 val)
15456 {
15457 	return tcu::toHex<4>(val).toString() + " (" + de::floatToString(tcu::Float16(val).asFloat(), 10) + ")";
15458 }
15459 
15460 template <size_t RES_COMPONENTS, size_t ARG0_COMPONENTS, size_t ARG1_COMPONENTS, size_t ARG2_COMPONENTS, class TestedArithmeticFunction>
compareFP16ArithmeticFunc(const std::vector<Resource> & inputs,const vector<AllocationSp> & outputAllocs,const std::vector<Resource> & expectedOutputs,TestLog & log)15461 bool compareFP16ArithmeticFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
15462 {
15463 	if (inputs.size() < 1 || inputs.size() > 3 || outputAllocs.size() != 1 || expectedOutputs.size() != 1)
15464 		return false;
15465 
15466 	const size_t	resultStep			= (RES_COMPONENTS == 3) ? 4 : RES_COMPONENTS;
15467 	const size_t	iterationsCount		= expectedOutputs[0].getByteSize() / (sizeof(deFloat16) * resultStep);
15468 	const size_t	inputsSteps[3]		=
15469 	{
15470 		(ARG0_COMPONENTS == 3) ? 4 : ARG0_COMPONENTS,
15471 		(ARG1_COMPONENTS == 3) ? 4 : ARG1_COMPONENTS,
15472 		(ARG2_COMPONENTS == 3) ? 4 : ARG2_COMPONENTS,
15473 	};
15474 
15475 	DE_ASSERT(expectedOutputs[0].getByteSize() > 0);
15476 	DE_ASSERT(expectedOutputs[0].getByteSize() == sizeof(deFloat16) * iterationsCount * resultStep);
15477 
15478 	for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15479 	{
15480 		DE_ASSERT(inputs[inputNdx].getByteSize() > 0);
15481 		DE_ASSERT(inputs[inputNdx].getByteSize() == sizeof(deFloat16) * iterationsCount * inputsSteps[inputNdx]);
15482 	}
15483 
15484 	const deFloat16* const		outputAsFP16					= (const deFloat16*)outputAllocs[0]->getHostPtr();
15485 	TestedArithmeticFunction	func;
15486 
15487 	func.setOutCompCount(RES_COMPONENTS);
15488 	func.setArgCompCount(0, ARG0_COMPONENTS);
15489 	func.setArgCompCount(1, ARG1_COMPONENTS);
15490 	func.setArgCompCount(2, ARG2_COMPONENTS);
15491 
15492 	const bool					callOncePerComponent			= func.callOncePerComponent();
15493 	const deUint32				componentValidityMask			= func.getComponentValidity();
15494 	const size_t				denormModesCount				= 2;
15495 	const char*					denormModes[denormModesCount]	= { "keep denormal numbers", "flush to zero" };
15496 	const size_t				successfulRunsPerComponent		= denormModesCount * func.getFlavorCount();
15497 	bool						success							= true;
15498 	size_t						validatedCount					= 0;
15499 
15500 	vector<deUint8>	inputBytes[3];
15501 
15502 	for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15503 		inputs[inputNdx].getBytes(inputBytes[inputNdx]);
15504 
15505 	const deFloat16* const			inputsAsFP16[3]			=
15506 	{
15507 		inputs.size() >= 1 ? (const deFloat16*)&inputBytes[0][0] : DE_NULL,
15508 		inputs.size() >= 2 ? (const deFloat16*)&inputBytes[1][0] : DE_NULL,
15509 		inputs.size() >= 3 ? (const deFloat16*)&inputBytes[2][0] : DE_NULL,
15510 	};
15511 
15512 	for (size_t idx = 0; idx < iterationsCount; ++idx)
15513 	{
15514 		std::vector<size_t>			successfulRuns		(RES_COMPONENTS, successfulRunsPerComponent);
15515 		std::vector<std::string>	errors				(RES_COMPONENTS);
15516 		bool						iterationValidated	(true);
15517 
15518 		for (size_t denormNdx = 0; denormNdx < 2; ++denormNdx)
15519 		{
15520 			for (size_t flavorNdx = 0; flavorNdx < func.getFlavorCount(); ++flavorNdx)
15521 			{
15522 				func.setFlavor(flavorNdx);
15523 
15524 				const deFloat16*			iterationOutputFP16		= &outputAsFP16[idx * resultStep];
15525 				vector<deFloat16>			iterationCalculatedFP16	(resultStep, 0);
15526 				vector<double>				iterationEdgeMin		(resultStep, 0.0);
15527 				vector<double>				iterationEdgeMax		(resultStep, 0.0);
15528 				vector<const deFloat16*>	arguments;
15529 
15530 				for (size_t componentNdx = 0; componentNdx < RES_COMPONENTS; ++componentNdx)
15531 				{
15532 					std::string	error;
15533 					bool		reportError = false;
15534 
15535 					if (callOncePerComponent || componentNdx == 0)
15536 					{
15537 						bool funcCallResult;
15538 
15539 						arguments.clear();
15540 
15541 						for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15542 							arguments.push_back(&inputsAsFP16[inputNdx][idx * inputsSteps[inputNdx] + componentNdx]);
15543 
15544 						if (denormNdx == 0)
15545 							funcCallResult = func.template calc<tcu::Float16>(arguments, &iterationCalculatedFP16[componentNdx], &iterationEdgeMin[componentNdx], &iterationEdgeMax[componentNdx]);
15546 						else
15547 							funcCallResult = func.template calc<tcu::Float16Denormless>(arguments, &iterationCalculatedFP16[componentNdx], &iterationEdgeMin[componentNdx], &iterationEdgeMax[componentNdx]);
15548 
15549 						if (!funcCallResult)
15550 						{
15551 							iterationValidated = false;
15552 
15553 							if (callOncePerComponent)
15554 								continue;
15555 							else
15556 								break;
15557 						}
15558 					}
15559 
15560 					if ((componentValidityMask != 0) && (componentValidityMask & (1<<componentNdx)) == 0)
15561 						continue;
15562 
15563 					reportError = !compare16BitFloat(iterationCalculatedFP16[componentNdx], iterationOutputFP16[componentNdx], error);
15564 
15565 					if (reportError)
15566 					{
15567 						tcu::Float16 expected	(iterationCalculatedFP16[componentNdx]);
15568 						tcu::Float16 outputted	(iterationOutputFP16[componentNdx]);
15569 
15570 						if (reportError && expected.isNaN())
15571 							reportError = false;
15572 
15573 						if (reportError && !expected.isNaN() && !outputted.isNaN())
15574 						{
15575 							if (reportError && !expected.isInf() && !outputted.isInf())
15576 							{
15577 								// Ignore rounding
15578 								if (expected.bits() == outputted.bits() + 1 || expected.bits() + 1 == outputted.bits())
15579 									reportError = false;
15580 							}
15581 
15582 							if (reportError && expected.isInf())
15583 							{
15584 								// RTZ rounding mode returns +/-65504 instead of Inf on overflow
15585 								if (expected.sign() == 1 && outputted.bits() == 0x7bff && iterationEdgeMin[componentNdx] <= std::numeric_limits<double>::max())
15586 									reportError = false;
15587 								else if (expected.sign() == -1 && outputted.bits() == 0xfbff && iterationEdgeMax[componentNdx] >= -std::numeric_limits<double>::max())
15588 									reportError = false;
15589 							}
15590 
15591 							if (reportError)
15592 							{
15593 								const double	outputtedDouble	= outputted.asDouble();
15594 
15595 								DE_ASSERT(iterationEdgeMin[componentNdx] <= iterationEdgeMax[componentNdx]);
15596 
15597 								if (de::inRange(outputtedDouble, iterationEdgeMin[componentNdx], iterationEdgeMax[componentNdx]))
15598 									reportError = false;
15599 							}
15600 						}
15601 
15602 						if (reportError)
15603 						{
15604 							const size_t		inputsComps[3]	=
15605 							{
15606 								ARG0_COMPONENTS,
15607 								ARG1_COMPONENTS,
15608 								ARG2_COMPONENTS,
15609 							};
15610 							string				inputsValues	("Inputs:");
15611 							string				flavorName		(func.getFlavorCount() == 1 ? "" : string(" flavor ") + de::toString(flavorNdx) + " (" + func.getCurrentFlavorName() + ")");
15612 							std::stringstream	errStream;
15613 
15614 							for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15615 							{
15616 								const size_t	inputCompsCount = inputsComps[inputNdx];
15617 
15618 								inputsValues += " [" + de::toString(inputNdx) + "]=(";
15619 
15620 								for (size_t compNdx = 0; compNdx < inputCompsCount; ++compNdx)
15621 								{
15622 									const deFloat16 inputComponentValue = inputsAsFP16[inputNdx][idx * inputsSteps[inputNdx] + compNdx];
15623 
15624 									inputsValues += fp16ToString(inputComponentValue) + ((compNdx + 1 == inputCompsCount) ? ")": ", ");
15625 								}
15626 							}
15627 
15628 							errStream	<< "At"
15629 										<< " iteration " << de::toString(idx)
15630 										<< " component " << de::toString(componentNdx)
15631 										<< " denormMode " << de::toString(denormNdx)
15632 										<< " (" << denormModes[denormNdx] << ")"
15633 										<< " " << flavorName
15634 										<< " " << inputsValues
15635 										<< " outputted:" + fp16ToString(iterationOutputFP16[componentNdx])
15636 										<< " expected:" + fp16ToString(iterationCalculatedFP16[componentNdx])
15637 										<< " or in range: [" << iterationEdgeMin[componentNdx] << ", " << iterationEdgeMax[componentNdx] << "]."
15638 										<< " " << error << "."
15639 										<< std::endl;
15640 
15641 							errors[componentNdx] += errStream.str();
15642 
15643 							successfulRuns[componentNdx]--;
15644 						}
15645 					}
15646 				}
15647 			}
15648 		}
15649 
15650 		for (size_t componentNdx = 0; componentNdx < RES_COMPONENTS; ++componentNdx)
15651 		{
15652 			// Check if any component has total failure
15653 			if (successfulRuns[componentNdx] == 0)
15654 			{
15655 				// Test failed in all denorm modes and all flavors for certain component: dump errors
15656 				log << TestLog::Message << errors[componentNdx] << TestLog::EndMessage;
15657 
15658 				success = false;
15659 			}
15660 		}
15661 
15662 		if (iterationValidated)
15663 			validatedCount++;
15664 	}
15665 
15666 	if (validatedCount < 16)
15667 		TCU_THROW(InternalError, "Too few samples has been validated.");
15668 
15669 	return success;
15670 }
15671 
15672 // IEEE-754 floating point numbers:
15673 // +--------+------+----------+-------------+
15674 // | binary | sign | exponent | significand |
15675 // +--------+------+----------+-------------+
15676 // | 16-bit |  1   |    5     |     10      |
15677 // +--------+------+----------+-------------+
15678 // | 32-bit |  1   |    8     |     23      |
15679 // +--------+------+----------+-------------+
15680 //
15681 // 16-bit floats:
15682 //
15683 // 0   000 00   00 0000 0001 (0x0001: 2e-24:         minimum positive denormalized)
15684 // 0   000 00   11 1111 1111 (0x03ff: 2e-14 - 2e-24: maximum positive denormalized)
15685 // 0   000 01   00 0000 0000 (0x0400: 2e-14:         minimum positive normalized)
15686 // 0   111 10   11 1111 1111 (0x7bff: 65504:         maximum positive normalized)
15687 //
15688 // 0   000 00   00 0000 0000 (0x0000: +0)
15689 // 0   111 11   00 0000 0000 (0x7c00: +Inf)
15690 // 0   000 00   11 1111 0000 (0x03f0: +Denorm)
15691 // 0   000 01   00 0000 0001 (0x0401: +Norm)
15692 // 0   111 11   00 0000 1111 (0x7c0f: +SNaN)
15693 // 0   111 11   11 1111 0000 (0x7ff0: +QNaN)
15694 // Generate and return 16-bit floats and their corresponding 32-bit values.
15695 //
15696 // The first 14 number pairs are manually picked, while the rest are randomly generated.
15697 // Expected count to be at least 14 (numPicks).
getFloat16a(de::Random & rnd,deUint32 count)15698 vector<deFloat16> getFloat16a (de::Random& rnd, deUint32 count)
15699 {
15700 	vector<deFloat16>	float16;
15701 
15702 	float16.reserve(count);
15703 
15704 	// Zero
15705 	float16.push_back(deUint16(0x0000));
15706 	float16.push_back(deUint16(0x8000));
15707 	// Infinity
15708 	float16.push_back(deUint16(0x7c00));
15709 	float16.push_back(deUint16(0xfc00));
15710 	// Normalized
15711 	float16.push_back(deUint16(0x0401));
15712 	float16.push_back(deUint16(0x8401));
15713 	// Some normal number
15714 	float16.push_back(deUint16(0x14cb));
15715 	float16.push_back(deUint16(0x94cb));
15716 	// Min/max positive normal
15717 	float16.push_back(deUint16(0x0400));
15718 	float16.push_back(deUint16(0x7bff));
15719 	// Min/max negative normal
15720 	float16.push_back(deUint16(0x8400));
15721 	float16.push_back(deUint16(0xfbff));
15722 	// PI
15723 	float16.push_back(deUint16(0x4248)); // 3.140625
15724 	float16.push_back(deUint16(0xb248)); // -3.140625
15725 	// PI/2
15726 	float16.push_back(deUint16(0x3e48)); // 1.5703125
15727 	float16.push_back(deUint16(0xbe48)); // -1.5703125
15728 	float16.push_back(deUint16(0x3c00)); // 1.0
15729 	float16.push_back(deUint16(0x3800)); // 0.5
15730 	// Some useful constants
15731 	float16.push_back(tcu::Float16(-2.5f).bits());
15732 	float16.push_back(tcu::Float16(-1.0f).bits());
15733 	float16.push_back(tcu::Float16( 0.4f).bits());
15734 	float16.push_back(tcu::Float16( 2.5f).bits());
15735 
15736 	const deUint32		numPicks	= static_cast<deUint32>(float16.size());
15737 
15738 	DE_ASSERT(count >= numPicks);
15739 	count -= numPicks;
15740 
15741 	for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
15742 	{
15743 		int			sign		= (rnd.getUint16() % 2 == 0) ? +1 : -1;
15744 		int			exponent	= (rnd.getUint16() % 29) - 14 + 1;
15745 		deUint16	mantissa	= static_cast<deUint16>(2 * (rnd.getUint16() % 512));
15746 
15747 		// Exclude power of -14 to avoid denorms
15748 		DE_ASSERT(de::inRange(exponent, -13, 15));
15749 
15750 		float16.push_back(tcu::Float16::constructBits(sign, exponent, mantissa).bits());
15751 	}
15752 
15753 	return float16;
15754 }
15755 
getInputData1(deUint32 seed,size_t count,size_t argNo)15756 static inline vector<deFloat16> getInputData1 (deUint32 seed, size_t count, size_t argNo)
15757 {
15758 	DE_UNREF(argNo);
15759 
15760 	de::Random	rnd(seed);
15761 
15762 	return getFloat16a(rnd, static_cast<deUint32>(count));
15763 }
15764 
getInputData2(deUint32 seed,size_t count,size_t argNo)15765 static inline vector<deFloat16> getInputData2 (deUint32 seed, size_t count, size_t argNo)
15766 {
15767 	de::Random	rnd		(seed);
15768 	size_t		newCount = static_cast<size_t>(deSqrt(double(count)));
15769 
15770 	DE_ASSERT(newCount * newCount == count);
15771 
15772 	vector<deFloat16>	float16 = getFloat16a(rnd, static_cast<deUint32>(newCount));
15773 
15774 	return squarize(float16, static_cast<deUint32>(argNo));
15775 }
15776 
getInputData3(deUint32 seed,size_t count,size_t argNo)15777 static inline vector<deFloat16> getInputData3 (deUint32 seed, size_t count, size_t argNo)
15778 {
15779 	if (argNo == 0 || argNo == 1)
15780 		return getInputData2(seed, count, argNo);
15781 	else
15782 		return getInputData1(seed<<argNo, count, argNo);
15783 }
15784 
getInputData(deUint32 seed,size_t count,size_t compCount,size_t stride,size_t argCount,size_t argNo)15785 vector<deFloat16> getInputData (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15786 {
15787 	DE_UNREF(stride);
15788 
15789 	vector<deFloat16>	result;
15790 
15791 	switch (argCount)
15792 	{
15793 		case 1:result = getInputData1(seed, count, argNo); break;
15794 		case 2:result = getInputData2(seed, count, argNo); break;
15795 		case 3:result = getInputData3(seed, count, argNo); break;
15796 		default: TCU_THROW(InternalError, "Invalid argument count specified");
15797 	}
15798 
15799 	if (compCount == 3)
15800 	{
15801 		const size_t		newCount = (3 * count) / 4;
15802 		vector<deFloat16>	newResult;
15803 
15804 		newResult.reserve(result.size());
15805 
15806 		for (size_t ndx = 0; ndx < newCount; ++ndx)
15807 		{
15808 			newResult.push_back(result[ndx]);
15809 
15810 			if (ndx % 3 == 2)
15811 				newResult.push_back(0);
15812 		}
15813 
15814 		result = newResult;
15815 	}
15816 
15817 	DE_ASSERT(result.size() == count);
15818 
15819 	return result;
15820 }
15821 
15822 // Generator for functions requiring data in range [1, inf]
getInputDataAC(deUint32 seed,size_t count,size_t compCount,size_t stride,size_t argCount,size_t argNo)15823 vector<deFloat16> getInputDataAC (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15824 {
15825 	vector<deFloat16>	result;
15826 
15827 	result = getInputData(seed, count, compCount, stride, argCount, argNo);
15828 
15829 	// Filter out values below 1.0 from upper half of numbers
15830 	for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15831 	{
15832 		const float f = tcu::Float16(result[idx]).asFloat();
15833 
15834 		if (f < 1.0f)
15835 			result[idx] = tcu::Float16(1.0f - f).bits();
15836 	}
15837 
15838 	return result;
15839 }
15840 
15841 // Generator for functions requiring data in range [-1, 1]
getInputDataA(deUint32 seed,size_t count,size_t compCount,size_t stride,size_t argCount,size_t argNo)15842 vector<deFloat16> getInputDataA (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15843 {
15844 	vector<deFloat16>	result;
15845 
15846 	result = getInputData(seed, count, compCount, stride, argCount, argNo);
15847 
15848 	for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15849 	{
15850 		const float f = tcu::Float16(result[idx]).asFloat();
15851 
15852 		if (!de::inRange(f, -1.0f, 1.0f))
15853 			result[idx] = tcu::Float16(deFloatFrac(f)).bits();
15854 	}
15855 
15856 	return result;
15857 }
15858 
15859 // Generator for functions requiring data in range [-pi, pi]
getInputDataPI(deUint32 seed,size_t count,size_t compCount,size_t stride,size_t argCount,size_t argNo)15860 vector<deFloat16> getInputDataPI (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15861 {
15862 	vector<deFloat16>	result;
15863 
15864 	result = getInputData(seed, count, compCount, stride, argCount, argNo);
15865 
15866 	for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15867 	{
15868 		const float f = tcu::Float16(result[idx]).asFloat();
15869 
15870 		if (!de::inRange(f, -DE_PI, DE_PI))
15871 			result[idx] = tcu::Float16(fmodf(f, DE_PI)).bits();
15872 	}
15873 
15874 	return result;
15875 }
15876 
15877 // Generator for functions requiring data in range [0, inf]
getInputDataP(deUint32 seed,size_t count,size_t compCount,size_t stride,size_t argCount,size_t argNo)15878 vector<deFloat16> getInputDataP (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15879 {
15880 	vector<deFloat16>	result;
15881 
15882 	result = getInputData(seed, count, compCount, stride, argCount, argNo);
15883 
15884 	if (argNo == 0)
15885 	{
15886 		for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15887 			result[idx] &= static_cast<deFloat16>(~0x8000);
15888 	}
15889 
15890 	return result;
15891 }
15892 
getInputDataV(deUint32 seed,size_t count,size_t compCount,size_t stride,size_t argCount,size_t argNo)15893 vector<deFloat16> getInputDataV (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15894 {
15895 	DE_UNREF(stride);
15896 	DE_UNREF(argCount);
15897 
15898 	vector<deFloat16>	result;
15899 
15900 	if (argNo == 0)
15901 		result = getInputData2(seed, count, argNo);
15902 	else
15903 	{
15904 		const size_t		alignedCount	= (compCount == 3) ? 4 : compCount;
15905 		const size_t		newCountX		= static_cast<size_t>(deSqrt(double(count * alignedCount)));
15906 		const size_t		newCountY		= count / newCountX;
15907 		de::Random			rnd				(seed);
15908 		vector<deFloat16>	float16			= getFloat16a(rnd, static_cast<deUint32>(newCountX));
15909 
15910 		DE_ASSERT(newCountX * newCountX == alignedCount * count);
15911 
15912 		for (size_t numIdx = 0; numIdx < newCountX; ++numIdx)
15913 		{
15914 			const vector<deFloat16>	tmp(newCountY, float16[numIdx]);
15915 
15916 			result.insert(result.end(), tmp.begin(), tmp.end());
15917 		}
15918 	}
15919 
15920 	DE_ASSERT(result.size() == count);
15921 
15922 	return result;
15923 }
15924 
getInputDataM(deUint32 seed,size_t count,size_t compCount,size_t stride,size_t argCount,size_t argNo)15925 vector<deFloat16> getInputDataM (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15926 {
15927 	DE_UNREF(compCount);
15928 	DE_UNREF(stride);
15929 	DE_UNREF(argCount);
15930 
15931 	de::Random			rnd		(seed << argNo);
15932 	vector<deFloat16>	result;
15933 
15934 	result = getFloat16a(rnd, static_cast<deUint32>(count));
15935 
15936 	DE_ASSERT(result.size() == count);
15937 
15938 	return result;
15939 }
15940 
getInputDataD(deUint32 seed,size_t count,size_t compCount,size_t stride,size_t argCount,size_t argNo)15941 vector<deFloat16> getInputDataD (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15942 {
15943 	DE_UNREF(compCount);
15944 	DE_UNREF(argCount);
15945 
15946 	de::Random			rnd		(seed << argNo);
15947 	vector<deFloat16>	result;
15948 
15949 	for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
15950 	{
15951 		int num	= (rnd.getUint16() % 16) - 8;
15952 
15953 		result.push_back(tcu::Float16(float(num)).bits());
15954 	}
15955 
15956 	result[0 * stride] = deUint16(0x7c00); // +Inf
15957 	result[1 * stride] = deUint16(0xfc00); // -Inf
15958 
15959 	DE_ASSERT(result.size() == count);
15960 
15961 	return result;
15962 }
15963 
15964 // Generator for smoothstep function
getInputDataSS(deUint32 seed,size_t count,size_t compCount,size_t stride,size_t argCount,size_t argNo)15965 vector<deFloat16> getInputDataSS (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15966 {
15967 	vector<deFloat16>	result;
15968 
15969 	result = getInputDataD(seed, count, compCount, stride, argCount, argNo);
15970 
15971 	if (argNo == 0)
15972 	{
15973 		for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15974 		{
15975 			const float f = tcu::Float16(result[idx]).asFloat();
15976 
15977 			if (f > 4.0f)
15978 				result[idx] = tcu::Float16(-f).bits();
15979 		}
15980 	}
15981 
15982 	if (argNo == 1)
15983 	{
15984 		for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15985 		{
15986 			const float f = tcu::Float16(result[idx]).asFloat();
15987 
15988 			if (f < 4.0f)
15989 				result[idx] = tcu::Float16(-f).bits();
15990 		}
15991 	}
15992 
15993 	return result;
15994 }
15995 
15996 // Generates normalized vectors for arguments 0 and 1
getInputDataN(deUint32 seed,size_t count,size_t compCount,size_t stride,size_t argCount,size_t argNo)15997 vector<deFloat16> getInputDataN (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15998 {
15999 	DE_UNREF(compCount);
16000 	DE_UNREF(argCount);
16001 
16002 	de::Random			rnd		(seed << argNo);
16003 	vector<deFloat16>	result;
16004 
16005 	if (argNo == 0 || argNo == 1)
16006 	{
16007 		// The input parameters for the incident vector I and the surface normal N must already be normalized
16008 		for (size_t numIdx = 0; numIdx < count; numIdx += stride)
16009 		{
16010 			vector <float>	unnormolized;
16011 			float			sum				= 0;
16012 
16013 			for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
16014 				unnormolized.push_back(float((rnd.getUint16() % 16) - 8));
16015 
16016 			for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
16017 				sum += unnormolized[compIdx] * unnormolized[compIdx];
16018 
16019 			sum = deFloatSqrt(sum);
16020 			if (sum == 0.0f)
16021 				unnormolized[0] = sum = 1.0f;
16022 
16023 			for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
16024 				result.push_back(tcu::Float16(unnormolized[compIdx] / sum).bits());
16025 
16026 			for (size_t compIdx = compCount; compIdx < stride; ++compIdx)
16027 				result.push_back(0);
16028 		}
16029 	}
16030 	else
16031 	{
16032 		// Input parameter eta
16033 		for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
16034 		{
16035 			int num	= (rnd.getUint16() % 16) - 8;
16036 
16037 			result.push_back(tcu::Float16(float(num)).bits());
16038 		}
16039 	}
16040 
16041 	DE_ASSERT(result.size() == count);
16042 
16043 	return result;
16044 }
16045 
16046 // Data generator for complex matrix functions like determinant and inverse
getInputDataC(deUint32 seed,size_t count,size_t compCount,size_t stride,size_t argCount,size_t argNo)16047 vector<deFloat16> getInputDataC (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16048 {
16049 	DE_UNREF(compCount);
16050 	DE_UNREF(stride);
16051 	DE_UNREF(argCount);
16052 
16053 	de::Random			rnd		(seed << argNo);
16054 	vector<deFloat16>	result;
16055 
16056 	for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
16057 	{
16058 		int num	= (rnd.getUint16() % 16) - 8;
16059 
16060 		result.push_back(tcu::Float16(float(num)).bits());
16061 	}
16062 
16063 	DE_ASSERT(result.size() == count);
16064 
16065 	return result;
16066 }
16067 
16068 struct Math16TestType
16069 {
16070 	const char*		typePrefix;
16071 	const size_t	typeComponents;
16072 	const size_t	typeArrayStride;
16073 	const size_t	typeStructStride;
16074 };
16075 
16076 enum Math16DataTypes
16077 {
16078 	NONE	= 0,
16079 	SCALAR	= 1,
16080 	VEC2	= 2,
16081 	VEC3	= 3,
16082 	VEC4	= 4,
16083 	MAT2X2,
16084 	MAT2X3,
16085 	MAT2X4,
16086 	MAT3X2,
16087 	MAT3X3,
16088 	MAT3X4,
16089 	MAT4X2,
16090 	MAT4X3,
16091 	MAT4X4,
16092 	MATH16_TYPE_LAST
16093 };
16094 
16095 struct Math16ArgFragments
16096 {
16097 	const char*	bodies;
16098 	const char*	variables;
16099 	const char*	decorations;
16100 	const char*	funcVariables;
16101 };
16102 
16103 typedef vector<deFloat16> Math16GetInputData (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo);
16104 
16105 struct Math16TestFunc
16106 {
16107 	const char*					funcName;
16108 	const char*					funcSuffix;
16109 	size_t						funcArgsCount;
16110 	size_t						typeResult;
16111 	size_t						typeArg0;
16112 	size_t						typeArg1;
16113 	size_t						typeArg2;
16114 	Math16GetInputData*			getInputDataFunc;
16115 	VerifyIOFunc				verifyFunc;
16116 };
16117 
16118 template<class SpecResource>
createFloat16ArithmeticFuncTest(tcu::TestContext & testCtx,tcu::TestCaseGroup & testGroup,const size_t testTypeIdx,const Math16TestFunc & testFunc)16119 void createFloat16ArithmeticFuncTest (tcu::TestContext& testCtx, tcu::TestCaseGroup& testGroup, const size_t testTypeIdx, const Math16TestFunc& testFunc)
16120 {
16121 	const int					testSpecificSeed			= deStringHash(testGroup.getName());
16122 	const int					seed						= testCtx.getCommandLine().getBaseSeed() ^ testSpecificSeed;
16123 	const size_t				numDataPointsByAxis			= 32;
16124 	const size_t				numDataPoints				= numDataPointsByAxis * numDataPointsByAxis;
16125 	const char*					componentType				= "f16";
16126 	const Math16TestType		testTypes[MATH16_TYPE_LAST]	=
16127 	{
16128 		{ "",		0,	 0,						 0,						},
16129 		{ "",		1,	 1 * sizeof(deFloat16),	 2 * sizeof(deFloat16)	},
16130 		{ "v2",		2,	 2 * sizeof(deFloat16),	 2 * sizeof(deFloat16)	},
16131 		{ "v3",		3,	 4 * sizeof(deFloat16),	 4 * sizeof(deFloat16)	},
16132 		{ "v4",		4,	 4 * sizeof(deFloat16),	 4 * sizeof(deFloat16)	},
16133 		{ "m2x2",	0,	 4 * sizeof(deFloat16),	 4 * sizeof(deFloat16)	},
16134 		{ "m2x3",	0,	 8 * sizeof(deFloat16),	 8 * sizeof(deFloat16)	},
16135 		{ "m2x4",	0,	 8 * sizeof(deFloat16),	 8 * sizeof(deFloat16)	},
16136 		{ "m3x2",	0,	 8 * sizeof(deFloat16),	 8 * sizeof(deFloat16)	},
16137 		{ "m3x3",	0,	16 * sizeof(deFloat16),	16 * sizeof(deFloat16)	},
16138 		{ "m3x4",	0,	16 * sizeof(deFloat16),	16 * sizeof(deFloat16)	},
16139 		{ "m4x2",	0,	 8 * sizeof(deFloat16),	 8 * sizeof(deFloat16)	},
16140 		{ "m4x3",	0,	16 * sizeof(deFloat16),	16 * sizeof(deFloat16)	},
16141 		{ "m4x4",	0,	16 * sizeof(deFloat16),	16 * sizeof(deFloat16)	},
16142 	};
16143 
16144 	DE_ASSERT(testTypeIdx == testTypes[testTypeIdx].typeComponents);
16145 
16146 
16147 	const StringTemplate preMain
16148 	(
16149 		"     %c_i32_ndp  = OpConstant %i32 ${num_data_points}\n"
16150 
16151 		"        %f16     = OpTypeFloat 16\n"
16152 		"        %v2f16   = OpTypeVector %f16 2\n"
16153 		"        %v3f16   = OpTypeVector %f16 3\n"
16154 		"        %v4f16   = OpTypeVector %f16 4\n"
16155 		"        %m2x2f16 = OpTypeMatrix %v2f16 2\n"
16156 		"        %m2x3f16 = OpTypeMatrix %v3f16 2\n"
16157 		"        %m2x4f16 = OpTypeMatrix %v4f16 2\n"
16158 		"        %m3x2f16 = OpTypeMatrix %v2f16 3\n"
16159 		"        %m3x3f16 = OpTypeMatrix %v3f16 3\n"
16160 		"        %m3x4f16 = OpTypeMatrix %v4f16 3\n"
16161 		"        %m4x2f16 = OpTypeMatrix %v2f16 4\n"
16162 		"        %m4x3f16 = OpTypeMatrix %v3f16 4\n"
16163 		"        %m4x4f16 = OpTypeMatrix %v4f16 4\n"
16164 
16165 		"     %up_f16     = OpTypePointer Uniform %f16    \n"
16166 		"     %up_v2f16   = OpTypePointer Uniform %v2f16  \n"
16167 		"     %up_v3f16   = OpTypePointer Uniform %v3f16  \n"
16168 		"     %up_v4f16   = OpTypePointer Uniform %v4f16  \n"
16169 		"     %up_m2x2f16 = OpTypePointer Uniform %m2x2f16\n"
16170 		"     %up_m2x3f16 = OpTypePointer Uniform %m2x3f16\n"
16171 		"     %up_m2x4f16 = OpTypePointer Uniform %m2x4f16\n"
16172 		"     %up_m3x2f16 = OpTypePointer Uniform %m3x2f16\n"
16173 		"     %up_m3x3f16 = OpTypePointer Uniform %m3x3f16\n"
16174 		"     %up_m3x4f16 = OpTypePointer Uniform %m3x4f16\n"
16175 		"     %up_m4x2f16 = OpTypePointer Uniform %m4x2f16\n"
16176 		"     %up_m4x3f16 = OpTypePointer Uniform %m4x3f16\n"
16177 		"     %up_m4x4f16 = OpTypePointer Uniform %m4x4f16\n"
16178 
16179 		"     %ra_f16     = OpTypeArray %f16     %c_i32_ndp\n"
16180 		"     %ra_v2f16   = OpTypeArray %v2f16   %c_i32_ndp\n"
16181 		"     %ra_v3f16   = OpTypeArray %v3f16   %c_i32_ndp\n"
16182 		"     %ra_v4f16   = OpTypeArray %v4f16   %c_i32_ndp\n"
16183 		"     %ra_m2x2f16 = OpTypeArray %m2x2f16 %c_i32_ndp\n"
16184 		"     %ra_m2x3f16 = OpTypeArray %m2x3f16 %c_i32_ndp\n"
16185 		"     %ra_m2x4f16 = OpTypeArray %m2x4f16 %c_i32_ndp\n"
16186 		"     %ra_m3x2f16 = OpTypeArray %m3x2f16 %c_i32_ndp\n"
16187 		"     %ra_m3x3f16 = OpTypeArray %m3x3f16 %c_i32_ndp\n"
16188 		"     %ra_m3x4f16 = OpTypeArray %m3x4f16 %c_i32_ndp\n"
16189 		"     %ra_m4x2f16 = OpTypeArray %m4x2f16 %c_i32_ndp\n"
16190 		"     %ra_m4x3f16 = OpTypeArray %m4x3f16 %c_i32_ndp\n"
16191 		"     %ra_m4x4f16 = OpTypeArray %m4x4f16 %c_i32_ndp\n"
16192 
16193 		"   %SSBO_f16     = OpTypeStruct %ra_f16    \n"
16194 		"   %SSBO_v2f16   = OpTypeStruct %ra_v2f16  \n"
16195 		"   %SSBO_v3f16   = OpTypeStruct %ra_v3f16  \n"
16196 		"   %SSBO_v4f16   = OpTypeStruct %ra_v4f16  \n"
16197 		"   %SSBO_m2x2f16 = OpTypeStruct %ra_m2x2f16\n"
16198 		"   %SSBO_m2x3f16 = OpTypeStruct %ra_m2x3f16\n"
16199 		"   %SSBO_m2x4f16 = OpTypeStruct %ra_m2x4f16\n"
16200 		"   %SSBO_m3x2f16 = OpTypeStruct %ra_m3x2f16\n"
16201 		"   %SSBO_m3x3f16 = OpTypeStruct %ra_m3x3f16\n"
16202 		"   %SSBO_m3x4f16 = OpTypeStruct %ra_m3x4f16\n"
16203 		"   %SSBO_m4x2f16 = OpTypeStruct %ra_m4x2f16\n"
16204 		"   %SSBO_m4x3f16 = OpTypeStruct %ra_m4x3f16\n"
16205 		"   %SSBO_m4x4f16 = OpTypeStruct %ra_m4x4f16\n"
16206 
16207 		"%up_SSBO_f16     = OpTypePointer Uniform %SSBO_f16    \n"
16208 		"%up_SSBO_v2f16   = OpTypePointer Uniform %SSBO_v2f16  \n"
16209 		"%up_SSBO_v3f16   = OpTypePointer Uniform %SSBO_v3f16  \n"
16210 		"%up_SSBO_v4f16   = OpTypePointer Uniform %SSBO_v4f16  \n"
16211 		"%up_SSBO_m2x2f16 = OpTypePointer Uniform %SSBO_m2x2f16\n"
16212 		"%up_SSBO_m2x3f16 = OpTypePointer Uniform %SSBO_m2x3f16\n"
16213 		"%up_SSBO_m2x4f16 = OpTypePointer Uniform %SSBO_m2x4f16\n"
16214 		"%up_SSBO_m3x2f16 = OpTypePointer Uniform %SSBO_m3x2f16\n"
16215 		"%up_SSBO_m3x3f16 = OpTypePointer Uniform %SSBO_m3x3f16\n"
16216 		"%up_SSBO_m3x4f16 = OpTypePointer Uniform %SSBO_m3x4f16\n"
16217 		"%up_SSBO_m4x2f16 = OpTypePointer Uniform %SSBO_m4x2f16\n"
16218 		"%up_SSBO_m4x3f16 = OpTypePointer Uniform %SSBO_m4x3f16\n"
16219 		"%up_SSBO_m4x4f16 = OpTypePointer Uniform %SSBO_m4x4f16\n"
16220 
16221 		"       %fp_v2i32 = OpTypePointer Function %v2i32\n"
16222 		"       %fp_v3i32 = OpTypePointer Function %v3i32\n"
16223 		"       %fp_v4i32 = OpTypePointer Function %v4i32\n"
16224 		"${arg_vars}"
16225 	);
16226 
16227 	const StringTemplate decoration
16228 	(
16229 		"OpDecorate %ra_f16     ArrayStride 2 \n"
16230 		"OpDecorate %ra_v2f16   ArrayStride 4 \n"
16231 		"OpDecorate %ra_v3f16   ArrayStride 8 \n"
16232 		"OpDecorate %ra_v4f16   ArrayStride 8 \n"
16233 		"OpDecorate %ra_m2x2f16 ArrayStride 8 \n"
16234 		"OpDecorate %ra_m2x3f16 ArrayStride 16\n"
16235 		"OpDecorate %ra_m2x4f16 ArrayStride 16\n"
16236 		"OpDecorate %ra_m3x2f16 ArrayStride 16\n"
16237 		"OpDecorate %ra_m3x3f16 ArrayStride 32\n"
16238 		"OpDecorate %ra_m3x4f16 ArrayStride 32\n"
16239 		"OpDecorate %ra_m4x2f16 ArrayStride 16\n"
16240 		"OpDecorate %ra_m4x3f16 ArrayStride 32\n"
16241 		"OpDecorate %ra_m4x4f16 ArrayStride 32\n"
16242 
16243 		"OpMemberDecorate %SSBO_f16     0 Offset 0\n"
16244 		"OpMemberDecorate %SSBO_v2f16   0 Offset 0\n"
16245 		"OpMemberDecorate %SSBO_v3f16   0 Offset 0\n"
16246 		"OpMemberDecorate %SSBO_v4f16   0 Offset 0\n"
16247 		"OpMemberDecorate %SSBO_m2x2f16 0 Offset 0\n"
16248 		"OpMemberDecorate %SSBO_m2x3f16 0 Offset 0\n"
16249 		"OpMemberDecorate %SSBO_m2x4f16 0 Offset 0\n"
16250 		"OpMemberDecorate %SSBO_m3x2f16 0 Offset 0\n"
16251 		"OpMemberDecorate %SSBO_m3x3f16 0 Offset 0\n"
16252 		"OpMemberDecorate %SSBO_m3x4f16 0 Offset 0\n"
16253 		"OpMemberDecorate %SSBO_m4x2f16 0 Offset 0\n"
16254 		"OpMemberDecorate %SSBO_m4x3f16 0 Offset 0\n"
16255 		"OpMemberDecorate %SSBO_m4x4f16 0 Offset 0\n"
16256 
16257 		"OpDecorate %SSBO_f16     BufferBlock\n"
16258 		"OpDecorate %SSBO_v2f16   BufferBlock\n"
16259 		"OpDecorate %SSBO_v3f16   BufferBlock\n"
16260 		"OpDecorate %SSBO_v4f16   BufferBlock\n"
16261 		"OpDecorate %SSBO_m2x2f16 BufferBlock\n"
16262 		"OpDecorate %SSBO_m2x3f16 BufferBlock\n"
16263 		"OpDecorate %SSBO_m2x4f16 BufferBlock\n"
16264 		"OpDecorate %SSBO_m3x2f16 BufferBlock\n"
16265 		"OpDecorate %SSBO_m3x3f16 BufferBlock\n"
16266 		"OpDecorate %SSBO_m3x4f16 BufferBlock\n"
16267 		"OpDecorate %SSBO_m4x2f16 BufferBlock\n"
16268 		"OpDecorate %SSBO_m4x3f16 BufferBlock\n"
16269 		"OpDecorate %SSBO_m4x4f16 BufferBlock\n"
16270 
16271 		"OpMemberDecorate %SSBO_m2x2f16 0 ColMajor\n"
16272 		"OpMemberDecorate %SSBO_m2x3f16 0 ColMajor\n"
16273 		"OpMemberDecorate %SSBO_m2x4f16 0 ColMajor\n"
16274 		"OpMemberDecorate %SSBO_m3x2f16 0 ColMajor\n"
16275 		"OpMemberDecorate %SSBO_m3x3f16 0 ColMajor\n"
16276 		"OpMemberDecorate %SSBO_m3x4f16 0 ColMajor\n"
16277 		"OpMemberDecorate %SSBO_m4x2f16 0 ColMajor\n"
16278 		"OpMemberDecorate %SSBO_m4x3f16 0 ColMajor\n"
16279 		"OpMemberDecorate %SSBO_m4x4f16 0 ColMajor\n"
16280 
16281 		"OpMemberDecorate %SSBO_m2x2f16 0 MatrixStride 4\n"
16282 		"OpMemberDecorate %SSBO_m2x3f16 0 MatrixStride 8\n"
16283 		"OpMemberDecorate %SSBO_m2x4f16 0 MatrixStride 8\n"
16284 		"OpMemberDecorate %SSBO_m3x2f16 0 MatrixStride 4\n"
16285 		"OpMemberDecorate %SSBO_m3x3f16 0 MatrixStride 8\n"
16286 		"OpMemberDecorate %SSBO_m3x4f16 0 MatrixStride 8\n"
16287 		"OpMemberDecorate %SSBO_m4x2f16 0 MatrixStride 4\n"
16288 		"OpMemberDecorate %SSBO_m4x3f16 0 MatrixStride 8\n"
16289 		"OpMemberDecorate %SSBO_m4x4f16 0 MatrixStride 8\n"
16290 
16291 		"${arg_decorations}"
16292 	);
16293 
16294 	const StringTemplate testFun
16295 	(
16296 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
16297 		"    %param = OpFunctionParameter %v4f32\n"
16298 		"    %entry = OpLabel\n"
16299 
16300 		"        %i = OpVariable %fp_i32 Function\n"
16301 		"${arg_infunc_vars}"
16302 		"             OpStore %i %c_i32_0\n"
16303 		"             OpBranch %loop\n"
16304 
16305 		"     %loop = OpLabel\n"
16306 		"    %i_cmp = OpLoad %i32 %i\n"
16307 		"       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
16308 		"             OpLoopMerge %merge %next None\n"
16309 		"             OpBranchConditional %lt %write %merge\n"
16310 
16311 		"    %write = OpLabel\n"
16312 		"      %ndx = OpLoad %i32 %i\n"
16313 
16314 		"${arg_func_call}"
16315 
16316 		"             OpBranch %next\n"
16317 
16318 		"     %next = OpLabel\n"
16319 		"    %i_cur = OpLoad %i32 %i\n"
16320 		"    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
16321 		"             OpStore %i %i_new\n"
16322 		"             OpBranch %loop\n"
16323 
16324 		"    %merge = OpLabel\n"
16325 		"             OpReturnValue %param\n"
16326 		"             OpFunctionEnd\n"
16327 	);
16328 
16329 	const Math16ArgFragments	argFragment1	=
16330 	{
16331 		"     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16332 		" %val_src0 = OpLoad %${t0} %src0\n"
16333 		"  %val_dst = ${op} %${tr} ${ext_inst} %val_src0\n"
16334 		"      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16335 		"             OpStore %dst %val_dst\n",
16336 		"",
16337 		"",
16338 		"",
16339 	};
16340 
16341 	const Math16ArgFragments	argFragment2	=
16342 	{
16343 		"     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16344 		" %val_src0 = OpLoad %${t0} %src0\n"
16345 		"     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16346 		" %val_src1 = OpLoad %${t1} %src1\n"
16347 		"  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1\n"
16348 		"      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16349 		"             OpStore %dst %val_dst\n",
16350 		"",
16351 		"",
16352 		"",
16353 	};
16354 
16355 	const Math16ArgFragments	argFragment3	=
16356 	{
16357 		"     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16358 		" %val_src0 = OpLoad %${t0} %src0\n"
16359 		"     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16360 		" %val_src1 = OpLoad %${t1} %src1\n"
16361 		"     %src2 = OpAccessChain %up_${t2} %ssbo_src2 %c_i32_0 %ndx\n"
16362 		" %val_src2 = OpLoad %${t2} %src2\n"
16363 		"  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1 %val_src2\n"
16364 		"      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16365 		"             OpStore %dst %val_dst\n",
16366 		"",
16367 		"",
16368 		"",
16369 	};
16370 
16371 	const Math16ArgFragments	argFragmentLdExp	=
16372 	{
16373 		"     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16374 		" %val_src0 = OpLoad %${t0} %src0\n"
16375 		"     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16376 		" %val_src1 = OpLoad %${t1} %src1\n"
16377 		"%val_src1i = OpConvertFToS %${dr}i32 %val_src1\n"
16378 		"  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1i\n"
16379 		"      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16380 		"             OpStore %dst %val_dst\n",
16381 
16382 		"",
16383 
16384 		"",
16385 
16386 		"",
16387 	};
16388 
16389 	const Math16ArgFragments	argFragmentModfFrac	=
16390 	{
16391 		"     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16392 		" %val_src0 = OpLoad %${t0} %src0\n"
16393 		"  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %tmp\n"
16394 		"      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16395 		"             OpStore %dst %val_dst\n",
16396 
16397 		"   %fp_tmp = OpTypePointer Function %${tr}\n",
16398 
16399 		"",
16400 
16401 		"      %tmp = OpVariable %fp_tmp Function\n",
16402 	};
16403 
16404 	const Math16ArgFragments	argFragmentModfInt	=
16405 	{
16406 		"     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16407 		" %val_src0 = OpLoad %${t0} %src0\n"
16408 		"%val_dummy = ${op} %${tr} ${ext_inst} %val_src0 %tmp\n"
16409 		"     %tmp0 = OpAccessChain %fp_tmp %tmp\n"
16410 		"  %val_dst = OpLoad %${tr} %tmp0\n"
16411 		"      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16412 		"             OpStore %dst %val_dst\n",
16413 
16414 		"   %fp_tmp = OpTypePointer Function %${tr}\n",
16415 
16416 		"",
16417 
16418 		"      %tmp = OpVariable %fp_tmp Function\n",
16419 	};
16420 
16421 	const Math16ArgFragments	argFragmentModfStruct	=
16422 	{
16423 		"     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16424 		" %val_src0 = OpLoad %${t0} %src0\n"
16425 		"  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16426 		"%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16427 		"             OpStore %tmp_ptr_s %val_tmp\n"
16428 		"%tmp_ptr_l = OpAccessChain %fp_${tr} %tmp %c_${struct_member}\n"
16429 		"  %val_dst = OpLoad %${tr} %tmp_ptr_l\n"
16430 		"      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16431 		"             OpStore %dst %val_dst\n",
16432 
16433 		"  %fp_${tr} = OpTypePointer Function %${tr}\n"
16434 		"   %st_tmp = OpTypeStruct %${tr} %${tr}\n"
16435 		"   %fp_tmp = OpTypePointer Function %st_tmp\n"
16436 		"   %c_frac = OpConstant %i32 0\n"
16437 		"    %c_int = OpConstant %i32 1\n",
16438 
16439 		"OpMemberDecorate %st_tmp 0 Offset 0\n"
16440 		"OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16441 
16442 		"      %tmp = OpVariable %fp_tmp Function\n",
16443 	};
16444 
16445 	const Math16ArgFragments	argFragmentFrexpStructS	=
16446 	{
16447 		"     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16448 		" %val_src0 = OpLoad %${t0} %src0\n"
16449 		"  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16450 		"%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16451 		"             OpStore %tmp_ptr_s %val_tmp\n"
16452 		"%tmp_ptr_l = OpAccessChain %fp_${tr} %tmp %c_i32_0\n"
16453 		"  %val_dst = OpLoad %${tr} %tmp_ptr_l\n"
16454 		"      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16455 		"             OpStore %dst %val_dst\n",
16456 
16457 		"  %fp_${tr} = OpTypePointer Function %${tr}\n"
16458 		"   %st_tmp = OpTypeStruct %${tr} %${dr}i32\n"
16459 		"   %fp_tmp = OpTypePointer Function %st_tmp\n",
16460 
16461 		"OpMemberDecorate %st_tmp 0 Offset 0\n"
16462 		"OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16463 
16464 		"      %tmp = OpVariable %fp_tmp Function\n",
16465 	};
16466 
16467 	const Math16ArgFragments	argFragmentFrexpStructE	=
16468 	{
16469 		"     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16470 		" %val_src0 = OpLoad %${t0} %src0\n"
16471 		"  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16472 		"%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16473 		"             OpStore %tmp_ptr_s %val_tmp\n"
16474 		"%tmp_ptr_l = OpAccessChain %fp_${dr}i32 %tmp %c_i32_1\n"
16475 		"%val_dst_i = OpLoad %${dr}i32 %tmp_ptr_l\n"
16476 		"  %val_dst = OpConvertSToF %${tr} %val_dst_i\n"
16477 		"      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16478 		"             OpStore %dst %val_dst\n",
16479 
16480 		"   %st_tmp = OpTypeStruct %${tr} %${dr}i32\n"
16481 		"   %fp_tmp = OpTypePointer Function %st_tmp\n",
16482 
16483 		"OpMemberDecorate %st_tmp 0 Offset 0\n"
16484 		"OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16485 
16486 		"      %tmp = OpVariable %fp_tmp Function\n",
16487 	};
16488 
16489 	const Math16ArgFragments	argFragmentFrexpS		=
16490 	{
16491 		"     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16492 		" %val_src0 = OpLoad %${t0} %src0\n"
16493 		"  %out_exp = OpAccessChain %fp_${dr}i32 %tmp\n"
16494 		"  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %out_exp\n"
16495 		"      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16496 		"             OpStore %dst %val_dst\n",
16497 
16498 		"",
16499 
16500 		"",
16501 
16502 		"      %tmp = OpVariable %fp_${dr}i32 Function\n",
16503 	};
16504 
16505 	const Math16ArgFragments	argFragmentFrexpE		=
16506 	{
16507 		"     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16508 		" %val_src0 = OpLoad %${t0} %src0\n"
16509 		"  %out_exp = OpAccessChain %fp_${dr}i32 %tmp\n"
16510 		"%val_dummy = ${op} %${tr} ${ext_inst} %val_src0 %out_exp\n"
16511 		"%val_dst_i = OpLoad %${dr}i32 %out_exp\n"
16512 		"  %val_dst = OpConvertSToF %${tr} %val_dst_i\n"
16513 		"      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16514 		"             OpStore %dst %val_dst\n",
16515 
16516 		"",
16517 
16518 		"",
16519 
16520 		"      %tmp = OpVariable %fp_${dr}i32 Function\n",
16521 	};
16522 
16523 	const Math16TestType&		testType				= testTypes[testTypeIdx];
16524 	const string				funcNameString			= string(testFunc.funcName) + string(testFunc.funcSuffix);
16525 	const string				testName				= de::toLower(funcNameString);
16526 	const Math16ArgFragments*	argFragments			= DE_NULL;
16527 	const size_t				typeStructStride		= testType.typeStructStride;
16528 	const bool					extInst					= !(testFunc.funcName[0] == 'O' && testFunc.funcName[1] == 'p');
16529 	const size_t				numFloatsPerArg0Type	= testTypes[testFunc.typeArg0].typeArrayStride / sizeof(deFloat16);
16530 	const size_t				iterations				= numDataPoints / numFloatsPerArg0Type;
16531 	const size_t				numFloatsPerResultType	= testTypes[testFunc.typeResult].typeArrayStride / sizeof(deFloat16);
16532 	const vector<deFloat16>		float16DummyOutput		(iterations * numFloatsPerResultType, 0);
16533 	VulkanFeatures				features;
16534 	SpecResource				specResource;
16535 	map<string, string>			specs;
16536 	map<string, string>			fragments;
16537 	vector<string>				extensions;
16538 	string						funcCall;
16539 	string						funcVariables;
16540 	string						variables;
16541 	string						declarations;
16542 	string						decorations;
16543 
16544 	switch (testFunc.funcArgsCount)
16545 	{
16546 		case 1:
16547 		{
16548 			argFragments = &argFragment1;
16549 
16550 			if (funcNameString == "ModfFrac")		argFragments = &argFragmentModfFrac;
16551 			if (funcNameString == "ModfInt")		argFragments = &argFragmentModfInt;
16552 			if (funcNameString == "ModfStructFrac")	argFragments = &argFragmentModfStruct;
16553 			if (funcNameString == "ModfStructInt")	argFragments = &argFragmentModfStruct;
16554 			if (funcNameString == "FrexpS")			argFragments = &argFragmentFrexpS;
16555 			if (funcNameString == "FrexpE")			argFragments = &argFragmentFrexpE;
16556 			if (funcNameString == "FrexpStructS")	argFragments = &argFragmentFrexpStructS;
16557 			if (funcNameString == "FrexpStructE")	argFragments = &argFragmentFrexpStructE;
16558 
16559 			break;
16560 		}
16561 		case 2:
16562 		{
16563 			argFragments = &argFragment2;
16564 
16565 			if (funcNameString == "Ldexp")			argFragments = &argFragmentLdExp;
16566 
16567 			break;
16568 		}
16569 		case 3:
16570 		{
16571 			argFragments = &argFragment3;
16572 
16573 			break;
16574 		}
16575 		default:
16576 		{
16577 			TCU_THROW(InternalError, "Invalid number of arguments");
16578 		}
16579 	}
16580 
16581 	if (testFunc.funcArgsCount == 1)
16582 	{
16583 		variables +=
16584 			" %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16585 			"  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16586 
16587 		decorations +=
16588 			"OpDecorate %ssbo_src0 DescriptorSet 0\n"
16589 			"OpDecorate %ssbo_src0 Binding 0\n"
16590 			"OpDecorate %ssbo_dst DescriptorSet 0\n"
16591 			"OpDecorate %ssbo_dst Binding 1\n";
16592 	}
16593 	else if (testFunc.funcArgsCount == 2)
16594 	{
16595 		variables +=
16596 			" %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16597 			" %ssbo_src1 = OpVariable %up_SSBO_${t1} Uniform\n"
16598 			"  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16599 
16600 		decorations +=
16601 			"OpDecorate %ssbo_src0 DescriptorSet 0\n"
16602 			"OpDecorate %ssbo_src0 Binding 0\n"
16603 			"OpDecorate %ssbo_src1 DescriptorSet 0\n"
16604 			"OpDecorate %ssbo_src1 Binding 1\n"
16605 			"OpDecorate %ssbo_dst DescriptorSet 0\n"
16606 			"OpDecorate %ssbo_dst Binding 2\n";
16607 	}
16608 	else if (testFunc.funcArgsCount == 3)
16609 	{
16610 		variables +=
16611 			" %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16612 			" %ssbo_src1 = OpVariable %up_SSBO_${t1} Uniform\n"
16613 			" %ssbo_src2 = OpVariable %up_SSBO_${t2} Uniform\n"
16614 			"  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16615 
16616 		decorations +=
16617 			"OpDecorate %ssbo_src0 DescriptorSet 0\n"
16618 			"OpDecorate %ssbo_src0 Binding 0\n"
16619 			"OpDecorate %ssbo_src1 DescriptorSet 0\n"
16620 			"OpDecorate %ssbo_src1 Binding 1\n"
16621 			"OpDecorate %ssbo_src2 DescriptorSet 0\n"
16622 			"OpDecorate %ssbo_src2 Binding 2\n"
16623 			"OpDecorate %ssbo_dst DescriptorSet 0\n"
16624 			"OpDecorate %ssbo_dst Binding 3\n";
16625 	}
16626 	else
16627 	{
16628 		TCU_THROW(InternalError, "Invalid number of function arguments");
16629 	}
16630 
16631 	variables	+= argFragments->variables;
16632 	decorations	+= argFragments->decorations;
16633 
16634 	specs["dr"]					= testTypes[testFunc.typeResult].typePrefix;
16635 	specs["d0"]					= testTypes[testFunc.typeArg0].typePrefix;
16636 	specs["d1"]					= testTypes[testFunc.typeArg1].typePrefix;
16637 	specs["d2"]					= testTypes[testFunc.typeArg2].typePrefix;
16638 	specs["tr"]					= string(testTypes[testFunc.typeResult].typePrefix) + componentType;
16639 	specs["t0"]					= string(testTypes[testFunc.typeArg0].typePrefix) + componentType;
16640 	specs["t1"]					= string(testTypes[testFunc.typeArg1].typePrefix) + componentType;
16641 	specs["t2"]					= string(testTypes[testFunc.typeArg2].typePrefix) + componentType;
16642 	specs["struct_stride"]		= de::toString(typeStructStride);
16643 	specs["op"]					= extInst ? "OpExtInst" : testFunc.funcName;
16644 	specs["ext_inst"]			= extInst ? string("%ext_import ") + testFunc.funcName : "";
16645 	specs["struct_member"]		= de::toLower(testFunc.funcSuffix);
16646 
16647 	variables					= StringTemplate(variables).specialize(specs);
16648 	decorations					= StringTemplate(decorations).specialize(specs);
16649 	funcVariables				= StringTemplate(argFragments->funcVariables).specialize(specs);
16650 	funcCall					= StringTemplate(argFragments->bodies).specialize(specs);
16651 
16652 	specs["num_data_points"]	= de::toString(iterations);
16653 	specs["arg_vars"]			= variables;
16654 	specs["arg_decorations"]	= decorations;
16655 	specs["arg_infunc_vars"]	= funcVariables;
16656 	specs["arg_func_call"]		= funcCall;
16657 
16658 	fragments["extension"]		= "OpExtension \"SPV_KHR_16bit_storage\"\n%ext_import = OpExtInstImport \"GLSL.std.450\"";
16659 	fragments["capability"]		= "OpCapability Matrix\nOpCapability StorageUniformBufferBlock16";
16660 	fragments["decoration"]		= decoration.specialize(specs);
16661 	fragments["pre_main"]		= preMain.specialize(specs);
16662 	fragments["testfun"]		= testFun.specialize(specs);
16663 
16664 	for (size_t inputArgNdx = 0; inputArgNdx < testFunc.funcArgsCount; ++inputArgNdx)
16665 	{
16666 		const size_t			numFloatsPerItem	= (inputArgNdx == 0) ? testTypes[testFunc.typeArg0].typeArrayStride / sizeof(deFloat16)
16667 													: (inputArgNdx == 1) ? testTypes[testFunc.typeArg1].typeArrayStride / sizeof(deFloat16)
16668 													: (inputArgNdx == 2) ? testTypes[testFunc.typeArg2].typeArrayStride / sizeof(deFloat16)
16669 													: -1;
16670 		const vector<deFloat16>	inputData			= testFunc.getInputDataFunc(seed, numFloatsPerItem * iterations, testTypeIdx, numFloatsPerItem, testFunc.funcArgsCount, inputArgNdx);
16671 
16672 		specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(inputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
16673 	}
16674 
16675 	specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16DummyOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
16676 	specResource.verifyIO = testFunc.verifyFunc;
16677 
16678 	extensions.push_back("VK_KHR_16bit_storage");
16679 	extensions.push_back("VK_KHR_shader_float16_int8");
16680 
16681 	features.ext16BitStorage	= EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
16682 	features.extFloat16Int8		= EXTFLOAT16INT8FEATURES_FLOAT16;
16683 
16684 	finalizeTestsCreation(specResource, fragments, testCtx, testGroup, testName, features, extensions, IVec3(1, 1, 1));
16685 }
16686 
16687 template<size_t C, class SpecResource>
createFloat16ArithmeticSet(tcu::TestContext & testCtx)16688 tcu::TestCaseGroup* createFloat16ArithmeticSet (tcu::TestContext& testCtx)
16689 {
16690 	DE_STATIC_ASSERT(C >= 1 && C <= 4);
16691 
16692 	const std::string				testGroupName	(string("arithmetic_") + de::toString(C));
16693 	de::MovePtr<tcu::TestCaseGroup>	testGroup		(new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Float 16 arithmetic and related tests"));
16694 	const Math16TestFunc			testFuncs[]		=
16695 	{
16696 		{	"OpFNegate",			"",			1,	C,		C,		0,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16OpFNegate>					},
16697 		{	"Round",				"",			1,	C,		C,		0,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Round>						},
16698 		{	"RoundEven",			"",			1,	C,		C,		0,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16RoundEven>					},
16699 		{	"Trunc",				"",			1,	C,		C,		0,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Trunc>						},
16700 		{	"FAbs",					"",			1,	C,		C,		0,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FAbs>						},
16701 		{	"FSign",				"",			1,	C,		C,		0,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FSign>						},
16702 		{	"Floor",				"",			1,	C,		C,		0,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Floor>						},
16703 		{	"Ceil",					"",			1,	C,		C,		0,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Ceil>						},
16704 		{	"Fract",				"",			1,	C,		C,		0,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Fract>						},
16705 		{	"Radians",				"",			1,	C,		C,		0,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Radians>						},
16706 		{	"Degrees",				"",			1,	C,		C,		0,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Degrees>						},
16707 		{	"Sin",					"",			1,	C,		C,		0,		0, &getInputDataPI,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sin>							},
16708 		{	"Cos",					"",			1,	C,		C,		0,		0, &getInputDataPI,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Cos>							},
16709 		{	"Tan",					"",			1,	C,		C,		0,		0, &getInputDataPI,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Tan>							},
16710 		{	"Asin",					"",			1,	C,		C,		0,		0, &getInputDataA,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Asin>						},
16711 		{	"Acos",					"",			1,	C,		C,		0,		0, &getInputDataA,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Acos>						},
16712 		{	"Atan",					"",			1,	C,		C,		0,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Atan>						},
16713 		{	"Sinh",					"",			1,	C,		C,		0,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sinh>						},
16714 		{	"Cosh",					"",			1,	C,		C,		0,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Cosh>						},
16715 		{	"Tanh",					"",			1,	C,		C,		0,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Tanh>						},
16716 		{	"Asinh",				"",			1,	C,		C,		0,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Asinh>						},
16717 		{	"Acosh",				"",			1,	C,		C,		0,		0, &getInputDataAC,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Acosh>						},
16718 		{	"Atanh",				"",			1,	C,		C,		0,		0, &getInputDataA,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Atanh>						},
16719 		{	"Exp",					"",			1,	C,		C,		0,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Exp>							},
16720 		{	"Log",					"",			1,	C,		C,		0,		0, &getInputDataP,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Log>							},
16721 		{	"Exp2",					"",			1,	C,		C,		0,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Exp2>						},
16722 		{	"Log2",					"",			1,	C,		C,		0,		0, &getInputDataP,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Log2>						},
16723 		{	"Sqrt",					"",			1,	C,		C,		0,		0, &getInputDataP,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sqrt>						},
16724 		{	"InverseSqrt",			"",			1,	C,		C,		0,		0, &getInputDataP,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16InverseSqrt>					},
16725 		{	"Modf",					"Frac",		1,	C,		C,		0,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfFrac>					},
16726 		{	"Modf",					"Int",		1,	C,		C,		0,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfInt>						},
16727 		{	"ModfStruct",			"Frac",		1,	C,		C,		0,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfFrac>					},
16728 		{	"ModfStruct",			"Int",		1,	C,		C,		0,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfInt>						},
16729 		{	"Frexp",				"S",		1,	C,		C,		0,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpS>						},
16730 		{	"Frexp",				"E",		1,	C,		C,		0,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpE>						},
16731 		{	"FrexpStruct",			"S",		1,	C,		C,		0,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpS>						},
16732 		{	"FrexpStruct",			"E",		1,	C,		C,		0,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpE>						},
16733 		{	"OpFAdd",				"",			2,	C,		C,		C,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFAdd>						},
16734 		{	"OpFSub",				"",			2,	C,		C,		C,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFSub>						},
16735 		{	"OpFMul",				"",			2,	C,		C,		C,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFMul>						},
16736 		{	"OpFDiv",				"",			2,	C,		C,		C,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFDiv>						},
16737 		{	"Atan2",				"",			2,	C,		C,		C,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Atan2>						},
16738 		{	"Pow",					"",			2,	C,		C,		C,		0, &getInputDataP,	compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Pow>							},
16739 		{	"FMin",					"",			2,	C,		C,		C,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16FMin>						},
16740 		{	"FMax",					"",			2,	C,		C,		C,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16FMax>						},
16741 		{	"Step",					"",			2,	C,		C,		C,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Step>						},
16742 		{	"Ldexp",				"",			2,	C,		C,		C,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Ldexp>						},
16743 		{	"FClamp",				"",			3,	C,		C,		C,		C, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FClamp>						},
16744 		{	"FMix",					"",			3,	C,		C,		C,		C, &getInputDataD,	compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FMix>						},
16745 		{	"SmoothStep",			"",			3,	C,		C,		C,		C, &getInputDataSS,	compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16SmoothStep>					},
16746 		{	"Fma",					"",			3,	C,		C,		C,		C, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16Fma>							},
16747 		{	"Length",				"",			1,	1,		C,		0,		0, &getInputData,	compareFP16ArithmeticFunc<  1,  C,  0,  0, fp16Length>						},
16748 		{	"Distance",				"",			2,	1,		C,		C,		0, &getInputData,	compareFP16ArithmeticFunc<  1,  C,  C,  0, fp16Distance>					},
16749 		{	"Cross",				"",			2,	C,		C,		C,		0, &getInputDataD,	compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Cross>						},
16750 		{	"Normalize",			"",			1,	C,		C,		0,		0, &getInputData,	compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Normalize>					},
16751 		{	"FaceForward",			"",			3,	C,		C,		C,		C, &getInputDataD,	compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FaceForward>					},
16752 		{	"Reflect",				"",			2,	C,		C,		C,		0, &getInputDataD,	compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Reflect>						},
16753 		{	"Refract",				"",			3,	C,		C,		C,		1, &getInputDataN,	compareFP16ArithmeticFunc<  C,  C,  C,  1, fp16Refract>						},
16754 		{	"OpDot",				"",			2,	1,		C,		C,		0, &getInputDataD,	compareFP16ArithmeticFunc<  1,  C,  C,  0, fp16Dot>							},
16755 		{	"OpVectorTimesScalar",	"",			2,	C,		C,		1,		0, &getInputDataV,	compareFP16ArithmeticFunc<  C,  C,  1,  0, fp16VectorTimesScalar>			},
16756 	};
16757 
16758 	for (deUint32 testFuncIdx = 0; testFuncIdx < DE_LENGTH_OF_ARRAY(testFuncs); ++testFuncIdx)
16759 	{
16760 		const Math16TestFunc&	testFunc		= testFuncs[testFuncIdx];
16761 		const string			funcNameString	= testFunc.funcName;
16762 
16763 		if ((C != 3) && funcNameString == "Cross")
16764 			continue;
16765 
16766 		if ((C < 2) && funcNameString == "OpDot")
16767 			continue;
16768 
16769 		if ((C < 2) && funcNameString == "OpVectorTimesScalar")
16770 			continue;
16771 
16772 		createFloat16ArithmeticFuncTest<SpecResource>(testCtx, *testGroup.get(), C, testFunc);
16773 	}
16774 
16775 	return testGroup.release();
16776 }
16777 
16778 template<class SpecResource>
createFloat16ArithmeticSet(tcu::TestContext & testCtx)16779 tcu::TestCaseGroup* createFloat16ArithmeticSet (tcu::TestContext& testCtx)
16780 {
16781 	const std::string				testGroupName	("arithmetic");
16782 	de::MovePtr<tcu::TestCaseGroup>	testGroup		(new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Float 16 arithmetic and related tests"));
16783 	const Math16TestFunc			testFuncs[]		=
16784 	{
16785 		{	"OpTranspose",			"2x2",		1,	MAT2X2,	MAT2X2,	0,		0, &getInputDataM,	compareFP16ArithmeticFunc<  4,  4,  0,  0, fp16Transpose<2,2> >				},
16786 		{	"OpTranspose",			"3x2",		1,	MAT2X3,	MAT3X2,	0,		0, &getInputDataM,	compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<3,2> >				},
16787 		{	"OpTranspose",			"4x2",		1,	MAT2X4,	MAT4X2,	0,		0, &getInputDataM,	compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<4,2> >				},
16788 		{	"OpTranspose",			"2x3",		1,	MAT3X2,	MAT2X3,	0,		0, &getInputDataM,	compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<2,3> >				},
16789 		{	"OpTranspose",			"3x3",		1,	MAT3X3,	MAT3X3,	0,		0, &getInputDataM,	compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<3,3> >				},
16790 		{	"OpTranspose",			"4x3",		1,	MAT3X4,	MAT4X3,	0,		0, &getInputDataM,	compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<4,3> >				},
16791 		{	"OpTranspose",			"2x4",		1,	MAT4X2,	MAT2X4,	0,		0, &getInputDataM,	compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<2,4> >				},
16792 		{	"OpTranspose",			"3x4",		1,	MAT4X3,	MAT3X4,	0,		0, &getInputDataM,	compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<3,4> >				},
16793 		{	"OpTranspose",			"4x4",		1,	MAT4X4,	MAT4X4,	0,		0, &getInputDataM,	compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<4,4> >				},
16794 		{	"OpMatrixTimesScalar",	"2x2",		2,	MAT2X2,	MAT2X2,	1,		0, &getInputDataD,	compareFP16ArithmeticFunc<  4,  4,  1,  0, fp16MatrixTimesScalar<2,2> >		},
16795 		{	"OpMatrixTimesScalar",	"2x3",		2,	MAT2X3,	MAT2X3,	1,		0, &getInputDataD,	compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<2,3> >		},
16796 		{	"OpMatrixTimesScalar",	"2x4",		2,	MAT2X4,	MAT2X4,	1,		0, &getInputDataD,	compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<2,4> >		},
16797 		{	"OpMatrixTimesScalar",	"3x2",		2,	MAT3X2,	MAT3X2,	1,		0, &getInputDataD,	compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<3,2> >		},
16798 		{	"OpMatrixTimesScalar",	"3x3",		2,	MAT3X3,	MAT3X3,	1,		0, &getInputDataD,	compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<3,3> >		},
16799 		{	"OpMatrixTimesScalar",	"3x4",		2,	MAT3X4,	MAT3X4,	1,		0, &getInputDataD,	compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<3,4> >		},
16800 		{	"OpMatrixTimesScalar",	"4x2",		2,	MAT4X2,	MAT4X2,	1,		0, &getInputDataD,	compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<4,2> >		},
16801 		{	"OpMatrixTimesScalar",	"4x3",		2,	MAT4X3,	MAT4X3,	1,		0, &getInputDataD,	compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<4,3> >		},
16802 		{	"OpMatrixTimesScalar",	"4x4",		2,	MAT4X4,	MAT4X4,	1,		0, &getInputDataD,	compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<4,4> >		},
16803 		{	"OpVectorTimesMatrix",	"2x2",		2,	VEC2,	VEC2,	MAT2X2,	0, &getInputDataD,	compareFP16ArithmeticFunc<  2,  2,  4,  0, fp16VectorTimesMatrix<2,2> >		},
16804 		{	"OpVectorTimesMatrix",	"2x3",		2,	VEC2,	VEC3,	MAT2X3,	0, &getInputDataD,	compareFP16ArithmeticFunc<  2,  3,  8,  0, fp16VectorTimesMatrix<2,3> >		},
16805 		{	"OpVectorTimesMatrix",	"2x4",		2,	VEC2,	VEC4,	MAT2X4,	0, &getInputDataD,	compareFP16ArithmeticFunc<  2,  4,  8,  0, fp16VectorTimesMatrix<2,4> >		},
16806 		{	"OpVectorTimesMatrix",	"3x2",		2,	VEC3,	VEC2,	MAT3X2,	0, &getInputDataD,	compareFP16ArithmeticFunc<  3,  2,  8,  0, fp16VectorTimesMatrix<3,2> >		},
16807 		{	"OpVectorTimesMatrix",	"3x3",		2,	VEC3,	VEC3,	MAT3X3,	0, &getInputDataD,	compareFP16ArithmeticFunc<  3,  3, 16,  0, fp16VectorTimesMatrix<3,3> >		},
16808 		{	"OpVectorTimesMatrix",	"3x4",		2,	VEC3,	VEC4,	MAT3X4,	0, &getInputDataD,	compareFP16ArithmeticFunc<  3,  4, 16,  0, fp16VectorTimesMatrix<3,4> >		},
16809 		{	"OpVectorTimesMatrix",	"4x2",		2,	VEC4,	VEC2,	MAT4X2,	0, &getInputDataD,	compareFP16ArithmeticFunc<  4,  2,  8,  0, fp16VectorTimesMatrix<4,2> >		},
16810 		{	"OpVectorTimesMatrix",	"4x3",		2,	VEC4,	VEC3,	MAT4X3,	0, &getInputDataD,	compareFP16ArithmeticFunc<  4,  3, 16,  0, fp16VectorTimesMatrix<4,3> >		},
16811 		{	"OpVectorTimesMatrix",	"4x4",		2,	VEC4,	VEC4,	MAT4X4,	0, &getInputDataD,	compareFP16ArithmeticFunc<  4,  4, 16,  0, fp16VectorTimesMatrix<4,4> >		},
16812 		{	"OpMatrixTimesVector",	"2x2",		2,	VEC2,	MAT2X2,	VEC2,	0, &getInputDataD,	compareFP16ArithmeticFunc<  2,  4,  2,  0, fp16MatrixTimesVector<2,2> >		},
16813 		{	"OpMatrixTimesVector",	"2x3",		2,	VEC3,	MAT2X3,	VEC2,	0, &getInputDataD,	compareFP16ArithmeticFunc<  3,  8,  2,  0, fp16MatrixTimesVector<2,3> >		},
16814 		{	"OpMatrixTimesVector",	"2x4",		2,	VEC4,	MAT2X4,	VEC2,	0, &getInputDataD,	compareFP16ArithmeticFunc<  4,  8,  2,  0, fp16MatrixTimesVector<2,4> >		},
16815 		{	"OpMatrixTimesVector",	"3x2",		2,	VEC2,	MAT3X2,	VEC3,	0, &getInputDataD,	compareFP16ArithmeticFunc<  2,  8,  3,  0, fp16MatrixTimesVector<3,2> >		},
16816 		{	"OpMatrixTimesVector",	"3x3",		2,	VEC3,	MAT3X3,	VEC3,	0, &getInputDataD,	compareFP16ArithmeticFunc<  3, 16,  3,  0, fp16MatrixTimesVector<3,3> >		},
16817 		{	"OpMatrixTimesVector",	"3x4",		2,	VEC4,	MAT3X4,	VEC3,	0, &getInputDataD,	compareFP16ArithmeticFunc<  4, 16,  3,  0, fp16MatrixTimesVector<3,4> >		},
16818 		{	"OpMatrixTimesVector",	"4x2",		2,	VEC2,	MAT4X2,	VEC4,	0, &getInputDataD,	compareFP16ArithmeticFunc<  2,  8,  4,  0, fp16MatrixTimesVector<4,2> >		},
16819 		{	"OpMatrixTimesVector",	"4x3",		2,	VEC3,	MAT4X3,	VEC4,	0, &getInputDataD,	compareFP16ArithmeticFunc<  3, 16,  4,  0, fp16MatrixTimesVector<4,3> >		},
16820 		{	"OpMatrixTimesVector",	"4x4",		2,	VEC4,	MAT4X4,	VEC4,	0, &getInputDataD,	compareFP16ArithmeticFunc<  4, 16,  4,  0, fp16MatrixTimesVector<4,4> >		},
16821 		{	"OpMatrixTimesMatrix",	"2x2_2x2",	2,	MAT2X2,	MAT2X2,	MAT2X2,	0, &getInputDataD,	compareFP16ArithmeticFunc<  4,  4,  4,  0, fp16MatrixTimesMatrix<2,2,2,2> >	},
16822 		{	"OpMatrixTimesMatrix",	"2x2_3x2",	2,	MAT3X2,	MAT2X2,	MAT3X2,	0, &getInputDataD,	compareFP16ArithmeticFunc<  8,  4,  8,  0, fp16MatrixTimesMatrix<2,2,3,2> >	},
16823 		{	"OpMatrixTimesMatrix",	"2x2_4x2",	2,	MAT4X2,	MAT2X2,	MAT4X2,	0, &getInputDataD,	compareFP16ArithmeticFunc<  8,  4,  8,  0, fp16MatrixTimesMatrix<2,2,4,2> >	},
16824 		{	"OpMatrixTimesMatrix",	"2x3_2x2",	2,	MAT2X3,	MAT2X3,	MAT2X2,	0, &getInputDataD,	compareFP16ArithmeticFunc<  8,  8,  4,  0, fp16MatrixTimesMatrix<2,3,2,2> >	},
16825 		{	"OpMatrixTimesMatrix",	"2x3_3x2",	2,	MAT3X3,	MAT2X3,	MAT3X2,	0, &getInputDataD,	compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,3,3,2> >	},
16826 		{	"OpMatrixTimesMatrix",	"2x3_4x2",	2,	MAT4X3,	MAT2X3,	MAT4X2,	0, &getInputDataD,	compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,3,4,2> >	},
16827 		{	"OpMatrixTimesMatrix",	"2x4_2x2",	2,	MAT2X4,	MAT2X4,	MAT2X2,	0, &getInputDataD,	compareFP16ArithmeticFunc<  8,  8,  4,  0, fp16MatrixTimesMatrix<2,4,2,2> >	},
16828 		{	"OpMatrixTimesMatrix",	"2x4_3x2",	2,	MAT3X4,	MAT2X4,	MAT3X2,	0, &getInputDataD,	compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,4,3,2> >	},
16829 		{	"OpMatrixTimesMatrix",	"2x4_4x2",	2,	MAT4X4,	MAT2X4,	MAT4X2,	0, &getInputDataD,	compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,4,4,2> >	},
16830 		{	"OpMatrixTimesMatrix",	"3x2_2x3",	2,	MAT2X2,	MAT3X2,	MAT2X3,	0, &getInputDataD,	compareFP16ArithmeticFunc<  4,  8,  8,  0, fp16MatrixTimesMatrix<3,2,2,3> >	},
16831 		{	"OpMatrixTimesMatrix",	"3x2_3x3",	2,	MAT3X2,	MAT3X2,	MAT3X3,	0, &getInputDataD,	compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<3,2,3,3> >	},
16832 		{	"OpMatrixTimesMatrix",	"3x2_4x3",	2,	MAT4X2,	MAT3X2,	MAT4X3,	0, &getInputDataD,	compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<3,2,4,3> >	},
16833 		{	"OpMatrixTimesMatrix",	"3x3_2x3",	2,	MAT2X3,	MAT3X3,	MAT2X3,	0, &getInputDataD,	compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<3,3,2,3> >	},
16834 		{	"OpMatrixTimesMatrix",	"3x3_3x3",	2,	MAT3X3,	MAT3X3,	MAT3X3,	0, &getInputDataD,	compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,3,3,3> >	},
16835 		{	"OpMatrixTimesMatrix",	"3x3_4x3",	2,	MAT4X3,	MAT3X3,	MAT4X3,	0, &getInputDataD,	compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,3,4,3> >	},
16836 		{	"OpMatrixTimesMatrix",	"3x4_2x3",	2,	MAT2X4,	MAT3X4,	MAT2X3,	0, &getInputDataD,	compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<3,4,2,3> >	},
16837 		{	"OpMatrixTimesMatrix",	"3x4_3x3",	2,	MAT3X4,	MAT3X4,	MAT3X3,	0, &getInputDataD,	compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,4,3,3> >	},
16838 		{	"OpMatrixTimesMatrix",	"3x4_4x3",	2,	MAT4X4,	MAT3X4,	MAT4X3,	0, &getInputDataD,	compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,4,4,3> >	},
16839 		{	"OpMatrixTimesMatrix",	"4x2_2x4",	2,	MAT2X2,	MAT4X2,	MAT2X4,	0, &getInputDataD,	compareFP16ArithmeticFunc<  4,  8,  8,  0, fp16MatrixTimesMatrix<4,2,2,4> >	},
16840 		{	"OpMatrixTimesMatrix",	"4x2_3x4",	2,	MAT3X2,	MAT4X2,	MAT3X4,	0, &getInputDataD,	compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<4,2,3,4> >	},
16841 		{	"OpMatrixTimesMatrix",	"4x2_4x4",	2,	MAT4X2,	MAT4X2,	MAT4X4,	0, &getInputDataD,	compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<4,2,4,4> >	},
16842 		{	"OpMatrixTimesMatrix",	"4x3_2x4",	2,	MAT2X3,	MAT4X3,	MAT2X4,	0, &getInputDataD,	compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<4,3,2,4> >	},
16843 		{	"OpMatrixTimesMatrix",	"4x3_3x4",	2,	MAT3X3,	MAT4X3,	MAT3X4,	0, &getInputDataD,	compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,3,3,4> >	},
16844 		{	"OpMatrixTimesMatrix",	"4x3_4x4",	2,	MAT4X3,	MAT4X3,	MAT4X4,	0, &getInputDataD,	compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,3,4,4> >	},
16845 		{	"OpMatrixTimesMatrix",	"4x4_2x4",	2,	MAT2X4,	MAT4X4,	MAT2X4,	0, &getInputDataD,	compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<4,4,2,4> >	},
16846 		{	"OpMatrixTimesMatrix",	"4x4_3x4",	2,	MAT3X4,	MAT4X4,	MAT3X4,	0, &getInputDataD,	compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,4,3,4> >	},
16847 		{	"OpMatrixTimesMatrix",	"4x4_4x4",	2,	MAT4X4,	MAT4X4,	MAT4X4,	0, &getInputDataD,	compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,4,4,4> >	},
16848 		{	"OpOuterProduct",		"2x2",		2,	MAT2X2,	VEC2,	VEC2,	0, &getInputDataD,	compareFP16ArithmeticFunc<  4,  2,  2,  0, fp16OuterProduct<2,2> >			},
16849 		{	"OpOuterProduct",		"2x3",		2,	MAT2X3,	VEC3,	VEC2,	0, &getInputDataD,	compareFP16ArithmeticFunc<  8,  3,  2,  0, fp16OuterProduct<2,3> >			},
16850 		{	"OpOuterProduct",		"2x4",		2,	MAT2X4,	VEC4,	VEC2,	0, &getInputDataD,	compareFP16ArithmeticFunc<  8,  4,  2,  0, fp16OuterProduct<2,4> >			},
16851 		{	"OpOuterProduct",		"3x2",		2,	MAT3X2,	VEC2,	VEC3,	0, &getInputDataD,	compareFP16ArithmeticFunc<  8,  2,  3,  0, fp16OuterProduct<3,2> >			},
16852 		{	"OpOuterProduct",		"3x3",		2,	MAT3X3,	VEC3,	VEC3,	0, &getInputDataD,	compareFP16ArithmeticFunc< 16,  3,  3,  0, fp16OuterProduct<3,3> >			},
16853 		{	"OpOuterProduct",		"3x4",		2,	MAT3X4,	VEC4,	VEC3,	0, &getInputDataD,	compareFP16ArithmeticFunc< 16,  4,  3,  0, fp16OuterProduct<3,4> >			},
16854 		{	"OpOuterProduct",		"4x2",		2,	MAT4X2,	VEC2,	VEC4,	0, &getInputDataD,	compareFP16ArithmeticFunc<  8,  2,  4,  0, fp16OuterProduct<4,2> >			},
16855 		{	"OpOuterProduct",		"4x3",		2,	MAT4X3,	VEC3,	VEC4,	0, &getInputDataD,	compareFP16ArithmeticFunc< 16,  3,  4,  0, fp16OuterProduct<4,3> >			},
16856 		{	"OpOuterProduct",		"4x4",		2,	MAT4X4,	VEC4,	VEC4,	0, &getInputDataD,	compareFP16ArithmeticFunc< 16,  4,  4,  0, fp16OuterProduct<4,4> >			},
16857 		{	"Determinant",			"2x2",		1,	SCALAR,	MAT2X2,	NONE,	0, &getInputDataC,	compareFP16ArithmeticFunc<  1,  4,  0,  0, fp16Determinant<2> >				},
16858 		{	"Determinant",			"3x3",		1,	SCALAR,	MAT3X3,	NONE,	0, &getInputDataC,	compareFP16ArithmeticFunc<  1, 16,  0,  0, fp16Determinant<3> >				},
16859 		{	"Determinant",			"4x4",		1,	SCALAR,	MAT4X4,	NONE,	0, &getInputDataC,	compareFP16ArithmeticFunc<  1, 16,  0,  0, fp16Determinant<4> >				},
16860 		{	"MatrixInverse",		"2x2",		1,	MAT2X2,	MAT2X2,	NONE,	0, &getInputDataC,	compareFP16ArithmeticFunc<  4,  4,  0,  0, fp16Inverse<2> >					},
16861 	};
16862 
16863 	for (deUint32 testFuncIdx = 0; testFuncIdx < DE_LENGTH_OF_ARRAY(testFuncs); ++testFuncIdx)
16864 	{
16865 		const Math16TestFunc&	testFunc	= testFuncs[testFuncIdx];
16866 
16867 		createFloat16ArithmeticFuncTest<SpecResource>(testCtx, *testGroup.get(), 0, testFunc);
16868 	}
16869 
16870 	return testGroup.release();
16871 }
16872 
getNumberTypeName(const NumberType type)16873 const string getNumberTypeName (const NumberType type)
16874 {
16875 	if (type == NUMBERTYPE_INT32)
16876 	{
16877 		return "int";
16878 	}
16879 	else if (type == NUMBERTYPE_UINT32)
16880 	{
16881 		return "uint";
16882 	}
16883 	else if (type == NUMBERTYPE_FLOAT32)
16884 	{
16885 		return "float";
16886 	}
16887 	else
16888 	{
16889 		DE_ASSERT(false);
16890 		return "";
16891 	}
16892 }
16893 
getInt(de::Random & rnd)16894 deInt32 getInt(de::Random& rnd)
16895 {
16896 	return rnd.getInt(std::numeric_limits<int>::min(), std::numeric_limits<int>::max());
16897 }
16898 
repeatString(const string & str,int times)16899 const string repeatString (const string& str, int times)
16900 {
16901 	string filler;
16902 	for (int i = 0; i < times; ++i)
16903 	{
16904 		filler += str;
16905 	}
16906 	return filler;
16907 }
16908 
getRandomConstantString(const NumberType type,de::Random & rnd)16909 const string getRandomConstantString (const NumberType type, de::Random& rnd)
16910 {
16911 	if (type == NUMBERTYPE_INT32)
16912 	{
16913 		return numberToString<deInt32>(getInt(rnd));
16914 	}
16915 	else if (type == NUMBERTYPE_UINT32)
16916 	{
16917 		return numberToString<deUint32>(rnd.getUint32());
16918 	}
16919 	else if (type == NUMBERTYPE_FLOAT32)
16920 	{
16921 		return numberToString<float>(rnd.getFloat());
16922 	}
16923 	else
16924 	{
16925 		DE_ASSERT(false);
16926 		return "";
16927 	}
16928 }
16929 
createVectorCompositeCases(vector<map<string,string>> & testCases,de::Random & rnd,const NumberType type)16930 void createVectorCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16931 {
16932 	map<string, string> params;
16933 
16934 	// Vec2 to Vec4
16935 	for (int width = 2; width <= 4; ++width)
16936 	{
16937 		const string randomConst = numberToString(getInt(rnd));
16938 		const string widthStr = numberToString(width);
16939 		const string composite_type = "${customType}vec" + widthStr;
16940 		const int index = rnd.getInt(0, width-1);
16941 
16942 		params["type"]			= "vec";
16943 		params["name"]			= params["type"] + "_" + widthStr;
16944 		params["compositeDecl"]		= composite_type + " = OpTypeVector ${customType} " + widthStr +"\n";
16945 		params["compositeType"]		= composite_type;
16946 		params["filler"]		= string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
16947 		params["compositeConstruct"]	= "%instance  = OpCompositeConstruct " + composite_type + repeatString(" %filler", width) + "\n";
16948 		params["indexes"]		= numberToString(index);
16949 		testCases.push_back(params);
16950 	}
16951 }
16952 
createArrayCompositeCases(vector<map<string,string>> & testCases,de::Random & rnd,const NumberType type)16953 void createArrayCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16954 {
16955 	const int limit = 10;
16956 	map<string, string> params;
16957 
16958 	for (int width = 2; width <= limit; ++width)
16959 	{
16960 		string randomConst = numberToString(getInt(rnd));
16961 		string widthStr = numberToString(width);
16962 		int index = rnd.getInt(0, width-1);
16963 
16964 		params["type"]			= "array";
16965 		params["name"]			= params["type"] + "_" + widthStr;
16966 		params["compositeDecl"]		= string("%arraywidth = OpConstant %u32 " + widthStr + "\n")
16967 											+	 "%composite = OpTypeArray ${customType} %arraywidth\n";
16968 		params["compositeType"]		= "%composite";
16969 		params["filler"]		= string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
16970 		params["compositeConstruct"]	= "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
16971 		params["indexes"]		= numberToString(index);
16972 		testCases.push_back(params);
16973 	}
16974 }
16975 
createStructCompositeCases(vector<map<string,string>> & testCases,de::Random & rnd,const NumberType type)16976 void createStructCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16977 {
16978 	const int limit = 10;
16979 	map<string, string> params;
16980 
16981 	for (int width = 2; width <= limit; ++width)
16982 	{
16983 		string randomConst = numberToString(getInt(rnd));
16984 		int index = rnd.getInt(0, width-1);
16985 
16986 		params["type"]			= "struct";
16987 		params["name"]			= params["type"] + "_" + numberToString(width);
16988 		params["compositeDecl"]		= "%composite = OpTypeStruct" + repeatString(" ${customType}", width) + "\n";
16989 		params["compositeType"]		= "%composite";
16990 		params["filler"]		= string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
16991 		params["compositeConstruct"]	= "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
16992 		params["indexes"]		= numberToString(index);
16993 		testCases.push_back(params);
16994 	}
16995 }
16996 
createMatrixCompositeCases(vector<map<string,string>> & testCases,de::Random & rnd,const NumberType type)16997 void createMatrixCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16998 {
16999 	map<string, string> params;
17000 
17001 	// Vec2 to Vec4
17002 	for (int width = 2; width <= 4; ++width)
17003 	{
17004 		string widthStr = numberToString(width);
17005 
17006 		for (int column = 2 ; column <= 4; ++column)
17007 		{
17008 			int index_0 = rnd.getInt(0, column-1);
17009 			int index_1 = rnd.getInt(0, width-1);
17010 			string columnStr = numberToString(column);
17011 
17012 			params["type"]		= "matrix";
17013 			params["name"]		= params["type"] + "_" + widthStr + "x" + columnStr;
17014 			params["compositeDecl"]	= string("%vectype   = OpTypeVector ${customType} " + widthStr + "\n")
17015 												+	 "%composite = OpTypeMatrix %vectype " + columnStr + "\n";
17016 			params["compositeType"]	= "%composite";
17017 
17018 			params["filler"]	= string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n"
17019 												+	 "%fillerVec = OpConstantComposite %vectype" + repeatString(" %filler", width) + "\n";
17020 
17021 			params["compositeConstruct"]	= "%instance  = OpCompositeConstruct %composite" + repeatString(" %fillerVec", column) + "\n";
17022 			params["indexes"]	= numberToString(index_0) + " " + numberToString(index_1);
17023 			testCases.push_back(params);
17024 		}
17025 	}
17026 }
17027 
createCompositeCases(vector<map<string,string>> & testCases,de::Random & rnd,const NumberType type)17028 void createCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
17029 {
17030 	createVectorCompositeCases(testCases, rnd, type);
17031 	createArrayCompositeCases(testCases, rnd, type);
17032 	createStructCompositeCases(testCases, rnd, type);
17033 	// Matrix only supports float types
17034 	if (type == NUMBERTYPE_FLOAT32)
17035 	{
17036 		createMatrixCompositeCases(testCases, rnd, type);
17037 	}
17038 }
17039 
getAssemblyTypeDeclaration(const NumberType type)17040 const string getAssemblyTypeDeclaration (const NumberType type)
17041 {
17042 	switch (type)
17043 	{
17044 		case NUMBERTYPE_INT32:		return "OpTypeInt 32 1";
17045 		case NUMBERTYPE_UINT32:		return "OpTypeInt 32 0";
17046 		case NUMBERTYPE_FLOAT32:	return "OpTypeFloat 32";
17047 		default:			DE_ASSERT(false); return "";
17048 	}
17049 }
17050 
getAssemblyTypeName(const NumberType type)17051 const string getAssemblyTypeName (const NumberType type)
17052 {
17053 	switch (type)
17054 	{
17055 		case NUMBERTYPE_INT32:		return "%i32";
17056 		case NUMBERTYPE_UINT32:		return "%u32";
17057 		case NUMBERTYPE_FLOAT32:	return "%f32";
17058 		default:			DE_ASSERT(false); return "";
17059 	}
17060 }
17061 
specializeCompositeInsertShaderTemplate(const NumberType type,const map<string,string> & params)17062 const string specializeCompositeInsertShaderTemplate (const NumberType type, const map<string, string>& params)
17063 {
17064 	map<string, string>	parameters(params);
17065 
17066 	const string customType = getAssemblyTypeName(type);
17067 	map<string, string> substCustomType;
17068 	substCustomType["customType"] = customType;
17069 	parameters["compositeDecl"] = StringTemplate(parameters.at("compositeDecl")).specialize(substCustomType);
17070 	parameters["compositeType"] = StringTemplate(parameters.at("compositeType")).specialize(substCustomType);
17071 	parameters["compositeConstruct"] = StringTemplate(parameters.at("compositeConstruct")).specialize(substCustomType);
17072 	parameters["filler"] = StringTemplate(parameters.at("filler")).specialize(substCustomType);
17073 	parameters["customType"] = customType;
17074 	parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
17075 
17076 	if (parameters.at("compositeType") != "%u32vec3")
17077 	{
17078 		parameters["u32vec3Decl"] = "%u32vec3   = OpTypeVector %u32 3\n";
17079 	}
17080 
17081 	return StringTemplate(
17082 		"OpCapability Shader\n"
17083 		"OpCapability Matrix\n"
17084 		"OpMemoryModel Logical GLSL450\n"
17085 		"OpEntryPoint GLCompute %main \"main\" %id\n"
17086 		"OpExecutionMode %main LocalSize 1 1 1\n"
17087 
17088 		"OpSource GLSL 430\n"
17089 		"OpName %main           \"main\"\n"
17090 		"OpName %id             \"gl_GlobalInvocationID\"\n"
17091 
17092 		// Decorators
17093 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
17094 		"OpDecorate %buf BufferBlock\n"
17095 		"OpDecorate %indata DescriptorSet 0\n"
17096 		"OpDecorate %indata Binding 0\n"
17097 		"OpDecorate %outdata DescriptorSet 0\n"
17098 		"OpDecorate %outdata Binding 1\n"
17099 		"OpDecorate %customarr ArrayStride 4\n"
17100 		"${compositeDecorator}"
17101 		"OpMemberDecorate %buf 0 Offset 0\n"
17102 
17103 		// General types
17104 		"%void      = OpTypeVoid\n"
17105 		"%voidf     = OpTypeFunction %void\n"
17106 		"%u32       = OpTypeInt 32 0\n"
17107 		"%i32       = OpTypeInt 32 1\n"
17108 		"%f32       = OpTypeFloat 32\n"
17109 
17110 		// Composite declaration
17111 		"${compositeDecl}"
17112 
17113 		// Constants
17114 		"${filler}"
17115 
17116 		"${u32vec3Decl:opt}"
17117 		"%uvec3ptr  = OpTypePointer Input %u32vec3\n"
17118 
17119 		// Inherited from custom
17120 		"%customptr = OpTypePointer Uniform ${customType}\n"
17121 		"%customarr = OpTypeRuntimeArray ${customType}\n"
17122 		"%buf       = OpTypeStruct %customarr\n"
17123 		"%bufptr    = OpTypePointer Uniform %buf\n"
17124 
17125 		"%indata    = OpVariable %bufptr Uniform\n"
17126 		"%outdata   = OpVariable %bufptr Uniform\n"
17127 
17128 		"%id        = OpVariable %uvec3ptr Input\n"
17129 		"%zero      = OpConstant %i32 0\n"
17130 
17131 		"%main      = OpFunction %void None %voidf\n"
17132 		"%label     = OpLabel\n"
17133 		"%idval     = OpLoad %u32vec3 %id\n"
17134 		"%x         = OpCompositeExtract %u32 %idval 0\n"
17135 
17136 		"%inloc     = OpAccessChain %customptr %indata %zero %x\n"
17137 		"%outloc    = OpAccessChain %customptr %outdata %zero %x\n"
17138 		// Read the input value
17139 		"%inval     = OpLoad ${customType} %inloc\n"
17140 		// Create the composite and fill it
17141 		"${compositeConstruct}"
17142 		// Insert the input value to a place
17143 		"%instance2 = OpCompositeInsert ${compositeType} %inval %instance ${indexes}\n"
17144 		// Read back the value from the position
17145 		"%out_val   = OpCompositeExtract ${customType} %instance2 ${indexes}\n"
17146 		// Store it in the output position
17147 		"             OpStore %outloc %out_val\n"
17148 		"             OpReturn\n"
17149 		"             OpFunctionEnd\n"
17150 	).specialize(parameters);
17151 }
17152 
17153 template<typename T>
createCompositeBuffer(T number)17154 BufferSp createCompositeBuffer(T number)
17155 {
17156 	return BufferSp(new Buffer<T>(vector<T>(1, number)));
17157 }
17158 
createOpCompositeInsertGroup(tcu::TestContext & testCtx)17159 tcu::TestCaseGroup* createOpCompositeInsertGroup (tcu::TestContext& testCtx)
17160 {
17161 	de::MovePtr<tcu::TestCaseGroup>	group	(new tcu::TestCaseGroup(testCtx, "opcompositeinsert", "Test the OpCompositeInsert instruction"));
17162 	de::Random						rnd		(deStringHash(group->getName()));
17163 
17164 	for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17165 	{
17166 		NumberType						numberType		= NumberType(type);
17167 		const string					typeName		= getNumberTypeName(numberType);
17168 		const string					description		= "Test the OpCompositeInsert instruction with " + typeName + "s";
17169 		de::MovePtr<tcu::TestCaseGroup>	subGroup		(new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17170 		vector<map<string, string> >	testCases;
17171 
17172 		createCompositeCases(testCases, rnd, numberType);
17173 
17174 		for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
17175 		{
17176 			ComputeShaderSpec	spec;
17177 
17178 			spec.assembly = specializeCompositeInsertShaderTemplate(numberType, *test);
17179 
17180 			switch (numberType)
17181 			{
17182 				case NUMBERTYPE_INT32:
17183 				{
17184 					deInt32 number = getInt(rnd);
17185 					spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17186 					spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17187 					break;
17188 				}
17189 				case NUMBERTYPE_UINT32:
17190 				{
17191 					deUint32 number = rnd.getUint32();
17192 					spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17193 					spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17194 					break;
17195 				}
17196 				case NUMBERTYPE_FLOAT32:
17197 				{
17198 					float number = rnd.getFloat();
17199 					spec.inputs.push_back(createCompositeBuffer<float>(number));
17200 					spec.outputs.push_back(createCompositeBuffer<float>(number));
17201 					break;
17202 				}
17203 				default:
17204 					DE_ASSERT(false);
17205 			}
17206 
17207 			spec.numWorkGroups = IVec3(1, 1, 1);
17208 			subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpCompositeInsert test", spec));
17209 		}
17210 		group->addChild(subGroup.release());
17211 	}
17212 	return group.release();
17213 }
17214 
17215 struct AssemblyStructInfo
17216 {
AssemblyStructInfovkt::SpirVAssembly::AssemblyStructInfo17217 	AssemblyStructInfo (const deUint32 comp, const deUint32 idx)
17218 	: components	(comp)
17219 	, index			(idx)
17220 	{}
17221 
17222 	deUint32 components;
17223 	deUint32 index;
17224 };
17225 
specializeInBoundsShaderTemplate(const NumberType type,const AssemblyStructInfo & structInfo,const map<string,string> & params)17226 const string specializeInBoundsShaderTemplate (const NumberType type, const AssemblyStructInfo& structInfo, const map<string, string>& params)
17227 {
17228 	// Create the full index string
17229 	string				fullIndex	= numberToString(structInfo.index) + " " + params.at("indexes");
17230 	// Convert it to list of indexes
17231 	vector<string>		indexes		= de::splitString(fullIndex, ' ');
17232 
17233 	map<string, string>	parameters	(params);
17234 	parameters["structType"]	= repeatString(" ${compositeType}", structInfo.components);
17235 	parameters["structConstruct"]	= repeatString(" %instance", structInfo.components);
17236 	parameters["insertIndexes"]	= fullIndex;
17237 
17238 	// In matrix cases the last two index is the CompositeExtract indexes
17239 	const deUint32 extractIndexes = (parameters["type"] == "matrix") ? 2 : 1;
17240 
17241 	// Construct the extractIndex
17242 	for (vector<string>::const_iterator index = indexes.end() - extractIndexes; index != indexes.end(); ++index)
17243 	{
17244 		parameters["extractIndexes"] += " " + *index;
17245 	}
17246 
17247 	// Remove the last 1 or 2 element depends on matrix case or not
17248 	indexes.erase(indexes.end() - extractIndexes, indexes.end());
17249 
17250 	deUint32 id = 0;
17251 	// Generate AccessChain index expressions (except for the last one, because we use ptr to the composite)
17252 	for (vector<string>::const_iterator index = indexes.begin(); index != indexes.end(); ++index)
17253 	{
17254 		string indexId = "%index_" + numberToString(id++);
17255 		parameters["accessChainConstDeclaration"] += indexId + "   = OpConstant %u32 " + *index + "\n";
17256 		parameters["accessChainIndexes"] += " " + indexId;
17257 	}
17258 
17259 	parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
17260 
17261 	const string customType = getAssemblyTypeName(type);
17262 	map<string, string> substCustomType;
17263 	substCustomType["customType"] = customType;
17264 	parameters["compositeDecl"] = StringTemplate(parameters.at("compositeDecl")).specialize(substCustomType);
17265 	parameters["compositeType"] = StringTemplate(parameters.at("compositeType")).specialize(substCustomType);
17266 	parameters["compositeConstruct"] = StringTemplate(parameters.at("compositeConstruct")).specialize(substCustomType);
17267 	parameters["filler"] = StringTemplate(parameters.at("filler")).specialize(substCustomType);
17268 	parameters["customType"] = customType;
17269 
17270 	const string compositeType = parameters.at("compositeType");
17271 	map<string, string> substCompositeType;
17272 	substCompositeType["compositeType"] = compositeType;
17273 	parameters["structType"] = StringTemplate(parameters.at("structType")).specialize(substCompositeType);
17274 	if (compositeType != "%u32vec3")
17275 	{
17276 		parameters["u32vec3Decl"] = "%u32vec3   = OpTypeVector %u32 3\n";
17277 	}
17278 
17279 	return StringTemplate(
17280 		"OpCapability Shader\n"
17281 		"OpCapability Matrix\n"
17282 		"OpMemoryModel Logical GLSL450\n"
17283 		"OpEntryPoint GLCompute %main \"main\" %id\n"
17284 		"OpExecutionMode %main LocalSize 1 1 1\n"
17285 
17286 		"OpSource GLSL 430\n"
17287 		"OpName %main           \"main\"\n"
17288 		"OpName %id             \"gl_GlobalInvocationID\"\n"
17289 		// Decorators
17290 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
17291 		"OpDecorate %buf BufferBlock\n"
17292 		"OpDecorate %indata DescriptorSet 0\n"
17293 		"OpDecorate %indata Binding 0\n"
17294 		"OpDecorate %outdata DescriptorSet 0\n"
17295 		"OpDecorate %outdata Binding 1\n"
17296 		"OpDecorate %customarr ArrayStride 4\n"
17297 		"${compositeDecorator}"
17298 		"OpMemberDecorate %buf 0 Offset 0\n"
17299 		// General types
17300 		"%void      = OpTypeVoid\n"
17301 		"%voidf     = OpTypeFunction %void\n"
17302 		"%i32       = OpTypeInt 32 1\n"
17303 		"%u32       = OpTypeInt 32 0\n"
17304 		"%f32       = OpTypeFloat 32\n"
17305 		// Custom types
17306 		"${compositeDecl}"
17307 		// %u32vec3 if not already declared in ${compositeDecl}
17308 		"${u32vec3Decl:opt}"
17309 		"%uvec3ptr  = OpTypePointer Input %u32vec3\n"
17310 		// Inherited from composite
17311 		"%composite_p = OpTypePointer Function ${compositeType}\n"
17312 		"%struct_t  = OpTypeStruct${structType}\n"
17313 		"%struct_p  = OpTypePointer Function %struct_t\n"
17314 		// Constants
17315 		"${filler}"
17316 		"${accessChainConstDeclaration}"
17317 		// Inherited from custom
17318 		"%customptr = OpTypePointer Uniform ${customType}\n"
17319 		"%customarr = OpTypeRuntimeArray ${customType}\n"
17320 		"%buf       = OpTypeStruct %customarr\n"
17321 		"%bufptr    = OpTypePointer Uniform %buf\n"
17322 		"%indata    = OpVariable %bufptr Uniform\n"
17323 		"%outdata   = OpVariable %bufptr Uniform\n"
17324 
17325 		"%id        = OpVariable %uvec3ptr Input\n"
17326 		"%zero      = OpConstant %u32 0\n"
17327 		"%main      = OpFunction %void None %voidf\n"
17328 		"%label     = OpLabel\n"
17329 		"%struct_v  = OpVariable %struct_p Function\n"
17330 		"%idval     = OpLoad %u32vec3 %id\n"
17331 		"%x         = OpCompositeExtract %u32 %idval 0\n"
17332 		// Create the input/output type
17333 		"%inloc     = OpInBoundsAccessChain %customptr %indata %zero %x\n"
17334 		"%outloc    = OpInBoundsAccessChain %customptr %outdata %zero %x\n"
17335 		// Read the input value
17336 		"%inval     = OpLoad ${customType} %inloc\n"
17337 		// Create the composite and fill it
17338 		"${compositeConstruct}"
17339 		// Create the struct and fill it with the composite
17340 		"%struct    = OpCompositeConstruct %struct_t${structConstruct}\n"
17341 		// Insert the value
17342 		"%comp_obj  = OpCompositeInsert %struct_t %inval %struct ${insertIndexes}\n"
17343 		// Store the object
17344 		"             OpStore %struct_v %comp_obj\n"
17345 		// Get deepest possible composite pointer
17346 		"%inner_ptr = OpInBoundsAccessChain %composite_p %struct_v${accessChainIndexes}\n"
17347 		"%read_obj  = OpLoad ${compositeType} %inner_ptr\n"
17348 		// Read back the stored value
17349 		"%read_val  = OpCompositeExtract ${customType} %read_obj${extractIndexes}\n"
17350 		"             OpStore %outloc %read_val\n"
17351 		"             OpReturn\n"
17352 		"             OpFunctionEnd\n"
17353 	).specialize(parameters);
17354 }
17355 
createOpInBoundsAccessChainGroup(tcu::TestContext & testCtx)17356 tcu::TestCaseGroup* createOpInBoundsAccessChainGroup (tcu::TestContext& testCtx)
17357 {
17358 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "opinboundsaccesschain", "Test the OpInBoundsAccessChain instruction"));
17359 	de::Random						rnd				(deStringHash(group->getName()));
17360 
17361 	for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17362 	{
17363 		NumberType						numberType	= NumberType(type);
17364 		const string					typeName	= getNumberTypeName(numberType);
17365 		const string					description	= "Test the OpInBoundsAccessChain instruction with " + typeName + "s";
17366 		de::MovePtr<tcu::TestCaseGroup>	subGroup	(new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17367 
17368 		vector<map<string, string> >	testCases;
17369 		createCompositeCases(testCases, rnd, numberType);
17370 
17371 		for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
17372 		{
17373 			ComputeShaderSpec	spec;
17374 
17375 			// Number of components inside of a struct
17376 			deUint32 structComponents = rnd.getInt(2, 8);
17377 			// Component index value
17378 			deUint32 structIndex = rnd.getInt(0, structComponents - 1);
17379 			AssemblyStructInfo structInfo(structComponents, structIndex);
17380 
17381 			spec.assembly = specializeInBoundsShaderTemplate(numberType, structInfo, *test);
17382 
17383 			switch (numberType)
17384 			{
17385 				case NUMBERTYPE_INT32:
17386 				{
17387 					deInt32 number = getInt(rnd);
17388 					spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17389 					spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17390 					break;
17391 				}
17392 				case NUMBERTYPE_UINT32:
17393 				{
17394 					deUint32 number = rnd.getUint32();
17395 					spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17396 					spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17397 					break;
17398 				}
17399 				case NUMBERTYPE_FLOAT32:
17400 				{
17401 					float number = rnd.getFloat();
17402 					spec.inputs.push_back(createCompositeBuffer<float>(number));
17403 					spec.outputs.push_back(createCompositeBuffer<float>(number));
17404 					break;
17405 				}
17406 				default:
17407 					DE_ASSERT(false);
17408 			}
17409 			spec.numWorkGroups = IVec3(1, 1, 1);
17410 			subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpInBoundsAccessChain test", spec));
17411 		}
17412 		group->addChild(subGroup.release());
17413 	}
17414 	return group.release();
17415 }
17416 
17417 // If the params missing, uninitialized case
17418 const string specializeDefaultOutputShaderTemplate (const NumberType type, const map<string, string>& params = map<string, string>())
17419 {
17420 	map<string, string> parameters(params);
17421 
17422 	parameters["customType"]	= getAssemblyTypeName(type);
17423 
17424 	// Declare the const value, and use it in the initializer
17425 	if (params.find("constValue") != params.end())
17426 	{
17427 		parameters["variableInitializer"]	= " %const";
17428 	}
17429 	// Uninitialized case
17430 	else
17431 	{
17432 		parameters["commentDecl"]	= ";";
17433 	}
17434 
17435 	return StringTemplate(
17436 		"OpCapability Shader\n"
17437 		"OpMemoryModel Logical GLSL450\n"
17438 		"OpEntryPoint GLCompute %main \"main\" %id\n"
17439 		"OpExecutionMode %main LocalSize 1 1 1\n"
17440 		"OpSource GLSL 430\n"
17441 		"OpName %main           \"main\"\n"
17442 		"OpName %id             \"gl_GlobalInvocationID\"\n"
17443 		// Decorators
17444 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
17445 		"OpDecorate %indata DescriptorSet 0\n"
17446 		"OpDecorate %indata Binding 0\n"
17447 		"OpDecorate %outdata DescriptorSet 0\n"
17448 		"OpDecorate %outdata Binding 1\n"
17449 		"OpDecorate %in_arr ArrayStride 4\n"
17450 		"OpDecorate %in_buf BufferBlock\n"
17451 		"OpMemberDecorate %in_buf 0 Offset 0\n"
17452 		// Base types
17453 		"%void       = OpTypeVoid\n"
17454 		"%voidf      = OpTypeFunction %void\n"
17455 		"%u32        = OpTypeInt 32 0\n"
17456 		"%i32        = OpTypeInt 32 1\n"
17457 		"%f32        = OpTypeFloat 32\n"
17458 		"%uvec3      = OpTypeVector %u32 3\n"
17459 		"%uvec3ptr   = OpTypePointer Input %uvec3\n"
17460 		"${commentDecl:opt}%const      = OpConstant ${customType} ${constValue:opt}\n"
17461 		// Derived types
17462 		"%in_ptr     = OpTypePointer Uniform ${customType}\n"
17463 		"%in_arr     = OpTypeRuntimeArray ${customType}\n"
17464 		"%in_buf     = OpTypeStruct %in_arr\n"
17465 		"%in_bufptr  = OpTypePointer Uniform %in_buf\n"
17466 		"%indata     = OpVariable %in_bufptr Uniform\n"
17467 		"%outdata    = OpVariable %in_bufptr Uniform\n"
17468 		"%id         = OpVariable %uvec3ptr Input\n"
17469 		"%var_ptr    = OpTypePointer Function ${customType}\n"
17470 		// Constants
17471 		"%zero       = OpConstant %i32 0\n"
17472 		// Main function
17473 		"%main       = OpFunction %void None %voidf\n"
17474 		"%label      = OpLabel\n"
17475 		"%out_var    = OpVariable %var_ptr Function${variableInitializer:opt}\n"
17476 		"%idval      = OpLoad %uvec3 %id\n"
17477 		"%x          = OpCompositeExtract %u32 %idval 0\n"
17478 		"%inloc      = OpAccessChain %in_ptr %indata %zero %x\n"
17479 		"%outloc     = OpAccessChain %in_ptr %outdata %zero %x\n"
17480 
17481 		"%outval     = OpLoad ${customType} %out_var\n"
17482 		"              OpStore %outloc %outval\n"
17483 		"              OpReturn\n"
17484 		"              OpFunctionEnd\n"
17485 	).specialize(parameters);
17486 }
17487 
compareFloats(const std::vector<Resource> &,const vector<AllocationSp> & outputAllocs,const std::vector<Resource> & expectedOutputs,TestLog & log)17488 bool compareFloats (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
17489 {
17490 	DE_ASSERT(outputAllocs.size() != 0);
17491 	DE_ASSERT(outputAllocs.size() == expectedOutputs.size());
17492 
17493 	// Use custom epsilon because of the float->string conversion
17494 	const float	epsilon	= 0.00001f;
17495 
17496 	for (size_t outputNdx = 0; outputNdx < outputAllocs.size(); ++outputNdx)
17497 	{
17498 		vector<deUint8>	expectedBytes;
17499 		float			expected;
17500 		float			actual;
17501 
17502 		expectedOutputs[outputNdx].getBytes(expectedBytes);
17503 		memcpy(&expected, &expectedBytes.front(), expectedBytes.size());
17504 		memcpy(&actual, outputAllocs[outputNdx]->getHostPtr(), expectedBytes.size());
17505 
17506 		// Test with epsilon
17507 		if (fabs(expected - actual) > epsilon)
17508 		{
17509 			log << TestLog::Message << "Error: The actual and expected values not matching."
17510 				<< " Expected: " << expected << " Actual: " << actual << " Epsilon: " << epsilon << TestLog::EndMessage;
17511 			return false;
17512 		}
17513 	}
17514 	return true;
17515 }
17516 
17517 // Checks if the driver crash with uninitialized cases
passthruVerify(const std::vector<Resource> &,const vector<AllocationSp> & outputAllocs,const std::vector<Resource> & expectedOutputs,TestLog &)17518 bool passthruVerify (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
17519 {
17520 	DE_ASSERT(outputAllocs.size() != 0);
17521 	DE_ASSERT(outputAllocs.size() == expectedOutputs.size());
17522 
17523 	// Copy and discard the result.
17524 	for (size_t outputNdx = 0; outputNdx < outputAllocs.size(); ++outputNdx)
17525 	{
17526 		vector<deUint8>	expectedBytes;
17527 		expectedOutputs[outputNdx].getBytes(expectedBytes);
17528 
17529 		const size_t	width			= expectedBytes.size();
17530 		vector<char>	data			(width);
17531 
17532 		memcpy(&data[0], outputAllocs[outputNdx]->getHostPtr(), width);
17533 	}
17534 	return true;
17535 }
17536 
createShaderDefaultOutputGroup(tcu::TestContext & testCtx)17537 tcu::TestCaseGroup* createShaderDefaultOutputGroup (tcu::TestContext& testCtx)
17538 {
17539 	de::MovePtr<tcu::TestCaseGroup>	group	(new tcu::TestCaseGroup(testCtx, "shader_default_output", "Test shader default output."));
17540 	de::Random						rnd		(deStringHash(group->getName()));
17541 
17542 	for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17543 	{
17544 		NumberType						numberType	= NumberType(type);
17545 		const string					typeName	= getNumberTypeName(numberType);
17546 		const string					description	= "Test the OpVariable initializer with " + typeName + ".";
17547 		de::MovePtr<tcu::TestCaseGroup>	subGroup	(new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17548 
17549 		// 2 similar subcases (initialized and uninitialized)
17550 		for (int subCase = 0; subCase < 2; ++subCase)
17551 		{
17552 			ComputeShaderSpec spec;
17553 			spec.numWorkGroups = IVec3(1, 1, 1);
17554 
17555 			map<string, string>				params;
17556 
17557 			switch (numberType)
17558 			{
17559 				case NUMBERTYPE_INT32:
17560 				{
17561 					deInt32 number = getInt(rnd);
17562 					spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17563 					spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17564 					params["constValue"] = numberToString(number);
17565 					break;
17566 				}
17567 				case NUMBERTYPE_UINT32:
17568 				{
17569 					deUint32 number = rnd.getUint32();
17570 					spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17571 					spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17572 					params["constValue"] = numberToString(number);
17573 					break;
17574 				}
17575 				case NUMBERTYPE_FLOAT32:
17576 				{
17577 					float number = rnd.getFloat();
17578 					spec.inputs.push_back(createCompositeBuffer<float>(number));
17579 					spec.outputs.push_back(createCompositeBuffer<float>(number));
17580 					spec.verifyIO = &compareFloats;
17581 					params["constValue"] = numberToString(number);
17582 					break;
17583 				}
17584 				default:
17585 					DE_ASSERT(false);
17586 			}
17587 
17588 			// Initialized subcase
17589 			if (!subCase)
17590 			{
17591 				spec.assembly = specializeDefaultOutputShaderTemplate(numberType, params);
17592 				subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "initialized", "OpVariable initializer tests.", spec));
17593 			}
17594 			// Uninitialized subcase
17595 			else
17596 			{
17597 				spec.assembly = specializeDefaultOutputShaderTemplate(numberType);
17598 				spec.verifyIO = &passthruVerify;
17599 				subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "uninitialized", "OpVariable initializer tests.", spec));
17600 			}
17601 		}
17602 		group->addChild(subGroup.release());
17603 	}
17604 	return group.release();
17605 }
17606 
createOpNopTests(tcu::TestContext & testCtx)17607 tcu::TestCaseGroup* createOpNopTests (tcu::TestContext& testCtx)
17608 {
17609 	de::MovePtr<tcu::TestCaseGroup>	testGroup (new tcu::TestCaseGroup(testCtx, "opnop", "Test OpNop"));
17610 	RGBA							defaultColors[4];
17611 	map<string, string>				opNopFragments;
17612 
17613 	getDefaultColors(defaultColors);
17614 
17615 	opNopFragments["testfun"]		=
17616 		"%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17617 		"%param1 = OpFunctionParameter %v4f32\n"
17618 		"%label_testfun = OpLabel\n"
17619 		"OpNop\n"
17620 		"OpNop\n"
17621 		"OpNop\n"
17622 		"OpNop\n"
17623 		"OpNop\n"
17624 		"OpNop\n"
17625 		"OpNop\n"
17626 		"OpNop\n"
17627 		"%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17628 		"%b = OpFAdd %f32 %a %a\n"
17629 		"OpNop\n"
17630 		"%c = OpFSub %f32 %b %a\n"
17631 		"%ret = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
17632 		"OpNop\n"
17633 		"OpNop\n"
17634 		"OpReturnValue %ret\n"
17635 		"OpFunctionEnd\n";
17636 
17637 	createTestsForAllStages("opnop", defaultColors, defaultColors, opNopFragments, testGroup.get());
17638 
17639 	return testGroup.release();
17640 }
17641 
createOpNameTests(tcu::TestContext & testCtx)17642 tcu::TestCaseGroup* createOpNameTests (tcu::TestContext& testCtx)
17643 {
17644 	de::MovePtr<tcu::TestCaseGroup>	testGroup	(new tcu::TestCaseGroup(testCtx, "opname","Test OpName"));
17645 	RGBA							defaultColors[4];
17646 	map<string, string>				opNameFragments;
17647 
17648 	getDefaultColors(defaultColors);
17649 
17650 	opNameFragments["testfun"] =
17651 		"%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17652 		"%param1     = OpFunctionParameter %v4f32\n"
17653 		"%label_func = OpLabel\n"
17654 		"%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17655 		"%b          = OpFAdd %f32 %a %a\n"
17656 		"%c          = OpFSub %f32 %b %a\n"
17657 		"%ret        = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
17658 		"OpReturnValue %ret\n"
17659 		"OpFunctionEnd\n";
17660 
17661 	opNameFragments["debug"] =
17662 		"OpName %BP_main \"not_main\"";
17663 
17664 	createTestsForAllStages("opname", defaultColors, defaultColors, opNameFragments, testGroup.get());
17665 
17666 	return testGroup.release();
17667 }
17668 
createFloat16Tests(tcu::TestContext & testCtx)17669 tcu::TestCaseGroup* createFloat16Tests (tcu::TestContext& testCtx)
17670 {
17671 	de::MovePtr<tcu::TestCaseGroup>		testGroup			(new tcu::TestCaseGroup(testCtx, "float16", "Float 16 tests"));
17672 
17673 	testGroup->addChild(createOpConstantFloat16Tests(testCtx));
17674 	testGroup->addChild(createFloat16LogicalSet<GraphicsResources>(testCtx, TEST_WITH_NAN));
17675 	testGroup->addChild(createFloat16LogicalSet<GraphicsResources>(testCtx, TEST_WITHOUT_NAN));
17676 	testGroup->addChild(createFloat16FuncSet<GraphicsResources>(testCtx));
17677 	testGroup->addChild(createDerivativeTests<256, 1>(testCtx));
17678 	testGroup->addChild(createDerivativeTests<256, 2>(testCtx));
17679 	testGroup->addChild(createDerivativeTests<256, 4>(testCtx));
17680 	testGroup->addChild(createFloat16VectorExtractSet<GraphicsResources>(testCtx));
17681 	testGroup->addChild(createFloat16VectorInsertSet<GraphicsResources>(testCtx));
17682 	testGroup->addChild(createFloat16VectorShuffleSet<GraphicsResources>(testCtx));
17683 	testGroup->addChild(createFloat16CompositeConstructSet<GraphicsResources>(testCtx));
17684 	testGroup->addChild(createFloat16CompositeInsertExtractSet<GraphicsResources>(testCtx, "OpCompositeExtract"));
17685 	testGroup->addChild(createFloat16CompositeInsertExtractSet<GraphicsResources>(testCtx, "OpCompositeInsert"));
17686 	testGroup->addChild(createFloat16ArithmeticSet<GraphicsResources>(testCtx));
17687 	testGroup->addChild(createFloat16ArithmeticSet<1, GraphicsResources>(testCtx));
17688 	testGroup->addChild(createFloat16ArithmeticSet<2, GraphicsResources>(testCtx));
17689 	testGroup->addChild(createFloat16ArithmeticSet<3, GraphicsResources>(testCtx));
17690 	testGroup->addChild(createFloat16ArithmeticSet<4, GraphicsResources>(testCtx));
17691 
17692 	return testGroup.release();
17693 }
17694 
createFloat16Group(tcu::TestContext & testCtx)17695 tcu::TestCaseGroup* createFloat16Group (tcu::TestContext& testCtx)
17696 {
17697 	de::MovePtr<tcu::TestCaseGroup>		testGroup			(new tcu::TestCaseGroup(testCtx, "float16", "Float 16 tests"));
17698 
17699 	testGroup->addChild(createFloat16OpConstantCompositeGroup(testCtx));
17700 	testGroup->addChild(createFloat16LogicalSet<ComputeShaderSpec>(testCtx, TEST_WITH_NAN));
17701 	testGroup->addChild(createFloat16LogicalSet<ComputeShaderSpec>(testCtx, TEST_WITHOUT_NAN));
17702 	testGroup->addChild(createFloat16FuncSet<ComputeShaderSpec>(testCtx));
17703 	testGroup->addChild(createFloat16VectorExtractSet<ComputeShaderSpec>(testCtx));
17704 	testGroup->addChild(createFloat16VectorInsertSet<ComputeShaderSpec>(testCtx));
17705 	testGroup->addChild(createFloat16VectorShuffleSet<ComputeShaderSpec>(testCtx));
17706 	testGroup->addChild(createFloat16CompositeConstructSet<ComputeShaderSpec>(testCtx));
17707 	testGroup->addChild(createFloat16CompositeInsertExtractSet<ComputeShaderSpec>(testCtx, "OpCompositeExtract"));
17708 	testGroup->addChild(createFloat16CompositeInsertExtractSet<ComputeShaderSpec>(testCtx, "OpCompositeInsert"));
17709 	testGroup->addChild(createFloat16ArithmeticSet<ComputeShaderSpec>(testCtx));
17710 	testGroup->addChild(createFloat16ArithmeticSet<1, ComputeShaderSpec>(testCtx));
17711 	testGroup->addChild(createFloat16ArithmeticSet<2, ComputeShaderSpec>(testCtx));
17712 	testGroup->addChild(createFloat16ArithmeticSet<3, ComputeShaderSpec>(testCtx));
17713 	testGroup->addChild(createFloat16ArithmeticSet<4, ComputeShaderSpec>(testCtx));
17714 
17715 	return testGroup.release();
17716 }
17717 
createBoolMixedBitSizeGroup(tcu::TestContext & testCtx)17718 tcu::TestCaseGroup* createBoolMixedBitSizeGroup (tcu::TestContext& testCtx)
17719 {
17720 	de::MovePtr<tcu::TestCaseGroup>	group			(new tcu::TestCaseGroup(testCtx, "mixed_bitsize", "Tests boolean operands produced from instructions of different bit-sizes"));
17721 
17722 	de::Random						rnd				(deStringHash(group->getName()));
17723 	const int		numElements		= 100;
17724 	vector<float>	inputData		(numElements, 0);
17725 	vector<float>	outputData		(numElements, 0);
17726 	fillRandomScalars(rnd, 0.0f, 100.0f, &inputData[0], 100);
17727 
17728 	const StringTemplate			shaderTemplate	(
17729 		"${CAPS}\n"
17730 		"OpMemoryModel Logical GLSL450\n"
17731 		"OpEntryPoint GLCompute %main \"main\" %id\n"
17732 		"OpExecutionMode %main LocalSize 1 1 1\n"
17733 		"OpSource GLSL 430\n"
17734 		"OpName %main           \"main\"\n"
17735 		"OpName %id             \"gl_GlobalInvocationID\"\n"
17736 
17737 		"OpDecorate %id BuiltIn GlobalInvocationId\n"
17738 
17739 		+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
17740 
17741 		"%id        = OpVariable %uvec3ptr Input\n"
17742 		"${CONST}\n"
17743 		"%main      = OpFunction %void None %voidf\n"
17744 		"%label     = OpLabel\n"
17745 		"%idval     = OpLoad %uvec3 %id\n"
17746 		"%x         = OpCompositeExtract %u32 %idval 0\n"
17747 		"%inloc     = OpAccessChain %f32ptr %indata %c0i32 %x\n"
17748 
17749 		"${TEST}\n"
17750 
17751 		"%outloc    = OpAccessChain %f32ptr %outdata %c0i32 %x\n"
17752 		"             OpStore %outloc %res\n"
17753 		"             OpReturn\n"
17754 		"             OpFunctionEnd\n"
17755 	);
17756 
17757 	// Each test case produces 4 boolean values, and we want each of these values
17758 	// to come froma different combination of the available bit-sizes, so compute
17759 	// all possible combinations here.
17760 	vector<deUint32>	widths;
17761 	widths.push_back(32);
17762 	widths.push_back(16);
17763 	widths.push_back(8);
17764 
17765 	vector<IVec4>	cases;
17766 	for (size_t width0 = 0; width0 < widths.size(); width0++)
17767 	{
17768 		for (size_t width1 = 0; width1 < widths.size(); width1++)
17769 		{
17770 			for (size_t width2 = 0; width2 < widths.size(); width2++)
17771 			{
17772 				for (size_t width3 = 0; width3 < widths.size(); width3++)
17773 				{
17774 					cases.push_back(IVec4(widths[width0], widths[width1], widths[width2], widths[width3]));
17775 				}
17776 			}
17777 		}
17778 	}
17779 
17780 	for (size_t caseNdx = 0; caseNdx < cases.size(); caseNdx++)
17781 	{
17782 		/// Skip cases where all bitsizes are the same, we are only interested in testing booleans produced from instructions with different native bit-sizes
17783 		if (cases[caseNdx][0] == cases[caseNdx][1] && cases[caseNdx][0] == cases[caseNdx][2] && cases[caseNdx][0] == cases[caseNdx][3])
17784 			continue;
17785 
17786 		map<string, string>	specializations;
17787 		ComputeShaderSpec	spec;
17788 
17789 		// Inject appropriate capabilities and reference constants depending
17790 		// on the bit-sizes required by this test case
17791 		bool hasFloat32	= cases[caseNdx][0] == 32 || cases[caseNdx][1] == 32 || cases[caseNdx][2] == 32 || cases[caseNdx][3] == 32;
17792 		bool hasFloat16	= cases[caseNdx][0] == 16 || cases[caseNdx][1] == 16 || cases[caseNdx][2] == 16 || cases[caseNdx][3] == 16;
17793 		bool hasInt8	= cases[caseNdx][0] == 8 || cases[caseNdx][1] == 8 || cases[caseNdx][2] == 8 || cases[caseNdx][3] == 8;
17794 
17795 		string capsStr	= "OpCapability Shader\n";
17796 		string constStr	=
17797 			"%c0i32     = OpConstant %i32 0\n"
17798 			"%c1f32     = OpConstant %f32 1.0\n"
17799 			"%c0f32     = OpConstant %f32 0.0\n";
17800 
17801 		if (hasFloat32)
17802 		{
17803 			constStr	+=
17804 				"%c10f32    = OpConstant %f32 10.0\n"
17805 				"%c25f32    = OpConstant %f32 25.0\n"
17806 				"%c50f32    = OpConstant %f32 50.0\n"
17807 				"%c90f32    = OpConstant %f32 90.0\n";
17808 		}
17809 
17810 		if (hasFloat16)
17811 		{
17812 			capsStr		+= "OpCapability Float16\n";
17813 			constStr	+=
17814 				"%f16       = OpTypeFloat 16\n"
17815 				"%c10f16    = OpConstant %f16 10.0\n"
17816 				"%c25f16    = OpConstant %f16 25.0\n"
17817 				"%c50f16    = OpConstant %f16 50.0\n"
17818 				"%c90f16    = OpConstant %f16 90.0\n";
17819 		}
17820 
17821 		if (hasInt8)
17822 		{
17823 			capsStr		+= "OpCapability Int8\n";
17824 			constStr	+=
17825 				"%i8        = OpTypeInt 8 1\n"
17826 				"%c10i8     = OpConstant %i8 10\n"
17827 				"%c25i8     = OpConstant %i8 25\n"
17828 				"%c50i8     = OpConstant %i8 50\n"
17829 				"%c90i8     = OpConstant %i8 90\n";
17830 		}
17831 
17832 		// Each invocation reads a different float32 value as input. Depending on
17833 		// the bit-sizes required by the particular test case, we also produce
17834 		// float16 and/or and int8 values by converting from the 32-bit float.
17835 		string testStr	= "";
17836 		testStr			+= "%inval32   = OpLoad %f32 %inloc\n";
17837 		if (hasFloat16)
17838 			testStr		+= "%inval16   = OpFConvert %f16 %inval32\n";
17839 		if (hasInt8)
17840 			testStr		+= "%inval8    = OpConvertFToS %i8 %inval32\n";
17841 
17842 		// Because conversions from Float to Int round towards 0 we want our "greater" comparisons to be >=,
17843 		// that way a float32/float16 comparison such as 50.6f >= 50.0f will preserve its result
17844 		// when converted to int8, since FtoS(50.6f) results in 50. For "less" comparisons, it is the
17845 		// other way around, so in this case we want < instead of <=.
17846 		if (cases[caseNdx][0] == 32)
17847 			testStr		+= "%cmp1      = OpFOrdGreaterThanEqual %bool %inval32 %c25f32\n";
17848 		else if (cases[caseNdx][0] == 16)
17849 			testStr		+= "%cmp1      = OpFOrdGreaterThanEqual %bool %inval16 %c25f16\n";
17850 		else
17851 			testStr		+= "%cmp1      = OpSGreaterThanEqual %bool %inval8 %c25i8\n";
17852 
17853 		if (cases[caseNdx][1] == 32)
17854 			testStr		+= "%cmp2      = OpFOrdLessThan %bool %inval32 %c50f32\n";
17855 		else if (cases[caseNdx][1] == 16)
17856 			testStr		+= "%cmp2      = OpFOrdLessThan %bool %inval16 %c50f16\n";
17857 		else
17858 			testStr		+= "%cmp2      = OpSLessThan %bool %inval8 %c50i8\n";
17859 
17860 		if (cases[caseNdx][2] == 32)
17861 			testStr		+= "%cmp3      = OpFOrdLessThan %bool %inval32 %c10f32\n";
17862 		else if (cases[caseNdx][2] == 16)
17863 			testStr		+= "%cmp3      = OpFOrdLessThan %bool %inval16 %c10f16\n";
17864 		else
17865 			testStr		+= "%cmp3      = OpSLessThan %bool %inval8 %c10i8\n";
17866 
17867 		if (cases[caseNdx][3] == 32)
17868 			testStr		+= "%cmp4      = OpFOrdGreaterThanEqual %bool %inval32 %c90f32\n";
17869 		else if (cases[caseNdx][3] == 16)
17870 			testStr		+= "%cmp4      = OpFOrdGreaterThanEqual %bool %inval16 %c90f16\n";
17871 		else
17872 			testStr		+= "%cmp4      = OpSGreaterThanEqual %bool %inval8 %c90i8\n";
17873 
17874 		testStr			+= "%and1      = OpLogicalAnd %bool %cmp1 %cmp2\n";
17875 		testStr			+= "%or1       = OpLogicalOr %bool %cmp3 %cmp4\n";
17876 		testStr			+= "%or2       = OpLogicalOr %bool %and1 %or1\n";
17877 		testStr			+= "%not1      = OpLogicalNot %bool %or2\n";
17878 		testStr			+= "%res       = OpSelect %f32 %not1 %c1f32 %c0f32\n";
17879 
17880 		specializations["CAPS"]		= capsStr;
17881 		specializations["CONST"]	= constStr;
17882 		specializations["TEST"]		= testStr;
17883 
17884 		// Compute expected result by evaluating the boolean expression computed in the shader for each input value
17885 		for (size_t ndx = 0; ndx < numElements; ++ndx)
17886 			outputData[ndx] = !((inputData[ndx] >= 25.0f && inputData[ndx] < 50.0f) || (inputData[ndx] < 10.0f || inputData[ndx] >= 90.0f));
17887 
17888 		spec.assembly = shaderTemplate.specialize(specializations);
17889 		spec.inputs.push_back(BufferSp(new Float32Buffer(inputData)));
17890 		spec.outputs.push_back(BufferSp(new Float32Buffer(outputData)));
17891 		spec.numWorkGroups = IVec3(numElements, 1, 1);
17892 		if (hasFloat16)
17893 			spec.requestedVulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_FLOAT16;
17894 		if (hasInt8)
17895 			spec.requestedVulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_INT8;
17896 		spec.extensions.push_back("VK_KHR_shader_float16_int8");
17897 
17898 		string testName = "b" + de::toString(cases[caseNdx][0]) + "b" + de::toString(cases[caseNdx][1]) + "b" + de::toString(cases[caseNdx][2]) + "b" + de::toString(cases[caseNdx][3]);
17899 		group->addChild(new SpvAsmComputeShaderCase(testCtx, testName.c_str(), "", spec));
17900 	}
17901 
17902 	return group.release();
17903 }
17904 
createBoolGroup(tcu::TestContext & testCtx)17905 tcu::TestCaseGroup* createBoolGroup (tcu::TestContext& testCtx)
17906 {
17907 	de::MovePtr<tcu::TestCaseGroup>		testGroup			(new tcu::TestCaseGroup(testCtx, "bool", "Boolean tests"));
17908 
17909 	testGroup->addChild(createBoolMixedBitSizeGroup(testCtx));
17910 
17911 	return testGroup.release();
17912 }
17913 
createOpNameAbuseTests(tcu::TestContext & testCtx)17914 tcu::TestCaseGroup* createOpNameAbuseTests (tcu::TestContext& testCtx)
17915 {
17916 	de::MovePtr<tcu::TestCaseGroup>	abuseGroup(new tcu::TestCaseGroup(testCtx, "opname_abuse", "OpName abuse tests"));
17917 	vector<CaseParameter>			abuseCases;
17918 	RGBA							defaultColors[4];
17919 	map<string, string>				opNameFragments;
17920 
17921 	getOpNameAbuseCases(abuseCases);
17922 	getDefaultColors(defaultColors);
17923 
17924 	opNameFragments["testfun"] =
17925 		"%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17926 		"%param1     = OpFunctionParameter %v4f32\n"
17927 		"%label_func = OpLabel\n"
17928 		"%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17929 		"%b          = OpFAdd %f32 %a %a\n"
17930 		"%c          = OpFSub %f32 %b %a\n"
17931 		"%ret        = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
17932 		"OpReturnValue %ret\n"
17933 		"OpFunctionEnd\n";
17934 
17935 	for (unsigned int i = 0; i < abuseCases.size(); i++)
17936 	{
17937 		string casename;
17938 		casename = string("main") + abuseCases[i].name;
17939 
17940 		opNameFragments["debug"] =
17941 			"OpName %BP_main \"" + abuseCases[i].param + "\"";
17942 
17943 		createTestsForAllStages(casename, defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17944 	}
17945 
17946 	for (unsigned int i = 0; i < abuseCases.size(); i++)
17947 	{
17948 		string casename;
17949 		casename = string("b") + abuseCases[i].name;
17950 
17951 		opNameFragments["debug"] =
17952 			"OpName %b \"" + abuseCases[i].param + "\"";
17953 
17954 		createTestsForAllStages(casename, defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17955 	}
17956 
17957 	{
17958 		opNameFragments["debug"] =
17959 			"OpName %test_code \"name1\"\n"
17960 			"OpName %param1    \"name2\"\n"
17961 			"OpName %a         \"name3\"\n"
17962 			"OpName %b         \"name4\"\n"
17963 			"OpName %c         \"name5\"\n"
17964 			"OpName %ret       \"name6\"\n";
17965 
17966 		createTestsForAllStages("everything_named", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17967 	}
17968 
17969 	{
17970 		opNameFragments["debug"] =
17971 			"OpName %test_code \"the_same\"\n"
17972 			"OpName %param1    \"the_same\"\n"
17973 			"OpName %a         \"the_same\"\n"
17974 			"OpName %b         \"the_same\"\n"
17975 			"OpName %c         \"the_same\"\n"
17976 			"OpName %ret       \"the_same\"\n";
17977 
17978 		createTestsForAllStages("everything_named_the_same", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17979 	}
17980 
17981 	{
17982 		opNameFragments["debug"] =
17983 			"OpName %BP_main \"to_be\"\n"
17984 			"OpName %BP_main \"or_not\"\n"
17985 			"OpName %BP_main \"to_be\"\n";
17986 
17987 		createTestsForAllStages("main_has_multiple_names", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17988 	}
17989 
17990 	{
17991 		opNameFragments["debug"] =
17992 			"OpName %b \"to_be\"\n"
17993 			"OpName %b \"or_not\"\n"
17994 			"OpName %b \"to_be\"\n";
17995 
17996 		createTestsForAllStages("b_has_multiple_names", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17997 	}
17998 
17999 	return abuseGroup.release();
18000 }
18001 
18002 
createOpMemberNameAbuseTests(tcu::TestContext & testCtx)18003 tcu::TestCaseGroup* createOpMemberNameAbuseTests (tcu::TestContext& testCtx)
18004 {
18005 	de::MovePtr<tcu::TestCaseGroup>	abuseGroup(new tcu::TestCaseGroup(testCtx, "opmembername_abuse", "OpName abuse tests"));
18006 	vector<CaseParameter>			abuseCases;
18007 	RGBA							defaultColors[4];
18008 	map<string, string>				opMemberNameFragments;
18009 
18010 	getOpNameAbuseCases(abuseCases);
18011 	getDefaultColors(defaultColors);
18012 
18013 	opMemberNameFragments["pre_main"] =
18014 		"%f3str = OpTypeStruct %f32 %f32 %f32\n";
18015 
18016 	opMemberNameFragments["testfun"] =
18017 		"%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
18018 		"%param1     = OpFunctionParameter %v4f32\n"
18019 		"%label_func = OpLabel\n"
18020 		"%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
18021 		"%b          = OpFAdd %f32 %a %a\n"
18022 		"%c          = OpFSub %f32 %b %a\n"
18023 		"%cstr       = OpCompositeConstruct %f3str %c %c %c\n"
18024 		"%d          = OpCompositeExtract %f32 %cstr 0\n"
18025 		"%ret        = OpVectorInsertDynamic %v4f32 %param1 %d %c_i32_0\n"
18026 		"OpReturnValue %ret\n"
18027 		"OpFunctionEnd\n";
18028 
18029 	for (unsigned int i = 0; i < abuseCases.size(); i++)
18030 	{
18031 		string casename;
18032 		casename = string("f3str_x") + abuseCases[i].name;
18033 
18034 		opMemberNameFragments["debug"] =
18035 			"OpMemberName %f3str 0 \"" + abuseCases[i].param + "\"";
18036 
18037 		createTestsForAllStages(casename, defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18038 	}
18039 
18040 	{
18041 		opMemberNameFragments["debug"] =
18042 			"OpMemberName %f3str 0 \"name1\"\n"
18043 			"OpMemberName %f3str 1 \"name2\"\n"
18044 			"OpMemberName %f3str 2 \"name3\"\n";
18045 
18046 		createTestsForAllStages("everything_named", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18047 	}
18048 
18049 	{
18050 		opMemberNameFragments["debug"] =
18051 			"OpMemberName %f3str 0 \"the_same\"\n"
18052 			"OpMemberName %f3str 1 \"the_same\"\n"
18053 			"OpMemberName %f3str 2 \"the_same\"\n";
18054 
18055 		createTestsForAllStages("everything_named_the_same", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18056 	}
18057 
18058 	{
18059 		opMemberNameFragments["debug"] =
18060 			"OpMemberName %f3str 0 \"to_be\"\n"
18061 			"OpMemberName %f3str 1 \"or_not\"\n"
18062 			"OpMemberName %f3str 0 \"to_be\"\n"
18063 			"OpMemberName %f3str 2 \"makes_no\"\n"
18064 			"OpMemberName %f3str 0 \"difference\"\n"
18065 			"OpMemberName %f3str 0 \"to_me\"\n";
18066 
18067 
18068 		createTestsForAllStages("f3str_x_has_multiple_names", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18069 	}
18070 
18071 	return abuseGroup.release();
18072 }
18073 
createInstructionTests(tcu::TestContext & testCtx)18074 tcu::TestCaseGroup* createInstructionTests (tcu::TestContext& testCtx)
18075 {
18076 	const bool testComputePipeline = true;
18077 
18078 	de::MovePtr<tcu::TestCaseGroup> instructionTests	(new tcu::TestCaseGroup(testCtx, "instruction", "Instructions with special opcodes/operands"));
18079 	de::MovePtr<tcu::TestCaseGroup> computeTests		(new tcu::TestCaseGroup(testCtx, "compute", "Compute Instructions with special opcodes/operands"));
18080 	de::MovePtr<tcu::TestCaseGroup> graphicsTests		(new tcu::TestCaseGroup(testCtx, "graphics", "Graphics Instructions with special opcodes/operands"));
18081 
18082 	computeTests->addChild(createSpivVersionCheckTests(testCtx, testComputePipeline));
18083 	computeTests->addChild(createLocalSizeGroup(testCtx));
18084 	computeTests->addChild(createOpNopGroup(testCtx));
18085 	computeTests->addChild(createOpFUnordGroup(testCtx, TEST_WITHOUT_NAN));
18086 	computeTests->addChild(createOpAtomicGroup(testCtx, false));
18087 	computeTests->addChild(createOpAtomicGroup(testCtx, true));					// Using new StorageBuffer decoration
18088 	computeTests->addChild(createOpAtomicGroup(testCtx, false, 1024, true));	// Return value validation
18089 	computeTests->addChild(createOpLineGroup(testCtx));
18090 	computeTests->addChild(createOpModuleProcessedGroup(testCtx));
18091 	computeTests->addChild(createOpNoLineGroup(testCtx));
18092 	computeTests->addChild(createOpConstantNullGroup(testCtx));
18093 	computeTests->addChild(createOpConstantCompositeGroup(testCtx));
18094 	computeTests->addChild(createOpConstantUsageGroup(testCtx));
18095 	computeTests->addChild(createSpecConstantGroup(testCtx));
18096 	computeTests->addChild(createOpSourceGroup(testCtx));
18097 	computeTests->addChild(createOpSourceExtensionGroup(testCtx));
18098 	computeTests->addChild(createDecorationGroupGroup(testCtx));
18099 	computeTests->addChild(createOpPhiGroup(testCtx));
18100 	computeTests->addChild(createLoopControlGroup(testCtx));
18101 	computeTests->addChild(createFunctionControlGroup(testCtx));
18102 	computeTests->addChild(createSelectionControlGroup(testCtx));
18103 	computeTests->addChild(createBlockOrderGroup(testCtx));
18104 	computeTests->addChild(createMultipleShaderGroup(testCtx));
18105 	computeTests->addChild(createMemoryAccessGroup(testCtx));
18106 	computeTests->addChild(createOpCopyMemoryGroup(testCtx));
18107 	computeTests->addChild(createOpCopyObjectGroup(testCtx));
18108 	computeTests->addChild(createNoContractionGroup(testCtx));
18109 	computeTests->addChild(createOpUndefGroup(testCtx));
18110 	computeTests->addChild(createOpUnreachableGroup(testCtx));
18111 	computeTests->addChild(createOpQuantizeToF16Group(testCtx));
18112 	computeTests->addChild(createOpFRemGroup(testCtx));
18113 	computeTests->addChild(createOpSRemComputeGroup(testCtx, QP_TEST_RESULT_PASS));
18114 	computeTests->addChild(createOpSRemComputeGroup64(testCtx, QP_TEST_RESULT_PASS));
18115 	computeTests->addChild(createOpSModComputeGroup(testCtx, QP_TEST_RESULT_PASS));
18116 	computeTests->addChild(createOpSModComputeGroup64(testCtx, QP_TEST_RESULT_PASS));
18117 	computeTests->addChild(createConvertComputeTests(testCtx, "OpSConvert", "sconvert"));
18118 	computeTests->addChild(createConvertComputeTests(testCtx, "OpUConvert", "uconvert"));
18119 	computeTests->addChild(createConvertComputeTests(testCtx, "OpFConvert", "fconvert"));
18120 	computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertSToF", "convertstof"));
18121 	computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertFToS", "convertftos"));
18122 	computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertUToF", "convertutof"));
18123 	computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertFToU", "convertftou"));
18124 	computeTests->addChild(createOpCompositeInsertGroup(testCtx));
18125 	computeTests->addChild(createOpInBoundsAccessChainGroup(testCtx));
18126 	computeTests->addChild(createShaderDefaultOutputGroup(testCtx));
18127 	computeTests->addChild(createOpNMinGroup(testCtx));
18128 	computeTests->addChild(createOpNMaxGroup(testCtx));
18129 	computeTests->addChild(createOpNClampGroup(testCtx));
18130 	{
18131 		de::MovePtr<tcu::TestCaseGroup>	computeAndroidTests	(new tcu::TestCaseGroup(testCtx, "android", "Android CTS Tests"));
18132 
18133 		computeAndroidTests->addChild(createOpSRemComputeGroup(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18134 		computeAndroidTests->addChild(createOpSModComputeGroup(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18135 
18136 		computeTests->addChild(computeAndroidTests.release());
18137 	}
18138 
18139 	computeTests->addChild(create8BitStorageComputeGroup(testCtx));
18140 	computeTests->addChild(create16BitStorageComputeGroup(testCtx));
18141 	computeTests->addChild(createFloatControlsComputeGroup(testCtx));
18142 	computeTests->addChild(createUboMatrixPaddingComputeGroup(testCtx));
18143 	computeTests->addChild(createCompositeInsertComputeGroup(testCtx));
18144 	computeTests->addChild(createVariableInitComputeGroup(testCtx));
18145 	computeTests->addChild(createConditionalBranchComputeGroup(testCtx));
18146 	computeTests->addChild(createIndexingComputeGroup(testCtx));
18147 	computeTests->addChild(createVariablePointersComputeGroup(testCtx));
18148 	computeTests->addChild(createImageSamplerComputeGroup(testCtx));
18149 	computeTests->addChild(createOpNameGroup(testCtx));
18150 	computeTests->addChild(createOpMemberNameGroup(testCtx));
18151 	computeTests->addChild(createPointerParameterComputeGroup(testCtx));
18152 	computeTests->addChild(createFloat16Group(testCtx));
18153 	computeTests->addChild(createBoolGroup(testCtx));
18154 	computeTests->addChild(createWorkgroupMemoryComputeGroup(testCtx));
18155 
18156 	graphicsTests->addChild(createCrossStageInterfaceTests(testCtx));
18157 	graphicsTests->addChild(createSpivVersionCheckTests(testCtx, !testComputePipeline));
18158 	graphicsTests->addChild(createOpNopTests(testCtx));
18159 	graphicsTests->addChild(createOpSourceTests(testCtx));
18160 	graphicsTests->addChild(createOpSourceContinuedTests(testCtx));
18161 	graphicsTests->addChild(createOpModuleProcessedTests(testCtx));
18162 	graphicsTests->addChild(createOpLineTests(testCtx));
18163 	graphicsTests->addChild(createOpNoLineTests(testCtx));
18164 	graphicsTests->addChild(createOpConstantNullTests(testCtx));
18165 	graphicsTests->addChild(createOpConstantCompositeTests(testCtx));
18166 	graphicsTests->addChild(createMemoryAccessTests(testCtx));
18167 	graphicsTests->addChild(createOpUndefTests(testCtx));
18168 	graphicsTests->addChild(createSelectionBlockOrderTests(testCtx));
18169 	graphicsTests->addChild(createModuleTests(testCtx));
18170 	graphicsTests->addChild(createSwitchBlockOrderTests(testCtx));
18171 	graphicsTests->addChild(createOpPhiTests(testCtx));
18172 	graphicsTests->addChild(createNoContractionTests(testCtx));
18173 	graphicsTests->addChild(createOpQuantizeTests(testCtx));
18174 	graphicsTests->addChild(createLoopTests(testCtx));
18175 	graphicsTests->addChild(createSpecConstantTests(testCtx));
18176 	graphicsTests->addChild(createSpecConstantOpQuantizeToF16Group(testCtx));
18177 	graphicsTests->addChild(createBarrierTests(testCtx));
18178 	graphicsTests->addChild(createDecorationGroupTests(testCtx));
18179 	graphicsTests->addChild(createFRemTests(testCtx));
18180 	graphicsTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
18181 	graphicsTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
18182 
18183 	{
18184 		de::MovePtr<tcu::TestCaseGroup>	graphicsAndroidTests	(new tcu::TestCaseGroup(testCtx, "android", "Android CTS Tests"));
18185 
18186 		graphicsAndroidTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18187 		graphicsAndroidTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18188 
18189 		graphicsTests->addChild(graphicsAndroidTests.release());
18190 	}
18191 	graphicsTests->addChild(createOpNameTests(testCtx));
18192 	graphicsTests->addChild(createOpNameAbuseTests(testCtx));
18193 	graphicsTests->addChild(createOpMemberNameAbuseTests(testCtx));
18194 
18195 	graphicsTests->addChild(create8BitStorageGraphicsGroup(testCtx));
18196 	graphicsTests->addChild(create16BitStorageGraphicsGroup(testCtx));
18197 	graphicsTests->addChild(createFloatControlsGraphicsGroup(testCtx));
18198 	graphicsTests->addChild(createUboMatrixPaddingGraphicsGroup(testCtx));
18199 	graphicsTests->addChild(createCompositeInsertGraphicsGroup(testCtx));
18200 	graphicsTests->addChild(createVariableInitGraphicsGroup(testCtx));
18201 	graphicsTests->addChild(createConditionalBranchGraphicsGroup(testCtx));
18202 	graphicsTests->addChild(createIndexingGraphicsGroup(testCtx));
18203 	graphicsTests->addChild(createVariablePointersGraphicsGroup(testCtx));
18204 	graphicsTests->addChild(createImageSamplerGraphicsGroup(testCtx));
18205 	graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpSConvert", "sconvert"));
18206 	graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpUConvert", "uconvert"));
18207 	graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpFConvert", "fconvert"));
18208 	graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertSToF", "convertstof"));
18209 	graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertFToS", "convertftos"));
18210 	graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertUToF", "convertutof"));
18211 	graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertFToU", "convertftou"));
18212 	graphicsTests->addChild(createPointerParameterGraphicsGroup(testCtx));
18213 	graphicsTests->addChild(createVaryingNameGraphicsGroup(testCtx));
18214 
18215 	graphicsTests->addChild(createFloat16Tests(testCtx));
18216 
18217 	instructionTests->addChild(computeTests.release());
18218 	instructionTests->addChild(graphicsTests.release());
18219 
18220 	return instructionTests.release();
18221 }
18222 
18223 } // SpirVAssembly
18224 } // vkt
18225