1 //
2 // Copyright (C) 2016-2017 Google, Inc.
3 // Copyright (C) 2020 The Khronos Group Inc.
4 //
5 // All rights reserved.
6 //
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
9 // are met:
10 //
11 //    Redistributions of source code must retain the above copyright
12 //    notice, this list of conditions and the following disclaimer.
13 //
14 //    Redistributions in binary form must reproduce the above
15 //    copyright notice, this list of conditions and the following
16 //    disclaimer in the documentation and/or other materials provided
17 //    with the distribution.
18 //
19 //    Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20 //    contributors may be used to endorse or promote products derived
21 //    from this software without specific prior written permission.
22 //
23 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27 // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29 // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34 // POSSIBILITY OF SUCH DAMAGE.
35 //
36 #include <algorithm>
37 
38 #include <gtest/gtest.h>
39 
40 #include "TestFixture.h"
41 
42 #include "glslang/MachineIndependent/iomapper.h"
43 #include "glslang/MachineIndependent/reflection.h"
44 
45 #ifndef GLSLANG_WEB
46 namespace glslangtest {
47 namespace {
48 
49 struct IoMapData {
50     std::vector<std::string> fileNames;
51     Semantics semantics;
52 };
53 
54 using GlslMapIOTest = GlslangTest <::testing::TestWithParam<IoMapData>>;
55 
56 template<class T>
interfaceName(T symbol)57 std::string interfaceName(T symbol) {
58     return symbol.getType()->getBasicType() == glslang::EbtBlock ? std::string(symbol.getType()->getTypeName().c_str()) : symbol.name;
59 }
60 
verifyIOMapping(std::string & linkingError,glslang::TProgram & program)61 bool verifyIOMapping(std::string& linkingError, glslang::TProgram& program) {
62     bool success = true;
63 
64     // Verify IO Mapping by generating reflection for each stage individually
65     // and comparing layout qualifiers on the results
66 
67 
68     int reflectionOptions = EShReflectionDefault;
69     //reflectionOptions |= EShReflectionStrictArraySuffix;
70     //reflectionOptions |= EShReflectionBasicArraySuffix;
71     reflectionOptions |= EShReflectionIntermediateIO;
72     reflectionOptions |= EShReflectionSeparateBuffers;
73     reflectionOptions |= EShReflectionAllBlockVariables;
74     //reflectionOptions |= EShReflectionUnwrapIOBlocks;
75 
76     success &= program.buildReflection(reflectionOptions);
77 
78     // check that the reflection output from the individual stages all makes sense..
79     std::vector<glslang::TReflection> stageReflections;
80     for (int s = 0; s < EShLangCount; ++s) {
81         if (program.getIntermediate((EShLanguage)s)) {
82             stageReflections.emplace_back((EShReflectionOptions)reflectionOptions, (EShLanguage)s, (EShLanguage)s);
83             success &= stageReflections.back().addStage((EShLanguage)s, *program.getIntermediate((EShLanguage)s));
84         }
85     }
86 
87     // check that input/output locations match between stages
88     auto it = stageReflections.begin();
89     auto nextIt = it + 1;
90     for (; nextIt != stageReflections.end(); it++, nextIt++) {
91         int numOut = it->getNumPipeOutputs();
92         std::map<std::string, const glslang::TObjectReflection*> pipeOut;
93 
94         for (int i = 0; i < numOut; i++) {
95             const glslang::TObjectReflection& out = it->getPipeOutput(i);
96             std::string name = interfaceName(out);
97             pipeOut[name] = &out;
98         }
99 
100         int numIn = nextIt->getNumPipeInputs();
101         for (int i = 0; i < numIn; i++) {
102             auto in = nextIt->getPipeInput(i);
103             std::string name = interfaceName(in);
104             auto out = pipeOut.find(name);
105 
106             if (out != pipeOut.end()) {
107                 auto inQualifier = in.getType()->getQualifier();
108                 auto outQualifier = out->second->getType()->getQualifier();
109                 success &= outQualifier.layoutLocation == inQualifier.layoutLocation;
110             }
111             else {
112                 success &= false;
113             }
114         }
115     }
116 
117     // compare uniforms in each stage to the program
118     {
119         int totalUniforms = program.getNumUniformVariables();
120         std::map<std::string, const glslang::TObjectReflection*> programUniforms;
121         for (int i = 0; i < totalUniforms; i++) {
122             const glslang::TObjectReflection& uniform = program.getUniform(i);
123             std::string name = interfaceName(uniform);
124             programUniforms[name] = &uniform;
125         }
126         it = stageReflections.begin();
127         for (; it != stageReflections.end(); it++) {
128             int numUniform = it->getNumUniforms();
129             std::map<std::string, glslang::TObjectReflection> uniforms;
130 
131             for (int i = 0; i < numUniform; i++) {
132                 glslang::TObjectReflection uniform = it->getUniform(i);
133                 std::string name = interfaceName(uniform);
134                 auto programUniform = programUniforms.find(name);
135 
136                 if (programUniform != programUniforms.end()) {
137                     auto stageQualifier = uniform.getType()->getQualifier();
138                     auto programQualifier = programUniform->second->getType()->getQualifier();
139 
140                     success &= stageQualifier.layoutLocation == programQualifier.layoutLocation;
141                     success &= stageQualifier.layoutBinding == programQualifier.layoutBinding;
142                     success &= stageQualifier.layoutSet == programQualifier.layoutSet;
143                 }
144                 else {
145                     success &= false;
146                 }
147             }
148         }
149     }
150 
151     // compare uniform blocks in each stage to the program table
152     {
153         int totalUniforms = program.getNumUniformBlocks();
154         std::map<std::string, const glslang::TObjectReflection*> programUniforms;
155         for (int i = 0; i < totalUniforms; i++) {
156             const glslang::TObjectReflection& uniform = program.getUniformBlock(i);
157             std::string name = interfaceName(uniform);
158             programUniforms[name] = &uniform;
159         }
160         it = stageReflections.begin();
161         for (; it != stageReflections.end(); it++) {
162             int numUniform = it->getNumUniformBlocks();
163             std::map<std::string, glslang::TObjectReflection> uniforms;
164 
165             for (int i = 0; i < numUniform; i++) {
166                 glslang::TObjectReflection uniform = it->getUniformBlock(i);
167                 std::string name = interfaceName(uniform);
168                 auto programUniform = programUniforms.find(name);
169 
170                 if (programUniform != programUniforms.end()) {
171                     auto stageQualifier = uniform.getType()->getQualifier();
172                     auto programQualifier = programUniform->second->getType()->getQualifier();
173 
174                     success &= stageQualifier.layoutLocation == programQualifier.layoutLocation;
175                     success &= stageQualifier.layoutBinding == programQualifier.layoutBinding;
176                     success &= stageQualifier.layoutSet == programQualifier.layoutSet;
177                 }
178                 else {
179                     success &= false;
180                 }
181             }
182         }
183     }
184 
185     if (!success) {
186         linkingError += "Mismatched cross-stage IO\n";
187     }
188 
189     return success;
190 }
191 
TEST_P(GlslMapIOTest,FromFile)192 TEST_P(GlslMapIOTest, FromFile)
193 {
194     const auto& fileNames = GetParam().fileNames;
195     Semantics semantics = GetParam().semantics;
196     const size_t fileCount = fileNames.size();
197     const EShMessages controls = DeriveOptions(Source::GLSL, semantics, Target::BothASTAndSpv);
198     GlslangResult result;
199 
200     // Compile each input shader file.
201     bool success = true;
202     std::vector<std::unique_ptr<glslang::TShader>> shaders;
203     for (size_t i = 0; i < fileCount; ++i) {
204         std::string contents;
205         tryLoadFile(GlobalTestSettings.testRoot + "/" + fileNames[i],
206             "input", &contents);
207         shaders.emplace_back(
208             new glslang::TShader(GetShaderStage(GetSuffix(fileNames[i]))));
209         auto* shader = shaders.back().get();
210 
211         shader->setAutoMapLocations(true);
212         shader->setAutoMapBindings(true);
213 
214         if (controls & EShMsgSpvRules) {
215             if (controls & EShMsgVulkanRules) {
216                 shader->setEnvInput((controls & EShMsgReadHlsl) ? glslang::EShSourceHlsl
217                                                                : glslang::EShSourceGlsl,
218                                     shader->getStage(), glslang::EShClientVulkan, 100);
219                 shader->setEnvClient(glslang::EShClientVulkan, glslang::EShTargetVulkan_1_1);
220                 shader->setEnvTarget(glslang::EShTargetSpv, glslang::EShTargetSpv_1_0);
221             } else {
222                 shader->setEnvInput((controls & EShMsgReadHlsl) ? glslang::EShSourceHlsl
223                                                                : glslang::EShSourceGlsl,
224                                     shader->getStage(), glslang::EShClientOpenGL, 100);
225                 shader->setEnvClient(glslang::EShClientOpenGL, glslang::EShTargetOpenGL_450);
226                 shader->setEnvTarget(glslang::EshTargetSpv, glslang::EShTargetSpv_1_0);
227             }
228         }
229 
230         success &= compile(shader, contents, "", controls);
231 
232         result.shaderResults.push_back(
233             { fileNames[i], shader->getInfoLog(), shader->getInfoDebugLog() });
234     }
235 
236     // Link all of them.
237     glslang::TProgram program;
238     for (const auto& shader : shaders) program.addShader(shader.get());
239     success &= program.link(controls);
240     result.linkingOutput = program.getInfoLog();
241     result.linkingError = program.getInfoDebugLog();
242 
243     unsigned int stage = 0;
244     glslang::TIntermediate* firstIntermediate = nullptr;
245     while (!program.getIntermediate((EShLanguage)stage) && stage < EShLangCount) { stage++; }
246     firstIntermediate = program.getIntermediate((EShLanguage)stage);
247 
248     glslang::TDefaultGlslIoResolver resolver(*firstIntermediate);
249     glslang::TGlslIoMapper ioMapper;
250 
251     if (success) {
252         success &= program.mapIO(&resolver, &ioMapper);
253         result.linkingOutput = program.getInfoLog();
254         result.linkingError = program.getInfoDebugLog();
255     }
256 
257     success &= verifyIOMapping(result.linkingError, program);
258     result.validationResult = success;
259 
260     if (success && (controls & EShMsgSpvRules)) {
261         for (int stage = 0; stage < EShLangCount; ++stage) {
262             if (program.getIntermediate((EShLanguage)stage)) {
263                 spv::SpvBuildLogger logger;
264                 std::vector<uint32_t> spirv_binary;
265                 options().disableOptimizer = false;
266                 glslang::GlslangToSpv(*program.getIntermediate((EShLanguage)stage),
267                     spirv_binary, &logger, &options());
268 
269                 std::ostringstream disassembly_stream;
270                 spv::Parameterize();
271                 spv::Disassemble(disassembly_stream, spirv_binary);
272                 result.spirvWarningsErrors += logger.getAllMessages();
273                 result.spirv += disassembly_stream.str();
274                 result.validationResult &= !options().validate || logger.getAllMessages().empty();
275             }
276         }
277     }
278 
279     std::ostringstream stream;
280     outputResultToStream(&stream, result, controls);
281 
282     // Check with expected results.
283     const std::string expectedOutputFname =
284         GlobalTestSettings.testRoot + "/baseResults/" + fileNames.front() + ".out";
285     std::string expectedOutput;
286     tryLoadFile(expectedOutputFname, "expected output", &expectedOutput);
287 
288     checkEqAndUpdateIfRequested(expectedOutput, stream.str(), expectedOutputFname,
289         result.spirvWarningsErrors);
290 }
291 
292 // clang-format off
293 INSTANTIATE_TEST_SUITE_P(
294     Glsl, GlslMapIOTest,
295     ::testing::ValuesIn(std::vector<IoMapData>({
296         {{"iomap.crossStage.vert", "iomap.crossStage.frag" }, Semantics::OpenGL},
297         {{"iomap.crossStage.2.vert", "iomap.crossStage.2.geom", "iomap.crossStage.2.frag" }, Semantics::OpenGL},
298         // vulkan semantics
299         {{"iomap.crossStage.vk.vert", "iomap.crossStage.vk.geom", "iomap.crossStage.vk.frag" }, Semantics::Vulkan},
300     }))
301 );
302 // clang-format on
303 
304 }  // anonymous namespace
305 }  // namespace glslangtest
306 #endif