Test behaviour of color write enable with colorWriteMask
[platform/upstream/VK-GL-CTS.git] / external / vulkancts / modules / vulkan / image / vktImageLoadStoreTests.cpp
1 /*------------------------------------------------------------------------
2  * Vulkan Conformance Tests
3  * ------------------------
4  *
5  * Copyright (c) 2016 The Khronos Group Inc.
6  * Copyright (c) 2016 The Android Open Source Project
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 Image load/store Tests
23  *//*--------------------------------------------------------------------*/
24
25 #include "vktImageLoadStoreTests.hpp"
26 #include "vktTestCaseUtil.hpp"
27 #include "vktImageTestsUtil.hpp"
28 #include "vktImageLoadStoreUtil.hpp"
29 #include "vktImageTexture.hpp"
30
31 #include "vkDefs.hpp"
32 #include "vkRef.hpp"
33 #include "vkRefUtil.hpp"
34 #include "vkPlatform.hpp"
35 #include "vkPrograms.hpp"
36 #include "vkMemUtil.hpp"
37 #include "vkBarrierUtil.hpp"
38 #include "vkBuilderUtil.hpp"
39 #include "vkQueryUtil.hpp"
40 #include "vkImageUtil.hpp"
41 #include "vkCmdUtil.hpp"
42 #include "vkObjUtil.hpp"
43
44 #include "deMath.h"
45 #include "deUniquePtr.hpp"
46 #include "deSharedPtr.hpp"
47 #include "deStringUtil.hpp"
48
49 #include "tcuImageCompare.hpp"
50 #include "tcuTexture.hpp"
51 #include "tcuTextureUtil.hpp"
52 #include "tcuFloat.hpp"
53 #include "tcuStringTemplate.hpp"
54
55 #include <string>
56 #include <vector>
57 #include <map>
58
59 using namespace vk;
60
61 namespace vkt
62 {
63 namespace image
64 {
65 namespace
66 {
67
68 // Check for three-component (non-packed) format, i.e. pixel size is a multiple of 3.
69 bool formatHasThreeComponents(VkFormat format)
70 {
71         const tcu::TextureFormat texFormat = mapVkFormat(format);
72         return (getPixelSize(texFormat) % 3) == 0;
73 }
74
75 VkFormat getSingleComponentFormat(VkFormat format)
76 {
77         tcu::TextureFormat texFormat = mapVkFormat(format);
78         texFormat = tcu::TextureFormat(tcu::TextureFormat::R, texFormat.type);
79         return mapTextureFormat(texFormat);
80 }
81
82 inline VkBufferImageCopy makeBufferImageCopy (const Texture& texture)
83 {
84         return image::makeBufferImageCopy(makeExtent3D(texture.layerSize()), texture.numLayers());
85 }
86
87 tcu::ConstPixelBufferAccess getLayerOrSlice (const Texture& texture, const tcu::ConstPixelBufferAccess access, const int layer)
88 {
89         switch (texture.type())
90         {
91                 case IMAGE_TYPE_1D:
92                 case IMAGE_TYPE_2D:
93                 case IMAGE_TYPE_BUFFER:
94                         // Not layered
95                         DE_ASSERT(layer == 0);
96                         return access;
97
98                 case IMAGE_TYPE_1D_ARRAY:
99                         return tcu::getSubregion(access, 0, layer, access.getWidth(), 1);
100
101                 case IMAGE_TYPE_2D_ARRAY:
102                 case IMAGE_TYPE_CUBE:
103                 case IMAGE_TYPE_CUBE_ARRAY:
104                 case IMAGE_TYPE_3D:                     // 3d texture is treated as if depth was the layers
105                         return tcu::getSubregion(access, 0, 0, layer, access.getWidth(), access.getHeight(), 1);
106
107                 default:
108                         DE_FATAL("Internal test error");
109                         return tcu::ConstPixelBufferAccess();
110         }
111 }
112
113 //! \return the size in bytes of a given level of a mipmap image, including array layers.
114 vk::VkDeviceSize getMipmapLevelImageSizeBytes (const Texture& texture, const vk::VkFormat format, const deUint32 mipmapLevel)
115 {
116         tcu::IVec3 size = texture.size(mipmapLevel);
117         return tcu::getPixelSize(vk::mapVkFormat(format)) * size.x() * size.y() * size.z();
118 }
119
120 //! \return the size in bytes of the whole mipmap image, including all mipmap levels and array layers
121 vk::VkDeviceSize getMipmapImageTotalSizeBytes (const Texture& texture, const vk::VkFormat format)
122 {
123         vk::VkDeviceSize        size                    = 0u;
124         deInt32                         levelCount              = 0u;
125
126         do
127         {
128                 size += getMipmapLevelImageSizeBytes(texture, format, levelCount);
129                 levelCount++;
130         } while (levelCount < texture.numMipmapLevels());
131         return size;
132 }
133
134 //! \return true if all layers match in both pixel buffers
135 bool comparePixelBuffers (tcu::TestLog&                                         log,
136                                                   const Texture&                                        texture,
137                                                   const VkFormat                                        format,
138                                                   const tcu::ConstPixelBufferAccess     reference,
139                                                   const tcu::ConstPixelBufferAccess     result,
140                                                   const deUint32                                        mipmapLevel = 0u)
141 {
142         DE_ASSERT(reference.getFormat() == result.getFormat());
143         DE_ASSERT(reference.getSize() == result.getSize());
144
145         const bool is3d = (texture.type() == IMAGE_TYPE_3D);
146         const int numLayersOrSlices = (is3d ? texture.size(mipmapLevel).z() : texture.numLayers());
147         const int numCubeFaces = 6;
148
149         int passedLayers = 0;
150         for (int layerNdx = 0; layerNdx < numLayersOrSlices; ++layerNdx)
151         {
152                 const std::string comparisonName = "Comparison" + de::toString(layerNdx);
153                 const std::string comparisonDesc = "Image Comparison, " +
154                         (isCube(texture) ? "face " + de::toString(layerNdx % numCubeFaces) + ", cube " + de::toString(layerNdx / numCubeFaces) :
155                         is3d                     ? "slice " + de::toString(layerNdx) : "layer " + de::toString(layerNdx) + " , level " + de::toString(mipmapLevel));
156
157                 const tcu::ConstPixelBufferAccess refLayer = getLayerOrSlice(texture, reference, layerNdx);
158                 const tcu::ConstPixelBufferAccess resultLayer = getLayerOrSlice(texture, result, layerNdx);
159
160                 bool ok = false;
161
162                 switch (tcu::getTextureChannelClass(mapVkFormat(format).type))
163                 {
164                         case tcu::TEXTURECHANNELCLASS_UNSIGNED_INTEGER:
165                         case tcu::TEXTURECHANNELCLASS_SIGNED_INTEGER:
166                         {
167                                 ok = tcu::intThresholdCompare(log, comparisonName.c_str(), comparisonDesc.c_str(), refLayer, resultLayer, tcu::UVec4(0), tcu::COMPARE_LOG_RESULT);
168                                 break;
169                         }
170
171                         case tcu::TEXTURECHANNELCLASS_UNSIGNED_FIXED_POINT:
172                         {
173                                 // Allow error of minimum representable difference
174                                 const tcu::Vec4 threshold (1.0f / ((tcu::UVec4(1u) << tcu::getTextureFormatMantissaBitDepth(mapVkFormat(format)).cast<deUint32>()) - 1u).cast<float>());
175
176                                 ok = tcu::floatThresholdCompare(log, comparisonName.c_str(), comparisonDesc.c_str(), refLayer, resultLayer, threshold, tcu::COMPARE_LOG_RESULT);
177                                 break;
178                         }
179
180                         case tcu::TEXTURECHANNELCLASS_SIGNED_FIXED_POINT:
181                         {
182                                 // Allow error of minimum representable difference
183                                 const tcu::Vec4 threshold (1.0f / ((tcu::UVec4(1u) << (tcu::getTextureFormatMantissaBitDepth(mapVkFormat(format)).cast<deUint32>() - 1u)) - 1u).cast<float>());
184
185                                 ok = tcu::floatThresholdCompare(log, comparisonName.c_str(), comparisonDesc.c_str(), refLayer, resultLayer, threshold, tcu::COMPARE_LOG_RESULT);
186                                 break;
187                         }
188
189                         case tcu::TEXTURECHANNELCLASS_FLOATING_POINT:
190                         {
191                                 // Convert target format ulps to float ulps and allow 1 ulp difference
192                                 const tcu::UVec4 threshold (tcu::UVec4(1u) << (tcu::UVec4(23) - tcu::getTextureFormatMantissaBitDepth(mapVkFormat(format)).cast<deUint32>()));
193
194                                 ok = tcu::floatUlpThresholdCompare(log, comparisonName.c_str(), comparisonDesc.c_str(), refLayer, resultLayer, threshold, tcu::COMPARE_LOG_RESULT);
195                                 break;
196                         }
197
198                         default:
199                                 DE_FATAL("Unknown channel class");
200                 }
201
202                 if (ok)
203                         ++passedLayers;
204         }
205
206         return passedLayers == numLayersOrSlices;
207 }
208
209 //!< Zero out invalid pixels in the image (denormalized, infinite, NaN values)
210 void replaceBadFloatReinterpretValues (const tcu::PixelBufferAccess access)
211 {
212         DE_ASSERT(tcu::getTextureChannelClass(access.getFormat().type) == tcu::TEXTURECHANNELCLASS_FLOATING_POINT);
213
214         for (int z = 0; z < access.getDepth(); ++z)
215         for (int y = 0; y < access.getHeight(); ++y)
216         for (int x = 0; x < access.getWidth(); ++x)
217         {
218                 const tcu::Vec4 color(access.getPixel(x, y, z));
219                 tcu::Vec4 newColor = color;
220
221                 for (int i = 0; i < 4; ++i)
222                 {
223                         if (access.getFormat().type == tcu::TextureFormat::HALF_FLOAT)
224                         {
225                                 const tcu::Float16 f(color[i]);
226                                 if (f.isDenorm() || f.isInf() || f.isNaN())
227                                         newColor[i] = 0.0f;
228                         }
229                         else
230                         {
231                                 const tcu::Float32 f(color[i]);
232                                 if (f.isDenorm() || f.isInf() || f.isNaN())
233                                         newColor[i] = 0.0f;
234                         }
235                 }
236
237                 if (newColor != color)
238                         access.setPixel(newColor, x, y, z);
239         }
240 }
241
242 //!< replace invalid pixels in the image (-128)
243 void replaceSnormReinterpretValues (const tcu::PixelBufferAccess access)
244 {
245         DE_ASSERT(tcu::getTextureChannelClass(access.getFormat().type) == tcu::TEXTURECHANNELCLASS_SIGNED_FIXED_POINT);
246
247         for (int z = 0; z < access.getDepth(); ++z)
248         for (int y = 0; y < access.getHeight(); ++y)
249         for (int x = 0; x < access.getWidth(); ++x)
250         {
251                 const tcu::IVec4 color(access.getPixelInt(x, y, z));
252                 tcu::IVec4 newColor = color;
253
254                 for (int i = 0; i < 4; ++i)
255                 {
256                         const deInt32 oldColor(color[i]);
257                         if (oldColor == -128) newColor[i] = -127;
258                 }
259
260                 if (newColor != color)
261                 access.setPixel(newColor, x, y, z);
262         }
263 }
264
265 tcu::TextureLevel generateReferenceImage (const tcu::IVec3& imageSize, const VkFormat imageFormat, const VkFormat readFormat)
266 {
267         // Generate a reference image data using the storage format
268
269         tcu::TextureLevel reference(mapVkFormat(imageFormat), imageSize.x(), imageSize.y(), imageSize.z());
270         const tcu::PixelBufferAccess access = reference.getAccess();
271
272         const float storeColorScale = computeStoreColorScale(imageFormat, imageSize);
273         const float storeColorBias = computeStoreColorBias(imageFormat);
274
275         const bool intFormat = isIntegerFormat(imageFormat);
276         const bool storeNegativeValues = isSignedFormat(imageFormat) && (storeColorBias == 0);
277         const int xMax = imageSize.x() - 1;
278         const int yMax = imageSize.y() - 1;
279
280         for (int z = 0; z < imageSize.z(); ++z)
281         for (int y = 0; y < imageSize.y(); ++y)
282         for (int x = 0; x < imageSize.x(); ++x)
283         {
284                 tcu::IVec4 color(x^y^z, (xMax - x)^y^z, x^(yMax - y)^z, (xMax - x)^(yMax - y)^z);
285
286                 if (storeNegativeValues)
287                         color -= tcu::IVec4(deRoundFloatToInt32((float)de::max(xMax, yMax) / 2.0f));
288
289                 if (intFormat)
290                         access.setPixel(color, x, y, z);
291                 else
292                         access.setPixel(color.asFloat()*storeColorScale + storeColorBias, x, y, z);
293         }
294
295         // If the image is to be accessed as a float texture, get rid of invalid values
296
297         if (isFloatFormat(readFormat) && imageFormat != readFormat)
298                 replaceBadFloatReinterpretValues(tcu::PixelBufferAccess(mapVkFormat(readFormat), imageSize, access.getDataPtr()));
299         if (isSnormFormat(readFormat) && imageFormat != readFormat)
300                 replaceSnormReinterpretValues(tcu::PixelBufferAccess(mapVkFormat(readFormat), imageSize, access.getDataPtr()));
301
302         return reference;
303 }
304
305 inline tcu::TextureLevel generateReferenceImage (const tcu::IVec3& imageSize, const VkFormat imageFormat)
306 {
307         return generateReferenceImage(imageSize, imageFormat, imageFormat);
308 }
309
310 void flipHorizontally (const tcu::PixelBufferAccess access)
311 {
312         const int xMax = access.getWidth() - 1;
313         const int halfWidth = access.getWidth() / 2;
314
315         if (isIntegerFormat(mapTextureFormat(access.getFormat())))
316                 for (int z = 0; z < access.getDepth(); z++)
317                 for (int y = 0; y < access.getHeight(); y++)
318                 for (int x = 0; x < halfWidth; x++)
319                 {
320                         const tcu::UVec4 temp = access.getPixelUint(xMax - x, y, z);
321                         access.setPixel(access.getPixelUint(x, y, z), xMax - x, y, z);
322                         access.setPixel(temp, x, y, z);
323                 }
324         else
325                 for (int z = 0; z < access.getDepth(); z++)
326                 for (int y = 0; y < access.getHeight(); y++)
327                 for (int x = 0; x < halfWidth; x++)
328                 {
329                         const tcu::Vec4 temp = access.getPixel(xMax - x, y, z);
330                         access.setPixel(access.getPixel(x, y, z), xMax - x, y, z);
331                         access.setPixel(temp, x, y, z);
332                 }
333 }
334
335 inline bool formatsAreCompatible (const VkFormat format0, const VkFormat format1)
336 {
337         return format0 == format1 || mapVkFormat(format0).getPixelSize() == mapVkFormat(format1).getPixelSize();
338 }
339
340 void commandImageWriteBarrierBetweenShaderInvocations (Context& context, const VkCommandBuffer cmdBuffer, const VkImage image, const Texture& texture)
341 {
342         const DeviceInterface& vk = context.getDeviceInterface();
343
344         const VkImageSubresourceRange fullImageSubresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, texture.numMipmapLevels(), 0u, texture.numLayers());
345         const VkImageMemoryBarrier shaderWriteBarrier = makeImageMemoryBarrier(
346                 VK_ACCESS_SHADER_WRITE_BIT, 0u,
347                 VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL,
348                 image, fullImageSubresourceRange);
349
350         vk.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 0, (const VkBufferMemoryBarrier*)DE_NULL, 1, &shaderWriteBarrier);
351 }
352
353 void commandBufferWriteBarrierBeforeHostRead (Context& context, const VkCommandBuffer cmdBuffer, const VkBuffer buffer, const VkDeviceSize bufferSizeBytes)
354 {
355         const DeviceInterface& vk = context.getDeviceInterface();
356
357         const VkBufferMemoryBarrier shaderWriteBarrier = makeBufferMemoryBarrier(
358                 VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT,
359                 buffer, 0ull, bufferSizeBytes);
360
361         vk.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_HOST_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 1, &shaderWriteBarrier, 0, (const VkImageMemoryBarrier*)DE_NULL);
362 }
363
364 //! Copy all layers of an image to a buffer.
365 void commandCopyImageToBuffer (Context&                                 context,
366                                                            const VkCommandBuffer        cmdBuffer,
367                                                            const VkImage                        image,
368                                                            const VkBuffer                       buffer,
369                                                            const VkDeviceSize           bufferSizeBytes,
370                                                            const Texture&                       texture)
371 {
372         const DeviceInterface& vk = context.getDeviceInterface();
373
374         const VkImageSubresourceRange fullImageSubresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, texture.numLayers());
375         const VkImageMemoryBarrier prepareForTransferBarrier = makeImageMemoryBarrier(
376                 VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT,
377                 VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
378                 image, fullImageSubresourceRange);
379
380         const VkBufferImageCopy copyRegion = makeBufferImageCopy(texture);
381
382         const VkBufferMemoryBarrier copyBarrier = makeBufferMemoryBarrier(
383                 VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT,
384                 buffer, 0ull, bufferSizeBytes);
385
386         vk.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 0, (const VkBufferMemoryBarrier*)DE_NULL, 1, &prepareForTransferBarrier);
387         vk.cmdCopyImageToBuffer(cmdBuffer, image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, buffer, 1u, &copyRegion);
388         vk.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 1, &copyBarrier, 0, (const VkImageMemoryBarrier*)DE_NULL);
389 }
390
391 //! Copy all layers of a mipmap image to a buffer.
392 void commandCopyMipmapImageToBuffer (Context&                           context,
393                                                                          const VkCommandBuffer  cmdBuffer,
394                                                                          const VkImage                  image,
395                                                                          const VkFormat                 imageFormat,
396                                                                          const VkBuffer                 buffer,
397                                                                          const VkDeviceSize             bufferSizeBytes,
398                                                                          const Texture&                 texture)
399 {
400         const DeviceInterface& vk = context.getDeviceInterface();
401
402         const VkImageSubresourceRange fullImageSubresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, texture.numMipmapLevels(), 0u, texture.numLayers());
403         const VkImageMemoryBarrier prepareForTransferBarrier = makeImageMemoryBarrier(
404                 VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT,
405                 VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
406                 image, fullImageSubresourceRange);
407
408         std::vector<VkBufferImageCopy> copyRegions;
409         VkDeviceSize bufferOffset = 0u;
410         for (deInt32 levelNdx = 0; levelNdx < texture.numMipmapLevels(); levelNdx++)
411         {
412                 const VkBufferImageCopy copyParams =
413                 {
414                         bufferOffset,                                                                                                                                                           //      VkDeviceSize                            bufferOffset;
415                         0u,                                                                                                                                                                                     //      deUint32                                        bufferRowLength;
416                         0u,                                                                                                                                                                                     //      deUint32                                        bufferImageHeight;
417                         makeImageSubresourceLayers(VK_IMAGE_ASPECT_COLOR_BIT, levelNdx, 0u, texture.numLayers()),       //      VkImageSubresourceLayers        imageSubresource;
418                         makeOffset3D(0, 0, 0),                                                                                                                                          //      VkOffset3D                                      imageOffset;
419                         makeExtent3D(texture.layerSize(levelNdx)),                                                                                                      //      VkExtent3D                                      imageExtent;
420                 };
421                 copyRegions.push_back(copyParams);
422                 bufferOffset += getMipmapLevelImageSizeBytes(texture, imageFormat, levelNdx);
423         }
424
425         const VkBufferMemoryBarrier copyBarrier = makeBufferMemoryBarrier(
426                 VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT,
427                 buffer, 0ull, bufferSizeBytes);
428
429         vk.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 0, (const VkBufferMemoryBarrier*)DE_NULL, 1, &prepareForTransferBarrier);
430         vk.cmdCopyImageToBuffer(cmdBuffer, image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, buffer, (deUint32) copyRegions.size(), copyRegions.data());
431         vk.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 1, &copyBarrier, 0, (const VkImageMemoryBarrier*)DE_NULL);
432 }
433
434 class StoreTest : public TestCase
435 {
436 public:
437         enum TestFlags
438         {
439                 FLAG_SINGLE_LAYER_BIND                          = 0x1,  //!< Run the shader multiple times, each time binding a different layer.
440                 FLAG_DECLARE_IMAGE_FORMAT_IN_SHADER     = 0x2,  //!< Declare the format of the images in the shader code
441                 FLAG_MINALIGN                                           = 0x4,  //!< Use bufferview offset that matches the advertised minimum alignment
442         };
443
444                                                         StoreTest                       (tcu::TestContext&      testCtx,
445                                                                                                  const std::string&     name,
446                                                                                                  const std::string&     description,
447                                                                                                  const Texture&         texture,
448                                                                                                  const VkFormat         format,
449                                                                                                  const deUint32         flags = FLAG_DECLARE_IMAGE_FORMAT_IN_SHADER);
450
451         virtual void                    checkSupport            (Context&                       context) const;
452         void                                    initPrograms            (SourceCollections&     programCollection) const;
453         TestInstance*                   createInstance          (Context&                       context) const;
454
455 private:
456         const Texture                   m_texture;
457         const VkFormat                  m_format;
458         const bool                              m_declareImageFormatInShader;
459         const bool                              m_singleLayerBind;
460         const bool                              m_minalign;
461 };
462
463 StoreTest::StoreTest (tcu::TestContext&         testCtx,
464                                           const std::string&    name,
465                                           const std::string&    description,
466                                           const Texture&                texture,
467                                           const VkFormat                format,
468                                           const deUint32                flags)
469         : TestCase                                              (testCtx, name, description)
470         , m_texture                                             (texture)
471         , m_format                                              (format)
472         , m_declareImageFormatInShader  ((flags & FLAG_DECLARE_IMAGE_FORMAT_IN_SHADER) != 0)
473         , m_singleLayerBind                             ((flags & FLAG_SINGLE_LAYER_BIND) != 0)
474         , m_minalign                                    ((flags & FLAG_MINALIGN) != 0)
475 {
476         if (m_singleLayerBind)
477                 DE_ASSERT(m_texture.numLayers() > 1);
478 }
479
480 void StoreTest::checkSupport (Context& context) const
481 {
482         const VkFormatProperties formatProperties (getPhysicalDeviceFormatProperties(context.getInstanceInterface(), context.getPhysicalDevice(), m_format));
483
484         if (!m_declareImageFormatInShader)
485                 context.requireDeviceCoreFeature(DEVICE_CORE_FEATURE_SHADER_STORAGE_IMAGE_WRITE_WITHOUT_FORMAT);
486
487         if (m_texture.type() == IMAGE_TYPE_CUBE_ARRAY)
488                 context.requireDeviceCoreFeature(DEVICE_CORE_FEATURE_IMAGE_CUBE_ARRAY);
489
490         if ((m_texture.type() != IMAGE_TYPE_BUFFER) && !(formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT))
491                 TCU_THROW(NotSupportedError, "Format not supported for storage images");
492
493         if (m_texture.type() == IMAGE_TYPE_BUFFER && !(formatProperties.bufferFeatures & VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT))
494                 TCU_THROW(NotSupportedError, "Format not supported for storage texel buffers");
495 }
496
497 void StoreTest::initPrograms (SourceCollections& programCollection) const
498 {
499         const float storeColorScale = computeStoreColorScale(m_format, m_texture.size());
500         const float storeColorBias = computeStoreColorBias(m_format);
501         DE_ASSERT(colorScaleAndBiasAreValid(m_format, storeColorScale, storeColorBias));
502
503         const deUint32 xMax = m_texture.size().x() - 1;
504         const deUint32 yMax = m_texture.size().y() - 1;
505         const std::string signednessPrefix = isUintFormat(m_format) ? "u" : isIntFormat(m_format) ? "i" : "";
506         const bool storeNegativeValues = isSignedFormat(m_format) && (storeColorBias == 0);
507         bool useClamp = false;
508         std::string colorBaseExpr = signednessPrefix + "vec4("
509                 + "gx^gy^gz, "
510                 + "(" + de::toString(xMax) + "-gx)^gy^gz, "
511                 + "gx^(" + de::toString(yMax) + "-gy)^gz, "
512                 + "(" + de::toString(xMax) + "-gx)^(" + de::toString(yMax) + "-gy)^gz)";
513
514         // Large integer values may not be represented with formats with low bit depths
515         if (isIntegerFormat(m_format))
516         {
517                 const deInt64 minStoreValue = storeNegativeValues ? 0 - deRoundFloatToInt64((float)de::max(xMax, yMax) / 2.0f) : 0;
518                 const deInt64 maxStoreValue = storeNegativeValues ? deRoundFloatToInt64((float)de::max(xMax, yMax) / 2.0f) : de::max(xMax, yMax);
519
520                 useClamp = !isRepresentableIntegerValue(tcu::Vector<deInt64, 4>(minStoreValue), mapVkFormat(m_format)) ||
521                                    !isRepresentableIntegerValue(tcu::Vector<deInt64, 4>(maxStoreValue), mapVkFormat(m_format));
522         }
523
524         // Clamp if integer value cannot be represented with the current format
525         if (useClamp)
526         {
527                 const tcu::IVec4 bitDepths = tcu::getTextureFormatBitDepth(mapVkFormat(m_format));
528                 tcu::IVec4 minRepresentableValue;
529                 tcu::IVec4 maxRepresentableValue;
530
531                 switch (tcu::getTextureChannelClass(mapVkFormat(m_format).type))
532                 {
533                         case tcu::TEXTURECHANNELCLASS_UNSIGNED_INTEGER:
534                         {
535                                 minRepresentableValue = tcu::IVec4(0);
536                                 maxRepresentableValue = (tcu::IVec4(1) << bitDepths) - tcu::IVec4(1);
537                                 break;
538                         }
539
540                         case tcu::TEXTURECHANNELCLASS_SIGNED_INTEGER:
541                         {
542                                 minRepresentableValue = -(tcu::IVec4(1) << bitDepths - tcu::IVec4(1));
543                                 maxRepresentableValue = (tcu::IVec4(1) << (bitDepths - tcu::IVec4(1))) - tcu::IVec4(1);
544                                 break;
545                         }
546
547                         default:
548                                 DE_ASSERT(isIntegerFormat(m_format));
549                 }
550
551                 colorBaseExpr = "clamp(" + colorBaseExpr + ", "
552                                                 + signednessPrefix + "vec4" + de::toString(minRepresentableValue) + ", "
553                                                 + signednessPrefix + "vec4" + de::toString(maxRepresentableValue) + ")";
554         }
555
556         std::string colorExpr = colorBaseExpr + (storeColorScale == 1.0f ? "" : "*" + de::toString(storeColorScale))
557                                                         + (storeColorBias == 0.0f ? "" : " + float(" + de::toString(storeColorBias) + ")");
558
559         if (storeNegativeValues)
560                 colorExpr += "-" + de::toString(deRoundFloatToInt32((float)deMax32(xMax, yMax) / 2.0f));
561
562         const int dimension = (m_singleLayerBind ? m_texture.layerDimension() : m_texture.dimension());
563         const std::string texelCoordStr = (dimension == 1 ? "gx" : dimension == 2 ? "ivec2(gx, gy)" : dimension == 3 ? "ivec3(gx, gy, gz)" : "");
564
565         const ImageType usedImageType = (m_singleLayerBind ? getImageTypeForSingleLayer(m_texture.type()) : m_texture.type());
566         const std::string imageTypeStr = getShaderImageType(mapVkFormat(m_format), usedImageType);
567
568         std::ostringstream src;
569         src << glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_440) << "\n"
570                 << "\n"
571                 << "layout (local_size_x = 1, local_size_y = 1, local_size_z = 1) in;\n";
572         if (m_declareImageFormatInShader)
573         {
574                 const std::string formatQualifierStr = getShaderImageFormatQualifier(mapVkFormat(m_format));
575                 src << "layout (binding = 0, " << formatQualifierStr << ") writeonly uniform " << imageTypeStr << " u_image;\n";
576         }
577         else
578                 src << "layout (binding = 0) writeonly uniform " << imageTypeStr << " u_image;\n";
579
580         if (m_singleLayerBind)
581                 src << "layout (binding = 1) readonly uniform Constants {\n"
582                         << "    int u_layerNdx;\n"
583                         << "};\n";
584
585         src << "\n"
586                 << "void main (void)\n"
587                 << "{\n"
588                 << "    int gx = int(gl_GlobalInvocationID.x);\n"
589                 << "    int gy = int(gl_GlobalInvocationID.y);\n"
590                 << "    int gz = " << (m_singleLayerBind ? "u_layerNdx" : "int(gl_GlobalInvocationID.z)") << ";\n"
591                 << "    imageStore(u_image, " << texelCoordStr << ", " << colorExpr << ");\n"
592                 << "}\n";
593
594         programCollection.glslSources.add("comp") << glu::ComputeSource(src.str());
595 }
596
597 //! Generic test iteration algorithm for image tests
598 class BaseTestInstance : public TestInstance
599 {
600 public:
601                                                                         BaseTestInstance                                                (Context&               context,
602                                                                                                                                                          const Texture& texture,
603                                                                                                                                                          const VkFormat format,
604                                                                                                                                                          const bool             declareImageFormatInShader,
605                                                                                                                                                          const bool             singleLayerBind,
606                                                                                                                                                          const bool             minalign,
607                                                                                                                                                          const bool             bufferLoadUniform);
608
609         tcu::TestStatus                                 iterate                                                                 (void);
610
611         virtual                                                 ~BaseTestInstance                                               (void) {}
612
613 protected:
614         virtual VkDescriptorSetLayout   prepareDescriptors                                              (void) = 0;
615         virtual tcu::TestStatus                 verifyResult                                                    (void) = 0;
616
617         virtual void                                    commandBeforeCompute                                    (const VkCommandBuffer  cmdBuffer) = 0;
618         virtual void                                    commandBetweenShaderInvocations                 (const VkCommandBuffer  cmdBuffer) = 0;
619         virtual void                                    commandAfterCompute                                             (const VkCommandBuffer  cmdBuffer) = 0;
620
621         virtual void                                    commandBindDescriptorsForLayer                  (const VkCommandBuffer  cmdBuffer,
622                                                                                                                                                          const VkPipelineLayout pipelineLayout,
623                                                                                                                                                          const int                              layerNdx) = 0;
624         virtual deUint32                                getViewOffset                                                   (Context&               context,
625                                                                                                                                                          const VkFormat format,
626                                                                                                                                                          bool                   uniform);
627
628         const Texture                                   m_texture;
629         const VkFormat                                  m_format;
630         const bool                                              m_declareImageFormatInShader;
631         const bool                                              m_singleLayerBind;
632         const bool                                              m_minalign;
633         const bool                                              m_bufferLoadUniform;
634         const deUint32                                  m_srcViewOffset;
635         const deUint32                                  m_dstViewOffset;
636 };
637
638 BaseTestInstance::BaseTestInstance (Context& context, const Texture& texture, const VkFormat format, const bool declareImageFormatInShader, const bool singleLayerBind, const bool minalign, const bool bufferLoadUniform)
639         : TestInstance                                  (context)
640         , m_texture                                             (texture)
641         , m_format                                              (format)
642         , m_declareImageFormatInShader  (declareImageFormatInShader)
643         , m_singleLayerBind                             (singleLayerBind)
644         , m_minalign                                    (minalign)
645         , m_bufferLoadUniform                   (bufferLoadUniform)
646         , m_srcViewOffset                               (getViewOffset(context, format, m_bufferLoadUniform))
647         , m_dstViewOffset                               (getViewOffset(context, formatHasThreeComponents(format) ? getSingleComponentFormat(format) : format, false))
648 {
649 }
650
651 tcu::TestStatus BaseTestInstance::iterate (void)
652 {
653         const DeviceInterface&                  vk                                      = m_context.getDeviceInterface();
654         const VkDevice                                  device                          = m_context.getDevice();
655         const VkQueue                                   queue                           = m_context.getUniversalQueue();
656         const deUint32                                  queueFamilyIndex        = m_context.getUniversalQueueFamilyIndex();
657
658         const Unique<VkShaderModule> shaderModule(createShaderModule(vk, device, m_context.getBinaryCollection().get("comp"), 0));
659
660         const VkDescriptorSetLayout descriptorSetLayout = prepareDescriptors();
661         const Unique<VkPipelineLayout> pipelineLayout(makePipelineLayout(vk, device, descriptorSetLayout));
662         const Unique<VkPipeline> pipeline(makeComputePipeline(vk, device, *pipelineLayout, *shaderModule));
663
664         const Unique<VkCommandPool> cmdPool(createCommandPool(vk, device, VK_COMMAND_POOL_CREATE_TRANSIENT_BIT, queueFamilyIndex));
665         const Unique<VkCommandBuffer> cmdBuffer(allocateCommandBuffer(vk, device, *cmdPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY));
666
667         beginCommandBuffer(vk, *cmdBuffer);
668
669         vk.cmdBindPipeline(*cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, *pipeline);
670         commandBeforeCompute(*cmdBuffer);
671
672         const tcu::IVec3 workSize = (m_singleLayerBind ? m_texture.layerSize() : m_texture.size());
673         const int loopNumLayers = (m_singleLayerBind ? m_texture.numLayers() : 1);
674         for (int layerNdx = 0; layerNdx < loopNumLayers; ++layerNdx)
675         {
676                 commandBindDescriptorsForLayer(*cmdBuffer, *pipelineLayout, layerNdx);
677
678                 if (layerNdx > 0)
679                         commandBetweenShaderInvocations(*cmdBuffer);
680
681                 vk.cmdDispatch(*cmdBuffer, workSize.x(), workSize.y(), workSize.z());
682         }
683
684         commandAfterCompute(*cmdBuffer);
685
686         endCommandBuffer(vk, *cmdBuffer);
687
688         submitCommandsAndWait(vk, device, queue, *cmdBuffer);
689
690         return verifyResult();
691 }
692
693 //! Base store test implementation
694 class StoreTestInstance : public BaseTestInstance
695 {
696 public:
697                                                                         StoreTestInstance                                               (Context&               context,
698                                                                                                                                                          const Texture& texture,
699                                                                                                                                                          const VkFormat format,
700                                                                                                                                                          const bool             declareImageFormatInShader,
701                                                                                                                                                          const bool             singleLayerBind,
702                                                                                                                                                          const bool             minalign);
703
704 protected:
705         virtual tcu::TestStatus                 verifyResult                                                    (void);
706
707         // Add empty implementations for functions that might be not needed
708         void                                                    commandBeforeCompute                                    (const VkCommandBuffer) {}
709         void                                                    commandBetweenShaderInvocations                 (const VkCommandBuffer) {}
710         void                                                    commandAfterCompute                                             (const VkCommandBuffer) {}
711
712         de::MovePtr<Buffer>                             m_imageBuffer;
713         const VkDeviceSize                              m_imageSizeBytes;
714 };
715
716 deUint32 BaseTestInstance::getViewOffset(Context&                       context,
717                                                                                  const VkFormat         format,
718                                                                                  bool                           uniform)
719 {
720         if (m_minalign)
721         {
722                 if (!context.getTexelBufferAlignmentFeaturesEXT().texelBufferAlignment)
723                         return (deUint32)context.getDeviceProperties().limits.minTexelBufferOffsetAlignment;
724
725                 VkPhysicalDeviceTexelBufferAlignmentPropertiesEXT alignmentProperties;
726                 deMemset(&alignmentProperties, 0, sizeof(alignmentProperties));
727                 alignmentProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TEXEL_BUFFER_ALIGNMENT_PROPERTIES_EXT;
728
729                 VkPhysicalDeviceProperties2 properties2;
730                 deMemset(&properties2, 0, sizeof(properties2));
731                 properties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
732                 properties2.pNext = &alignmentProperties;
733
734                 context.getInstanceInterface().getPhysicalDeviceProperties2(context.getPhysicalDevice(), &properties2);
735
736                 VkBool32 singleTexelAlignment = uniform ? alignmentProperties.uniformTexelBufferOffsetSingleTexelAlignment :
737                                                                                                   alignmentProperties.storageTexelBufferOffsetSingleTexelAlignment;
738                 VkDeviceSize align = uniform ? alignmentProperties.uniformTexelBufferOffsetAlignmentBytes :
739                                                                            alignmentProperties.storageTexelBufferOffsetAlignmentBytes;
740
741                 VkDeviceSize texelSize = formatHasThreeComponents(format) ? tcu::getChannelSize(vk::mapVkFormat(format).type) : tcu::getPixelSize(vk::mapVkFormat(format));
742
743                 if (singleTexelAlignment)
744                         align = de::min(align, texelSize);
745
746                 return (deUint32)align;
747         }
748
749         return 0;
750 }
751
752 StoreTestInstance::StoreTestInstance (Context& context, const Texture& texture, const VkFormat format, const bool declareImageFormatInShader, const bool singleLayerBind, const bool minalign)
753         : BaseTestInstance              (context, texture, format, declareImageFormatInShader, singleLayerBind, minalign, false)
754         , m_imageSizeBytes              (getImageSizeBytes(texture.size(), format))
755 {
756         const DeviceInterface&  vk                      = m_context.getDeviceInterface();
757         const VkDevice                  device          = m_context.getDevice();
758         Allocator&                              allocator       = m_context.getDefaultAllocator();
759
760         // A helper buffer with enough space to hold the whole image. Usage flags accommodate all derived test instances.
761
762         m_imageBuffer = de::MovePtr<Buffer>(new Buffer(
763                 vk, device, allocator,
764                 makeBufferCreateInfo(m_imageSizeBytes + m_dstViewOffset, VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT),
765                 MemoryRequirement::HostVisible));
766 }
767
768 tcu::TestStatus StoreTestInstance::verifyResult (void)
769 {
770         const DeviceInterface&  vk              = m_context.getDeviceInterface();
771         const VkDevice                  device  = m_context.getDevice();
772
773         const tcu::IVec3 imageSize = m_texture.size();
774         const tcu::TextureLevel reference = generateReferenceImage(imageSize, m_format);
775
776         const Allocation& alloc = m_imageBuffer->getAllocation();
777         invalidateAlloc(vk, device, alloc);
778         const tcu::ConstPixelBufferAccess result(mapVkFormat(m_format), imageSize, (const char *)alloc.getHostPtr() + m_dstViewOffset);
779
780         if (comparePixelBuffers(m_context.getTestContext().getLog(), m_texture, m_format, reference.getAccess(), result))
781                 return tcu::TestStatus::pass("Passed");
782         else
783                 return tcu::TestStatus::fail("Image comparison failed");
784 }
785
786 //! Store test for images
787 class ImageStoreTestInstance : public StoreTestInstance
788 {
789 public:
790                                                                                 ImageStoreTestInstance                                  (Context&                               context,
791                                                                                                                                                                  const Texture&                 texture,
792                                                                                                                                                                  const VkFormat                 format,
793                                                                                                                                                                  const bool                             declareImageFormatInShader,
794                                                                                                                                                                  const bool                             singleLayerBind,
795                                                                                                                                                                  const bool                             minalign);
796
797 protected:
798         VkDescriptorSetLayout                           prepareDescriptors                                              (void);
799         void                                                            commandBeforeCompute                                    (const VkCommandBuffer  cmdBuffer);
800         void                                                            commandBetweenShaderInvocations                 (const VkCommandBuffer  cmdBuffer);
801         void                                                            commandAfterCompute                                             (const VkCommandBuffer  cmdBuffer);
802
803         void                                                            commandBindDescriptorsForLayer                  (const VkCommandBuffer  cmdBuffer,
804                                                                                                                                                                  const VkPipelineLayout pipelineLayout,
805                                                                                                                                                                  const int                              layerNdx);
806
807         de::MovePtr<Image>                                      m_image;
808         de::MovePtr<Buffer>                                     m_constantsBuffer;
809         const VkDeviceSize                                      m_constantsBufferChunkSizeBytes;
810         Move<VkDescriptorSetLayout>                     m_descriptorSetLayout;
811         Move<VkDescriptorPool>                          m_descriptorPool;
812         std::vector<SharedVkDescriptorSet>      m_allDescriptorSets;
813         std::vector<SharedVkImageView>          m_allImageViews;
814 };
815
816 ImageStoreTestInstance::ImageStoreTestInstance (Context&                context,
817                                                                                                 const Texture&  texture,
818                                                                                                 const VkFormat  format,
819                                                                                                 const bool              declareImageFormatInShader,
820                                                                                                 const bool              singleLayerBind,
821                                                                                                 const bool              minalign)
822         : StoreTestInstance                                     (context, texture, format, declareImageFormatInShader, singleLayerBind, minalign)
823         , m_constantsBufferChunkSizeBytes       (getOptimalUniformBufferChunkSize(context.getInstanceInterface(), context.getPhysicalDevice(), sizeof(deUint32)))
824         , m_allDescriptorSets                           (texture.numLayers())
825         , m_allImageViews                                       (texture.numLayers())
826 {
827         const DeviceInterface&  vk                      = m_context.getDeviceInterface();
828         const VkDevice                  device          = m_context.getDevice();
829         Allocator&                              allocator       = m_context.getDefaultAllocator();
830
831         m_image = de::MovePtr<Image>(new Image(
832                 vk, device, allocator,
833                 makeImageCreateInfo(m_texture, m_format, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, 0u),
834                 MemoryRequirement::Any));
835
836         // This buffer will be used to pass constants to the shader
837
838         const int numLayers = m_texture.numLayers();
839         const VkDeviceSize constantsBufferSizeBytes = numLayers * m_constantsBufferChunkSizeBytes;
840         m_constantsBuffer = de::MovePtr<Buffer>(new Buffer(
841                 vk, device, allocator,
842                 makeBufferCreateInfo(constantsBufferSizeBytes, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT),
843                 MemoryRequirement::HostVisible));
844
845         {
846                 const Allocation& alloc = m_constantsBuffer->getAllocation();
847                 deUint8* const basePtr = static_cast<deUint8*>(alloc.getHostPtr());
848
849                 deMemset(alloc.getHostPtr(), 0, static_cast<size_t>(constantsBufferSizeBytes));
850
851                 for (int layerNdx = 0; layerNdx < numLayers; ++layerNdx)
852                 {
853                         deUint32* valuePtr = reinterpret_cast<deUint32*>(basePtr + layerNdx * m_constantsBufferChunkSizeBytes);
854                         *valuePtr = static_cast<deUint32>(layerNdx);
855                 }
856
857                 flushAlloc(vk, device, alloc);
858         }
859 }
860
861 VkDescriptorSetLayout ImageStoreTestInstance::prepareDescriptors (void)
862 {
863         const DeviceInterface&  vk              = m_context.getDeviceInterface();
864         const VkDevice                  device  = m_context.getDevice();
865
866         const int numLayers = m_texture.numLayers();
867         m_descriptorSetLayout = DescriptorSetLayoutBuilder()
868                 .addSingleBinding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_SHADER_STAGE_COMPUTE_BIT)
869                 .addSingleBinding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_COMPUTE_BIT)
870                 .build(vk, device);
871
872         m_descriptorPool = DescriptorPoolBuilder()
873                 .addType(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, numLayers)
874                 .addType(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, numLayers)
875                 .build(vk, device, VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, numLayers);
876
877         if (m_singleLayerBind)
878         {
879                 for (int layerNdx = 0; layerNdx < numLayers; ++layerNdx)
880                 {
881                         m_allDescriptorSets[layerNdx]   = makeVkSharedPtr(makeDescriptorSet(vk, device, *m_descriptorPool, *m_descriptorSetLayout));
882                         m_allImageViews[layerNdx]               = makeVkSharedPtr(makeImageView(
883                                                                                                 vk, device, m_image->get(), mapImageViewType(getImageTypeForSingleLayer(m_texture.type())), m_format,
884                                                                                                 makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, layerNdx, 1u)));
885                 }
886         }
887         else // bind all layers at once
888         {
889                 m_allDescriptorSets[0] = makeVkSharedPtr(makeDescriptorSet(vk, device, *m_descriptorPool, *m_descriptorSetLayout));
890                 m_allImageViews[0] = makeVkSharedPtr(makeImageView(
891                                                                 vk, device, m_image->get(), mapImageViewType(m_texture.type()), m_format,
892                                                                 makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, numLayers)));
893         }
894
895         return *m_descriptorSetLayout;  // not passing the ownership
896 }
897
898 void ImageStoreTestInstance::commandBindDescriptorsForLayer (const VkCommandBuffer cmdBuffer, const VkPipelineLayout pipelineLayout, const int layerNdx)
899 {
900         const DeviceInterface&  vk              = m_context.getDeviceInterface();
901         const VkDevice                  device  = m_context.getDevice();
902
903         const VkDescriptorSet descriptorSet = **m_allDescriptorSets[layerNdx];
904         const VkImageView imageView = **m_allImageViews[layerNdx];
905
906         const VkDescriptorImageInfo descriptorImageInfo = makeDescriptorImageInfo(DE_NULL, imageView, VK_IMAGE_LAYOUT_GENERAL);
907
908         // Set the next chunk of the constants buffer. Each chunk begins with layer index that we've set before.
909         const VkDescriptorBufferInfo descriptorConstantsBufferInfo = makeDescriptorBufferInfo(
910                 m_constantsBuffer->get(), layerNdx*m_constantsBufferChunkSizeBytes, m_constantsBufferChunkSizeBytes);
911
912         DescriptorSetUpdateBuilder()
913                 .writeSingle(descriptorSet, DescriptorSetUpdateBuilder::Location::binding(0u), VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &descriptorImageInfo)
914                 .writeSingle(descriptorSet, DescriptorSetUpdateBuilder::Location::binding(1u), VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, &descriptorConstantsBufferInfo)
915                 .update(vk, device);
916         vk.cmdBindDescriptorSets(cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0u, 1u, &descriptorSet, 0u, DE_NULL);
917 }
918
919 void ImageStoreTestInstance::commandBeforeCompute (const VkCommandBuffer cmdBuffer)
920 {
921         const DeviceInterface& vk = m_context.getDeviceInterface();
922
923         const VkImageSubresourceRange fullImageSubresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, m_texture.numLayers());
924         const VkImageMemoryBarrier setImageLayoutBarrier = makeImageMemoryBarrier(
925                 0u, VK_ACCESS_SHADER_WRITE_BIT,
926                 VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL,
927                 m_image->get(), fullImageSubresourceRange);
928
929         const VkDeviceSize constantsBufferSize = m_texture.numLayers() * m_constantsBufferChunkSizeBytes;
930         const VkBufferMemoryBarrier writeConstantsBarrier = makeBufferMemoryBarrier(
931                 VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT,
932                 m_constantsBuffer->get(), 0ull, constantsBufferSize);
933
934         vk.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 1, &writeConstantsBarrier, 1, &setImageLayoutBarrier);
935 }
936
937 void ImageStoreTestInstance::commandBetweenShaderInvocations (const VkCommandBuffer cmdBuffer)
938 {
939         commandImageWriteBarrierBetweenShaderInvocations(m_context, cmdBuffer, m_image->get(), m_texture);
940 }
941
942 void ImageStoreTestInstance::commandAfterCompute (const VkCommandBuffer cmdBuffer)
943 {
944         commandCopyImageToBuffer(m_context, cmdBuffer, m_image->get(), m_imageBuffer->get(), m_imageSizeBytes, m_texture);
945 }
946
947 //! Store test for buffers
948 class BufferStoreTestInstance : public StoreTestInstance
949 {
950 public:
951                                                                         BufferStoreTestInstance                                 (Context&                               context,
952                                                                                                                                                          const Texture&                 texture,
953                                                                                                                                                          const VkFormat                 format,
954                                                                                                                                                          const bool                             declareImageFormatInShader,
955                                                                                                                                                          const bool                             minalign);
956
957 protected:
958         VkDescriptorSetLayout                   prepareDescriptors                                              (void);
959         void                                                    commandAfterCompute                                             (const VkCommandBuffer  cmdBuffer);
960
961         void                                                    commandBindDescriptorsForLayer                  (const VkCommandBuffer  cmdBuffer,
962                                                                                                                                                          const VkPipelineLayout pipelineLayout,
963                                                                                                                                                          const int                              layerNdx);
964
965         Move<VkDescriptorSetLayout>             m_descriptorSetLayout;
966         Move<VkDescriptorPool>                  m_descriptorPool;
967         Move<VkDescriptorSet>                   m_descriptorSet;
968         Move<VkBufferView>                              m_bufferView;
969 };
970
971 BufferStoreTestInstance::BufferStoreTestInstance (Context&                      context,
972                                                                                                   const Texture&        texture,
973                                                                                                   const VkFormat        format,
974                                                                                                   const bool            declareImageFormatInShader,
975                                                                                                   const bool            minalign)
976         : StoreTestInstance(context, texture, format, declareImageFormatInShader, false, minalign)
977 {
978 }
979
980 VkDescriptorSetLayout BufferStoreTestInstance::prepareDescriptors (void)
981 {
982         const DeviceInterface&  vk              = m_context.getDeviceInterface();
983         const VkDevice                  device  = m_context.getDevice();
984
985         m_descriptorSetLayout = DescriptorSetLayoutBuilder()
986                 .addSingleBinding(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, VK_SHADER_STAGE_COMPUTE_BIT)
987                 .build(vk, device);
988
989         m_descriptorPool = DescriptorPoolBuilder()
990                 .addType(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER)
991                 .build(vk, device, VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, 1u);
992
993         m_descriptorSet = makeDescriptorSet(vk, device, *m_descriptorPool, *m_descriptorSetLayout);
994         m_bufferView = makeBufferView(vk, device, m_imageBuffer->get(), m_format, m_dstViewOffset, m_imageSizeBytes);
995
996         return *m_descriptorSetLayout;  // not passing the ownership
997 }
998
999 void BufferStoreTestInstance::commandBindDescriptorsForLayer (const VkCommandBuffer cmdBuffer, const VkPipelineLayout pipelineLayout, const int layerNdx)
1000 {
1001         DE_ASSERT(layerNdx == 0);
1002         DE_UNREF(layerNdx);
1003
1004         const VkDevice                  device  = m_context.getDevice();
1005         const DeviceInterface&  vk              = m_context.getDeviceInterface();
1006
1007         DescriptorSetUpdateBuilder()
1008                 .writeSingle(*m_descriptorSet, DescriptorSetUpdateBuilder::Location::binding(0u), VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, &m_bufferView.get())
1009                 .update(vk, device);
1010         vk.cmdBindDescriptorSets(cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0u, 1u, &m_descriptorSet.get(), 0u, DE_NULL);
1011 }
1012
1013 void BufferStoreTestInstance::commandAfterCompute (const VkCommandBuffer cmdBuffer)
1014 {
1015         commandBufferWriteBarrierBeforeHostRead(m_context, cmdBuffer, m_imageBuffer->get(), m_imageSizeBytes + m_dstViewOffset);
1016 }
1017
1018 class LoadStoreTest : public TestCase
1019 {
1020 public:
1021         enum TestFlags
1022         {
1023                 FLAG_SINGLE_LAYER_BIND                          = 1 << 0,       //!< Run the shader multiple times, each time binding a different layer.
1024                 FLAG_RESTRICT_IMAGES                            = 1 << 1,       //!< If given, images in the shader will be qualified with "restrict".
1025                 FLAG_DECLARE_IMAGE_FORMAT_IN_SHADER     = 1 << 2,       //!< Declare the format of the images in the shader code
1026                 FLAG_MINALIGN                                           = 1 << 3,       //!< Use bufferview offset that matches the advertised minimum alignment
1027                 FLAG_UNIFORM_TEXEL_BUFFER                       = 1 << 4,       //!< Load from a uniform texel buffer rather than a storage texel buffer
1028         };
1029
1030                                                         LoadStoreTest                   (tcu::TestContext&              testCtx,
1031                                                                                                          const std::string&             name,
1032                                                                                                          const std::string&             description,
1033                                                                                                          const Texture&                 texture,
1034                                                                                                          const VkFormat                 format,
1035                                                                                                          const VkFormat                 imageFormat,
1036                                                                                                          const deUint32                 flags = FLAG_DECLARE_IMAGE_FORMAT_IN_SHADER,
1037                                                                                                          const deBool                   imageLoadStoreLodAMD = DE_FALSE);
1038
1039         virtual void                    checkSupport                    (Context&                               context) const;
1040         void                                    initPrograms                    (SourceCollections&             programCollection) const;
1041         TestInstance*                   createInstance                  (Context&                               context) const;
1042
1043 private:
1044         const Texture                   m_texture;
1045         const VkFormat                  m_format;                                               //!< Format as accessed in the shader
1046         const VkFormat                  m_imageFormat;                                  //!< Storage format
1047         const bool                              m_declareImageFormatInShader;   //!< Whether the shader will specify the format layout qualifier of the images
1048         const bool                              m_singleLayerBind;
1049         const bool                              m_restrictImages;
1050         const bool                              m_minalign;
1051         bool                                    m_bufferLoadUniform;
1052         const deBool                    m_imageLoadStoreLodAMD;
1053 };
1054
1055 LoadStoreTest::LoadStoreTest (tcu::TestContext&         testCtx,
1056                                                           const std::string&    name,
1057                                                           const std::string&    description,
1058                                                           const Texture&                texture,
1059                                                           const VkFormat                format,
1060                                                           const VkFormat                imageFormat,
1061                                                           const deUint32                flags,
1062                                                           const deBool                  imageLoadStoreLodAMD)
1063         : TestCase                                              (testCtx, name, description)
1064         , m_texture                                             (texture)
1065         , m_format                                              (format)
1066         , m_imageFormat                                 (imageFormat)
1067         , m_declareImageFormatInShader  ((flags & FLAG_DECLARE_IMAGE_FORMAT_IN_SHADER) != 0)
1068         , m_singleLayerBind                             ((flags & FLAG_SINGLE_LAYER_BIND) != 0)
1069         , m_restrictImages                              ((flags & FLAG_RESTRICT_IMAGES) != 0)
1070         , m_minalign                                    ((flags & FLAG_MINALIGN) != 0)
1071         , m_bufferLoadUniform                   ((flags & FLAG_UNIFORM_TEXEL_BUFFER) != 0)
1072         , m_imageLoadStoreLodAMD                (imageLoadStoreLodAMD)
1073 {
1074         if (m_singleLayerBind)
1075                 DE_ASSERT(m_texture.numLayers() > 1);
1076
1077         DE_ASSERT(formatsAreCompatible(m_format, m_imageFormat));
1078 }
1079
1080 void LoadStoreTest::checkSupport (Context& context) const
1081 {
1082         const vk::VkFormatProperties    formatProperties        (vk::getPhysicalDeviceFormatProperties(context.getInstanceInterface(),
1083                                                                                                                                                                                            context.getPhysicalDevice(),
1084                                                                                                                                                                                            m_format));
1085         const vk::VkFormatProperties imageFormatProperties  (vk::getPhysicalDeviceFormatProperties(context.getInstanceInterface(),
1086                                                                                                                                                                                            context.getPhysicalDevice(),
1087                                                                                                                                                                                            m_imageFormat));
1088         if (m_imageLoadStoreLodAMD)
1089                 context.requireDeviceFunctionality("VK_AMD_shader_image_load_store_lod");
1090
1091         if (!m_bufferLoadUniform && !m_declareImageFormatInShader)
1092                 context.requireDeviceCoreFeature(DEVICE_CORE_FEATURE_SHADER_STORAGE_IMAGE_READ_WITHOUT_FORMAT);
1093
1094         if (m_texture.type() == IMAGE_TYPE_CUBE_ARRAY)
1095                 context.requireDeviceCoreFeature(DEVICE_CORE_FEATURE_IMAGE_CUBE_ARRAY);
1096
1097         if ((m_texture.type() != IMAGE_TYPE_BUFFER) && !(formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT))
1098                 TCU_THROW(NotSupportedError, "Format not supported for storage images");
1099
1100         if (m_texture.type() == IMAGE_TYPE_BUFFER && !(formatProperties.bufferFeatures & VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT))
1101                 TCU_THROW(NotSupportedError, "Format not supported for storage texel buffers");
1102
1103         if ((m_texture.type() != IMAGE_TYPE_BUFFER) && !(imageFormatProperties.optimalTilingFeatures))
1104                 TCU_THROW(NotSupportedError, "Underlying format not supported at all for images");
1105
1106         if ((m_texture.type() == IMAGE_TYPE_BUFFER) && !(imageFormatProperties.bufferFeatures))
1107                 TCU_THROW(NotSupportedError, "Underlying format not supported at all for buffers");
1108
1109     if (formatHasThreeComponents(m_format))
1110         {
1111                 // When the source buffer is three-component, the destination buffer is single-component.
1112                 VkFormat dstFormat = getSingleComponentFormat(m_format);
1113                 const vk::VkFormatProperties    dstFormatProperties     (vk::getPhysicalDeviceFormatProperties(context.getInstanceInterface(),
1114                                                                                                                                                                                                    context.getPhysicalDevice(),
1115                                                                                                                                                                                                    dstFormat));
1116
1117                 if (m_texture.type() == IMAGE_TYPE_BUFFER && !(dstFormatProperties.bufferFeatures & VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT))
1118                         TCU_THROW(NotSupportedError, "Format not supported for storage texel buffers");
1119         }
1120         else
1121                 if (m_texture.type() == IMAGE_TYPE_BUFFER && !(formatProperties.bufferFeatures & VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT))
1122                         TCU_THROW(NotSupportedError, "Format not supported for storage texel buffers");
1123
1124         if (m_bufferLoadUniform && m_texture.type() == IMAGE_TYPE_BUFFER && !(formatProperties.bufferFeatures & VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT))
1125                 TCU_THROW(NotSupportedError, "Format not supported for uniform texel buffers");
1126 }
1127
1128 void LoadStoreTest::initPrograms (SourceCollections& programCollection) const
1129 {
1130         const tcu::TextureFormat        texFormat                       = mapVkFormat(m_format);
1131         const int                                       dimension                       = (m_singleLayerBind ? m_texture.layerDimension() : m_texture.dimension());
1132         const ImageType                         usedImageType           = (m_singleLayerBind ? getImageTypeForSingleLayer(m_texture.type()) : m_texture.type());
1133         const std::string                       formatQualifierStr      = getShaderImageFormatQualifier(texFormat);
1134         const std::string                       uniformTypeStr          = getFormatPrefix(texFormat) + "textureBuffer";
1135         const std::string                       imageTypeStr            = getShaderImageType(texFormat, usedImageType);
1136         const std::string                       maybeRestrictStr        = (m_restrictImages ? "restrict " : "");
1137         const std::string                       xMax                            = de::toString(m_texture.size().x() - 1);
1138
1139         std::ostringstream src;
1140         src << glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_450) << "\n"
1141                 << "\n";
1142         if (!m_declareImageFormatInShader)
1143         {
1144                 src << "#extension GL_EXT_shader_image_load_formatted : require\n";
1145         }
1146
1147         if (m_imageLoadStoreLodAMD)
1148         {
1149                 src << "#extension GL_AMD_shader_image_load_store_lod : require\n";
1150         }
1151
1152         src << "layout (local_size_x = 1, local_size_y = 1, local_size_z = 1) in;\n";
1153         if (m_bufferLoadUniform)
1154                 src << "layout (binding = 0) uniform " << uniformTypeStr << " u_image0;\n";
1155         else if (m_declareImageFormatInShader)
1156                 src << "layout (binding = 0, " << formatQualifierStr << ") " << maybeRestrictStr << "readonly uniform " << imageTypeStr << " u_image0;\n";
1157         else
1158                 src << "layout (binding = 0) " << maybeRestrictStr << "readonly uniform " << imageTypeStr << " u_image0;\n";
1159
1160         if (formatHasThreeComponents(m_format))
1161                 src << "layout (binding = 1) " << maybeRestrictStr << "writeonly uniform " << imageTypeStr << " u_image1;\n";
1162         else
1163                 src << "layout (binding = 1, " << formatQualifierStr << ") " << maybeRestrictStr << "writeonly uniform " << imageTypeStr << " u_image1;\n";
1164
1165         src << "\n"
1166                 << "void main (void)\n"
1167                 << "{\n";
1168         switch (dimension)
1169         {
1170         default: DE_ASSERT(0); // fallthrough
1171         case 1:
1172                 if (m_bufferLoadUniform)
1173                 {
1174                         // for three-component formats, the dst buffer is single-component and the shader
1175                         // expands the store into 3 component-wise stores.
1176                         std::string type = getFormatPrefix(texFormat) + "vec4";
1177                         src << "    int pos = int(gl_GlobalInvocationID.x);\n"
1178                                    "    " << type << " t = texelFetch(u_image0, " + xMax + "-pos);\n";
1179                         if (formatHasThreeComponents(m_format))
1180                         {
1181                                 src << "    imageStore(u_image1, 3*pos+0, " << type << "(t.x));\n";
1182                                 src << "    imageStore(u_image1, 3*pos+1, " << type << "(t.y));\n";
1183                                 src << "    imageStore(u_image1, 3*pos+2, " << type << "(t.z));\n";
1184                         }
1185                         else
1186                                 src << "    imageStore(u_image1, pos, t);\n";
1187                 }
1188                 else if (m_imageLoadStoreLodAMD)
1189                 {
1190                         src <<
1191                                 "    int pos = int(gl_GlobalInvocationID.x);\n";
1192
1193                         for (deInt32 levelNdx = 0; levelNdx < m_texture.numMipmapLevels(); levelNdx++)
1194                         {
1195                                 std::string xMaxSize = de::toString(deMax32(((m_texture.layerSize().x() >> levelNdx) - 1), 1u));
1196                                 src << "    imageStoreLodAMD(u_image1, pos, " + de::toString(levelNdx) + ", imageLoadLodAMD(u_image0, " + xMaxSize + "-pos, " + de::toString(levelNdx) + "));\n";
1197                         }
1198                 }
1199                 else
1200                 {
1201                         src <<
1202                                 "    int pos = int(gl_GlobalInvocationID.x);\n"
1203                                 "    imageStore(u_image1, pos, imageLoad(u_image0, " + xMax + "-pos));\n";
1204                 }
1205                 break;
1206         case 2:
1207                 if (m_imageLoadStoreLodAMD)
1208                 {
1209                         src << "    ivec2 pos = ivec2(gl_GlobalInvocationID.xy);\n";
1210
1211                         for (deInt32 levelNdx = 0; levelNdx < m_texture.numMipmapLevels(); levelNdx++)
1212                         {
1213                                 std::string xMaxSize = de::toString(deMax32(((m_texture.layerSize().x() >> levelNdx) - 1), 1u));
1214                                 src << "    imageStoreLodAMD(u_image1, pos, " + de::toString(levelNdx) + ", imageLoadLodAMD(u_image0, ivec2(" + xMaxSize + "-pos.x, pos.y), " + de::toString(levelNdx) + "));\n";
1215                         }
1216
1217                 }
1218                 else
1219                 {
1220                         src <<
1221                                 "    ivec2 pos = ivec2(gl_GlobalInvocationID.xy);\n"
1222                                 "    imageStore(u_image1, pos, imageLoad(u_image0, ivec2(" + xMax + "-pos.x, pos.y)));\n";
1223                 }
1224                 break;
1225         case 3:
1226                 if (m_imageLoadStoreLodAMD)
1227                 {
1228                         src << "    ivec3 pos = ivec3(gl_GlobalInvocationID);\n";
1229
1230                         for (deInt32 levelNdx = 0; levelNdx < m_texture.numMipmapLevels(); levelNdx++)
1231                         {
1232                                 std::string xMaxSize = de::toString(deMax32(((m_texture.layerSize().x() >> levelNdx) - 1), 1u));
1233                                 src << "    imageStoreLodAMD(u_image1, pos, " + de::toString(levelNdx) + ", imageLoadLodAMD(u_image0, ivec3(" + xMaxSize + "-pos.x, pos.y, pos.z), " + de::toString(levelNdx) + "));\n";
1234                         }
1235                 }
1236                 else
1237                 {
1238                         src <<
1239                                 "    ivec3 pos = ivec3(gl_GlobalInvocationID);\n"
1240                                 "    imageStore(u_image1, pos, imageLoad(u_image0, ivec3(" + xMax + "-pos.x, pos.y, pos.z)));\n";
1241                 }
1242                 break;
1243         }
1244         src << "}\n";
1245
1246         programCollection.glslSources.add("comp") << glu::ComputeSource(src.str());
1247 }
1248
1249 //! Load/store test base implementation
1250 class LoadStoreTestInstance : public BaseTestInstance
1251 {
1252 public:
1253                                                                         LoadStoreTestInstance                           (Context&                       context,
1254                                                                                                                                                  const Texture&         texture,
1255                                                                                                                                                  const VkFormat         format,
1256                                                                                                                                                  const VkFormat         imageFormat,
1257                                                                                                                                                  const bool                     declareImageFormatInShader,
1258                                                                                                                                                  const bool                     singleLayerBind,
1259                                                                                                                                                  const bool                     minalign,
1260                                                                                                                                                  const bool                     bufferLoadUniform);
1261
1262 protected:
1263         virtual Buffer*                                 getResultBuffer                                         (void) const = 0;       //!< Get the buffer that contains the result image
1264
1265         tcu::TestStatus                                 verifyResult                                            (void);
1266
1267         // Add empty implementations for functions that might be not needed
1268         void                                                    commandBeforeCompute                            (const VkCommandBuffer) {}
1269         void                                                    commandBetweenShaderInvocations         (const VkCommandBuffer) {}
1270         void                                                    commandAfterCompute                                     (const VkCommandBuffer) {}
1271
1272         de::MovePtr<Buffer>                             m_imageBuffer;          //!< Source data and helper buffer
1273         const VkDeviceSize                              m_imageSizeBytes;
1274         const VkFormat                                  m_imageFormat;          //!< Image format (for storage, may be different than texture format)
1275         tcu::TextureLevel                               m_referenceImage;       //!< Used as input data and later to verify result image
1276
1277         bool                                                    m_bufferLoadUniform;
1278         VkDescriptorType                                m_bufferLoadDescriptorType;
1279         VkBufferUsageFlagBits                   m_bufferLoadUsageBit;
1280 };
1281
1282 LoadStoreTestInstance::LoadStoreTestInstance (Context&                  context,
1283                                                                                           const Texture&        texture,
1284                                                                                           const VkFormat        format,
1285                                                                                           const VkFormat        imageFormat,
1286                                                                                           const bool            declareImageFormatInShader,
1287                                                                                           const bool            singleLayerBind,
1288                                                                                           const bool            minalign,
1289                                                                                           const bool            bufferLoadUniform)
1290         : BaseTestInstance              (context, texture, format, declareImageFormatInShader, singleLayerBind, minalign, bufferLoadUniform)
1291         , m_imageSizeBytes              (getImageSizeBytes(texture.size(), format))
1292         , m_imageFormat                 (imageFormat)
1293         , m_referenceImage              (generateReferenceImage(texture.size(), imageFormat, format))
1294         , m_bufferLoadUniform   (bufferLoadUniform)
1295 {
1296         const DeviceInterface&  vk                      = m_context.getDeviceInterface();
1297         const VkDevice                  device          = m_context.getDevice();
1298         Allocator&                              allocator       = m_context.getDefaultAllocator();
1299
1300         m_bufferLoadDescriptorType = m_bufferLoadUniform ? VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER : VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER;
1301         m_bufferLoadUsageBit = m_bufferLoadUniform ? VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT : VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT;
1302
1303         // A helper buffer with enough space to hold the whole image.
1304
1305         m_imageBuffer = de::MovePtr<Buffer>(new Buffer(
1306                 vk, device, allocator,
1307                 makeBufferCreateInfo(m_imageSizeBytes + m_srcViewOffset, m_bufferLoadUsageBit | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT),
1308                 MemoryRequirement::HostVisible));
1309
1310         // Copy reference data to buffer for subsequent upload to image.
1311
1312         const Allocation& alloc = m_imageBuffer->getAllocation();
1313         deMemcpy((char *)alloc.getHostPtr() + m_srcViewOffset, m_referenceImage.getAccess().getDataPtr(), static_cast<size_t>(m_imageSizeBytes));
1314         flushAlloc(vk, device, alloc);
1315 }
1316
1317 tcu::TestStatus LoadStoreTestInstance::verifyResult     (void)
1318 {
1319         const DeviceInterface&  vk              = m_context.getDeviceInterface();
1320         const VkDevice                  device  = m_context.getDevice();
1321
1322         // Apply the same transformation as done in the shader
1323         const tcu::PixelBufferAccess reference = m_referenceImage.getAccess();
1324         flipHorizontally(reference);
1325
1326         const Allocation& alloc = getResultBuffer()->getAllocation();
1327         invalidateAlloc(vk, device, alloc);
1328         const tcu::ConstPixelBufferAccess result(mapVkFormat(m_imageFormat), m_texture.size(), (const char *)alloc.getHostPtr() + m_dstViewOffset);
1329
1330         if (comparePixelBuffers(m_context.getTestContext().getLog(), m_texture, m_imageFormat, reference, result))
1331                 return tcu::TestStatus::pass("Passed");
1332         else
1333                 return tcu::TestStatus::fail("Image comparison failed");
1334 }
1335
1336 //! Load/store test for images
1337 class ImageLoadStoreTestInstance : public LoadStoreTestInstance
1338 {
1339 public:
1340                                                                                 ImageLoadStoreTestInstance                      (Context&                               context,
1341                                                                                                                                                          const Texture&                 texture,
1342                                                                                                                                                          const VkFormat                 format,
1343                                                                                                                                                          const VkFormat                 imageFormat,
1344                                                                                                                                                          const bool                             declareImageFormatInShader,
1345                                                                                                                                                          const bool                             singleLayerBind,
1346                                                                                                                                                          const bool                             minalign,
1347                                                                                                                                                          const bool                             bufferLoadUniform);
1348
1349 protected:
1350         VkDescriptorSetLayout                           prepareDescriptors                                      (void);
1351         void                                                            commandBeforeCompute                            (const VkCommandBuffer  cmdBuffer);
1352         void                                                            commandBetweenShaderInvocations         (const VkCommandBuffer  cmdBuffer);
1353         void                                                            commandAfterCompute                                     (const VkCommandBuffer  cmdBuffer);
1354
1355         void                                                            commandBindDescriptorsForLayer          (const VkCommandBuffer  cmdBuffer,
1356                                                                                                                                                          const VkPipelineLayout pipelineLayout,
1357                                                                                                                                                          const int                              layerNdx);
1358
1359         Buffer*                                                         getResultBuffer                                         (void) const { return m_imageBuffer.get(); }
1360
1361         de::MovePtr<Image>                                      m_imageSrc;
1362         de::MovePtr<Image>                                      m_imageDst;
1363         Move<VkDescriptorSetLayout>                     m_descriptorSetLayout;
1364         Move<VkDescriptorPool>                          m_descriptorPool;
1365         std::vector<SharedVkDescriptorSet>      m_allDescriptorSets;
1366         std::vector<SharedVkImageView>          m_allSrcImageViews;
1367         std::vector<SharedVkImageView>          m_allDstImageViews;
1368 };
1369
1370 ImageLoadStoreTestInstance::ImageLoadStoreTestInstance (Context&                context,
1371                                                                                                                 const Texture&  texture,
1372                                                                                                                 const VkFormat  format,
1373                                                                                                                 const VkFormat  imageFormat,
1374                                                                                                                 const bool              declareImageFormatInShader,
1375                                                                                                                 const bool              singleLayerBind,
1376                                                                                                                 const bool              minalign,
1377                                                                                                                 const bool              bufferLoadUniform)
1378         : LoadStoreTestInstance (context, texture, format, imageFormat, declareImageFormatInShader, singleLayerBind, minalign, bufferLoadUniform)
1379         , m_allDescriptorSets   (texture.numLayers())
1380         , m_allSrcImageViews    (texture.numLayers())
1381         , m_allDstImageViews    (texture.numLayers())
1382 {
1383         const DeviceInterface&          vk                                      = m_context.getDeviceInterface();
1384         const VkDevice                          device                          = m_context.getDevice();
1385         Allocator&                                      allocator                       = m_context.getDefaultAllocator();
1386         const VkImageCreateFlags        imageFlags                      = (m_format == m_imageFormat ? 0u : (VkImageCreateFlags)VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT);
1387
1388         m_imageSrc = de::MovePtr<Image>(new Image(
1389                 vk, device, allocator,
1390                 makeImageCreateInfo(m_texture, m_imageFormat, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, imageFlags),
1391                 MemoryRequirement::Any));
1392
1393         m_imageDst = de::MovePtr<Image>(new Image(
1394                 vk, device, allocator,
1395                 makeImageCreateInfo(m_texture, m_imageFormat, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, imageFlags),
1396                 MemoryRequirement::Any));
1397 }
1398
1399 VkDescriptorSetLayout ImageLoadStoreTestInstance::prepareDescriptors (void)
1400 {
1401         const VkDevice                  device  = m_context.getDevice();
1402         const DeviceInterface&  vk              = m_context.getDeviceInterface();
1403
1404         const int numLayers = m_texture.numLayers();
1405         m_descriptorSetLayout = DescriptorSetLayoutBuilder()
1406                 .addSingleBinding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_SHADER_STAGE_COMPUTE_BIT)
1407                 .addSingleBinding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_SHADER_STAGE_COMPUTE_BIT)
1408                 .build(vk, device);
1409
1410         m_descriptorPool = DescriptorPoolBuilder()
1411                 .addType(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, numLayers)
1412                 .addType(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, numLayers)
1413                 .build(vk, device, VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, numLayers);
1414
1415         if (m_singleLayerBind)
1416         {
1417                 for (int layerNdx = 0; layerNdx < numLayers; ++layerNdx)
1418                 {
1419                         const VkImageViewType viewType = mapImageViewType(getImageTypeForSingleLayer(m_texture.type()));
1420                         const VkImageSubresourceRange subresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, layerNdx, 1u);
1421
1422                         m_allDescriptorSets[layerNdx] = makeVkSharedPtr(makeDescriptorSet(vk, device, *m_descriptorPool, *m_descriptorSetLayout));
1423                         m_allSrcImageViews[layerNdx]  = makeVkSharedPtr(makeImageView(vk, device, m_imageSrc->get(), viewType, m_format, subresourceRange));
1424                         m_allDstImageViews[layerNdx]  = makeVkSharedPtr(makeImageView(vk, device, m_imageDst->get(), viewType, m_format, subresourceRange));
1425                 }
1426         }
1427         else // bind all layers at once
1428         {
1429                 const VkImageViewType viewType = mapImageViewType(m_texture.type());
1430                 const VkImageSubresourceRange subresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, numLayers);
1431
1432                 m_allDescriptorSets[0] = makeVkSharedPtr(makeDescriptorSet(vk, device, *m_descriptorPool, *m_descriptorSetLayout));
1433                 m_allSrcImageViews[0]  = makeVkSharedPtr(makeImageView(vk, device, m_imageSrc->get(), viewType, m_format, subresourceRange));
1434                 m_allDstImageViews[0]  = makeVkSharedPtr(makeImageView(vk, device, m_imageDst->get(), viewType, m_format, subresourceRange));
1435         }
1436
1437         return *m_descriptorSetLayout;  // not passing the ownership
1438 }
1439
1440 void ImageLoadStoreTestInstance::commandBindDescriptorsForLayer (const VkCommandBuffer cmdBuffer, const VkPipelineLayout pipelineLayout, const int layerNdx)
1441 {
1442         const VkDevice                  device  = m_context.getDevice();
1443         const DeviceInterface&  vk              = m_context.getDeviceInterface();
1444
1445         const VkDescriptorSet descriptorSet = **m_allDescriptorSets[layerNdx];
1446         const VkImageView         srcImageView  = **m_allSrcImageViews[layerNdx];
1447         const VkImageView         dstImageView  = **m_allDstImageViews[layerNdx];
1448
1449         const VkDescriptorImageInfo descriptorSrcImageInfo = makeDescriptorImageInfo(DE_NULL, srcImageView, VK_IMAGE_LAYOUT_GENERAL);
1450         const VkDescriptorImageInfo descriptorDstImageInfo = makeDescriptorImageInfo(DE_NULL, dstImageView, VK_IMAGE_LAYOUT_GENERAL);
1451
1452         DescriptorSetUpdateBuilder()
1453                 .writeSingle(descriptorSet, DescriptorSetUpdateBuilder::Location::binding(0u), VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &descriptorSrcImageInfo)
1454                 .writeSingle(descriptorSet, DescriptorSetUpdateBuilder::Location::binding(1u), VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &descriptorDstImageInfo)
1455                 .update(vk, device);
1456         vk.cmdBindDescriptorSets(cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0u, 1u, &descriptorSet, 0u, DE_NULL);
1457 }
1458
1459 void ImageLoadStoreTestInstance::commandBeforeCompute (const VkCommandBuffer cmdBuffer)
1460 {
1461         const DeviceInterface& vk = m_context.getDeviceInterface();
1462
1463         const VkImageSubresourceRange fullImageSubresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, m_texture.numLayers());
1464         {
1465                 const VkImageMemoryBarrier preCopyImageBarriers[] =
1466                 {
1467                         makeImageMemoryBarrier(
1468                                 0u, VK_ACCESS_TRANSFER_WRITE_BIT,
1469                                 VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1470                                 m_imageSrc->get(), fullImageSubresourceRange),
1471                         makeImageMemoryBarrier(
1472                                 0u, VK_ACCESS_SHADER_WRITE_BIT,
1473                                 VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL,
1474                                 m_imageDst->get(), fullImageSubresourceRange)
1475                 };
1476
1477                 const VkBufferMemoryBarrier barrierFlushHostWriteBeforeCopy = makeBufferMemoryBarrier(
1478                         VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT,
1479                         m_imageBuffer->get(), 0ull, m_imageSizeBytes + m_srcViewOffset);
1480
1481                 vk.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT,
1482                         (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 1, &barrierFlushHostWriteBeforeCopy, DE_LENGTH_OF_ARRAY(preCopyImageBarriers), preCopyImageBarriers);
1483         }
1484         {
1485                 const VkImageMemoryBarrier barrierAfterCopy = makeImageMemoryBarrier(
1486                         VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT,
1487                         VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL,
1488                         m_imageSrc->get(), fullImageSubresourceRange);
1489
1490                 const VkBufferImageCopy copyRegion = makeBufferImageCopy(m_texture);
1491
1492                 vk.cmdCopyBufferToImage(cmdBuffer, m_imageBuffer->get(), m_imageSrc->get(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1u, &copyRegion);
1493                 vk.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 0, (const VkBufferMemoryBarrier*)DE_NULL, 1, &barrierAfterCopy);
1494         }
1495 }
1496
1497 void ImageLoadStoreTestInstance::commandBetweenShaderInvocations (const VkCommandBuffer cmdBuffer)
1498 {
1499         commandImageWriteBarrierBetweenShaderInvocations(m_context, cmdBuffer, m_imageDst->get(), m_texture);
1500 }
1501
1502 void ImageLoadStoreTestInstance::commandAfterCompute (const VkCommandBuffer cmdBuffer)
1503 {
1504         commandCopyImageToBuffer(m_context, cmdBuffer, m_imageDst->get(), m_imageBuffer->get(), m_imageSizeBytes, m_texture);
1505 }
1506
1507 //! Load/store Lod AMD test for images
1508 class ImageLoadStoreLodAMDTestInstance : public BaseTestInstance
1509 {
1510 public:
1511                                                                                 ImageLoadStoreLodAMDTestInstance        (Context&                               context,
1512                                                                                                                                                          const Texture&                 texture,
1513                                                                                                                                                          const VkFormat                 format,
1514                                                                                                                                                          const VkFormat                 imageFormat,
1515                                                                                                                                                          const bool                             declareImageFormatInShader,
1516                                                                                                                                                          const bool                             singleLayerBind,
1517                                                                                                                                                          const bool                             minalign,
1518                                                                                                                                                          const bool                             bufferLoadUniform);
1519
1520 protected:
1521         VkDescriptorSetLayout                           prepareDescriptors                                      (void);
1522         void                                                            commandBeforeCompute                            (const VkCommandBuffer  cmdBuffer);
1523         void                                                            commandBetweenShaderInvocations         (const VkCommandBuffer  cmdBuffer);
1524         void                                                            commandAfterCompute                                     (const VkCommandBuffer  cmdBuffer);
1525
1526         void                                                            commandBindDescriptorsForLayer          (const VkCommandBuffer  cmdBuffer,
1527                                                                                                                                                          const VkPipelineLayout pipelineLayout,
1528                                                                                                                                                          const int                              layerNdx);
1529
1530         Buffer*                                                         getResultBuffer                                         (void) const { return m_imageBuffer.get(); }
1531         tcu::TestStatus                                         verifyResult                                            (void);
1532
1533         de::MovePtr<Buffer>                                     m_imageBuffer;          //!< Source data and helper buffer
1534         const VkDeviceSize                                      m_imageSizeBytes;
1535         const VkFormat                                          m_imageFormat;          //!< Image format (for storage, may be different than texture format)
1536         std::vector<tcu::TextureLevel>          m_referenceImages;      //!< Used as input data and later to verify result image
1537
1538         bool                                                            m_bufferLoadUniform;
1539         VkDescriptorType                                        m_bufferLoadDescriptorType;
1540         VkBufferUsageFlagBits                           m_bufferLoadUsageBit;
1541
1542         de::MovePtr<Image>                                      m_imageSrc;
1543         de::MovePtr<Image>                                      m_imageDst;
1544         Move<VkDescriptorSetLayout>                     m_descriptorSetLayout;
1545         Move<VkDescriptorPool>                          m_descriptorPool;
1546         std::vector<SharedVkDescriptorSet>  m_allDescriptorSets;
1547         std::vector<SharedVkImageView>      m_allSrcImageViews;
1548         std::vector<SharedVkImageView>      m_allDstImageViews;
1549
1550 };
1551
1552 ImageLoadStoreLodAMDTestInstance::ImageLoadStoreLodAMDTestInstance (Context&            context,
1553                                                                                                                                         const Texture&  texture,
1554                                                                                                                                         const VkFormat  format,
1555                                                                                                                                         const VkFormat  imageFormat,
1556                                                                                                                                         const bool              declareImageFormatInShader,
1557                                                                                                                                         const bool              singleLayerBind,
1558                                                                                                                                         const bool              minalign,
1559                                                                                                                                         const bool              bufferLoadUniform)
1560         : BaseTestInstance                      (context, texture, format, declareImageFormatInShader, singleLayerBind, minalign, bufferLoadUniform)
1561         , m_imageSizeBytes                      (getMipmapImageTotalSizeBytes(texture, format))
1562         , m_imageFormat                         (imageFormat)
1563         , m_bufferLoadUniform           (bufferLoadUniform)
1564         , m_allDescriptorSets       (texture.numLayers())
1565         , m_allSrcImageViews        (texture.numLayers())
1566         , m_allDstImageViews        (texture.numLayers())
1567 {
1568         const DeviceInterface&          vk                                      = m_context.getDeviceInterface();
1569         const VkDevice                          device                          = m_context.getDevice();
1570         Allocator&                                      allocator                       = m_context.getDefaultAllocator();
1571         const VkImageCreateFlags        imageFlags                      = (m_format == m_imageFormat ? 0u : (VkImageCreateFlags)VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT);
1572
1573         const VkSampleCountFlagBits samples = static_cast<VkSampleCountFlagBits>(m_texture.numSamples());       // integer and bit mask are aligned, so we can cast like this
1574
1575         for (deInt32 levelNdx = 0; levelNdx < m_texture.numMipmapLevels(); levelNdx++)
1576         {
1577                 tcu::TextureLevel referenceImage = generateReferenceImage(texture.size(levelNdx), imageFormat, format);
1578                 m_referenceImages.push_back(referenceImage);
1579         }
1580
1581         m_bufferLoadDescriptorType = m_bufferLoadUniform ? VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER : VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER;
1582         m_bufferLoadUsageBit = m_bufferLoadUniform ? VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT : VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT;
1583
1584         // A helper buffer with enough space to hold the whole image.
1585         m_imageBuffer = de::MovePtr<Buffer>(new Buffer(
1586                                                                                                    vk, device, allocator,
1587                                                                                                    makeBufferCreateInfo(m_imageSizeBytes + m_srcViewOffset, m_bufferLoadUsageBit | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT),
1588                                                                                                    MemoryRequirement::HostVisible));
1589
1590         // Copy reference data to buffer for subsequent upload to image.
1591         {
1592                 const Allocation& alloc = m_imageBuffer->getAllocation();
1593                 VkDeviceSize bufferOffset = 0u;
1594                 for (deInt32 levelNdx = 0; levelNdx < m_texture.numMipmapLevels(); levelNdx++)
1595                 {
1596                         deMemcpy((char *)alloc.getHostPtr() + m_srcViewOffset + bufferOffset, m_referenceImages[levelNdx].getAccess().getDataPtr(), static_cast<size_t>(getMipmapLevelImageSizeBytes(m_texture, m_imageFormat, levelNdx)));
1597                         bufferOffset += getMipmapLevelImageSizeBytes(m_texture, m_imageFormat, levelNdx);
1598                 }
1599                 flushAlloc(vk, device, alloc);
1600         }
1601
1602         {
1603                 const VkImageCreateInfo imageParamsSrc =
1604                 {
1605                         VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,                                                                                                                            // VkStructureType                      sType;
1606                         DE_NULL,                                                                                                                                                                                        // const void*                          pNext;
1607                         (isCube(m_texture) ? (VkImageCreateFlags)VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT : 0u) | imageFlags,        // VkImageCreateFlags           flags;
1608                         mapImageType(m_texture.type()),                                                                                                                                         // VkImageType                          imageType;
1609                         m_imageFormat,                                                                                                                                                                          // VkFormat                                     format;
1610                         makeExtent3D(m_texture.layerSize()),                                                                                                                            // VkExtent3D                           extent;
1611                         (deUint32)m_texture.numMipmapLevels(),                                                                                                                          // deUint32                                     mipLevels;
1612                         (deUint32)m_texture.numLayers(),                                                                                                                                        // deUint32                                     arrayLayers;
1613                         samples,                                                                                                                                                                                        // VkSampleCountFlagBits        samples;
1614                         VK_IMAGE_TILING_OPTIMAL,                                                                                                                                                        // VkImageTiling                        tiling;
1615                         VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT,                                                                           // VkImageUsageFlags            usage;
1616                         VK_SHARING_MODE_EXCLUSIVE,                                                                                                                                                      // VkSharingMode                        sharingMode;
1617                         0u,                                                                                                                                                                                                     // deUint32                                     queueFamilyIndexCount;
1618                         DE_NULL,                                                                                                                                                                                        // const deUint32*                      pQueueFamilyIndices;
1619                         VK_IMAGE_LAYOUT_UNDEFINED,                                                                                                                                                      // VkImageLayout                        initialLayout;
1620                 };
1621
1622                 m_imageSrc = de::MovePtr<Image>(new Image(
1623                                                                                                   vk, device, allocator,
1624                                                                                                   imageParamsSrc,
1625                                                                                                   MemoryRequirement::Any));
1626         }
1627
1628         {
1629                 const VkImageCreateInfo imageParamsDst =
1630                 {
1631                         VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,                                                                                                                            // VkStructureType                      sType;
1632                         DE_NULL,                                                                                                                                                                                        // const void*                          pNext;
1633                         (isCube(m_texture) ? (VkImageCreateFlags)VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT : 0u) | imageFlags,        // VkImageCreateFlags           flags;
1634                         mapImageType(m_texture.type()),                                                                                                                                         // VkImageType                          imageType;
1635                         m_imageFormat,                                                                                                                                                                          // VkFormat                                     format;
1636                         makeExtent3D(m_texture.layerSize()),                                                                                                                            // VkExtent3D                           extent;
1637                         (deUint32)m_texture.numMipmapLevels(),                                                                                                                          // deUint32                                     mipLevels;
1638                         (deUint32)m_texture.numLayers(),                                                                                                                                        // deUint32                                     arrayLayers;
1639                         samples,                                                                                                                                                                                        // VkSampleCountFlagBits        samples;
1640                         VK_IMAGE_TILING_OPTIMAL,                                                                                                                                                        // VkImageTiling                        tiling;
1641                     VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT,                                                                               // VkImageUsageFlags            usage;
1642                         VK_SHARING_MODE_EXCLUSIVE,                                                                                                                                                      // VkSharingMode                        sharingMode;
1643                         0u,                                                                                                                                                                                                     // deUint32                                     queueFamilyIndexCount;
1644                         DE_NULL,                                                                                                                                                                                        // const deUint32*                      pQueueFamilyIndices;
1645                         VK_IMAGE_LAYOUT_UNDEFINED,                                                                                                                                                      // VkImageLayout                        initialLayout;
1646                 };
1647
1648                 m_imageDst = de::MovePtr<Image>(new Image(
1649                                                                                                   vk, device, allocator,
1650                                                                                                   imageParamsDst,
1651                                                                                                   MemoryRequirement::Any));
1652         }
1653 }
1654
1655 tcu::TestStatus ImageLoadStoreLodAMDTestInstance::verifyResult  (void)
1656 {
1657         const DeviceInterface&  vk              = m_context.getDeviceInterface();
1658         const VkDevice                  device  = m_context.getDevice();
1659
1660         const Allocation& alloc = getResultBuffer()->getAllocation();
1661         invalidateAlloc(vk, device, alloc);
1662
1663     VkDeviceSize bufferOffset = 0;
1664         for (deInt32 levelNdx = 0; levelNdx < m_texture.numMipmapLevels(); levelNdx++)
1665         {
1666                 // Apply the same transformation as done in the shader
1667                 const tcu::PixelBufferAccess reference = m_referenceImages[levelNdx].getAccess();
1668                 flipHorizontally(reference);
1669
1670                 const tcu::ConstPixelBufferAccess result(mapVkFormat(m_imageFormat), m_texture.size(levelNdx), (const char *)alloc.getHostPtr() + m_dstViewOffset + bufferOffset);
1671
1672                 if (!comparePixelBuffers(m_context.getTestContext().getLog(), m_texture, m_imageFormat, reference, result, levelNdx))
1673                 {
1674                         std::ostringstream errorMessage;
1675                         errorMessage << "Image Level " << levelNdx << " comparison failed";
1676                         return tcu::TestStatus::fail(errorMessage.str());
1677                 }
1678                 bufferOffset += getMipmapLevelImageSizeBytes(m_texture, m_imageFormat, levelNdx);
1679         }
1680
1681         return tcu::TestStatus::pass("Passed");
1682 }
1683
1684 VkDescriptorSetLayout ImageLoadStoreLodAMDTestInstance::prepareDescriptors (void)
1685 {
1686         const VkDevice                  device  = m_context.getDevice();
1687         const DeviceInterface&  vk              = m_context.getDeviceInterface();
1688
1689         const int numLayers = m_texture.numLayers();
1690         m_descriptorSetLayout = DescriptorSetLayoutBuilder()
1691                 .addSingleBinding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_SHADER_STAGE_COMPUTE_BIT)
1692                 .addSingleBinding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_SHADER_STAGE_COMPUTE_BIT)
1693                 .build(vk, device);
1694
1695         m_descriptorPool = DescriptorPoolBuilder()
1696                 .addType(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, numLayers)
1697                 .addType(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, numLayers)
1698                 .build(vk, device, VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, numLayers);
1699
1700         if (m_singleLayerBind)
1701         {
1702                 for (int layerNdx = 0; layerNdx < numLayers; ++layerNdx)
1703                 {
1704                         const VkImageViewType viewType = mapImageViewType(getImageTypeForSingleLayer(m_texture.type()));
1705                         const VkImageSubresourceRange subresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, m_texture.numMipmapLevels(), layerNdx, 1u);
1706
1707                         m_allDescriptorSets[layerNdx] = makeVkSharedPtr(makeDescriptorSet(vk, device, *m_descriptorPool, *m_descriptorSetLayout));
1708                         m_allSrcImageViews[layerNdx]  = makeVkSharedPtr(makeImageView(vk, device, m_imageSrc->get(), viewType, m_format, subresourceRange));
1709                         m_allDstImageViews[layerNdx]  = makeVkSharedPtr(makeImageView(vk, device, m_imageDst->get(), viewType, m_format, subresourceRange));
1710                 }
1711         }
1712         else // bind all layers at once
1713         {
1714                 const VkImageViewType viewType = mapImageViewType(m_texture.type());
1715                 const VkImageSubresourceRange subresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, m_texture.numMipmapLevels(), 0u, numLayers);
1716
1717                 m_allDescriptorSets[0] = makeVkSharedPtr(makeDescriptorSet(vk, device, *m_descriptorPool, *m_descriptorSetLayout));
1718                 m_allSrcImageViews[0]  = makeVkSharedPtr(makeImageView(vk, device, m_imageSrc->get(), viewType, m_format, subresourceRange));
1719                 m_allDstImageViews[0]  = makeVkSharedPtr(makeImageView(vk, device, m_imageDst->get(), viewType, m_format, subresourceRange));
1720         }
1721
1722         return *m_descriptorSetLayout;  // not passing the ownership
1723 }
1724
1725 void ImageLoadStoreLodAMDTestInstance::commandBindDescriptorsForLayer (const VkCommandBuffer cmdBuffer, const VkPipelineLayout pipelineLayout, const int layerNdx)
1726 {
1727         const VkDevice                  device  = m_context.getDevice();
1728         const DeviceInterface&  vk              = m_context.getDeviceInterface();
1729
1730         const VkDescriptorSet descriptorSet = **m_allDescriptorSets[layerNdx];
1731         const VkImageView         srcImageView  = **m_allSrcImageViews[layerNdx];
1732         const VkImageView         dstImageView  = **m_allDstImageViews[layerNdx];
1733
1734         const VkDescriptorImageInfo descriptorSrcImageInfo = makeDescriptorImageInfo(DE_NULL, srcImageView, VK_IMAGE_LAYOUT_GENERAL);
1735         const VkDescriptorImageInfo descriptorDstImageInfo = makeDescriptorImageInfo(DE_NULL, dstImageView, VK_IMAGE_LAYOUT_GENERAL);
1736
1737         DescriptorSetUpdateBuilder()
1738                 .writeSingle(descriptorSet, DescriptorSetUpdateBuilder::Location::binding(0u), VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &descriptorSrcImageInfo)
1739                 .writeSingle(descriptorSet, DescriptorSetUpdateBuilder::Location::binding(1u), VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &descriptorDstImageInfo)
1740                 .update(vk, device);
1741         vk.cmdBindDescriptorSets(cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0u, 1u, &descriptorSet, 0u, DE_NULL);
1742 }
1743
1744 void ImageLoadStoreLodAMDTestInstance::commandBeforeCompute (const VkCommandBuffer cmdBuffer)
1745 {
1746         const DeviceInterface& vk = m_context.getDeviceInterface();
1747         const VkImageSubresourceRange fullImageSubresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, m_texture.numMipmapLevels(), 0u, m_texture.numLayers());
1748         {
1749                 const VkImageMemoryBarrier preCopyImageBarriers[] =
1750                 {
1751                         makeImageMemoryBarrier(
1752                                 0u, VK_ACCESS_TRANSFER_WRITE_BIT,
1753                                 VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1754                                 m_imageSrc->get(), fullImageSubresourceRange),
1755                         makeImageMemoryBarrier(
1756                                 0u, VK_ACCESS_SHADER_WRITE_BIT,
1757                                 VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL,
1758                                 m_imageDst->get(), fullImageSubresourceRange)
1759                 };
1760
1761                 const VkBufferMemoryBarrier barrierFlushHostWriteBeforeCopy = makeBufferMemoryBarrier(
1762                         VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT,
1763                         m_imageBuffer->get(), 0ull, m_imageSizeBytes + m_srcViewOffset);
1764
1765                 vk.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT,
1766                         (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 1, &barrierFlushHostWriteBeforeCopy, DE_LENGTH_OF_ARRAY(preCopyImageBarriers), preCopyImageBarriers);
1767         }
1768         {
1769                 const VkImageMemoryBarrier barrierAfterCopy = makeImageMemoryBarrier(
1770                         VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT,
1771                         VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL,
1772                         m_imageSrc->get(), fullImageSubresourceRange);
1773
1774                 std::vector<VkBufferImageCopy> copyRegions;
1775                 VkDeviceSize bufferOffset = 0u;
1776                 for (deInt32 levelNdx = 0; levelNdx < m_texture.numMipmapLevels(); levelNdx++)
1777                 {
1778                         const VkBufferImageCopy copyParams =
1779                         {
1780                                 bufferOffset,                                                                                                                                                                   //      VkDeviceSize                            bufferOffset;
1781                                 0u,                                                                                                                                                                                             //      deUint32                                        bufferRowLength;
1782                                 0u,                                                                                                                                                                                             //      deUint32                                        bufferImageHeight;
1783                                 makeImageSubresourceLayers(VK_IMAGE_ASPECT_COLOR_BIT, levelNdx, 0u, m_texture.numLayers()),             //      VkImageSubresourceLayers        imageSubresource;
1784                                 makeOffset3D(0, 0, 0),                                                                                                                                                  //      VkOffset3D                                      imageOffset;
1785                                 makeExtent3D(m_texture.layerSize(levelNdx)),                                                                                                    //      VkExtent3D                                      imageExtent;
1786                         };
1787                         copyRegions.push_back(copyParams);
1788                         bufferOffset += getMipmapLevelImageSizeBytes(m_texture, m_imageFormat, levelNdx);
1789                 }
1790
1791                 vk.cmdCopyBufferToImage(cmdBuffer, m_imageBuffer->get(), m_imageSrc->get(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, (deUint32) copyRegions.size(), copyRegions.data());
1792                 vk.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 0, (const VkBufferMemoryBarrier*)DE_NULL, 1, &barrierAfterCopy);
1793         }
1794 }
1795
1796 void ImageLoadStoreLodAMDTestInstance::commandBetweenShaderInvocations (const VkCommandBuffer cmdBuffer)
1797 {
1798         commandImageWriteBarrierBetweenShaderInvocations(m_context, cmdBuffer, m_imageDst->get(), m_texture);
1799 }
1800
1801 void ImageLoadStoreLodAMDTestInstance::commandAfterCompute (const VkCommandBuffer cmdBuffer)
1802 {
1803         commandCopyMipmapImageToBuffer(m_context, cmdBuffer, m_imageDst->get(), m_imageFormat, m_imageBuffer->get(), m_imageSizeBytes, m_texture);
1804 }
1805
1806 //! Load/store test for buffers
1807 class BufferLoadStoreTestInstance : public LoadStoreTestInstance
1808 {
1809 public:
1810                                                                         BufferLoadStoreTestInstance             (Context&                               context,
1811                                                                                                                                          const Texture&                 texture,
1812                                                                                                                                          const VkFormat                 format,
1813                                                                                                                                          const VkFormat                 imageFormat,
1814                                                                                                                                          const bool                             declareImageFormatInShader,
1815                                                                                                                                          const bool                             minalign,
1816                                                                                                                                          const bool                             bufferLoadUniform);
1817
1818 protected:
1819         VkDescriptorSetLayout                   prepareDescriptors                              (void);
1820         void                                                    commandAfterCompute                             (const VkCommandBuffer  cmdBuffer);
1821
1822         void                                                    commandBindDescriptorsForLayer  (const VkCommandBuffer  cmdBuffer,
1823                                                                                                                                          const VkPipelineLayout pipelineLayout,
1824                                                                                                                                          const int                              layerNdx);
1825
1826         Buffer*                                                 getResultBuffer                                 (void) const { return m_imageBufferDst.get(); }
1827
1828         de::MovePtr<Buffer>                             m_imageBufferDst;
1829         Move<VkDescriptorSetLayout>             m_descriptorSetLayout;
1830         Move<VkDescriptorPool>                  m_descriptorPool;
1831         Move<VkDescriptorSet>                   m_descriptorSet;
1832         Move<VkBufferView>                              m_bufferViewSrc;
1833         Move<VkBufferView>                              m_bufferViewDst;
1834 };
1835
1836 BufferLoadStoreTestInstance::BufferLoadStoreTestInstance (Context&                      context,
1837                                                                                                                   const Texture&        texture,
1838                                                                                                                   const VkFormat        format,
1839                                                                                                                   const VkFormat        imageFormat,
1840                                                                                                                   const bool            declareImageFormatInShader,
1841                                                                                                                   const bool            minalign,
1842                                                                                                                   const bool            bufferLoadUniform)
1843         : LoadStoreTestInstance(context, texture, format, imageFormat, declareImageFormatInShader, false, minalign, bufferLoadUniform)
1844 {
1845         const DeviceInterface&  vk                      = m_context.getDeviceInterface();
1846         const VkDevice                  device          = m_context.getDevice();
1847         Allocator&                              allocator       = m_context.getDefaultAllocator();
1848
1849         // Create a destination buffer.
1850
1851         m_imageBufferDst = de::MovePtr<Buffer>(new Buffer(
1852                 vk, device, allocator,
1853                 makeBufferCreateInfo(m_imageSizeBytes + m_dstViewOffset, VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT),
1854                 MemoryRequirement::HostVisible));
1855 }
1856
1857 VkDescriptorSetLayout BufferLoadStoreTestInstance::prepareDescriptors (void)
1858 {
1859         const DeviceInterface&  vk              = m_context.getDeviceInterface();
1860         const VkDevice                  device  = m_context.getDevice();
1861
1862         m_descriptorSetLayout = DescriptorSetLayoutBuilder()
1863                 .addSingleBinding(m_bufferLoadDescriptorType, VK_SHADER_STAGE_COMPUTE_BIT)
1864                 .addSingleBinding(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, VK_SHADER_STAGE_COMPUTE_BIT)
1865                 .build(vk, device);
1866
1867         m_descriptorPool = DescriptorPoolBuilder()
1868                 .addType(m_bufferLoadDescriptorType)
1869                 .addType(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER)
1870                 .build(vk, device, VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, 1u);
1871
1872         VkFormat dstFormat = formatHasThreeComponents(m_format) ? getSingleComponentFormat(m_format) : m_format;
1873
1874         m_descriptorSet = makeDescriptorSet(vk, device, *m_descriptorPool, *m_descriptorSetLayout);
1875         m_bufferViewSrc = makeBufferView(vk, device, m_imageBuffer->get(), m_format, m_srcViewOffset, m_imageSizeBytes);
1876         m_bufferViewDst = makeBufferView(vk, device, m_imageBufferDst->get(), dstFormat, m_dstViewOffset, m_imageSizeBytes);
1877
1878         return *m_descriptorSetLayout;  // not passing the ownership
1879 }
1880
1881 void BufferLoadStoreTestInstance::commandBindDescriptorsForLayer (const VkCommandBuffer cmdBuffer, const VkPipelineLayout pipelineLayout, const int layerNdx)
1882 {
1883         DE_ASSERT(layerNdx == 0);
1884         DE_UNREF(layerNdx);
1885
1886         const VkDevice                  device  = m_context.getDevice();
1887         const DeviceInterface&  vk              = m_context.getDeviceInterface();
1888
1889         DescriptorSetUpdateBuilder()
1890                 .writeSingle(*m_descriptorSet, DescriptorSetUpdateBuilder::Location::binding(0u), m_bufferLoadDescriptorType, &m_bufferViewSrc.get())
1891                 .writeSingle(*m_descriptorSet, DescriptorSetUpdateBuilder::Location::binding(1u), VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, &m_bufferViewDst.get())
1892                 .update(vk, device);
1893         vk.cmdBindDescriptorSets(cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0u, 1u, &m_descriptorSet.get(), 0u, DE_NULL);
1894 }
1895
1896 void BufferLoadStoreTestInstance::commandAfterCompute (const VkCommandBuffer cmdBuffer)
1897 {
1898         commandBufferWriteBarrierBeforeHostRead(m_context, cmdBuffer, m_imageBufferDst->get(), m_imageSizeBytes + m_dstViewOffset);
1899 }
1900
1901 TestInstance* StoreTest::createInstance (Context& context) const
1902 {
1903         if (m_texture.type() == IMAGE_TYPE_BUFFER)
1904                 return new BufferStoreTestInstance(context, m_texture, m_format, m_declareImageFormatInShader, m_minalign);
1905         else
1906                 return new ImageStoreTestInstance(context, m_texture, m_format, m_declareImageFormatInShader, m_singleLayerBind, m_minalign);
1907 }
1908
1909 TestInstance* LoadStoreTest::createInstance (Context& context) const
1910 {
1911         if (m_imageLoadStoreLodAMD)
1912                 return new ImageLoadStoreLodAMDTestInstance(context, m_texture, m_format, m_imageFormat, m_declareImageFormatInShader, m_singleLayerBind, m_minalign, m_bufferLoadUniform);
1913
1914         if (m_texture.type() == IMAGE_TYPE_BUFFER)
1915                 return new BufferLoadStoreTestInstance(context, m_texture, m_format, m_imageFormat, m_declareImageFormatInShader, m_minalign, m_bufferLoadUniform);
1916         else
1917                 return new ImageLoadStoreTestInstance(context, m_texture, m_format, m_imageFormat, m_declareImageFormatInShader, m_singleLayerBind, m_minalign, m_bufferLoadUniform);
1918 }
1919
1920 class ImageExtendOperandTestInstance : public BaseTestInstance
1921 {
1922 public:
1923                                                                         ImageExtendOperandTestInstance                  (Context&                               context,
1924                                                                                                                                                          const Texture&                 texture,
1925                                                                                                                                                          const VkFormat                 readFormat,
1926                                                                                                                                                          const VkFormat                 writeFormat,
1927                                                                                                                                                          bool                                   relaxedPrecision);
1928
1929         virtual                                                 ~ImageExtendOperandTestInstance                 (void) {};
1930
1931 protected:
1932
1933         VkDescriptorSetLayout                   prepareDescriptors                                              (void);
1934         void                                                    commandBeforeCompute                                    (const VkCommandBuffer  cmdBuffer);
1935         void                                                    commandBetweenShaderInvocations                 (const VkCommandBuffer  cmdBuffer);
1936         void                                                    commandAfterCompute                                             (const VkCommandBuffer  cmdBuffer);
1937
1938         void                                                    commandBindDescriptorsForLayer                  (const VkCommandBuffer  cmdBuffer,
1939                                                                                                                                                          const VkPipelineLayout pipelineLayout,
1940                                                                                                                                                          const int                              layerNdx);
1941
1942         tcu::TestStatus                                 verifyResult                                                    (void);
1943
1944 protected:
1945
1946         bool                                                    m_isSigned;
1947         tcu::TextureLevel                               m_inputImageData;
1948
1949         de::MovePtr<Image>                              m_imageSrc;                             // source image
1950         SharedVkImageView                               m_imageSrcView;
1951         VkDeviceSize                                    m_imageSrcSize;
1952
1953         de::MovePtr<Image>                              m_imageDst;                             // dest image
1954         SharedVkImageView                               m_imageDstView;
1955         VkFormat                                                m_imageDstFormat;
1956         VkDeviceSize                                    m_imageDstSize;
1957
1958         de::MovePtr<Buffer>                             m_buffer;                               // result buffer
1959
1960         Move<VkDescriptorSetLayout>             m_descriptorSetLayout;
1961         Move<VkDescriptorPool>                  m_descriptorPool;
1962         SharedVkDescriptorSet                   m_descriptorSet;
1963
1964         bool                                                    m_relaxedPrecision;
1965 };
1966
1967 ImageExtendOperandTestInstance::ImageExtendOperandTestInstance (Context& context,
1968                                                                                                                                 const Texture& texture,
1969                                                                                                                                 const VkFormat readFormat,
1970                                                                                                                                 const VkFormat writeFormat,
1971                                                                                                                                 bool relaxedPrecision)
1972         : BaseTestInstance              (context, texture, readFormat, true, true, false, false)
1973         , m_imageDstFormat              (writeFormat)
1974         , m_relaxedPrecision    (relaxedPrecision)
1975 {
1976         const DeviceInterface&          vk                              = m_context.getDeviceInterface();
1977         const VkDevice                          device                  = m_context.getDevice();
1978         Allocator&                                      allocator               = m_context.getDefaultAllocator();
1979         const deInt32                           width                   = texture.size().x();
1980         const deInt32                           height                  = texture.size().y();
1981         const tcu::TextureFormat        textureFormat   = mapVkFormat(m_format);
1982
1983         // Generate reference image
1984         m_isSigned = (getTextureChannelClass(textureFormat.type) == tcu::TEXTURECHANNELCLASS_SIGNED_INTEGER);
1985         m_inputImageData.setStorage(textureFormat, width, height, 1);
1986
1987         const tcu::PixelBufferAccess    access          = m_inputImageData.getAccess();
1988         const int                                               valueStart      = (m_isSigned ? (-width / 2) : 0);
1989
1990         for (int x = 0; x < width; ++x)
1991         for (int y = 0; y < height; ++y)
1992         {
1993                 const tcu::IVec4 color(valueStart + x, valueStart + y, valueStart, valueStart);
1994                 access.setPixel(color, x, y);
1995         }
1996
1997         // Create source image
1998         m_imageSrc = de::MovePtr<Image>(new Image(
1999                 vk, device, allocator,
2000                 makeImageCreateInfo(m_texture, m_format, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, 0u),
2001                 MemoryRequirement::Any));
2002
2003         // Create destination image
2004         m_imageDst = de::MovePtr<Image>(new Image(
2005                 vk, device, allocator,
2006                 makeImageCreateInfo(m_texture, m_imageDstFormat, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, 0u),
2007                 MemoryRequirement::Any));
2008
2009         // Compute image and buffer sizes
2010         m_imageSrcSize                                  = width * height * tcu::getPixelSize(textureFormat);
2011         m_imageDstSize                                  = width * height * tcu::getPixelSize(mapVkFormat(m_imageDstFormat));
2012         VkDeviceSize bufferSizeBytes    = de::max(m_imageSrcSize, m_imageDstSize);
2013
2014         // Create helper buffer able to store input data and image write result
2015         m_buffer = de::MovePtr<Buffer>(new Buffer(
2016                 vk, device, allocator,
2017                 makeBufferCreateInfo(bufferSizeBytes, VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT),
2018                 MemoryRequirement::HostVisible));
2019
2020         const Allocation& alloc = m_buffer->getAllocation();
2021         deMemcpy(alloc.getHostPtr(), m_inputImageData.getAccess().getDataPtr(), static_cast<size_t>(m_imageSrcSize));
2022         flushAlloc(vk, device, alloc);
2023 }
2024
2025 VkDescriptorSetLayout ImageExtendOperandTestInstance::prepareDescriptors (void)
2026 {
2027         const DeviceInterface&  vk              = m_context.getDeviceInterface();
2028         const VkDevice                  device  = m_context.getDevice();
2029
2030         m_descriptorSetLayout = DescriptorSetLayoutBuilder()
2031                 .addSingleBinding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_SHADER_STAGE_COMPUTE_BIT)
2032                 .addSingleBinding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_SHADER_STAGE_COMPUTE_BIT)
2033                 .build(vk, device);
2034
2035         m_descriptorPool = DescriptorPoolBuilder()
2036                 .addType(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1)
2037                 .addType(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1)
2038                 .build(vk, device, VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, 1);
2039
2040         const VkImageViewType viewType = mapImageViewType(m_texture.type());
2041         const VkImageSubresourceRange subresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, 1u);
2042
2043         m_descriptorSet = makeVkSharedPtr(makeDescriptorSet(vk, device, *m_descriptorPool, *m_descriptorSetLayout));
2044         m_imageSrcView  = makeVkSharedPtr(makeImageView(vk, device, m_imageSrc->get(), viewType, m_format, subresourceRange));
2045         m_imageDstView  = makeVkSharedPtr(makeImageView(vk, device, m_imageDst->get(), viewType, m_imageDstFormat, subresourceRange));
2046
2047         return *m_descriptorSetLayout;  // not passing the ownership
2048 }
2049
2050 void ImageExtendOperandTestInstance::commandBindDescriptorsForLayer (const VkCommandBuffer cmdBuffer, const VkPipelineLayout pipelineLayout, const int layerNdx)
2051 {
2052         DE_UNREF(layerNdx);
2053
2054         const DeviceInterface&  vk                              = m_context.getDeviceInterface();
2055         const VkDevice                  device                  = m_context.getDevice();
2056         const VkDescriptorSet   descriptorSet   = **m_descriptorSet;
2057
2058         const VkDescriptorImageInfo descriptorSrcImageInfo = makeDescriptorImageInfo(DE_NULL, **m_imageSrcView, VK_IMAGE_LAYOUT_GENERAL);
2059         const VkDescriptorImageInfo descriptorDstImageInfo = makeDescriptorImageInfo(DE_NULL, **m_imageDstView, VK_IMAGE_LAYOUT_GENERAL);
2060
2061         typedef DescriptorSetUpdateBuilder::Location DSUBL;
2062         DescriptorSetUpdateBuilder()
2063                 .writeSingle(descriptorSet, DSUBL::binding(0u), VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &descriptorSrcImageInfo)
2064                 .writeSingle(descriptorSet, DSUBL::binding(1u), VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &descriptorDstImageInfo)
2065                 .update(vk, device);
2066         vk.cmdBindDescriptorSets(cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0u, 1u, &descriptorSet, 0u, DE_NULL);
2067 }
2068
2069 void ImageExtendOperandTestInstance::commandBeforeCompute (const VkCommandBuffer cmdBuffer)
2070 {
2071         const DeviceInterface& vk = m_context.getDeviceInterface();
2072
2073         const VkImageSubresourceRange fullImageSubresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, m_texture.numLayers());
2074         {
2075                 const VkImageMemoryBarrier preCopyImageBarriers[] =
2076                 {
2077                         makeImageMemoryBarrier(
2078                                 0u, VK_ACCESS_TRANSFER_WRITE_BIT,
2079                                 VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
2080                                 m_imageSrc->get(), fullImageSubresourceRange),
2081                         makeImageMemoryBarrier(
2082                                 0u, VK_ACCESS_SHADER_WRITE_BIT,
2083                                 VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL,
2084                                 m_imageDst->get(), fullImageSubresourceRange)
2085                 };
2086
2087                 const VkBufferMemoryBarrier barrierFlushHostWriteBeforeCopy = makeBufferMemoryBarrier(
2088                         VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT,
2089                         m_buffer->get(), 0ull, m_imageSrcSize);
2090
2091                 vk.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT,
2092                         (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 1, &barrierFlushHostWriteBeforeCopy, DE_LENGTH_OF_ARRAY(preCopyImageBarriers), preCopyImageBarriers);
2093         }
2094         {
2095                 const VkImageMemoryBarrier barrierAfterCopy = makeImageMemoryBarrier(
2096                         VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT,
2097                         VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL,
2098                         m_imageSrc->get(), fullImageSubresourceRange);
2099
2100                 const VkBufferImageCopy copyRegion = makeBufferImageCopy(m_texture);
2101
2102                 vk.cmdCopyBufferToImage(cmdBuffer, m_buffer->get(), m_imageSrc->get(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1u, &copyRegion);
2103                 vk.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 0, (const VkBufferMemoryBarrier*)DE_NULL, 1, &barrierAfterCopy);
2104         }
2105 }
2106
2107 void ImageExtendOperandTestInstance::commandBetweenShaderInvocations (const VkCommandBuffer cmdBuffer)
2108 {
2109         commandImageWriteBarrierBetweenShaderInvocations(m_context, cmdBuffer, m_imageDst->get(), m_texture);
2110 }
2111
2112 void ImageExtendOperandTestInstance::commandAfterCompute (const VkCommandBuffer cmdBuffer)
2113 {
2114         commandCopyImageToBuffer(m_context, cmdBuffer, m_imageDst->get(), m_buffer->get(), m_imageDstSize, m_texture);
2115 }
2116
2117 // Clears the high bits of every pixel in the pixel buffer, leaving only the lowest 16 bits of each component.
2118 void clearHighBits (const tcu::PixelBufferAccess& pixels, int width, int height)
2119 {
2120         for (int y = 0; y < height; ++y)
2121         for (int x = 0; x < width; ++x)
2122         {
2123                 auto color = pixels.getPixelUint(x, y);
2124                 for (int c = 0; c < decltype(color)::SIZE; ++c)
2125                         color[c] &= 0xFFFFull;
2126                 pixels.setPixel(color, x, y);
2127         }
2128 }
2129
2130 tcu::TestStatus ImageExtendOperandTestInstance::verifyResult (void)
2131 {
2132         const DeviceInterface&                  vk                      = m_context.getDeviceInterface();
2133         const VkDevice                                  device          = m_context.getDevice();
2134         const tcu::IVec3                                imageSize       = m_texture.size();
2135         const tcu::PixelBufferAccess    inputAccess     = m_inputImageData.getAccess();
2136         const deInt32                                   width           = inputAccess.getWidth();
2137         const deInt32                                   height          = inputAccess.getHeight();
2138         tcu::TextureLevel                               refImage        (mapVkFormat(m_imageDstFormat), width, height);
2139         tcu::PixelBufferAccess                  refAccess       = refImage.getAccess();
2140
2141         for (int x = 0; x < width; ++x)
2142         for (int y = 0; y < height; ++y)
2143         {
2144                 tcu::IVec4 color = inputAccess.getPixelInt(x, y);
2145                 refAccess.setPixel(color, x, y);
2146         }
2147
2148         const Allocation& alloc = m_buffer->getAllocation();
2149         invalidateAlloc(vk, device, alloc);
2150         const tcu::PixelBufferAccess result(mapVkFormat(m_imageDstFormat), imageSize, alloc.getHostPtr());
2151
2152         if (m_relaxedPrecision)
2153         {
2154                 // Preserve the lowest 16 bits of the reference and result pixels only.
2155                 clearHighBits(refAccess, width, height);
2156                 clearHighBits(result, width, height);
2157         }
2158
2159         if (tcu::intThresholdCompare (m_context.getTestContext().getLog(), "Comparison", "Comparison", refAccess, result, tcu::UVec4(0), tcu::COMPARE_LOG_RESULT, true/*use64Bits*/))
2160                 return tcu::TestStatus::pass("Passed");
2161         else
2162                 return tcu::TestStatus::fail("Image comparison failed");
2163 }
2164
2165 enum class ExtendTestType
2166 {
2167         READ  = 0,
2168         WRITE = 1,
2169 };
2170
2171 enum class ExtendOperand
2172 {
2173         SIGN_EXTEND = 0,
2174         ZERO_EXTEND = 1
2175 };
2176
2177 class ImageExtendOperandTest : public TestCase
2178 {
2179 public:
2180                                                         ImageExtendOperandTest  (tcu::TestContext&                                      testCtx,
2181                                                                                                          const std::string&                                     name,
2182                                                                                                          const Texture                                          texture,
2183                                                                                                          const VkFormat                                         readFormat,
2184                                                                                                          const VkFormat                                         writeFormat,
2185                                                                                                          const bool                                                     signedInt,
2186                                                                                                          const bool                                                     relaxedPrecision,
2187                                                                                                          ExtendTestType                                         extendTestType);
2188
2189         void                                    checkSupport                    (Context&                               context) const;
2190         void                                    initPrograms                    (SourceCollections&             programCollection) const;
2191         TestInstance*                   createInstance                  (Context&                               context) const;
2192
2193 private:
2194         bool                                    isWriteTest                             () const { return (m_extendTestType == ExtendTestType::WRITE); }
2195
2196         const Texture                   m_texture;
2197         VkFormat                                m_readFormat;
2198         VkFormat                                m_writeFormat;
2199         bool                                    m_operandForce;                 // Use an operand that doesn't match SampledType?
2200         bool                                    m_relaxedPrecision;
2201         ExtendTestType                  m_extendTestType;
2202 };
2203
2204 ImageExtendOperandTest::ImageExtendOperandTest (tcu::TestContext&                               testCtx,
2205                                                                                                 const std::string&                              name,
2206                                                                                                 const Texture                                   texture,
2207                                                                                                 const VkFormat                                  readFormat,
2208                                                                                                 const VkFormat                                  writeFormat,
2209                                                                                                 const bool                                              operandForce,
2210                                                                                                 const bool                                              relaxedPrecision,
2211                                                                                                 ExtendTestType                                  extendTestType)
2212         : TestCase                                              (testCtx, name, "")
2213         , m_texture                                             (texture)
2214         , m_readFormat                                  (readFormat)
2215         , m_writeFormat                                 (writeFormat)
2216         , m_operandForce                                (operandForce)
2217         , m_relaxedPrecision                    (relaxedPrecision)
2218         , m_extendTestType                              (extendTestType)
2219 {
2220 }
2221
2222 void checkFormatProperties (const InstanceInterface& vki, VkPhysicalDevice physDev, VkFormat format)
2223 {
2224         const auto formatProperties = getPhysicalDeviceFormatProperties(vki, physDev, format);
2225
2226         if (!(formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT))
2227                 TCU_THROW(NotSupportedError, "Format not supported for storage images");
2228 }
2229
2230 void check64BitSupportIfNeeded (Context& context, VkFormat readFormat, VkFormat writeFormat)
2231 {
2232         if (is64BitIntegerFormat(readFormat) || is64BitIntegerFormat(writeFormat))
2233         {
2234                 const auto& features = context.getDeviceFeatures();
2235                 if (!features.shaderInt64)
2236                         TCU_THROW(NotSupportedError, "64-bit integers not supported in shaders");
2237         }
2238 }
2239
2240 void ImageExtendOperandTest::checkSupport (Context& context) const
2241 {
2242         DE_ASSERT(m_texture.type() != IMAGE_TYPE_BUFFER);
2243
2244         if (!context.requireDeviceFunctionality("VK_KHR_spirv_1_4"))
2245                 TCU_THROW(NotSupportedError, "VK_KHR_spirv_1_4 not supported");
2246
2247         check64BitSupportIfNeeded(context, m_readFormat, m_writeFormat);
2248
2249         const auto& vki     = context.getInstanceInterface();
2250         const auto  physDev = context.getPhysicalDevice();
2251
2252         checkFormatProperties(vki, physDev, m_readFormat);
2253         checkFormatProperties(vki, physDev, m_writeFormat);
2254 }
2255
2256 void ImageExtendOperandTest::initPrograms (SourceCollections& programCollection) const
2257 {
2258         tcu::StringTemplate shaderTemplate(
2259                 "OpCapability Shader\n"
2260                 "OpCapability StorageImageExtendedFormats\n"
2261
2262                 "${capability}"
2263                 "${extension}"
2264
2265                 "%std450 = OpExtInstImport \"GLSL.std.450\"\n"
2266                 "OpMemoryModel Logical GLSL450\n"
2267                 "OpEntryPoint GLCompute %main \"main\" %id %src_image_ptr %dst_image_ptr\n"
2268                 "OpExecutionMode %main LocalSize 1 1 1\n"
2269
2270                 // decorations
2271                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2272
2273                 "OpDecorate %src_image_ptr DescriptorSet 0\n"
2274                 "OpDecorate %src_image_ptr Binding 0\n"
2275                 "OpDecorate %src_image_ptr NonWritable\n"
2276
2277                 "${relaxed_precision}"
2278
2279                 "OpDecorate %dst_image_ptr DescriptorSet 0\n"
2280                 "OpDecorate %dst_image_ptr Binding 1\n"
2281                 "OpDecorate %dst_image_ptr NonReadable\n"
2282
2283                 // types
2284                 "%type_void                          = OpTypeVoid\n"
2285                 "%type_i32                           = OpTypeInt 32 1\n"
2286                 "%type_u32                           = OpTypeInt 32 0\n"
2287                 "%type_vec2_i32                      = OpTypeVector %type_i32 2\n"
2288                 "%type_vec2_u32                      = OpTypeVector %type_u32 2\n"
2289                 "%type_vec3_i32                      = OpTypeVector %type_i32 3\n"
2290                 "%type_vec3_u32                      = OpTypeVector %type_u32 3\n"
2291                 "%type_vec4_i32                      = OpTypeVector %type_i32 4\n"
2292                 "%type_vec4_u32                      = OpTypeVector %type_u32 4\n"
2293                 "${extra_types}"
2294
2295                 "%type_fun_void                      = OpTypeFunction %type_void\n"
2296
2297                 "${image_types}"
2298
2299                 "%type_ptr_in_vec3_u32               = OpTypePointer Input %type_vec3_u32\n"
2300                 "%type_ptr_in_u32                    = OpTypePointer Input %type_u32\n"
2301
2302                 "${image_uniforms}"
2303
2304                 // variables
2305                 "%id                                 = OpVariable %type_ptr_in_vec3_u32 Input\n"
2306
2307                 "${image_variables}"
2308
2309                 // main function
2310                 "%main                               = OpFunction %type_void None %type_fun_void\n"
2311                 "%label                              = OpLabel\n"
2312
2313                 "${image_load}"
2314
2315                 "%idvec                              = OpLoad %type_vec3_u32 %id\n"
2316                 "%id_xy                              = OpVectorShuffle %type_vec2_u32 %idvec %idvec 0 1\n"
2317                 "%coord                              = OpBitcast %type_vec2_i32 %id_xy\n"
2318                 "%value                              = OpImageRead ${sampled_type_vec4} %src_image %coord ${read_extend_operand}\n"
2319                 "                                      OpImageWrite %dst_image %coord %value ${write_extend_operand}\n"
2320                 "                                      OpReturn\n"
2321                 "                                      OpFunctionEnd\n");
2322
2323         const auto      testedFormat    = mapVkFormat(isWriteTest() ? m_writeFormat : m_readFormat);
2324         const bool      isSigned                = (getTextureChannelClass(testedFormat.type) == tcu::TEXTURECHANNELCLASS_SIGNED_INTEGER);
2325
2326         const auto isRead64             = is64BitIntegerFormat(m_readFormat);
2327         const auto isWrite64    = is64BitIntegerFormat(m_writeFormat);
2328         DE_ASSERT(isRead64 == isWrite64);
2329
2330         const bool using64Bits                          = (isRead64 || isWrite64);
2331
2332         // Additional capabilities when needed.
2333         std::string capability;
2334         std::string extension;
2335         std::string extraTypes;
2336
2337         if (using64Bits)
2338         {
2339                         extension  += "OpExtension \"SPV_EXT_shader_image_int64\"\n";
2340                         capability +=
2341                                 "OpCapability Int64\n"
2342                                 "OpCapability Int64ImageEXT\n"
2343                                 ;
2344                         extraTypes +=
2345                                 "%type_i64                           = OpTypeInt 64 1\n"
2346                                 "%type_u64                           = OpTypeInt 64 0\n"
2347                                 "%type_vec3_i64                      = OpTypeVector %type_i64 3\n"
2348                                 "%type_vec3_u64                      = OpTypeVector %type_u64 3\n"
2349                                 "%type_vec4_i64                      = OpTypeVector %type_i64 4\n"
2350                                 "%type_vec4_u64                      = OpTypeVector %type_u64 4\n"
2351                                 ;
2352         }
2353
2354         std::string relaxed = "";
2355         if (m_relaxedPrecision)
2356                 relaxed += "OpDecorate %src_image_ptr RelaxedPrecision\n";
2357
2358         // Sampled type depends on the format sign and mismatch force flag.
2359         const bool                      signedSampleType        = ((isSigned && !m_operandForce) || (!isSigned && m_operandForce));
2360         const std::string       bits                            = (using64Bits ? "64" : "32");
2361         const std::string       sampledTypePostfix      = (signedSampleType ? "i" : "u") + bits;
2362         const std::string       extendOperandStr        = (isSigned ? "SignExtend" : "ZeroExtend");
2363
2364         std::map<std::string, std::string> specializations =
2365         {
2366                 { "image_type_id",                      "%type_image" },
2367                 { "image_uni_ptr_type_id",      "%type_ptr_uniform_const_image" },
2368                 { "image_var_id",                       "%src_image_ptr" },
2369                 { "image_id",                           "%src_image" },
2370                 { "capability",                         capability },
2371                 { "extension",                          extension },
2372                 { "extra_types",                        extraTypes },
2373                 { "relaxed_precision",          relaxed },
2374                 { "image_format",                       getSpirvFormat(m_readFormat) },
2375                 { "sampled_type",                       (std::string("%type_") + sampledTypePostfix) },
2376                 { "sampled_type_vec4",          (std::string("%type_vec4_") + sampledTypePostfix) },
2377                 { "read_extend_operand",        (!isWriteTest() ? extendOperandStr : "") },
2378                 { "write_extend_operand",       (isWriteTest()  ? extendOperandStr : "") },
2379         };
2380
2381         // Addidtional parametrization is needed for a case when source and destination textures have same format
2382         tcu::StringTemplate imageTypeTemplate(
2383                 "${image_type_id}                     = OpTypeImage ${sampled_type} 2D 0 0 0 2 ${image_format}\n");
2384         tcu::StringTemplate imageUniformTypeTemplate(
2385                 "${image_uni_ptr_type_id}   = OpTypePointer UniformConstant ${image_type_id}\n");
2386         tcu::StringTemplate imageVariablesTemplate(
2387                 "${image_var_id}                      = OpVariable ${image_uni_ptr_type_id} UniformConstant\n");
2388         tcu::StringTemplate imageLoadTemplate(
2389                 "${image_id}                          = OpLoad ${image_type_id} ${image_var_id}\n");
2390
2391         std::string imageTypes;
2392         std::string imageUniformTypes;
2393         std::string imageVariables;
2394         std::string imageLoad;
2395
2396         // If input image format is the same as output there is less spir-v definitions
2397         if (m_readFormat == m_writeFormat)
2398         {
2399                 imageTypes                      = imageTypeTemplate.specialize(specializations);
2400                 imageUniformTypes       = imageUniformTypeTemplate.specialize(specializations);
2401                 imageVariables          = imageVariablesTemplate.specialize(specializations);
2402                 imageLoad                       = imageLoadTemplate.specialize(specializations);
2403
2404                 specializations["image_var_id"]                         = "%dst_image_ptr";
2405                 specializations["image_id"]                                     = "%dst_image";
2406                 imageVariables          += imageVariablesTemplate.specialize(specializations);
2407                 imageLoad                       += imageLoadTemplate.specialize(specializations);
2408         }
2409         else
2410         {
2411                 specializations["image_type_id"]                        = "%type_src_image";
2412                 specializations["image_uni_ptr_type_id"]        = "%type_ptr_uniform_const_src_image";
2413                 imageTypes                      = imageTypeTemplate.specialize(specializations);
2414                 imageUniformTypes       = imageUniformTypeTemplate.specialize(specializations);
2415                 imageVariables          = imageVariablesTemplate.specialize(specializations);
2416                 imageLoad                       = imageLoadTemplate.specialize(specializations);
2417
2418                 specializations["image_format"]                         = getSpirvFormat(m_writeFormat);
2419                 specializations["image_type_id"]                        = "%type_dst_image";
2420                 specializations["image_uni_ptr_type_id"]        = "%type_ptr_uniform_const_dst_image";
2421                 specializations["image_var_id"]                         = "%dst_image_ptr";
2422                 specializations["image_id"]                                     = "%dst_image";
2423                 imageTypes                      += imageTypeTemplate.specialize(specializations);
2424                 imageUniformTypes       += imageUniformTypeTemplate.specialize(specializations);
2425                 imageVariables          += imageVariablesTemplate.specialize(specializations);
2426                 imageLoad                       += imageLoadTemplate.specialize(specializations);
2427         }
2428
2429         specializations["image_types"]          = imageTypes;
2430         specializations["image_uniforms"]       = imageUniformTypes;
2431         specializations["image_variables"]      = imageVariables;
2432         specializations["image_load"]           = imageLoad;
2433
2434         // Specialize whole shader and add it to program collection
2435         programCollection.spirvAsmSources.add("comp") << shaderTemplate.specialize(specializations)
2436                 << vk::SpirVAsmBuildOptions(programCollection.usedVulkanVersion, vk::SPIRV_VERSION_1_4, true);
2437 }
2438
2439 TestInstance* ImageExtendOperandTest::createInstance(Context& context) const
2440 {
2441         return new ImageExtendOperandTestInstance(context, m_texture, m_readFormat, m_writeFormat, m_relaxedPrecision);
2442 }
2443
2444 static const Texture s_textures[] =
2445 {
2446         Texture(IMAGE_TYPE_1D,                  tcu::IVec3(64,  1,      1),     1),
2447         Texture(IMAGE_TYPE_1D_ARRAY,    tcu::IVec3(64,  1,      1),     8),
2448         Texture(IMAGE_TYPE_2D,                  tcu::IVec3(64,  64,     1),     1),
2449         Texture(IMAGE_TYPE_2D_ARRAY,    tcu::IVec3(64,  64,     1),     8),
2450         Texture(IMAGE_TYPE_3D,                  tcu::IVec3(64,  64,     8),     1),
2451         Texture(IMAGE_TYPE_CUBE,                tcu::IVec3(64,  64,     1),     6),
2452         Texture(IMAGE_TYPE_CUBE_ARRAY,  tcu::IVec3(64,  64,     1),     2*6),
2453         Texture(IMAGE_TYPE_BUFFER,              tcu::IVec3(64,  1,      1),     1),
2454 };
2455
2456 const Texture& getTestTexture (const ImageType imageType)
2457 {
2458         for (int textureNdx = 0; textureNdx < DE_LENGTH_OF_ARRAY(s_textures); ++textureNdx)
2459                 if (s_textures[textureNdx].type() == imageType)
2460                         return s_textures[textureNdx];
2461
2462         DE_FATAL("Internal error");
2463         return s_textures[0];
2464 }
2465
2466 static const VkFormat s_formats[] =
2467 {
2468         // Mandatory support
2469         VK_FORMAT_R32G32B32A32_SFLOAT,
2470         VK_FORMAT_R16G16B16A16_SFLOAT,
2471         VK_FORMAT_R32_SFLOAT,
2472
2473         VK_FORMAT_R32G32B32A32_UINT,
2474         VK_FORMAT_R16G16B16A16_UINT,
2475         VK_FORMAT_R8G8B8A8_UINT,
2476         VK_FORMAT_R32_UINT,
2477
2478         VK_FORMAT_R32G32B32A32_SINT,
2479         VK_FORMAT_R16G16B16A16_SINT,
2480         VK_FORMAT_R8G8B8A8_SINT,
2481         VK_FORMAT_R32_SINT,
2482
2483         VK_FORMAT_R8G8B8A8_UNORM,
2484
2485         VK_FORMAT_R8G8B8A8_SNORM,
2486
2487         // Requires StorageImageExtendedFormats capability
2488         VK_FORMAT_B10G11R11_UFLOAT_PACK32,
2489
2490         VK_FORMAT_R32G32_SFLOAT,
2491         VK_FORMAT_R16G16_SFLOAT,
2492         VK_FORMAT_R16_SFLOAT,
2493
2494         VK_FORMAT_A2B10G10R10_UINT_PACK32,
2495         VK_FORMAT_R32G32_UINT,
2496         VK_FORMAT_R16G16_UINT,
2497         VK_FORMAT_R16_UINT,
2498         VK_FORMAT_R8G8_UINT,
2499         VK_FORMAT_R8_UINT,
2500
2501         VK_FORMAT_R32G32_SINT,
2502         VK_FORMAT_R16G16_SINT,
2503         VK_FORMAT_R16_SINT,
2504         VK_FORMAT_R8G8_SINT,
2505         VK_FORMAT_R8_SINT,
2506
2507         VK_FORMAT_A2B10G10R10_UNORM_PACK32,
2508         VK_FORMAT_R16G16B16A16_UNORM,
2509         VK_FORMAT_R16G16B16A16_SNORM,
2510         VK_FORMAT_R16G16_UNORM,
2511         VK_FORMAT_R16_UNORM,
2512         VK_FORMAT_R8G8_UNORM,
2513         VK_FORMAT_R8_UNORM,
2514
2515         VK_FORMAT_R16G16_SNORM,
2516         VK_FORMAT_R16_SNORM,
2517         VK_FORMAT_R8G8_SNORM,
2518         VK_FORMAT_R8_SNORM
2519 };
2520
2521 static const VkFormat s_formatsThreeComponent[] =
2522 {
2523         VK_FORMAT_R8G8B8_UINT,
2524         VK_FORMAT_R8G8B8_SINT,
2525         VK_FORMAT_R8G8B8_UNORM,
2526         VK_FORMAT_R8G8B8_SNORM,
2527         VK_FORMAT_R16G16B16_UINT,
2528         VK_FORMAT_R16G16B16_SINT,
2529         VK_FORMAT_R16G16B16_UNORM,
2530         VK_FORMAT_R16G16B16_SNORM,
2531         VK_FORMAT_R16G16B16_SFLOAT,
2532         VK_FORMAT_R32G32B32_UINT,
2533         VK_FORMAT_R32G32B32_SINT,
2534         VK_FORMAT_R32G32B32_SFLOAT,
2535 };
2536
2537 } // anonymous ns
2538
2539 tcu::TestCaseGroup* createImageStoreTests (tcu::TestContext& testCtx)
2540 {
2541         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "store", "Plain imageStore() cases"));
2542         de::MovePtr<tcu::TestCaseGroup> testGroupWithFormat(new tcu::TestCaseGroup(testCtx, "with_format", "Declare a format layout qualifier for write images"));
2543         de::MovePtr<tcu::TestCaseGroup> testGroupWithoutFormat(new tcu::TestCaseGroup(testCtx, "without_format", "Do not declare a format layout qualifier for write images"));
2544
2545         for (int textureNdx = 0; textureNdx < DE_LENGTH_OF_ARRAY(s_textures); ++textureNdx)
2546         {
2547                 const Texture& texture = s_textures[textureNdx];
2548                 de::MovePtr<tcu::TestCaseGroup> groupWithFormatByImageViewType (new tcu::TestCaseGroup(testCtx, getImageTypeName(texture.type()).c_str(), ""));
2549                 de::MovePtr<tcu::TestCaseGroup> groupWithoutFormatByImageViewType (new tcu::TestCaseGroup(testCtx, getImageTypeName(texture.type()).c_str(), ""));
2550                 const bool isLayered = (texture.numLayers() > 1);
2551
2552                 for (int formatNdx = 0; formatNdx < DE_LENGTH_OF_ARRAY(s_formats); ++formatNdx)
2553                 {
2554                         const bool hasSpirvFmt = hasSpirvFormat(s_formats[formatNdx]);
2555
2556                         if (hasSpirvFmt)
2557                                 groupWithFormatByImageViewType->addChild(new StoreTest(testCtx, getFormatShortString(s_formats[formatNdx]), "", texture, s_formats[formatNdx]));
2558                         groupWithoutFormatByImageViewType->addChild(new StoreTest(testCtx, getFormatShortString(s_formats[formatNdx]), "", texture, s_formats[formatNdx], 0));
2559
2560                         if (isLayered && hasSpirvFmt)
2561                                 groupWithFormatByImageViewType->addChild(new StoreTest(testCtx, getFormatShortString(s_formats[formatNdx]) + "_single_layer", "",
2562                                                                                                                  texture, s_formats[formatNdx],
2563                                                                                                                  StoreTest::FLAG_SINGLE_LAYER_BIND | StoreTest::FLAG_DECLARE_IMAGE_FORMAT_IN_SHADER));
2564
2565                         if (texture.type() == IMAGE_TYPE_BUFFER)
2566                         {
2567                                 if (hasSpirvFmt)
2568                                         groupWithFormatByImageViewType->addChild(new StoreTest(testCtx, getFormatShortString(s_formats[formatNdx]) + "_minalign", "", texture, s_formats[formatNdx], StoreTest::FLAG_MINALIGN | StoreTest::FLAG_DECLARE_IMAGE_FORMAT_IN_SHADER));
2569                                 groupWithoutFormatByImageViewType->addChild(new StoreTest(testCtx, getFormatShortString(s_formats[formatNdx]) + "_minalign", "", texture, s_formats[formatNdx], StoreTest::FLAG_MINALIGN));
2570                         }
2571                 }
2572
2573                 testGroupWithFormat->addChild(groupWithFormatByImageViewType.release());
2574                 testGroupWithoutFormat->addChild(groupWithoutFormatByImageViewType.release());
2575         }
2576
2577         testGroup->addChild(testGroupWithFormat.release());
2578         testGroup->addChild(testGroupWithoutFormat.release());
2579
2580         return testGroup.release();
2581 }
2582
2583 tcu::TestCaseGroup* createImageLoadStoreTests (tcu::TestContext& testCtx)
2584 {
2585         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "load_store", "Cases with imageLoad() followed by imageStore()"));
2586         de::MovePtr<tcu::TestCaseGroup> testGroupWithFormat(new tcu::TestCaseGroup(testCtx, "with_format", "Declare a format layout qualifier for read images"));
2587         de::MovePtr<tcu::TestCaseGroup> testGroupWithoutFormat(new tcu::TestCaseGroup(testCtx, "without_format", "Do not declare a format layout qualifier for read images"));
2588
2589         for (int textureNdx = 0; textureNdx < DE_LENGTH_OF_ARRAY(s_textures); ++textureNdx)
2590         {
2591                 const Texture& texture = s_textures[textureNdx];
2592                 de::MovePtr<tcu::TestCaseGroup> groupWithFormatByImageViewType (new tcu::TestCaseGroup(testCtx, getImageTypeName(texture.type()).c_str(), ""));
2593                 de::MovePtr<tcu::TestCaseGroup> groupWithoutFormatByImageViewType (new tcu::TestCaseGroup(testCtx, getImageTypeName(texture.type()).c_str(), ""));
2594                 const bool isLayered = (texture.numLayers() > 1);
2595
2596                 for (int formatNdx = 0; formatNdx < DE_LENGTH_OF_ARRAY(s_formats); ++formatNdx)
2597                 {
2598                         // These tests always require a SPIR-V format for the write image, even if the read
2599                         // image is being used without a format.
2600                         if (!hasSpirvFormat(s_formats[formatNdx]))
2601                                 continue;
2602
2603                         groupWithFormatByImageViewType->addChild(new LoadStoreTest(testCtx, getFormatShortString(s_formats[formatNdx]), "", texture, s_formats[formatNdx], s_formats[formatNdx]));
2604                         groupWithoutFormatByImageViewType->addChild(new LoadStoreTest(testCtx, getFormatShortString(s_formats[formatNdx]), "", texture, s_formats[formatNdx], s_formats[formatNdx], 0));
2605
2606                         if (isLayered)
2607                                 groupWithFormatByImageViewType->addChild(new LoadStoreTest(testCtx, getFormatShortString(s_formats[formatNdx]) + "_single_layer", "",
2608                                                                                                                  texture, s_formats[formatNdx], s_formats[formatNdx],
2609                                                                                                                  LoadStoreTest::FLAG_SINGLE_LAYER_BIND | LoadStoreTest::FLAG_DECLARE_IMAGE_FORMAT_IN_SHADER));
2610                         if (texture.type() == IMAGE_TYPE_BUFFER)
2611                         {
2612                                 groupWithFormatByImageViewType->addChild(new LoadStoreTest(testCtx, getFormatShortString(s_formats[formatNdx]) + "_minalign", "", texture, s_formats[formatNdx], s_formats[formatNdx], LoadStoreTest::FLAG_MINALIGN | LoadStoreTest::FLAG_DECLARE_IMAGE_FORMAT_IN_SHADER));
2613                                 groupWithFormatByImageViewType->addChild(new LoadStoreTest(testCtx, getFormatShortString(s_formats[formatNdx]) + "_minalign_uniform", "", texture, s_formats[formatNdx], s_formats[formatNdx], LoadStoreTest::FLAG_MINALIGN | LoadStoreTest::FLAG_DECLARE_IMAGE_FORMAT_IN_SHADER | LoadStoreTest::FLAG_UNIFORM_TEXEL_BUFFER));
2614                                 groupWithoutFormatByImageViewType->addChild(new LoadStoreTest(testCtx, getFormatShortString(s_formats[formatNdx]) + "_minalign", "", texture, s_formats[formatNdx], s_formats[formatNdx], LoadStoreTest::FLAG_MINALIGN));
2615                                 groupWithoutFormatByImageViewType->addChild(new LoadStoreTest(testCtx, getFormatShortString(s_formats[formatNdx]) + "_minalign_uniform", "", texture, s_formats[formatNdx], s_formats[formatNdx], LoadStoreTest::FLAG_MINALIGN | LoadStoreTest::FLAG_UNIFORM_TEXEL_BUFFER));
2616                         }
2617                 }
2618
2619                 if (texture.type() == IMAGE_TYPE_BUFFER)
2620                 {
2621                         for (int formatNdx = 0; formatNdx < DE_LENGTH_OF_ARRAY(s_formatsThreeComponent); ++formatNdx)
2622                         {
2623                                 groupWithoutFormatByImageViewType->addChild(new LoadStoreTest(testCtx, getFormatShortString(s_formatsThreeComponent[formatNdx]) + "_uniform", "", texture, s_formatsThreeComponent[formatNdx], s_formatsThreeComponent[formatNdx], LoadStoreTest::FLAG_UNIFORM_TEXEL_BUFFER));
2624                                 groupWithoutFormatByImageViewType->addChild(new LoadStoreTest(testCtx, getFormatShortString(s_formatsThreeComponent[formatNdx]) + "_minalign_uniform", "", texture, s_formatsThreeComponent[formatNdx], s_formatsThreeComponent[formatNdx], LoadStoreTest::FLAG_MINALIGN | LoadStoreTest::FLAG_UNIFORM_TEXEL_BUFFER));
2625                         }
2626                 }
2627
2628                 testGroupWithFormat->addChild(groupWithFormatByImageViewType.release());
2629                 testGroupWithoutFormat->addChild(groupWithoutFormatByImageViewType.release());
2630         }
2631
2632         testGroup->addChild(testGroupWithFormat.release());
2633         testGroup->addChild(testGroupWithoutFormat.release());
2634
2635         return testGroup.release();
2636 }
2637
2638 tcu::TestCaseGroup* createImageLoadStoreLodAMDTests (tcu::TestContext& testCtx)
2639 {
2640         static const Texture textures[] =
2641         {
2642                 Texture(IMAGE_TYPE_1D_ARRAY,    tcu::IVec3(64,  1,      1),     8, 1, 6),
2643                 Texture(IMAGE_TYPE_1D,                  tcu::IVec3(64,  1,      1),     1, 1, 6),
2644                 Texture(IMAGE_TYPE_2D,                  tcu::IVec3(64,  64,     1),     1, 1, 6),
2645                 Texture(IMAGE_TYPE_2D_ARRAY,    tcu::IVec3(64,  64,     1),     8, 1, 6),
2646                 Texture(IMAGE_TYPE_3D,                  tcu::IVec3(64,  64,     8),     1, 1, 6),
2647                 Texture(IMAGE_TYPE_CUBE,                tcu::IVec3(64,  64,     1),     6, 1, 6),
2648                 Texture(IMAGE_TYPE_CUBE_ARRAY,  tcu::IVec3(64,  64,     1),     2*6, 1, 6),
2649         };
2650
2651         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "load_store_lod", "Cases with imageLoad() followed by imageStore()"));
2652         de::MovePtr<tcu::TestCaseGroup> testGroupWithFormat(new tcu::TestCaseGroup(testCtx, "with_format", "Declare a format layout qualifier for read images"));
2653         de::MovePtr<tcu::TestCaseGroup> testGroupWithoutFormat(new tcu::TestCaseGroup(testCtx, "without_format", "Do not declare a format layout qualifier for read images"));
2654
2655         for (int textureNdx = 0; textureNdx < DE_LENGTH_OF_ARRAY(textures); ++textureNdx)
2656         {
2657                 const Texture& texture = textures[textureNdx];
2658                 de::MovePtr<tcu::TestCaseGroup> groupWithFormatByImageViewType (new tcu::TestCaseGroup(testCtx, getImageTypeName(texture.type()).c_str(), ""));
2659                 de::MovePtr<tcu::TestCaseGroup> groupWithoutFormatByImageViewType (new tcu::TestCaseGroup(testCtx, getImageTypeName(texture.type()).c_str(), ""));
2660                 const bool isLayered = (texture.numLayers() > 1);
2661
2662                 if (texture.type() == IMAGE_TYPE_BUFFER)
2663                         continue;
2664
2665                 for (int formatNdx = 0; formatNdx < DE_LENGTH_OF_ARRAY(s_formats); ++formatNdx)
2666                 {
2667                         // These tests always require a SPIR-V format for the write image, even if the read
2668                         // image is being used without a format.
2669                         if (!hasSpirvFormat(s_formats[formatNdx]))
2670                                 continue;
2671
2672                         groupWithFormatByImageViewType->addChild(new LoadStoreTest(testCtx, getFormatShortString(s_formats[formatNdx]), "", texture, s_formats[formatNdx], s_formats[formatNdx], LoadStoreTest::FLAG_DECLARE_IMAGE_FORMAT_IN_SHADER, DE_TRUE));
2673                         groupWithoutFormatByImageViewType->addChild(new LoadStoreTest(testCtx, getFormatShortString(s_formats[formatNdx]), "", texture, s_formats[formatNdx], s_formats[formatNdx], 0, DE_TRUE));
2674
2675                         if (isLayered)
2676                                 groupWithFormatByImageViewType->addChild(new LoadStoreTest(testCtx, getFormatShortString(s_formats[formatNdx]) + "_single_layer", "",
2677                                                                                                                  texture, s_formats[formatNdx], s_formats[formatNdx],
2678                                                                                                                  LoadStoreTest::FLAG_SINGLE_LAYER_BIND | LoadStoreTest::FLAG_DECLARE_IMAGE_FORMAT_IN_SHADER, DE_TRUE));
2679                 }
2680
2681                 testGroupWithFormat->addChild(groupWithFormatByImageViewType.release());
2682                 testGroupWithoutFormat->addChild(groupWithoutFormatByImageViewType.release());
2683         }
2684
2685         testGroup->addChild(testGroupWithFormat.release());
2686         testGroup->addChild(testGroupWithoutFormat.release());
2687
2688         return testGroup.release();
2689 }
2690
2691 tcu::TestCaseGroup* createImageFormatReinterpretTests (tcu::TestContext& testCtx)
2692 {
2693         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "format_reinterpret", "Cases with differing texture and image formats"));
2694
2695         for (int textureNdx = 0; textureNdx < DE_LENGTH_OF_ARRAY(s_textures); ++textureNdx)
2696         {
2697                 const Texture& texture = s_textures[textureNdx];
2698                 de::MovePtr<tcu::TestCaseGroup> groupByImageViewType (new tcu::TestCaseGroup(testCtx, getImageTypeName(texture.type()).c_str(), ""));
2699
2700                 for (int imageFormatNdx = 0; imageFormatNdx < DE_LENGTH_OF_ARRAY(s_formats); ++imageFormatNdx)
2701                 for (int formatNdx = 0; formatNdx < DE_LENGTH_OF_ARRAY(s_formats); ++formatNdx)
2702                 {
2703                         if (!hasSpirvFormat(s_formats[formatNdx]))
2704                                 continue;
2705
2706                         const std::string caseName = getFormatShortString(s_formats[imageFormatNdx]) + "_" + getFormatShortString(s_formats[formatNdx]);
2707                         if (imageFormatNdx != formatNdx && formatsAreCompatible(s_formats[imageFormatNdx], s_formats[formatNdx]))
2708                                 groupByImageViewType->addChild(new LoadStoreTest(testCtx, caseName, "", texture, s_formats[formatNdx], s_formats[imageFormatNdx]));
2709                 }
2710                 testGroup->addChild(groupByImageViewType.release());
2711         }
2712
2713         return testGroup.release();
2714 }
2715
2716 de::MovePtr<TestCase> createImageQualifierRestrictCase (tcu::TestContext& testCtx, const ImageType imageType, const std::string& name)
2717 {
2718         const VkFormat format = VK_FORMAT_R32G32B32A32_UINT;
2719         const Texture& texture = getTestTexture(imageType);
2720         return de::MovePtr<TestCase>(new LoadStoreTest(testCtx, name, "", texture, format, format, LoadStoreTest::FLAG_RESTRICT_IMAGES | LoadStoreTest::FLAG_DECLARE_IMAGE_FORMAT_IN_SHADER));
2721 }
2722
2723 namespace
2724 {
2725
2726 bool relaxedOK(VkFormat format)
2727 {
2728         tcu::IVec4 bitDepth = tcu::getTextureFormatBitDepth(mapVkFormat(format));
2729         int maxBitDepth = deMax32(deMax32(bitDepth[0], bitDepth[1]), deMax32(bitDepth[2], bitDepth[3]));
2730         return maxBitDepth <= 16;
2731 }
2732
2733 // Get a format used for reading or writing in extension operand tests. These formats allow representing the shader sampled type to
2734 // verify results from read or write operations.
2735 VkFormat getShaderExtensionOperandFormat (bool isSigned, bool is64Bit)
2736 {
2737         const VkFormat formats[] =
2738         {
2739                 VK_FORMAT_R32G32B32A32_UINT,
2740                 VK_FORMAT_R32G32B32A32_SINT,
2741                 VK_FORMAT_R64_UINT,
2742                 VK_FORMAT_R64_SINT,
2743         };
2744         return formats[2u * (is64Bit ? 1u : 0u) + (isSigned ? 1u : 0u)];
2745 }
2746
2747 // INT or UINT format?
2748 bool isIntegralFormat (VkFormat format)
2749 {
2750         return (isIntFormat(format) || isUintFormat(format));
2751 }
2752
2753 // Return the list of formats used for the extension operand tests (SignExten/ZeroExtend).
2754 std::vector<VkFormat> getExtensionOperandFormatList (void)
2755 {
2756         std::vector<VkFormat> formatList;
2757
2758         for (auto format : s_formats)
2759         {
2760                 if (isIntegralFormat(format))
2761                         formatList.push_back(format);
2762         }
2763
2764         formatList.push_back(VK_FORMAT_R64_SINT);
2765         formatList.push_back(VK_FORMAT_R64_UINT);
2766
2767         return formatList;
2768 }
2769
2770 } // anonymous
2771
2772 tcu::TestCaseGroup* createImageExtendOperandsTests(tcu::TestContext& testCtx)
2773 {
2774         using GroupPtr = de::MovePtr<tcu::TestCaseGroup>;
2775
2776         GroupPtr testGroup(new tcu::TestCaseGroup(testCtx, "extend_operands_spirv1p4", "Cases with SignExtend and ZeroExtend"));
2777
2778         const struct
2779         {
2780                 ExtendTestType  testType;
2781                 const char*             name;
2782         } testTypes[] =
2783         {
2784                 { ExtendTestType::READ,         "read"  },
2785                 { ExtendTestType::WRITE,        "write" },
2786         };
2787
2788         const auto texture              = Texture(IMAGE_TYPE_2D, tcu::IVec3(8, 8, 1), 1);
2789         const auto formatList   = getExtensionOperandFormatList();
2790
2791         for (const auto format : formatList)
2792         {
2793                 const auto isInt                = isIntFormat(format);
2794                 const auto isUint               = isUintFormat(format);
2795                 const auto use64Bits    = is64BitIntegerFormat(format);
2796
2797                 DE_ASSERT(isInt || isUint);
2798
2799                 GroupPtr formatGroup (new tcu::TestCaseGroup(testCtx, getFormatShortString(format).c_str(), ""));
2800
2801                 for (const auto& testType : testTypes)
2802                 {
2803                         GroupPtr testTypeGroup (new tcu::TestCaseGroup(testCtx, testType.name, ""));
2804
2805                         for (int match = 0; match < 2; ++match)
2806                         {
2807                                 const bool      mismatched              = (match == 1);
2808                                 const char*     matchGroupName  = (mismatched ? "mismatched_sign" : "matched_sign");
2809
2810                                 // SPIR-V does not allow this kind of sampled type override.
2811                                 if (mismatched && isUint)
2812                                         continue;
2813
2814                                 GroupPtr matchGroup (new tcu::TestCaseGroup(testCtx, matchGroupName, ""));
2815
2816                                 for (int prec = 0; prec < 2; prec++)
2817                                 {
2818                                         const bool relaxedPrecision = (prec != 0);
2819
2820                                         const char* precisionName       = (relaxedPrecision ? "relaxed_precision" : "normal_precision");
2821                                         const auto  signedOther         = ((isInt && !mismatched) || (isUint && mismatched));
2822                                         const auto      otherFormat             = getShaderExtensionOperandFormat(signedOther, use64Bits);
2823                                         const auto  readFormat          = (testType.testType == ExtendTestType::READ ?  format : otherFormat);
2824                                         const auto  writeFormat         = (testType.testType == ExtendTestType::WRITE ? format : otherFormat);
2825
2826                                         if (relaxedPrecision && !relaxedOK(readFormat))
2827                                                 continue;
2828
2829                                         if (!hasSpirvFormat(readFormat) || !hasSpirvFormat(writeFormat))
2830                                                 continue;
2831
2832                                         matchGroup->addChild(new ImageExtendOperandTest(testCtx, precisionName, texture, readFormat, writeFormat, mismatched, relaxedPrecision, testType.testType));
2833                                 }
2834
2835                                 testTypeGroup->addChild(matchGroup.release());
2836                         }
2837
2838                         formatGroup->addChild(testTypeGroup.release());
2839                 }
2840
2841                 testGroup->addChild(formatGroup.release());
2842         }
2843
2844         return testGroup.release();
2845 }
2846
2847 } // image
2848 } // vkt