Merge pull request #3050 from Try/mesh-shader-ibo-fixup
[platform/upstream/glslang.git] / glslang / MachineIndependent / ParseHelper.cpp
1 //
2 // Copyright (C) 2002-2005  3Dlabs Inc. Ltd.
3 // Copyright (C) 2012-2015 LunarG, Inc.
4 // Copyright (C) 2015-2018 Google, Inc.
5 // Copyright (C) 2017, 2019 ARM Limited.
6 // Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights reserved.
7 //
8 // All rights reserved.
9 //
10 // Redistribution and use in source and binary forms, with or without
11 // modification, are permitted provided that the following conditions
12 // are met:
13 //
14 //    Redistributions of source code must retain the above copyright
15 //    notice, this list of conditions and the following disclaimer.
16 //
17 //    Redistributions in binary form must reproduce the above
18 //    copyright notice, this list of conditions and the following
19 //    disclaimer in the documentation and/or other materials provided
20 //    with the distribution.
21 //
22 //    Neither the name of 3Dlabs Inc. Ltd. nor the names of its
23 //    contributors may be used to endorse or promote products derived
24 //    from this software without specific prior written permission.
25 //
26 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
27 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
28 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
29 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
30 // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
31 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
32 // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
33 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
34 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
36 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37 // POSSIBILITY OF SUCH DAMAGE.
38 //
39
40 #include "ParseHelper.h"
41 #include "Scan.h"
42
43 #include "../OSDependent/osinclude.h"
44 #include <algorithm>
45
46 #include "preprocessor/PpContext.h"
47
48 extern int yyparse(glslang::TParseContext*);
49
50 namespace glslang {
51
52 TParseContext::TParseContext(TSymbolTable& symbolTable, TIntermediate& interm, bool parsingBuiltins,
53                              int version, EProfile profile, const SpvVersion& spvVersion, EShLanguage language,
54                              TInfoSink& infoSink, bool forwardCompatible, EShMessages messages,
55                              const TString* entryPoint) :
56             TParseContextBase(symbolTable, interm, parsingBuiltins, version, profile, spvVersion, language,
57                               infoSink, forwardCompatible, messages, entryPoint),
58             inMain(false),
59             blockName(nullptr),
60             limits(resources.limits)
61 #ifndef GLSLANG_WEB
62             ,
63             atomicUintOffsets(nullptr), anyIndexLimits(false)
64 #endif
65 {
66     // decide whether precision qualifiers should be ignored or respected
67     if (isEsProfile() || spvVersion.vulkan > 0) {
68         precisionManager.respectPrecisionQualifiers();
69         if (! parsingBuiltins && language == EShLangFragment && !isEsProfile() && spvVersion.vulkan > 0)
70             precisionManager.warnAboutDefaults();
71     }
72
73     setPrecisionDefaults();
74
75     globalUniformDefaults.clear();
76     globalUniformDefaults.layoutMatrix = ElmColumnMajor;
77     globalUniformDefaults.layoutPacking = spvVersion.spv != 0 ? ElpStd140 : ElpShared;
78
79     globalBufferDefaults.clear();
80     globalBufferDefaults.layoutMatrix = ElmColumnMajor;
81     globalBufferDefaults.layoutPacking = spvVersion.spv != 0 ? ElpStd430 : ElpShared;
82
83     // use storage buffer on SPIR-V 1.3 and up
84     if (spvVersion.spv >= EShTargetSpv_1_3)
85         intermediate.setUseStorageBuffer();
86
87     globalInputDefaults.clear();
88     globalOutputDefaults.clear();
89
90     globalSharedDefaults.clear();
91     globalSharedDefaults.layoutMatrix = ElmColumnMajor;
92     globalSharedDefaults.layoutPacking = ElpStd430;
93
94 #ifndef GLSLANG_WEB
95     // "Shaders in the transform
96     // feedback capturing mode have an initial global default of
97     //     layout(xfb_buffer = 0) out;"
98     if (language == EShLangVertex ||
99         language == EShLangTessControl ||
100         language == EShLangTessEvaluation ||
101         language == EShLangGeometry)
102         globalOutputDefaults.layoutXfbBuffer = 0;
103
104     if (language == EShLangGeometry)
105         globalOutputDefaults.layoutStream = 0;
106 #endif
107
108     if (entryPoint != nullptr && entryPoint->size() > 0 && *entryPoint != "main")
109         infoSink.info.message(EPrefixError, "Source entry point must be \"main\"");
110 }
111
112 TParseContext::~TParseContext()
113 {
114 #ifndef GLSLANG_WEB
115     delete [] atomicUintOffsets;
116 #endif
117 }
118
119 // Set up all default precisions as needed by the current environment.
120 // Intended just as a TParseContext constructor helper.
121 void TParseContext::setPrecisionDefaults()
122 {
123     // Set all precision defaults to EpqNone, which is correct for all types
124     // when not obeying precision qualifiers, and correct for types that don't
125     // have defaults (thus getting an error on use) when obeying precision
126     // qualifiers.
127
128     for (int type = 0; type < EbtNumTypes; ++type)
129         defaultPrecision[type] = EpqNone;
130
131     for (int type = 0; type < maxSamplerIndex; ++type)
132         defaultSamplerPrecision[type] = EpqNone;
133
134     // replace with real precision defaults for those that have them
135     if (obeyPrecisionQualifiers()) {
136         if (isEsProfile()) {
137             // Most don't have defaults, a few default to lowp.
138             TSampler sampler;
139             sampler.set(EbtFloat, Esd2D);
140             defaultSamplerPrecision[computeSamplerTypeIndex(sampler)] = EpqLow;
141             sampler.set(EbtFloat, EsdCube);
142             defaultSamplerPrecision[computeSamplerTypeIndex(sampler)] = EpqLow;
143             sampler.set(EbtFloat, Esd2D);
144             sampler.setExternal(true);
145             defaultSamplerPrecision[computeSamplerTypeIndex(sampler)] = EpqLow;
146         }
147
148         // If we are parsing built-in computational variables/functions, it is meaningful to record
149         // whether the built-in has no precision qualifier, as that ambiguity
150         // is used to resolve the precision from the supplied arguments/operands instead.
151         // So, we don't actually want to replace EpqNone with a default precision for built-ins.
152         if (! parsingBuiltins) {
153             if (isEsProfile() && language == EShLangFragment) {
154                 defaultPrecision[EbtInt] = EpqMedium;
155                 defaultPrecision[EbtUint] = EpqMedium;
156             } else {
157                 defaultPrecision[EbtInt] = EpqHigh;
158                 defaultPrecision[EbtUint] = EpqHigh;
159                 defaultPrecision[EbtFloat] = EpqHigh;
160             }
161
162             if (!isEsProfile()) {
163                 // Non-ES profile
164                 // All sampler precisions default to highp.
165                 for (int type = 0; type < maxSamplerIndex; ++type)
166                     defaultSamplerPrecision[type] = EpqHigh;
167             }
168         }
169
170         defaultPrecision[EbtSampler] = EpqLow;
171         defaultPrecision[EbtAtomicUint] = EpqHigh;
172     }
173 }
174
175 void TParseContext::setLimits(const TBuiltInResource& r)
176 {
177     resources = r;
178     intermediate.setLimits(r);
179
180 #ifndef GLSLANG_WEB
181     anyIndexLimits = ! limits.generalAttributeMatrixVectorIndexing ||
182                      ! limits.generalConstantMatrixVectorIndexing ||
183                      ! limits.generalSamplerIndexing ||
184                      ! limits.generalUniformIndexing ||
185                      ! limits.generalVariableIndexing ||
186                      ! limits.generalVaryingIndexing;
187
188
189     // "Each binding point tracks its own current default offset for
190     // inheritance of subsequent variables using the same binding. The initial state of compilation is that all
191     // binding points have an offset of 0."
192     atomicUintOffsets = new int[resources.maxAtomicCounterBindings];
193     for (int b = 0; b < resources.maxAtomicCounterBindings; ++b)
194         atomicUintOffsets[b] = 0;
195 #endif
196 }
197
198 //
199 // Parse an array of strings using yyparse, going through the
200 // preprocessor to tokenize the shader strings, then through
201 // the GLSL scanner.
202 //
203 // Returns true for successful acceptance of the shader, false if any errors.
204 //
205 bool TParseContext::parseShaderStrings(TPpContext& ppContext, TInputScanner& input, bool versionWillBeError)
206 {
207     currentScanner = &input;
208     ppContext.setInput(input, versionWillBeError);
209     yyparse(this);
210
211     finish();
212
213     return numErrors == 0;
214 }
215
216 // This is called from bison when it has a parse (syntax) error
217 // Note though that to stop cascading errors, we set EOF, which
218 // will usually cause a syntax error, so be more accurate that
219 // compilation is terminating.
220 void TParseContext::parserError(const char* s)
221 {
222     if (! getScanner()->atEndOfInput() || numErrors == 0)
223         error(getCurrentLoc(), "", "", s, "");
224     else
225         error(getCurrentLoc(), "compilation terminated", "", "");
226 }
227
228 void TParseContext::growGlobalUniformBlock(const TSourceLoc& loc, TType& memberType, const TString& memberName, TTypeList* typeList)
229 {
230     bool createBlock = globalUniformBlock == nullptr;
231
232     if (createBlock) {
233         globalUniformBinding = intermediate.getGlobalUniformBinding();
234         globalUniformSet = intermediate.getGlobalUniformSet();
235     }
236
237     // use base class function to create/expand block
238     TParseContextBase::growGlobalUniformBlock(loc, memberType, memberName, typeList);
239
240     if (spvVersion.vulkan > 0 && spvVersion.vulkanRelaxed) {
241         // check for a block storage override
242         TBlockStorageClass storageOverride = intermediate.getBlockStorageOverride(getGlobalUniformBlockName());
243         TQualifier& qualifier = globalUniformBlock->getWritableType().getQualifier();
244         qualifier.defaultBlock = true;
245
246         if (storageOverride != EbsNone) {
247             if (createBlock) {
248                 // Remap block storage
249                 qualifier.setBlockStorage(storageOverride);
250
251                 // check that the change didn't create errors
252                 blockQualifierCheck(loc, qualifier, false);
253             }
254
255             // remap meber storage as well
256             memberType.getQualifier().setBlockStorage(storageOverride);
257         }
258     }
259 }
260
261 void TParseContext::growAtomicCounterBlock(int binding, const TSourceLoc& loc, TType& memberType, const TString& memberName, TTypeList* typeList)
262 {
263     bool createBlock = atomicCounterBuffers.find(binding) == atomicCounterBuffers.end();
264
265     if (createBlock) {
266         atomicCounterBlockSet = intermediate.getAtomicCounterBlockSet();
267     }
268
269     // use base class function to create/expand block
270     TParseContextBase::growAtomicCounterBlock(binding, loc, memberType, memberName, typeList);
271     TQualifier& qualifier = atomicCounterBuffers[binding]->getWritableType().getQualifier();
272     qualifier.defaultBlock = true;
273
274     if (spvVersion.vulkan > 0 && spvVersion.vulkanRelaxed) {
275         // check for a Block storage override
276         TBlockStorageClass storageOverride = intermediate.getBlockStorageOverride(getAtomicCounterBlockName());
277
278         if (storageOverride != EbsNone) {
279             if (createBlock) {
280                 // Remap block storage
281
282                 qualifier.setBlockStorage(storageOverride);
283
284                 // check that the change didn't create errors
285                 blockQualifierCheck(loc, qualifier, false);
286             }
287
288             // remap meber storage as well
289             memberType.getQualifier().setBlockStorage(storageOverride);
290         }
291     }
292 }
293
294 const char* TParseContext::getGlobalUniformBlockName() const
295 {
296     const char* name = intermediate.getGlobalUniformBlockName();
297     if (std::string(name) == "")
298         return "gl_DefaultUniformBlock";
299     else
300         return name;
301 }
302 void TParseContext::finalizeGlobalUniformBlockLayout(TVariable&)
303 {
304 }
305 void TParseContext::setUniformBlockDefaults(TType& block) const
306 {
307     block.getQualifier().layoutPacking = ElpStd140;
308     block.getQualifier().layoutMatrix = ElmColumnMajor;
309 }
310
311
312 const char* TParseContext::getAtomicCounterBlockName() const
313 {
314     const char* name = intermediate.getAtomicCounterBlockName();
315     if (std::string(name) == "")
316         return "gl_AtomicCounterBlock";
317     else
318         return name;
319 }
320 void TParseContext::finalizeAtomicCounterBlockLayout(TVariable&)
321 {
322 }
323
324 void TParseContext::setAtomicCounterBlockDefaults(TType& block) const
325 {
326     block.getQualifier().layoutPacking = ElpStd430;
327     block.getQualifier().layoutMatrix = ElmRowMajor;
328 }
329
330 void TParseContext::setInvariant(const TSourceLoc& loc, const char* builtin) {
331     TSymbol* symbol = symbolTable.find(builtin);
332     if (symbol && symbol->getType().getQualifier().isPipeOutput()) {
333         if (intermediate.inIoAccessed(builtin))
334             warn(loc, "changing qualification after use", "invariant", builtin);
335         TSymbol* csymbol = symbolTable.copyUp(symbol);
336         csymbol->getWritableType().getQualifier().invariant = true;
337     }
338 }
339
340 void TParseContext::handlePragma(const TSourceLoc& loc, const TVector<TString>& tokens)
341 {
342 #ifndef GLSLANG_WEB
343     if (pragmaCallback)
344         pragmaCallback(loc.line, tokens);
345
346     if (tokens.size() == 0)
347         return;
348
349     if (tokens[0].compare("optimize") == 0) {
350         if (tokens.size() != 4) {
351             error(loc, "optimize pragma syntax is incorrect", "#pragma", "");
352             return;
353         }
354
355         if (tokens[1].compare("(") != 0) {
356             error(loc, "\"(\" expected after 'optimize' keyword", "#pragma", "");
357             return;
358         }
359
360         if (tokens[2].compare("on") == 0)
361             contextPragma.optimize = true;
362         else if (tokens[2].compare("off") == 0)
363             contextPragma.optimize = false;
364         else {
365             if(relaxedErrors())
366                 //  If an implementation does not recognize the tokens following #pragma, then it will ignore that pragma.
367                 warn(loc, "\"on\" or \"off\" expected after '(' for 'optimize' pragma", "#pragma", "");
368             return;
369         }
370
371         if (tokens[3].compare(")") != 0) {
372             error(loc, "\")\" expected to end 'optimize' pragma", "#pragma", "");
373             return;
374         }
375     } else if (tokens[0].compare("debug") == 0) {
376         if (tokens.size() != 4) {
377             error(loc, "debug pragma syntax is incorrect", "#pragma", "");
378             return;
379         }
380
381         if (tokens[1].compare("(") != 0) {
382             error(loc, "\"(\" expected after 'debug' keyword", "#pragma", "");
383             return;
384         }
385
386         if (tokens[2].compare("on") == 0)
387             contextPragma.debug = true;
388         else if (tokens[2].compare("off") == 0)
389             contextPragma.debug = false;
390         else {
391             if(relaxedErrors())
392                 //  If an implementation does not recognize the tokens following #pragma, then it will ignore that pragma.
393                 warn(loc, "\"on\" or \"off\" expected after '(' for 'debug' pragma", "#pragma", "");
394             return;
395         }
396
397         if (tokens[3].compare(")") != 0) {
398             error(loc, "\")\" expected to end 'debug' pragma", "#pragma", "");
399             return;
400         }
401     } else if (spvVersion.spv > 0 && tokens[0].compare("use_storage_buffer") == 0) {
402         if (tokens.size() != 1)
403             error(loc, "extra tokens", "#pragma", "");
404         intermediate.setUseStorageBuffer();
405     } else if (spvVersion.spv > 0 && tokens[0].compare("use_vulkan_memory_model") == 0) {
406         if (tokens.size() != 1)
407             error(loc, "extra tokens", "#pragma", "");
408         intermediate.setUseVulkanMemoryModel();
409     } else if (spvVersion.spv > 0 && tokens[0].compare("use_variable_pointers") == 0) {
410         if (tokens.size() != 1)
411             error(loc, "extra tokens", "#pragma", "");
412         if (spvVersion.spv < glslang::EShTargetSpv_1_3)
413             error(loc, "requires SPIR-V 1.3", "#pragma use_variable_pointers", "");
414         intermediate.setUseVariablePointers();
415     } else if (tokens[0].compare("once") == 0) {
416         warn(loc, "not implemented", "#pragma once", "");
417     } else if (tokens[0].compare("glslang_binary_double_output") == 0) {
418         intermediate.setBinaryDoubleOutput();
419     } else if (spvVersion.spv > 0 && tokens[0].compare("STDGL") == 0 &&
420                tokens[1].compare("invariant") == 0 && tokens[3].compare("all") == 0) {
421         intermediate.setInvariantAll();
422         // Set all builtin out variables invariant if declared
423         setInvariant(loc, "gl_Position");
424         setInvariant(loc, "gl_PointSize");
425         setInvariant(loc, "gl_ClipDistance");
426         setInvariant(loc, "gl_CullDistance");
427         setInvariant(loc, "gl_TessLevelOuter");
428         setInvariant(loc, "gl_TessLevelInner");
429         setInvariant(loc, "gl_PrimitiveID");
430         setInvariant(loc, "gl_Layer");
431         setInvariant(loc, "gl_ViewportIndex");
432         setInvariant(loc, "gl_FragDepth");
433         setInvariant(loc, "gl_SampleMask");
434         setInvariant(loc, "gl_ClipVertex");
435         setInvariant(loc, "gl_FrontColor");
436         setInvariant(loc, "gl_BackColor");
437         setInvariant(loc, "gl_FrontSecondaryColor");
438         setInvariant(loc, "gl_BackSecondaryColor");
439         setInvariant(loc, "gl_TexCoord");
440         setInvariant(loc, "gl_FogFragCoord");
441         setInvariant(loc, "gl_FragColor");
442         setInvariant(loc, "gl_FragData");
443     }
444 #endif
445 }
446
447 //
448 // Handle seeing a variable identifier in the grammar.
449 //
450 TIntermTyped* TParseContext::handleVariable(const TSourceLoc& loc, TSymbol* symbol, const TString* string)
451 {
452     TIntermTyped* node = nullptr;
453
454     // Error check for requiring specific extensions present.
455     if (symbol && symbol->getNumExtensions())
456         requireExtensions(loc, symbol->getNumExtensions(), symbol->getExtensions(), symbol->getName().c_str());
457
458 #ifndef GLSLANG_WEB
459     if (symbol && symbol->isReadOnly()) {
460         // All shared things containing an unsized array must be copied up
461         // on first use, so that all future references will share its array structure,
462         // so that editing the implicit size will effect all nodes consuming it,
463         // and so that editing the implicit size won't change the shared one.
464         //
465         // If this is a variable or a block, check it and all it contains, but if this
466         // is a member of an anonymous block, check the whole block, as the whole block
467         // will need to be copied up if it contains an unsized array.
468         //
469         // This check is being done before the block-name check further down, so guard
470         // for that too.
471         if (!symbol->getType().isUnusableName()) {
472             if (symbol->getType().containsUnsizedArray() ||
473                 (symbol->getAsAnonMember() &&
474                  symbol->getAsAnonMember()->getAnonContainer().getType().containsUnsizedArray()))
475                 makeEditable(symbol);
476         }
477     }
478 #endif
479
480     const TVariable* variable;
481     const TAnonMember* anon = symbol ? symbol->getAsAnonMember() : nullptr;
482     if (anon) {
483         // It was a member of an anonymous container.
484
485         // Create a subtree for its dereference.
486         variable = anon->getAnonContainer().getAsVariable();
487         TIntermTyped* container = intermediate.addSymbol(*variable, loc);
488         TIntermTyped* constNode = intermediate.addConstantUnion(anon->getMemberNumber(), loc);
489         node = intermediate.addIndex(EOpIndexDirectStruct, container, constNode, loc);
490
491         node->setType(*(*variable->getType().getStruct())[anon->getMemberNumber()].type);
492         if (node->getType().hiddenMember())
493             error(loc, "member of nameless block was not redeclared", string->c_str(), "");
494     } else {
495         // Not a member of an anonymous container.
496
497         // The symbol table search was done in the lexical phase.
498         // See if it was a variable.
499         variable = symbol ? symbol->getAsVariable() : nullptr;
500         if (variable) {
501             if (variable->getType().isUnusableName()) {
502                 error(loc, "cannot be used (maybe an instance name is needed)", string->c_str(), "");
503                 variable = nullptr;
504             }
505
506             if (language == EShLangMesh && variable) {
507                 TLayoutGeometry primitiveType = intermediate.getOutputPrimitive();
508                 if ((variable->getMangledName() == "gl_PrimitiveTriangleIndicesEXT" && primitiveType != ElgTriangles) ||
509                     (variable->getMangledName() == "gl_PrimitiveLineIndicesEXT" && primitiveType != ElgLines) ||
510                     (variable->getMangledName() == "gl_PrimitivePointIndicesEXT" && primitiveType != ElgPoints)) {
511                     error(loc, "cannot be used (ouput primitive type mismatch)", string->c_str(), "");
512                     variable = nullptr;
513                 }
514             }
515         } else {
516             if (symbol)
517                 error(loc, "variable name expected", string->c_str(), "");
518         }
519
520         // Recovery, if it wasn't found or was not a variable.
521         if (! variable)
522             variable = new TVariable(string, TType(EbtVoid));
523
524         if (variable->getType().getQualifier().isFrontEndConstant())
525             node = intermediate.addConstantUnion(variable->getConstArray(), variable->getType(), loc);
526         else
527             node = intermediate.addSymbol(*variable, loc);
528     }
529
530     if (variable->getType().getQualifier().isIo())
531         intermediate.addIoAccessed(*string);
532
533     if (variable->getType().isReference() &&
534         variable->getType().getQualifier().bufferReferenceNeedsVulkanMemoryModel()) {
535         intermediate.setUseVulkanMemoryModel();
536     }
537
538     return node;
539 }
540
541 //
542 // Handle seeing a base[index] dereference in the grammar.
543 //
544 TIntermTyped* TParseContext::handleBracketDereference(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
545 {
546     int indexValue = 0;
547     if (index->getQualifier().isFrontEndConstant())
548         indexValue = index->getAsConstantUnion()->getConstArray()[0].getIConst();
549
550     // basic type checks...
551     variableCheck(base);
552
553     if (! base->isArray() && ! base->isMatrix() && ! base->isVector() && ! base->getType().isCoopMat() &&
554         ! base->isReference()) {
555         if (base->getAsSymbolNode())
556             error(loc, " left of '[' is not of type array, matrix, or vector ", base->getAsSymbolNode()->getName().c_str(), "");
557         else
558             error(loc, " left of '[' is not of type array, matrix, or vector ", "expression", "");
559
560         // Insert dummy error-recovery result
561         return intermediate.addConstantUnion(0.0, EbtFloat, loc);
562     }
563
564     if (!base->isArray() && base->isVector()) {
565         if (base->getType().contains16BitFloat())
566             requireFloat16Arithmetic(loc, "[", "does not operate on types containing float16");
567         if (base->getType().contains16BitInt())
568             requireInt16Arithmetic(loc, "[", "does not operate on types containing (u)int16");
569         if (base->getType().contains8BitInt())
570             requireInt8Arithmetic(loc, "[", "does not operate on types containing (u)int8");
571     }
572
573     // check for constant folding
574     if (base->getType().getQualifier().isFrontEndConstant() && index->getQualifier().isFrontEndConstant()) {
575         // both base and index are front-end constants
576         checkIndex(loc, base->getType(), indexValue);
577         return intermediate.foldDereference(base, indexValue, loc);
578     }
579
580     // at least one of base and index is not a front-end constant variable...
581     TIntermTyped* result = nullptr;
582
583 #ifndef GLSLANG_WEB
584     if (base->isReference() && ! base->isArray()) {
585         requireExtensions(loc, 1, &E_GL_EXT_buffer_reference2, "buffer reference indexing");
586         if (base->getType().getReferentType()->containsUnsizedArray()) {
587             error(loc, "cannot index reference to buffer containing an unsized array", "", "");
588             result = nullptr;
589         } else {
590             result = intermediate.addBinaryMath(EOpAdd, base, index, loc);
591             if (result != nullptr)
592                 result->setType(base->getType());
593         }
594         if (result == nullptr) {
595             error(loc, "cannot index buffer reference", "", "");
596             result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
597         }
598         return result;
599     }
600     if (base->getAsSymbolNode() && isIoResizeArray(base->getType()))
601         handleIoResizeArrayAccess(loc, base);
602 #endif
603
604     if (index->getQualifier().isFrontEndConstant())
605         checkIndex(loc, base->getType(), indexValue);
606
607     if (index->getQualifier().isFrontEndConstant()) {
608 #ifndef GLSLANG_WEB
609         if (base->getType().isUnsizedArray()) {
610             base->getWritableType().updateImplicitArraySize(indexValue + 1);
611             // For 2D per-view builtin arrays, update the inner dimension size in parent type
612             if (base->getQualifier().isPerView() && base->getQualifier().builtIn != EbvNone) {
613                 TIntermBinary* binaryNode = base->getAsBinaryNode();
614                 if (binaryNode) {
615                     TType& leftType = binaryNode->getLeft()->getWritableType();
616                     TArraySizes& arraySizes = *leftType.getArraySizes();
617                     assert(arraySizes.getNumDims() == 2);
618                     arraySizes.setDimSize(1, std::max(arraySizes.getDimSize(1), indexValue + 1));
619                 }
620             }
621         } else
622 #endif
623             checkIndex(loc, base->getType(), indexValue);
624         result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
625     } else {
626 #ifndef GLSLANG_WEB
627         if (base->getType().isUnsizedArray()) {
628             // we have a variable index into an unsized array, which is okay,
629             // depending on the situation
630             if (base->getAsSymbolNode() && isIoResizeArray(base->getType()))
631                 error(loc, "", "[", "array must be sized by a redeclaration or layout qualifier before being indexed with a variable");
632             else {
633                 // it is okay for a run-time sized array
634                 checkRuntimeSizable(loc, *base);
635             }
636             base->getWritableType().setArrayVariablyIndexed();
637         }
638 #endif
639         if (base->getBasicType() == EbtBlock) {
640             if (base->getQualifier().storage == EvqBuffer)
641                 requireProfile(base->getLoc(), ~EEsProfile, "variable indexing buffer block array");
642             else if (base->getQualifier().storage == EvqUniform)
643                 profileRequires(base->getLoc(), EEsProfile, 320, Num_AEP_gpu_shader5, AEP_gpu_shader5,
644                                 "variable indexing uniform block array");
645             else {
646                 // input/output blocks either don't exist or can't be variably indexed
647             }
648         } else if (language == EShLangFragment && base->getQualifier().isPipeOutput())
649             requireProfile(base->getLoc(), ~EEsProfile, "variable indexing fragment shader output array");
650         else if (base->getBasicType() == EbtSampler && version >= 130) {
651             const char* explanation = "variable indexing sampler array";
652             requireProfile(base->getLoc(), EEsProfile | ECoreProfile | ECompatibilityProfile, explanation);
653             profileRequires(base->getLoc(), EEsProfile, 320, Num_AEP_gpu_shader5, AEP_gpu_shader5, explanation);
654             profileRequires(base->getLoc(), ECoreProfile | ECompatibilityProfile, 400, nullptr, explanation);
655         }
656
657         result = intermediate.addIndex(EOpIndexIndirect, base, index, loc);
658     }
659
660     // Insert valid dereferenced result type
661     TType newType(base->getType(), 0);
662     if (base->getType().getQualifier().isConstant() && index->getQualifier().isConstant()) {
663         newType.getQualifier().storage = EvqConst;
664         // If base or index is a specialization constant, the result should also be a specialization constant.
665         if (base->getType().getQualifier().isSpecConstant() || index->getQualifier().isSpecConstant()) {
666             newType.getQualifier().makeSpecConstant();
667         }
668     } else {
669         newType.getQualifier().storage = EvqTemporary;
670         newType.getQualifier().specConstant = false;
671     }
672     result->setType(newType);
673
674 #ifndef GLSLANG_WEB
675     inheritMemoryQualifiers(base->getQualifier(), result->getWritableType().getQualifier());
676
677     // Propagate nonuniform
678     if (base->getQualifier().isNonUniform() || index->getQualifier().isNonUniform())
679         result->getWritableType().getQualifier().nonUniform = true;
680
681     if (anyIndexLimits)
682         handleIndexLimits(loc, base, index);
683 #endif
684
685     return result;
686 }
687
688 #ifndef GLSLANG_WEB
689
690 // for ES 2.0 (version 100) limitations for almost all index operations except vertex-shader uniforms
691 void TParseContext::handleIndexLimits(const TSourceLoc& /*loc*/, TIntermTyped* base, TIntermTyped* index)
692 {
693     if ((! limits.generalSamplerIndexing && base->getBasicType() == EbtSampler) ||
694         (! limits.generalUniformIndexing && base->getQualifier().isUniformOrBuffer() && language != EShLangVertex) ||
695         (! limits.generalAttributeMatrixVectorIndexing && base->getQualifier().isPipeInput() && language == EShLangVertex && (base->getType().isMatrix() || base->getType().isVector())) ||
696         (! limits.generalConstantMatrixVectorIndexing && base->getAsConstantUnion()) ||
697         (! limits.generalVariableIndexing && ! base->getType().getQualifier().isUniformOrBuffer() &&
698                                              ! base->getType().getQualifier().isPipeInput() &&
699                                              ! base->getType().getQualifier().isPipeOutput() &&
700                                              ! base->getType().getQualifier().isConstant()) ||
701         (! limits.generalVaryingIndexing && (base->getType().getQualifier().isPipeInput() ||
702                                                 base->getType().getQualifier().isPipeOutput()))) {
703         // it's too early to know what the inductive variables are, save it for post processing
704         needsIndexLimitationChecking.push_back(index);
705     }
706 }
707
708 // Make a shared symbol have a non-shared version that can be edited by the current
709 // compile, such that editing its type will not change the shared version and will
710 // effect all nodes sharing it.
711 void TParseContext::makeEditable(TSymbol*& symbol)
712 {
713     TParseContextBase::makeEditable(symbol);
714
715     // See if it's tied to IO resizing
716     if (isIoResizeArray(symbol->getType()))
717         ioArraySymbolResizeList.push_back(symbol);
718 }
719
720 // Return true if this is a geometry shader input array or tessellation control output array
721 // or mesh shader output array.
722 bool TParseContext::isIoResizeArray(const TType& type) const
723 {
724     return type.isArray() &&
725            ((language == EShLangGeometry    && type.getQualifier().storage == EvqVaryingIn) ||
726             (language == EShLangTessControl && type.getQualifier().storage == EvqVaryingOut &&
727                 ! type.getQualifier().patch) ||
728             (language == EShLangFragment && type.getQualifier().storage == EvqVaryingIn &&
729                 (type.getQualifier().pervertexNV || type.getQualifier().pervertexEXT)) ||
730             (language == EShLangMesh && type.getQualifier().storage == EvqVaryingOut &&
731                 !type.getQualifier().perTaskNV));
732 }
733
734 // If an array is not isIoResizeArray() but is an io array, make sure it has the right size
735 void TParseContext::fixIoArraySize(const TSourceLoc& loc, TType& type)
736 {
737     if (! type.isArray() || type.getQualifier().patch || symbolTable.atBuiltInLevel())
738         return;
739
740     assert(! isIoResizeArray(type));
741
742     if (type.getQualifier().storage != EvqVaryingIn || type.getQualifier().patch)
743         return;
744
745     if (language == EShLangTessControl || language == EShLangTessEvaluation) {
746         if (type.getOuterArraySize() != resources.maxPatchVertices) {
747             if (type.isSizedArray())
748                 error(loc, "tessellation input array size must be gl_MaxPatchVertices or implicitly sized", "[]", "");
749             type.changeOuterArraySize(resources.maxPatchVertices);
750         }
751     }
752 }
753
754 // Issue any errors if the non-array object is missing arrayness WRT
755 // shader I/O that has array requirements.
756 // All arrayness checking is handled in array paths, this is for
757 void TParseContext::ioArrayCheck(const TSourceLoc& loc, const TType& type, const TString& identifier)
758 {
759     if (! type.isArray() && ! symbolTable.atBuiltInLevel()) {
760         if (type.getQualifier().isArrayedIo(language) && !type.getQualifier().layoutPassthrough)
761             error(loc, "type must be an array:", type.getStorageQualifierString(), identifier.c_str());
762     }
763 }
764
765 // Handle a dereference of a geometry shader input array or tessellation control output array.
766 // See ioArraySymbolResizeList comment in ParseHelper.h.
767 //
768 void TParseContext::handleIoResizeArrayAccess(const TSourceLoc& /*loc*/, TIntermTyped* base)
769 {
770     TIntermSymbol* symbolNode = base->getAsSymbolNode();
771     assert(symbolNode);
772     if (! symbolNode)
773         return;
774
775     // fix array size, if it can be fixed and needs to be fixed (will allow variable indexing)
776     if (symbolNode->getType().isUnsizedArray()) {
777         int newSize = getIoArrayImplicitSize(symbolNode->getType().getQualifier());
778         if (newSize > 0)
779             symbolNode->getWritableType().changeOuterArraySize(newSize);
780     }
781 }
782
783 // If there has been an input primitive declaration (geometry shader) or an output
784 // number of vertices declaration(tessellation shader), make sure all input array types
785 // match it in size.  Types come either from nodes in the AST or symbols in the
786 // symbol table.
787 //
788 // Types without an array size will be given one.
789 // Types already having a size that is wrong will get an error.
790 //
791 void TParseContext::checkIoArraysConsistency(const TSourceLoc &loc, bool tailOnly)
792 {
793     int requiredSize = 0;
794     TString featureString;
795     size_t listSize = ioArraySymbolResizeList.size();
796     size_t i = 0;
797
798     // If tailOnly = true, only check the last array symbol in the list.
799     if (tailOnly) {
800         i = listSize - 1;
801     }
802     for (bool firstIteration = true; i < listSize; ++i) {
803         TType &type = ioArraySymbolResizeList[i]->getWritableType();
804
805         // As I/O array sizes don't change, fetch requiredSize only once,
806         // except for mesh shaders which could have different I/O array sizes based on type qualifiers.
807         if (firstIteration || (language == EShLangMesh)) {
808             requiredSize = getIoArrayImplicitSize(type.getQualifier(), &featureString);
809             if (requiredSize == 0)
810                 break;
811             firstIteration = false;
812         }
813
814         checkIoArrayConsistency(loc, requiredSize, featureString.c_str(), type,
815                                 ioArraySymbolResizeList[i]->getName());
816     }
817 }
818
819 int TParseContext::getIoArrayImplicitSize(const TQualifier &qualifier, TString *featureString) const
820 {
821     int expectedSize = 0;
822     TString str = "unknown";
823     unsigned int maxVertices = intermediate.getVertices() != TQualifier::layoutNotSet ? intermediate.getVertices() : 0;
824
825     if (language == EShLangGeometry) {
826         expectedSize = TQualifier::mapGeometryToSize(intermediate.getInputPrimitive());
827         str = TQualifier::getGeometryString(intermediate.getInputPrimitive());
828     }
829     else if (language == EShLangTessControl) {
830         expectedSize = maxVertices;
831         str = "vertices";
832     } else if (language == EShLangFragment) {
833         // Number of vertices for Fragment shader is always three.
834         expectedSize = 3;
835         str = "vertices";
836     } else if (language == EShLangMesh) {
837         unsigned int maxPrimitives =
838             intermediate.getPrimitives() != TQualifier::layoutNotSet ? intermediate.getPrimitives() : 0;
839         if (qualifier.builtIn == EbvPrimitiveIndicesNV) {
840             expectedSize = maxPrimitives * TQualifier::mapGeometryToSize(intermediate.getOutputPrimitive());
841             str = "max_primitives*";
842             str += TQualifier::getGeometryString(intermediate.getOutputPrimitive());
843         }
844         else if (qualifier.builtIn == EbvPrimitiveTriangleIndicesEXT || qualifier.builtIn == EbvPrimitiveLineIndicesEXT ||
845                  qualifier.builtIn == EbvPrimitivePointIndicesEXT) {
846             expectedSize = maxPrimitives;
847             str = "max_primitives";
848         }
849         else if (qualifier.isPerPrimitive()) {
850             expectedSize = maxPrimitives;
851             str = "max_primitives";
852         }
853         else {
854             expectedSize = maxVertices;
855             str = "max_vertices";
856         }
857     }
858     if (featureString)
859         *featureString = str;
860     return expectedSize;
861 }
862
863 void TParseContext::checkIoArrayConsistency(const TSourceLoc& loc, int requiredSize, const char* feature, TType& type, const TString& name)
864 {
865     if (type.isUnsizedArray())
866         type.changeOuterArraySize(requiredSize);
867     else if (type.getOuterArraySize() != requiredSize) {
868         if (language == EShLangGeometry)
869             error(loc, "inconsistent input primitive for array size of", feature, name.c_str());
870         else if (language == EShLangTessControl)
871             error(loc, "inconsistent output number of vertices for array size of", feature, name.c_str());
872         else if (language == EShLangFragment) {
873             if (type.getOuterArraySize() > requiredSize)
874                 error(loc, " cannot be greater than 3 for pervertexEXT", feature, name.c_str());
875         }
876         else if (language == EShLangMesh)
877             error(loc, "inconsistent output array size of", feature, name.c_str());
878         else
879             assert(0);
880     }
881 }
882
883 #endif // GLSLANG_WEB
884
885 // Handle seeing a binary node with a math operation.
886 // Returns nullptr if not semantically allowed.
887 TIntermTyped* TParseContext::handleBinaryMath(const TSourceLoc& loc, const char* str, TOperator op, TIntermTyped* left, TIntermTyped* right)
888 {
889     rValueErrorCheck(loc, str, left->getAsTyped());
890     rValueErrorCheck(loc, str, right->getAsTyped());
891
892     bool allowed = true;
893     switch (op) {
894     // TODO: Bring more source language-specific checks up from intermediate.cpp
895     // to the specific parse helpers for that source language.
896     case EOpLessThan:
897     case EOpGreaterThan:
898     case EOpLessThanEqual:
899     case EOpGreaterThanEqual:
900         if (! left->isScalar() || ! right->isScalar())
901             allowed = false;
902         break;
903     default:
904         break;
905     }
906
907     if (((left->getType().contains16BitFloat() || right->getType().contains16BitFloat()) && !float16Arithmetic()) ||
908         ((left->getType().contains16BitInt() || right->getType().contains16BitInt()) && !int16Arithmetic()) ||
909         ((left->getType().contains8BitInt() || right->getType().contains8BitInt()) && !int8Arithmetic())) {
910         allowed = false;
911     }
912
913     TIntermTyped* result = nullptr;
914     if (allowed) {
915         if ((left->isReference() || right->isReference()))
916             requireExtensions(loc, 1, &E_GL_EXT_buffer_reference2, "buffer reference math");
917         result = intermediate.addBinaryMath(op, left, right, loc);
918     }
919
920     if (result == nullptr) {
921         bool enhanced = intermediate.getEnhancedMsgs();
922         binaryOpError(loc, str, left->getCompleteString(enhanced), right->getCompleteString(enhanced));
923     }
924
925     return result;
926 }
927
928 // Handle seeing a unary node with a math operation.
929 TIntermTyped* TParseContext::handleUnaryMath(const TSourceLoc& loc, const char* str, TOperator op, TIntermTyped* childNode)
930 {
931     rValueErrorCheck(loc, str, childNode);
932
933     bool allowed = true;
934     if ((childNode->getType().contains16BitFloat() && !float16Arithmetic()) ||
935         (childNode->getType().contains16BitInt() && !int16Arithmetic()) ||
936         (childNode->getType().contains8BitInt() && !int8Arithmetic())) {
937         allowed = false;
938     }
939
940     TIntermTyped* result = nullptr;
941     if (allowed)
942         result = intermediate.addUnaryMath(op, childNode, loc);
943
944     if (result)
945         return result;
946     else {
947         bool enhanced = intermediate.getEnhancedMsgs();
948         unaryOpError(loc, str, childNode->getCompleteString(enhanced));
949     }
950
951     return childNode;
952 }
953
954 //
955 // Handle seeing a base.field dereference in the grammar.
956 //
957 TIntermTyped* TParseContext::handleDotDereference(const TSourceLoc& loc, TIntermTyped* base, const TString& field)
958 {
959     variableCheck(base);
960
961     //
962     // .length() can't be resolved until we later see the function-calling syntax.
963     // Save away the name in the AST for now.  Processing is completed in
964     // handleLengthMethod().
965     //
966     if (field == "length") {
967         if (base->isArray()) {
968             profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, ".length");
969             profileRequires(loc, EEsProfile, 300, nullptr, ".length");
970         } else if (base->isVector() || base->isMatrix()) {
971             const char* feature = ".length() on vectors and matrices";
972             requireProfile(loc, ~EEsProfile, feature);
973             profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, feature);
974         } else if (!base->getType().isCoopMat()) {
975             bool enhanced = intermediate.getEnhancedMsgs();
976             error(loc, "does not operate on this type:", field.c_str(), base->getType().getCompleteString(enhanced).c_str());
977             return base;
978         }
979
980         return intermediate.addMethod(base, TType(EbtInt), &field, loc);
981     }
982
983     // It's not .length() if we get to here.
984
985     if (base->isArray()) {
986         error(loc, "cannot apply to an array:", ".", field.c_str());
987
988         return base;
989     }
990
991     if (base->getType().isCoopMat()) {
992         error(loc, "cannot apply to a cooperative matrix type:", ".", field.c_str());
993         return base;
994     }
995
996     // It's neither an array nor .length() if we get here,
997     // leaving swizzles and struct/block dereferences.
998
999     TIntermTyped* result = base;
1000     if ((base->isVector() || base->isScalar()) &&
1001         (base->isFloatingDomain() || base->isIntegerDomain() || base->getBasicType() == EbtBool)) {
1002         result = handleDotSwizzle(loc, base, field);
1003     } else if (base->isStruct() || base->isReference()) {
1004         const TTypeList* fields = base->isReference() ?
1005                                   base->getType().getReferentType()->getStruct() :
1006                                   base->getType().getStruct();
1007         bool fieldFound = false;
1008         int member;
1009         for (member = 0; member < (int)fields->size(); ++member) {
1010             if ((*fields)[member].type->getFieldName() == field) {
1011                 fieldFound = true;
1012                 break;
1013             }
1014         }
1015         if (fieldFound) {
1016             if (base->getType().getQualifier().isFrontEndConstant())
1017                 result = intermediate.foldDereference(base, member, loc);
1018             else {
1019                 blockMemberExtensionCheck(loc, base, member, field);
1020                 TIntermTyped* index = intermediate.addConstantUnion(member, loc);
1021                 result = intermediate.addIndex(EOpIndexDirectStruct, base, index, loc);
1022                 result->setType(*(*fields)[member].type);
1023                 if ((*fields)[member].type->getQualifier().isIo())
1024                     intermediate.addIoAccessed(field);
1025             }
1026             inheritMemoryQualifiers(base->getQualifier(), result->getWritableType().getQualifier());
1027         } else {
1028             auto baseSymbol = base;
1029             while (baseSymbol->getAsSymbolNode() == nullptr)
1030                 baseSymbol = baseSymbol->getAsBinaryNode()->getLeft();
1031             TString structName;
1032             structName.append("\'").append(baseSymbol->getAsSymbolNode()->getName().c_str()).append( "\'");
1033             error(loc, "no such field in structure", field.c_str(), structName.c_str());
1034         }
1035     } else
1036         error(loc, "does not apply to this type:", field.c_str(), base->getType().getCompleteString(intermediate.getEnhancedMsgs()).c_str());
1037
1038     // Propagate noContraction up the dereference chain
1039     if (base->getQualifier().isNoContraction())
1040         result->getWritableType().getQualifier().setNoContraction();
1041
1042     // Propagate nonuniform
1043     if (base->getQualifier().isNonUniform())
1044         result->getWritableType().getQualifier().nonUniform = true;
1045
1046     return result;
1047 }
1048
1049 //
1050 // Handle seeing a base.swizzle, a subset of base.identifier in the grammar.
1051 //
1052 TIntermTyped* TParseContext::handleDotSwizzle(const TSourceLoc& loc, TIntermTyped* base, const TString& field)
1053 {
1054     TIntermTyped* result = base;
1055     if (base->isScalar()) {
1056         const char* dotFeature = "scalar swizzle";
1057         requireProfile(loc, ~EEsProfile, dotFeature);
1058         profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, dotFeature);
1059     }
1060
1061     TSwizzleSelectors<TVectorSelector> selectors;
1062     parseSwizzleSelector(loc, field, base->getVectorSize(), selectors);
1063
1064     if (base->isVector() && selectors.size() != 1 && base->getType().contains16BitFloat())
1065         requireFloat16Arithmetic(loc, ".", "can't swizzle types containing float16");
1066     if (base->isVector() && selectors.size() != 1 && base->getType().contains16BitInt())
1067         requireInt16Arithmetic(loc, ".", "can't swizzle types containing (u)int16");
1068     if (base->isVector() && selectors.size() != 1 && base->getType().contains8BitInt())
1069         requireInt8Arithmetic(loc, ".", "can't swizzle types containing (u)int8");
1070
1071     if (base->isScalar()) {
1072         if (selectors.size() == 1)
1073             return result;
1074         else {
1075             TType type(base->getBasicType(), EvqTemporary, selectors.size());
1076             // Swizzle operations propagate specialization-constantness
1077             if (base->getQualifier().isSpecConstant())
1078                 type.getQualifier().makeSpecConstant();
1079             return addConstructor(loc, base, type);
1080         }
1081     }
1082
1083     if (base->getType().getQualifier().isFrontEndConstant())
1084         result = intermediate.foldSwizzle(base, selectors, loc);
1085     else {
1086         if (selectors.size() == 1) {
1087             TIntermTyped* index = intermediate.addConstantUnion(selectors[0], loc);
1088             result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
1089             result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision));
1090         } else {
1091             TIntermTyped* index = intermediate.addSwizzle(selectors, loc);
1092             result = intermediate.addIndex(EOpVectorSwizzle, base, index, loc);
1093             result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision, selectors.size()));
1094         }
1095         // Swizzle operations propagate specialization-constantness
1096         if (base->getType().getQualifier().isSpecConstant())
1097             result->getWritableType().getQualifier().makeSpecConstant();
1098     }
1099
1100     return result;
1101 }
1102
1103 void TParseContext::blockMemberExtensionCheck(const TSourceLoc& loc, const TIntermTyped* base, int member, const TString& memberName)
1104 {
1105     // a block that needs extension checking is either 'base', or if arrayed,
1106     // one level removed to the left
1107     const TIntermSymbol* baseSymbol = nullptr;
1108     if (base->getAsBinaryNode() == nullptr)
1109         baseSymbol = base->getAsSymbolNode();
1110     else
1111         baseSymbol = base->getAsBinaryNode()->getLeft()->getAsSymbolNode();
1112     if (baseSymbol == nullptr)
1113         return;
1114     const TSymbol* symbol = symbolTable.find(baseSymbol->getName());
1115     if (symbol == nullptr)
1116         return;
1117     const TVariable* variable = symbol->getAsVariable();
1118     if (variable == nullptr)
1119         return;
1120     if (!variable->hasMemberExtensions())
1121         return;
1122
1123     // We now have a variable that is the base of a dot reference
1124     // with members that need extension checking.
1125     if (variable->getNumMemberExtensions(member) > 0)
1126         requireExtensions(loc, variable->getNumMemberExtensions(member), variable->getMemberExtensions(member), memberName.c_str());
1127 }
1128
1129 //
1130 // Handle seeing a function declarator in the grammar.  This is the precursor
1131 // to recognizing a function prototype or function definition.
1132 //
1133 TFunction* TParseContext::handleFunctionDeclarator(const TSourceLoc& loc, TFunction& function, bool prototype)
1134 {
1135     // ES can't declare prototypes inside functions
1136     if (! symbolTable.atGlobalLevel())
1137         requireProfile(loc, ~EEsProfile, "local function declaration");
1138
1139     //
1140     // Multiple declarations of the same function name are allowed.
1141     //
1142     // If this is a definition, the definition production code will check for redefinitions
1143     // (we don't know at this point if it's a definition or not).
1144     //
1145     // Redeclarations (full signature match) are allowed.  But, return types and parameter qualifiers must also match.
1146     //  - except ES 100, which only allows a single prototype
1147     //
1148     // ES 100 does not allow redefining, but does allow overloading of built-in functions.
1149     // ES 300 does not allow redefining or overloading of built-in functions.
1150     //
1151     bool builtIn;
1152     TSymbol* symbol = symbolTable.find(function.getMangledName(), &builtIn);
1153     if (symbol && symbol->getAsFunction() && builtIn)
1154         requireProfile(loc, ~EEsProfile, "redefinition of built-in function");
1155 #ifndef GLSLANG_WEB
1156     // Check the validity of using spirv_literal qualifier
1157     for (int i = 0; i < function.getParamCount(); ++i) {
1158         if (function[i].type->getQualifier().isSpirvLiteral() && function.getBuiltInOp() != EOpSpirvInst)
1159             error(loc, "'spirv_literal' can only be used on functions defined with 'spirv_instruction' for argument",
1160                   function.getName().c_str(), "%d", i + 1);
1161     }
1162
1163     // For function declaration with SPIR-V instruction qualifier, always ignore the built-in function and
1164     // respect this redeclared one.
1165     if (symbol && builtIn && function.getBuiltInOp() == EOpSpirvInst)
1166         symbol = nullptr;
1167 #endif
1168     const TFunction* prevDec = symbol ? symbol->getAsFunction() : 0;
1169     if (prevDec) {
1170         if (prevDec->isPrototyped() && prototype)
1171             profileRequires(loc, EEsProfile, 300, nullptr, "multiple prototypes for same function");
1172         if (prevDec->getType() != function.getType())
1173             error(loc, "overloaded functions must have the same return type", function.getName().c_str(), "");
1174 #ifndef GLSLANG_WEB
1175         if (prevDec->getSpirvInstruction() != function.getSpirvInstruction()) {
1176             error(loc, "overloaded functions must have the same qualifiers", function.getName().c_str(),
1177                   "spirv_instruction");
1178         }
1179 #endif
1180         for (int i = 0; i < prevDec->getParamCount(); ++i) {
1181             if ((*prevDec)[i].type->getQualifier().storage != function[i].type->getQualifier().storage)
1182                 error(loc, "overloaded functions must have the same parameter storage qualifiers for argument", function[i].type->getStorageQualifierString(), "%d", i+1);
1183
1184             if ((*prevDec)[i].type->getQualifier().precision != function[i].type->getQualifier().precision)
1185                 error(loc, "overloaded functions must have the same parameter precision qualifiers for argument", function[i].type->getPrecisionQualifierString(), "%d", i+1);
1186         }
1187     }
1188
1189     arrayObjectCheck(loc, function.getType(), "array in function return type");
1190
1191     if (prototype) {
1192         // All built-in functions are defined, even though they don't have a body.
1193         // Count their prototype as a definition instead.
1194         if (symbolTable.atBuiltInLevel())
1195             function.setDefined();
1196         else {
1197             if (prevDec && ! builtIn)
1198                 symbol->getAsFunction()->setPrototyped();  // need a writable one, but like having prevDec as a const
1199             function.setPrototyped();
1200         }
1201     }
1202
1203     // This insert won't actually insert it if it's a duplicate signature, but it will still check for
1204     // other forms of name collisions.
1205     if (! symbolTable.insert(function))
1206         error(loc, "function name is redeclaration of existing name", function.getName().c_str(), "");
1207
1208     //
1209     // If this is a redeclaration, it could also be a definition,
1210     // in which case, we need to use the parameter names from this one, and not the one that's
1211     // being redeclared.  So, pass back this declaration, not the one in the symbol table.
1212     //
1213     return &function;
1214 }
1215
1216 //
1217 // Handle seeing the function prototype in front of a function definition in the grammar.
1218 // The body is handled after this function returns.
1219 //
1220 TIntermAggregate* TParseContext::handleFunctionDefinition(const TSourceLoc& loc, TFunction& function)
1221 {
1222     currentCaller = function.getMangledName();
1223     TSymbol* symbol = symbolTable.find(function.getMangledName());
1224     TFunction* prevDec = symbol ? symbol->getAsFunction() : nullptr;
1225
1226     if (! prevDec)
1227         error(loc, "can't find function", function.getName().c_str(), "");
1228     // Note:  'prevDec' could be 'function' if this is the first time we've seen function
1229     // as it would have just been put in the symbol table.  Otherwise, we're looking up
1230     // an earlier occurrence.
1231
1232     if (prevDec && prevDec->isDefined()) {
1233         // Then this function already has a body.
1234         error(loc, "function already has a body", function.getName().c_str(), "");
1235     }
1236     if (prevDec && ! prevDec->isDefined()) {
1237         prevDec->setDefined();
1238
1239         // Remember the return type for later checking for RETURN statements.
1240         currentFunctionType = &(prevDec->getType());
1241     } else
1242         currentFunctionType = new TType(EbtVoid);
1243     functionReturnsValue = false;
1244
1245     // Check for entry point
1246     if (function.getName().compare(intermediate.getEntryPointName().c_str()) == 0) {
1247         intermediate.setEntryPointMangledName(function.getMangledName().c_str());
1248         intermediate.incrementEntryPointCount();
1249         inMain = true;
1250     } else
1251         inMain = false;
1252
1253     //
1254     // Raise error message if main function takes any parameters or returns anything other than void
1255     //
1256     if (inMain) {
1257         if (function.getParamCount() > 0)
1258             error(loc, "function cannot take any parameter(s)", function.getName().c_str(), "");
1259         if (function.getType().getBasicType() != EbtVoid)
1260             error(loc, "", function.getType().getBasicTypeString().c_str(), "entry point cannot return a value");
1261     }
1262
1263     //
1264     // New symbol table scope for body of function plus its arguments
1265     //
1266     symbolTable.push();
1267
1268     //
1269     // Insert parameters into the symbol table.
1270     // If the parameter has no name, it's not an error, just don't insert it
1271     // (could be used for unused args).
1272     //
1273     // Also, accumulate the list of parameters into the HIL, so lower level code
1274     // knows where to find parameters.
1275     //
1276     TIntermAggregate* paramNodes = new TIntermAggregate;
1277     for (int i = 0; i < function.getParamCount(); i++) {
1278         TParameter& param = function[i];
1279         if (param.name != nullptr) {
1280             TVariable *variable = new TVariable(param.name, *param.type);
1281
1282             // Insert the parameters with name in the symbol table.
1283             if (! symbolTable.insert(*variable))
1284                 error(loc, "redefinition", variable->getName().c_str(), "");
1285             else {
1286                 // Transfer ownership of name pointer to symbol table.
1287                 param.name = nullptr;
1288
1289                 // Add the parameter to the HIL
1290                 paramNodes = intermediate.growAggregate(paramNodes,
1291                                                         intermediate.addSymbol(*variable, loc),
1292                                                         loc);
1293             }
1294         } else
1295             paramNodes = intermediate.growAggregate(paramNodes, intermediate.addSymbol(*param.type, loc), loc);
1296     }
1297     intermediate.setAggregateOperator(paramNodes, EOpParameters, TType(EbtVoid), loc);
1298     loopNestingLevel = 0;
1299     statementNestingLevel = 0;
1300     controlFlowNestingLevel = 0;
1301     postEntryPointReturn = false;
1302
1303     return paramNodes;
1304 }
1305
1306 //
1307 // Handle seeing function call syntax in the grammar, which could be any of
1308 //  - .length() method
1309 //  - constructor
1310 //  - a call to a built-in function mapped to an operator
1311 //  - a call to a built-in function that will remain a function call (e.g., texturing)
1312 //  - user function
1313 //  - subroutine call (not implemented yet)
1314 //
1315 TIntermTyped* TParseContext::handleFunctionCall(const TSourceLoc& loc, TFunction* function, TIntermNode* arguments)
1316 {
1317     TIntermTyped* result = nullptr;
1318
1319     if (spvVersion.vulkan != 0 && spvVersion.vulkanRelaxed) {
1320         // allow calls that are invalid in Vulkan Semantics to be invisibily
1321         // remapped to equivalent valid functions
1322         result = vkRelaxedRemapFunctionCall(loc, function, arguments);
1323         if (result)
1324             return result;
1325     }
1326
1327     if (function->getBuiltInOp() == EOpArrayLength)
1328         result = handleLengthMethod(loc, function, arguments);
1329     else if (function->getBuiltInOp() != EOpNull) {
1330         //
1331         // Then this should be a constructor.
1332         // Don't go through the symbol table for constructors.
1333         // Their parameters will be verified algorithmically.
1334         //
1335         TType type(EbtVoid);  // use this to get the type back
1336         if (! constructorError(loc, arguments, *function, function->getBuiltInOp(), type)) {
1337             //
1338             // It's a constructor, of type 'type'.
1339             //
1340             result = addConstructor(loc, arguments, type);
1341             if (result == nullptr)
1342                 error(loc, "cannot construct with these arguments", type.getCompleteString(intermediate.getEnhancedMsgs()).c_str(), "");
1343         }
1344     } else {
1345         //
1346         // Find it in the symbol table.
1347         //
1348         const TFunction* fnCandidate;
1349         bool builtIn {false};
1350         fnCandidate = findFunction(loc, *function, builtIn);
1351         if (fnCandidate) {
1352             // This is a declared function that might map to
1353             //  - a built-in operator,
1354             //  - a built-in function not mapped to an operator, or
1355             //  - a user function.
1356
1357             // Error check for a function requiring specific extensions present.
1358             if (builtIn && fnCandidate->getNumExtensions())
1359                 requireExtensions(loc, fnCandidate->getNumExtensions(), fnCandidate->getExtensions(), fnCandidate->getName().c_str());
1360
1361             if (builtIn && fnCandidate->getType().contains16BitFloat())
1362                 requireFloat16Arithmetic(loc, "built-in function", "float16 types can only be in uniform block or buffer storage");
1363             if (builtIn && fnCandidate->getType().contains16BitInt())
1364                 requireInt16Arithmetic(loc, "built-in function", "(u)int16 types can only be in uniform block or buffer storage");
1365             if (builtIn && fnCandidate->getType().contains8BitInt())
1366                 requireInt8Arithmetic(loc, "built-in function", "(u)int8 types can only be in uniform block or buffer storage");
1367
1368             if (arguments != nullptr) {
1369                 // Make sure qualifications work for these arguments.
1370                 TIntermAggregate* aggregate = arguments->getAsAggregate();
1371                 for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
1372                     // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
1373                     // is the single argument itself or its children are the arguments.  Only one argument
1374                     // means take 'arguments' itself as the one argument.
1375                     TIntermNode* arg = fnCandidate->getParamCount() == 1 ? arguments : (aggregate ? aggregate->getSequence()[i] : arguments);
1376                     TQualifier& formalQualifier = (*fnCandidate)[i].type->getQualifier();
1377                     if (formalQualifier.isParamOutput()) {
1378                         if (lValueErrorCheck(arguments->getLoc(), "assign", arg->getAsTyped()))
1379                             error(arguments->getLoc(), "Non-L-value cannot be passed for 'out' or 'inout' parameters.", "out", "");
1380                     }
1381 #ifndef GLSLANG_WEB
1382                     if (formalQualifier.isSpirvLiteral()) {
1383                         if (!arg->getAsTyped()->getQualifier().isFrontEndConstant()) {
1384                             error(arguments->getLoc(),
1385                                   "Non front-end constant expressions cannot be passed for 'spirv_literal' parameters.",
1386                                   "spirv_literal", "");
1387                         }
1388                     }
1389 #endif
1390                     const TType& argType = arg->getAsTyped()->getType();
1391                     const TQualifier& argQualifier = argType.getQualifier();
1392                     if (argQualifier.isMemory() && (argType.containsOpaque() || argType.isReference())) {
1393                         const char* message = "argument cannot drop memory qualifier when passed to formal parameter";
1394 #ifndef GLSLANG_WEB
1395                         if (argQualifier.volatil && ! formalQualifier.volatil)
1396                             error(arguments->getLoc(), message, "volatile", "");
1397                         if (argQualifier.coherent && ! (formalQualifier.devicecoherent || formalQualifier.coherent))
1398                             error(arguments->getLoc(), message, "coherent", "");
1399                         if (argQualifier.devicecoherent && ! (formalQualifier.devicecoherent || formalQualifier.coherent))
1400                             error(arguments->getLoc(), message, "devicecoherent", "");
1401                         if (argQualifier.queuefamilycoherent && ! (formalQualifier.queuefamilycoherent || formalQualifier.devicecoherent || formalQualifier.coherent))
1402                             error(arguments->getLoc(), message, "queuefamilycoherent", "");
1403                         if (argQualifier.workgroupcoherent && ! (formalQualifier.workgroupcoherent || formalQualifier.queuefamilycoherent || formalQualifier.devicecoherent || formalQualifier.coherent))
1404                             error(arguments->getLoc(), message, "workgroupcoherent", "");
1405                         if (argQualifier.subgroupcoherent && ! (formalQualifier.subgroupcoherent || formalQualifier.workgroupcoherent || formalQualifier.queuefamilycoherent || formalQualifier.devicecoherent || formalQualifier.coherent))
1406                             error(arguments->getLoc(), message, "subgroupcoherent", "");
1407                         if (argQualifier.readonly && ! formalQualifier.readonly)
1408                             error(arguments->getLoc(), message, "readonly", "");
1409                         if (argQualifier.writeonly && ! formalQualifier.writeonly)
1410                             error(arguments->getLoc(), message, "writeonly", "");
1411                         // Don't check 'restrict', it is different than the rest:
1412                         // "...but only restrict can be taken away from a calling argument, by a formal parameter that
1413                         // lacks the restrict qualifier..."
1414 #endif
1415                     }
1416                     if (!builtIn && argQualifier.getFormat() != formalQualifier.getFormat()) {
1417                         // we have mismatched formats, which should only be allowed if writeonly
1418                         // and at least one format is unknown
1419                         if (!formalQualifier.isWriteOnly() || (formalQualifier.getFormat() != ElfNone &&
1420                                                                   argQualifier.getFormat() != ElfNone))
1421                             error(arguments->getLoc(), "image formats must match", "format", "");
1422                     }
1423                     if (builtIn && arg->getAsTyped()->getType().contains16BitFloat())
1424                         requireFloat16Arithmetic(arguments->getLoc(), "built-in function", "float16 types can only be in uniform block or buffer storage");
1425                     if (builtIn && arg->getAsTyped()->getType().contains16BitInt())
1426                         requireInt16Arithmetic(arguments->getLoc(), "built-in function", "(u)int16 types can only be in uniform block or buffer storage");
1427                     if (builtIn && arg->getAsTyped()->getType().contains8BitInt())
1428                         requireInt8Arithmetic(arguments->getLoc(), "built-in function", "(u)int8 types can only be in uniform block or buffer storage");
1429
1430                     // TODO 4.5 functionality:  A shader will fail to compile
1431                     // if the value passed to the memargument of an atomic memory function does not correspond to a buffer or
1432                     // shared variable. It is acceptable to pass an element of an array or a single component of a vector to the
1433                     // memargument of an atomic memory function, as long as the underlying array or vector is a buffer or
1434                     // shared variable.
1435                 }
1436
1437                 // Convert 'in' arguments
1438                 addInputArgumentConversions(*fnCandidate, arguments);  // arguments may be modified if it's just a single argument node
1439             }
1440
1441             if (builtIn && fnCandidate->getBuiltInOp() != EOpNull) {
1442                 // A function call mapped to a built-in operation.
1443                 result = handleBuiltInFunctionCall(loc, arguments, *fnCandidate);
1444 #ifndef GLSLANG_WEB
1445             } else if (fnCandidate->getBuiltInOp() == EOpSpirvInst) {
1446                 // When SPIR-V instruction qualifier is specified, the function call is still mapped to a built-in operation.
1447                 result = handleBuiltInFunctionCall(loc, arguments, *fnCandidate);
1448 #endif
1449             } else {
1450                 // This is a function call not mapped to built-in operator.
1451                 // It could still be a built-in function, but only if PureOperatorBuiltins == false.
1452                 result = intermediate.setAggregateOperator(arguments, EOpFunctionCall, fnCandidate->getType(), loc);
1453                 TIntermAggregate* call = result->getAsAggregate();
1454                 call->setName(fnCandidate->getMangledName());
1455
1456                 // this is how we know whether the given function is a built-in function or a user-defined function
1457                 // if builtIn == false, it's a userDefined -> could be an overloaded built-in function also
1458                 // if builtIn == true, it's definitely a built-in function with EOpNull
1459                 if (! builtIn) {
1460                     call->setUserDefined();
1461                     if (symbolTable.atGlobalLevel()) {
1462                         requireProfile(loc, ~EEsProfile, "calling user function from global scope");
1463                         intermediate.addToCallGraph(infoSink, "main(", fnCandidate->getMangledName());
1464                     } else
1465                         intermediate.addToCallGraph(infoSink, currentCaller, fnCandidate->getMangledName());
1466                 }
1467
1468 #ifndef GLSLANG_WEB
1469                 if (builtIn)
1470                     nonOpBuiltInCheck(loc, *fnCandidate, *call);
1471                 else
1472 #endif
1473                     userFunctionCallCheck(loc, *call);
1474             }
1475
1476             // Convert 'out' arguments.  If it was a constant folded built-in, it won't be an aggregate anymore.
1477             // Built-ins with a single argument aren't called with an aggregate, but they also don't have an output.
1478             // Also, build the qualifier list for user function calls, which are always called with an aggregate.
1479             if (result->getAsAggregate()) {
1480                 TQualifierList& qualifierList = result->getAsAggregate()->getQualifierList();
1481                 for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
1482                     TStorageQualifier qual = (*fnCandidate)[i].type->getQualifier().storage;
1483                     qualifierList.push_back(qual);
1484                 }
1485                 result = addOutputArgumentConversions(*fnCandidate, *result->getAsAggregate());
1486             }
1487
1488             if (result->getAsTyped()->getType().isCoopMat() &&
1489                !result->getAsTyped()->getType().isParameterized()) {
1490                 assert(fnCandidate->getBuiltInOp() == EOpCooperativeMatrixMulAdd);
1491
1492                 result->setType(result->getAsAggregate()->getSequence()[2]->getAsTyped()->getType());
1493             }
1494         }
1495     }
1496
1497     // generic error recovery
1498     // TODO: simplification: localize all the error recoveries that look like this, and taking type into account to reduce cascades
1499     if (result == nullptr)
1500         result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
1501
1502     return result;
1503 }
1504
1505 TIntermTyped* TParseContext::handleBuiltInFunctionCall(TSourceLoc loc, TIntermNode* arguments,
1506                                                        const TFunction& function)
1507 {
1508     checkLocation(loc, function.getBuiltInOp());
1509     TIntermTyped *result = intermediate.addBuiltInFunctionCall(loc, function.getBuiltInOp(),
1510                                                                function.getParamCount() == 1,
1511                                                                arguments, function.getType());
1512     if (result != nullptr && obeyPrecisionQualifiers())
1513         computeBuiltinPrecisions(*result, function);
1514
1515     if (result == nullptr) {
1516         if (arguments == nullptr)
1517             error(loc, " wrong operand type", "Internal Error",
1518                                       "built in unary operator function.  Type: %s", "");
1519         else
1520             error(arguments->getLoc(), " wrong operand type", "Internal Error",
1521                                       "built in unary operator function.  Type: %s",
1522                                       static_cast<TIntermTyped*>(arguments)->getCompleteString(intermediate.getEnhancedMsgs()).c_str());
1523     } else if (result->getAsOperator())
1524         builtInOpCheck(loc, function, *result->getAsOperator());
1525
1526 #ifndef GLSLANG_WEB
1527     // Special handling for function call with SPIR-V instruction qualifier specified
1528     if (function.getBuiltInOp() == EOpSpirvInst) {
1529         if (auto agg = result->getAsAggregate()) {
1530             // Propogate spirv_by_reference/spirv_literal from parameters to arguments
1531             auto& sequence = agg->getSequence();
1532             for (unsigned i = 0; i < sequence.size(); ++i) {
1533                 if (function[i].type->getQualifier().isSpirvByReference())
1534                     sequence[i]->getAsTyped()->getQualifier().setSpirvByReference();
1535                 if (function[i].type->getQualifier().isSpirvLiteral())
1536                     sequence[i]->getAsTyped()->getQualifier().setSpirvLiteral();
1537             }
1538
1539             // Attach the function call to SPIR-V intruction
1540             agg->setSpirvInstruction(function.getSpirvInstruction());
1541         } else if (auto unaryNode = result->getAsUnaryNode()) {
1542             // Propogate spirv_by_reference/spirv_literal from parameters to arguments
1543             if (function[0].type->getQualifier().isSpirvByReference())
1544                 unaryNode->getOperand()->getQualifier().setSpirvByReference();
1545             if (function[0].type->getQualifier().isSpirvLiteral())
1546                 unaryNode->getOperand()->getQualifier().setSpirvLiteral();
1547
1548             // Attach the function call to SPIR-V intruction
1549             unaryNode->setSpirvInstruction(function.getSpirvInstruction());
1550         } else
1551             assert(0);
1552     }
1553 #endif
1554
1555     return result;
1556 }
1557
1558 // "The operation of a built-in function can have a different precision
1559 // qualification than the precision qualification of the resulting value.
1560 // These two precision qualifications are established as follows.
1561 //
1562 // The precision qualification of the operation of a built-in function is
1563 // based on the precision qualification of its input arguments and formal
1564 // parameters:  When a formal parameter specifies a precision qualifier,
1565 // that is used, otherwise, the precision qualification of the calling
1566 // argument is used.  The highest precision of these will be the precision
1567 // qualification of the operation of the built-in function. Generally,
1568 // this is applied across all arguments to a built-in function, with the
1569 // exceptions being:
1570 //   - bitfieldExtract and bitfieldInsert ignore the 'offset' and 'bits'
1571 //     arguments.
1572 //   - interpolateAt* functions only look at the 'interpolant' argument.
1573 //
1574 // The precision qualification of the result of a built-in function is
1575 // determined in one of the following ways:
1576 //
1577 //   - For the texture sampling, image load, and image store functions,
1578 //     the precision of the return type matches the precision of the
1579 //     sampler type
1580 //
1581 //   Otherwise:
1582 //
1583 //   - For prototypes that do not specify a resulting precision qualifier,
1584 //     the precision will be the same as the precision of the operation.
1585 //
1586 //   - For prototypes that do specify a resulting precision qualifier,
1587 //     the specified precision qualifier is the precision qualification of
1588 //     the result."
1589 //
1590 void TParseContext::computeBuiltinPrecisions(TIntermTyped& node, const TFunction& function)
1591 {
1592     TPrecisionQualifier operationPrecision = EpqNone;
1593     TPrecisionQualifier resultPrecision = EpqNone;
1594
1595     TIntermOperator* opNode = node.getAsOperator();
1596     if (opNode == nullptr)
1597         return;
1598
1599     if (TIntermUnary* unaryNode = node.getAsUnaryNode()) {
1600         operationPrecision = std::max(function[0].type->getQualifier().precision,
1601                                       unaryNode->getOperand()->getType().getQualifier().precision);
1602         if (function.getType().getBasicType() != EbtBool)
1603             resultPrecision = function.getType().getQualifier().precision == EpqNone ?
1604                                         operationPrecision :
1605                                         function.getType().getQualifier().precision;
1606     } else if (TIntermAggregate* agg = node.getAsAggregate()) {
1607         TIntermSequence& sequence = agg->getSequence();
1608         unsigned int numArgs = (unsigned int)sequence.size();
1609         switch (agg->getOp()) {
1610         case EOpBitfieldExtract:
1611             numArgs = 1;
1612             break;
1613         case EOpBitfieldInsert:
1614             numArgs = 2;
1615             break;
1616         case EOpInterpolateAtCentroid:
1617         case EOpInterpolateAtOffset:
1618         case EOpInterpolateAtSample:
1619             numArgs = 1;
1620             break;
1621         case EOpDebugPrintf:
1622             numArgs = 0;
1623             break;
1624         default:
1625             break;
1626         }
1627         // find the maximum precision from the arguments and parameters
1628         for (unsigned int arg = 0; arg < numArgs; ++arg) {
1629             operationPrecision = std::max(operationPrecision, sequence[arg]->getAsTyped()->getQualifier().precision);
1630             operationPrecision = std::max(operationPrecision, function[arg].type->getQualifier().precision);
1631         }
1632         // compute the result precision
1633         if (agg->isSampling() ||
1634             agg->getOp() == EOpImageLoad || agg->getOp() == EOpImageStore ||
1635             agg->getOp() == EOpImageLoadLod || agg->getOp() == EOpImageStoreLod)
1636             resultPrecision = sequence[0]->getAsTyped()->getQualifier().precision;
1637         else if (function.getType().getBasicType() != EbtBool)
1638             resultPrecision = function.getType().getQualifier().precision == EpqNone ?
1639                                         operationPrecision :
1640                                         function.getType().getQualifier().precision;
1641     }
1642
1643     // Propagate precision through this node and its children. That algorithm stops
1644     // when a precision is found, so start by clearing this subroot precision
1645     opNode->getQualifier().precision = EpqNone;
1646     if (operationPrecision != EpqNone) {
1647         opNode->propagatePrecision(operationPrecision);
1648         opNode->setOperationPrecision(operationPrecision);
1649     }
1650     // Now, set the result precision, which might not match
1651     opNode->getQualifier().precision = resultPrecision;
1652 }
1653
1654 TIntermNode* TParseContext::handleReturnValue(const TSourceLoc& loc, TIntermTyped* value)
1655 {
1656 #ifndef GLSLANG_WEB
1657     storage16BitAssignmentCheck(loc, value->getType(), "return");
1658 #endif
1659
1660     functionReturnsValue = true;
1661     TIntermBranch* branch = nullptr;
1662     if (currentFunctionType->getBasicType() == EbtVoid) {
1663         error(loc, "void function cannot return a value", "return", "");
1664         branch = intermediate.addBranch(EOpReturn, loc);
1665     } else if (*currentFunctionType != value->getType()) {
1666         TIntermTyped* converted = intermediate.addConversion(EOpReturn, *currentFunctionType, value);
1667         if (converted) {
1668             if (*currentFunctionType != converted->getType())
1669                 error(loc, "cannot convert return value to function return type", "return", "");
1670             if (version < 420)
1671                 warn(loc, "type conversion on return values was not explicitly allowed until version 420",
1672                      "return", "");
1673             branch = intermediate.addBranch(EOpReturn, converted, loc);
1674         } else {
1675             error(loc, "type does not match, or is not convertible to, the function's return type", "return", "");
1676             branch = intermediate.addBranch(EOpReturn, value, loc);
1677         }
1678     } else
1679         branch = intermediate.addBranch(EOpReturn, value, loc);
1680
1681     branch->updatePrecision(currentFunctionType->getQualifier().precision);
1682     return branch;
1683 }
1684
1685 // See if the operation is being done in an illegal location.
1686 void TParseContext::checkLocation(const TSourceLoc& loc, TOperator op)
1687 {
1688 #ifndef GLSLANG_WEB
1689     switch (op) {
1690     case EOpBarrier:
1691         if (language == EShLangTessControl) {
1692             if (controlFlowNestingLevel > 0)
1693                 error(loc, "tessellation control barrier() cannot be placed within flow control", "", "");
1694             if (! inMain)
1695                 error(loc, "tessellation control barrier() must be in main()", "", "");
1696             else if (postEntryPointReturn)
1697                 error(loc, "tessellation control barrier() cannot be placed after a return from main()", "", "");
1698         }
1699         break;
1700     case EOpBeginInvocationInterlock:
1701         if (language != EShLangFragment)
1702             error(loc, "beginInvocationInterlockARB() must be in a fragment shader", "", "");
1703         if (! inMain)
1704             error(loc, "beginInvocationInterlockARB() must be in main()", "", "");
1705         else if (postEntryPointReturn)
1706             error(loc, "beginInvocationInterlockARB() cannot be placed after a return from main()", "", "");
1707         if (controlFlowNestingLevel > 0)
1708             error(loc, "beginInvocationInterlockARB() cannot be placed within flow control", "", "");
1709
1710         if (beginInvocationInterlockCount > 0)
1711             error(loc, "beginInvocationInterlockARB() must only be called once", "", "");
1712         if (endInvocationInterlockCount > 0)
1713             error(loc, "beginInvocationInterlockARB() must be called before endInvocationInterlockARB()", "", "");
1714
1715         beginInvocationInterlockCount++;
1716
1717         // default to pixel_interlock_ordered
1718         if (intermediate.getInterlockOrdering() == EioNone)
1719             intermediate.setInterlockOrdering(EioPixelInterlockOrdered);
1720         break;
1721     case EOpEndInvocationInterlock:
1722         if (language != EShLangFragment)
1723             error(loc, "endInvocationInterlockARB() must be in a fragment shader", "", "");
1724         if (! inMain)
1725             error(loc, "endInvocationInterlockARB() must be in main()", "", "");
1726         else if (postEntryPointReturn)
1727             error(loc, "endInvocationInterlockARB() cannot be placed after a return from main()", "", "");
1728         if (controlFlowNestingLevel > 0)
1729             error(loc, "endInvocationInterlockARB() cannot be placed within flow control", "", "");
1730
1731         if (endInvocationInterlockCount > 0)
1732             error(loc, "endInvocationInterlockARB() must only be called once", "", "");
1733         if (beginInvocationInterlockCount == 0)
1734             error(loc, "beginInvocationInterlockARB() must be called before endInvocationInterlockARB()", "", "");
1735
1736         endInvocationInterlockCount++;
1737         break;
1738     default:
1739         break;
1740     }
1741 #endif
1742 }
1743
1744 // Finish processing object.length(). This started earlier in handleDotDereference(), where
1745 // the ".length" part was recognized and semantically checked, and finished here where the
1746 // function syntax "()" is recognized.
1747 //
1748 // Return resulting tree node.
1749 TIntermTyped* TParseContext::handleLengthMethod(const TSourceLoc& loc, TFunction* function, TIntermNode* intermNode)
1750 {
1751     int length = 0;
1752
1753     if (function->getParamCount() > 0)
1754         error(loc, "method does not accept any arguments", function->getName().c_str(), "");
1755     else {
1756         const TType& type = intermNode->getAsTyped()->getType();
1757         if (type.isArray()) {
1758             if (type.isUnsizedArray()) {
1759 #ifndef GLSLANG_WEB
1760                 if (intermNode->getAsSymbolNode() && isIoResizeArray(type)) {
1761                     // We could be between a layout declaration that gives a built-in io array implicit size and
1762                     // a user redeclaration of that array, meaning we have to substitute its implicit size here
1763                     // without actually redeclaring the array.  (It is an error to use a member before the
1764                     // redeclaration, but not an error to use the array name itself.)
1765                     const TString& name = intermNode->getAsSymbolNode()->getName();
1766                     if (name == "gl_in" || name == "gl_out" || name == "gl_MeshVerticesNV" ||
1767                         name == "gl_MeshPrimitivesNV") {
1768                         length = getIoArrayImplicitSize(type.getQualifier());
1769                     }
1770                 }
1771 #endif
1772                 if (length == 0) {
1773 #ifndef GLSLANG_WEB
1774                     if (intermNode->getAsSymbolNode() && isIoResizeArray(type))
1775                         error(loc, "", function->getName().c_str(), "array must first be sized by a redeclaration or layout qualifier");
1776                     else if (isRuntimeLength(*intermNode->getAsTyped())) {
1777                         // Create a unary op and let the back end handle it
1778                         return intermediate.addBuiltInFunctionCall(loc, EOpArrayLength, true, intermNode, TType(EbtInt));
1779                     } else
1780 #endif
1781                         error(loc, "", function->getName().c_str(), "array must be declared with a size before using this method");
1782                 }
1783             } else if (type.getOuterArrayNode()) {
1784                 // If the array's outer size is specified by an intermediate node, it means the array's length
1785                 // was specified by a specialization constant. In such a case, we should return the node of the
1786                 // specialization constants to represent the length.
1787                 return type.getOuterArrayNode();
1788             } else
1789                 length = type.getOuterArraySize();
1790         } else if (type.isMatrix())
1791             length = type.getMatrixCols();
1792         else if (type.isVector())
1793             length = type.getVectorSize();
1794         else if (type.isCoopMat())
1795             return intermediate.addBuiltInFunctionCall(loc, EOpArrayLength, true, intermNode, TType(EbtInt));
1796         else {
1797             // we should not get here, because earlier semantic checking should have prevented this path
1798             error(loc, ".length()", "unexpected use of .length()", "");
1799         }
1800     }
1801
1802     if (length == 0)
1803         length = 1;
1804
1805     return intermediate.addConstantUnion(length, loc);
1806 }
1807
1808 //
1809 // Add any needed implicit conversions for function-call arguments to input parameters.
1810 //
1811 void TParseContext::addInputArgumentConversions(const TFunction& function, TIntermNode*& arguments) const
1812 {
1813 #ifndef GLSLANG_WEB
1814     TIntermAggregate* aggregate = arguments->getAsAggregate();
1815
1816     // Process each argument's conversion
1817     for (int i = 0; i < function.getParamCount(); ++i) {
1818         // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
1819         // is the single argument itself or its children are the arguments.  Only one argument
1820         // means take 'arguments' itself as the one argument.
1821         TIntermTyped* arg = function.getParamCount() == 1 ? arguments->getAsTyped() : (aggregate ? aggregate->getSequence()[i]->getAsTyped() : arguments->getAsTyped());
1822         if (*function[i].type != arg->getType()) {
1823             if (function[i].type->getQualifier().isParamInput() &&
1824                !function[i].type->isCoopMat()) {
1825                 // In-qualified arguments just need an extra node added above the argument to
1826                 // convert to the correct type.
1827                 arg = intermediate.addConversion(EOpFunctionCall, *function[i].type, arg);
1828                 if (arg) {
1829                     if (function.getParamCount() == 1)
1830                         arguments = arg;
1831                     else {
1832                         if (aggregate)
1833                             aggregate->getSequence()[i] = arg;
1834                         else
1835                             arguments = arg;
1836                     }
1837                 }
1838             }
1839         }
1840     }
1841 #endif
1842 }
1843
1844 //
1845 // Add any needed implicit output conversions for function-call arguments.  This
1846 // can require a new tree topology, complicated further by whether the function
1847 // has a return value.
1848 //
1849 // Returns a node of a subtree that evaluates to the return value of the function.
1850 //
1851 TIntermTyped* TParseContext::addOutputArgumentConversions(const TFunction& function, TIntermAggregate& intermNode) const
1852 {
1853 #ifdef GLSLANG_WEB
1854     return &intermNode;
1855 #else
1856     TIntermSequence& arguments = intermNode.getSequence();
1857
1858     // Will there be any output conversions?
1859     bool outputConversions = false;
1860     for (int i = 0; i < function.getParamCount(); ++i) {
1861         if (*function[i].type != arguments[i]->getAsTyped()->getType() && function[i].type->getQualifier().isParamOutput()) {
1862             outputConversions = true;
1863             break;
1864         }
1865     }
1866
1867     if (! outputConversions)
1868         return &intermNode;
1869
1870     // Setup for the new tree, if needed:
1871     //
1872     // Output conversions need a different tree topology.
1873     // Out-qualified arguments need a temporary of the correct type, with the call
1874     // followed by an assignment of the temporary to the original argument:
1875     //     void: function(arg, ...)  ->        (          function(tempArg, ...), arg = tempArg, ...)
1876     //     ret = function(arg, ...)  ->  ret = (tempRet = function(tempArg, ...), arg = tempArg, ..., tempRet)
1877     // Where the "tempArg" type needs no conversion as an argument, but will convert on assignment.
1878     TIntermTyped* conversionTree = nullptr;
1879     TVariable* tempRet = nullptr;
1880     if (intermNode.getBasicType() != EbtVoid) {
1881         // do the "tempRet = function(...), " bit from above
1882         tempRet = makeInternalVariable("tempReturn", intermNode.getType());
1883         TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, intermNode.getLoc());
1884         conversionTree = intermediate.addAssign(EOpAssign, tempRetNode, &intermNode, intermNode.getLoc());
1885     } else
1886         conversionTree = &intermNode;
1887
1888     conversionTree = intermediate.makeAggregate(conversionTree);
1889
1890     // Process each argument's conversion
1891     for (int i = 0; i < function.getParamCount(); ++i) {
1892         if (*function[i].type != arguments[i]->getAsTyped()->getType()) {
1893             if (function[i].type->getQualifier().isParamOutput()) {
1894                 // Out-qualified arguments need to use the topology set up above.
1895                 // do the " ...(tempArg, ...), arg = tempArg" bit from above
1896                 TType paramType;
1897                 paramType.shallowCopy(*function[i].type);
1898                 if (arguments[i]->getAsTyped()->getType().isParameterized() &&
1899                     !paramType.isParameterized()) {
1900                     paramType.shallowCopy(arguments[i]->getAsTyped()->getType());
1901                     paramType.copyTypeParameters(*arguments[i]->getAsTyped()->getType().getTypeParameters());
1902                 }
1903                 TVariable* tempArg = makeInternalVariable("tempArg", paramType);
1904                 tempArg->getWritableType().getQualifier().makeTemporary();
1905                 TIntermSymbol* tempArgNode = intermediate.addSymbol(*tempArg, intermNode.getLoc());
1906                 TIntermTyped* tempAssign = intermediate.addAssign(EOpAssign, arguments[i]->getAsTyped(), tempArgNode, arguments[i]->getLoc());
1907                 conversionTree = intermediate.growAggregate(conversionTree, tempAssign, arguments[i]->getLoc());
1908                 // replace the argument with another node for the same tempArg variable
1909                 arguments[i] = intermediate.addSymbol(*tempArg, intermNode.getLoc());
1910             }
1911         }
1912     }
1913
1914     // Finalize the tree topology (see bigger comment above).
1915     if (tempRet) {
1916         // do the "..., tempRet" bit from above
1917         TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, intermNode.getLoc());
1918         conversionTree = intermediate.growAggregate(conversionTree, tempRetNode, intermNode.getLoc());
1919     }
1920     conversionTree = intermediate.setAggregateOperator(conversionTree, EOpComma, intermNode.getType(), intermNode.getLoc());
1921
1922     return conversionTree;
1923 #endif
1924 }
1925
1926 TIntermTyped* TParseContext::addAssign(const TSourceLoc& loc, TOperator op, TIntermTyped* left, TIntermTyped* right)
1927 {
1928     if ((op == EOpAddAssign || op == EOpSubAssign) && left->isReference())
1929         requireExtensions(loc, 1, &E_GL_EXT_buffer_reference2, "+= and -= on a buffer reference");
1930
1931     return intermediate.addAssign(op, left, right, loc);
1932 }
1933
1934 void TParseContext::memorySemanticsCheck(const TSourceLoc& loc, const TFunction& fnCandidate, const TIntermOperator& callNode)
1935 {
1936     const TIntermSequence* argp = &callNode.getAsAggregate()->getSequence();
1937
1938     //const int gl_SemanticsRelaxed         = 0x0;
1939     const int gl_SemanticsAcquire         = 0x2;
1940     const int gl_SemanticsRelease         = 0x4;
1941     const int gl_SemanticsAcquireRelease  = 0x8;
1942     const int gl_SemanticsMakeAvailable   = 0x2000;
1943     const int gl_SemanticsMakeVisible     = 0x4000;
1944     const int gl_SemanticsVolatile        = 0x8000;
1945
1946     //const int gl_StorageSemanticsNone     = 0x0;
1947     const int gl_StorageSemanticsBuffer   = 0x40;
1948     const int gl_StorageSemanticsShared   = 0x100;
1949     const int gl_StorageSemanticsImage    = 0x800;
1950     const int gl_StorageSemanticsOutput   = 0x1000;
1951
1952
1953     unsigned int semantics = 0, storageClassSemantics = 0;
1954     unsigned int semantics2 = 0, storageClassSemantics2 = 0;
1955
1956     const TIntermTyped* arg0 = (*argp)[0]->getAsTyped();
1957     const bool isMS = arg0->getBasicType() == EbtSampler && arg0->getType().getSampler().isMultiSample();
1958
1959     // Grab the semantics and storage class semantics from the operands, based on opcode
1960     switch (callNode.getOp()) {
1961     case EOpAtomicAdd:
1962     case EOpAtomicSubtract:
1963     case EOpAtomicMin:
1964     case EOpAtomicMax:
1965     case EOpAtomicAnd:
1966     case EOpAtomicOr:
1967     case EOpAtomicXor:
1968     case EOpAtomicExchange:
1969     case EOpAtomicStore:
1970         storageClassSemantics = (*argp)[3]->getAsConstantUnion()->getConstArray()[0].getIConst();
1971         semantics = (*argp)[4]->getAsConstantUnion()->getConstArray()[0].getIConst();
1972         break;
1973     case EOpAtomicLoad:
1974         storageClassSemantics = (*argp)[2]->getAsConstantUnion()->getConstArray()[0].getIConst();
1975         semantics = (*argp)[3]->getAsConstantUnion()->getConstArray()[0].getIConst();
1976         break;
1977     case EOpAtomicCompSwap:
1978         storageClassSemantics = (*argp)[4]->getAsConstantUnion()->getConstArray()[0].getIConst();
1979         semantics = (*argp)[5]->getAsConstantUnion()->getConstArray()[0].getIConst();
1980         storageClassSemantics2 = (*argp)[6]->getAsConstantUnion()->getConstArray()[0].getIConst();
1981         semantics2 = (*argp)[7]->getAsConstantUnion()->getConstArray()[0].getIConst();
1982         break;
1983
1984     case EOpImageAtomicAdd:
1985     case EOpImageAtomicMin:
1986     case EOpImageAtomicMax:
1987     case EOpImageAtomicAnd:
1988     case EOpImageAtomicOr:
1989     case EOpImageAtomicXor:
1990     case EOpImageAtomicExchange:
1991     case EOpImageAtomicStore:
1992         storageClassSemantics = (*argp)[isMS ? 5 : 4]->getAsConstantUnion()->getConstArray()[0].getIConst();
1993         semantics = (*argp)[isMS ? 6 : 5]->getAsConstantUnion()->getConstArray()[0].getIConst();
1994         break;
1995     case EOpImageAtomicLoad:
1996         storageClassSemantics = (*argp)[isMS ? 4 : 3]->getAsConstantUnion()->getConstArray()[0].getIConst();
1997         semantics = (*argp)[isMS ? 5 : 4]->getAsConstantUnion()->getConstArray()[0].getIConst();
1998         break;
1999     case EOpImageAtomicCompSwap:
2000         storageClassSemantics = (*argp)[isMS ? 6 : 5]->getAsConstantUnion()->getConstArray()[0].getIConst();
2001         semantics = (*argp)[isMS ? 7 : 6]->getAsConstantUnion()->getConstArray()[0].getIConst();
2002         storageClassSemantics2 = (*argp)[isMS ? 8 : 7]->getAsConstantUnion()->getConstArray()[0].getIConst();
2003         semantics2 = (*argp)[isMS ? 9 : 8]->getAsConstantUnion()->getConstArray()[0].getIConst();
2004         break;
2005
2006     case EOpBarrier:
2007         storageClassSemantics = (*argp)[2]->getAsConstantUnion()->getConstArray()[0].getIConst();
2008         semantics = (*argp)[3]->getAsConstantUnion()->getConstArray()[0].getIConst();
2009         break;
2010     case EOpMemoryBarrier:
2011         storageClassSemantics = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getIConst();
2012         semantics = (*argp)[2]->getAsConstantUnion()->getConstArray()[0].getIConst();
2013         break;
2014     default:
2015         break;
2016     }
2017
2018     if ((semantics & gl_SemanticsAcquire) &&
2019         (callNode.getOp() == EOpAtomicStore || callNode.getOp() == EOpImageAtomicStore)) {
2020         error(loc, "gl_SemanticsAcquire must not be used with (image) atomic store",
2021               fnCandidate.getName().c_str(), "");
2022     }
2023     if ((semantics & gl_SemanticsRelease) &&
2024         (callNode.getOp() == EOpAtomicLoad || callNode.getOp() == EOpImageAtomicLoad)) {
2025         error(loc, "gl_SemanticsRelease must not be used with (image) atomic load",
2026               fnCandidate.getName().c_str(), "");
2027     }
2028     if ((semantics & gl_SemanticsAcquireRelease) &&
2029         (callNode.getOp() == EOpAtomicStore || callNode.getOp() == EOpImageAtomicStore ||
2030          callNode.getOp() == EOpAtomicLoad  || callNode.getOp() == EOpImageAtomicLoad)) {
2031         error(loc, "gl_SemanticsAcquireRelease must not be used with (image) atomic load/store",
2032               fnCandidate.getName().c_str(), "");
2033     }
2034     if (((semantics | semantics2) & ~(gl_SemanticsAcquire |
2035                                       gl_SemanticsRelease |
2036                                       gl_SemanticsAcquireRelease |
2037                                       gl_SemanticsMakeAvailable |
2038                                       gl_SemanticsMakeVisible |
2039                                       gl_SemanticsVolatile))) {
2040         error(loc, "Invalid semantics value", fnCandidate.getName().c_str(), "");
2041     }
2042     if (((storageClassSemantics | storageClassSemantics2) & ~(gl_StorageSemanticsBuffer |
2043                                                               gl_StorageSemanticsShared |
2044                                                               gl_StorageSemanticsImage |
2045                                                               gl_StorageSemanticsOutput))) {
2046         error(loc, "Invalid storage class semantics value", fnCandidate.getName().c_str(), "");
2047     }
2048
2049     if (callNode.getOp() == EOpMemoryBarrier) {
2050         if (!IsPow2(semantics & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
2051             error(loc, "Semantics must include exactly one of gl_SemanticsRelease, gl_SemanticsAcquire, or "
2052                        "gl_SemanticsAcquireRelease", fnCandidate.getName().c_str(), "");
2053         }
2054     } else {
2055         if (semantics & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease)) {
2056             if (!IsPow2(semantics & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
2057                 error(loc, "Semantics must not include multiple of gl_SemanticsRelease, gl_SemanticsAcquire, or "
2058                            "gl_SemanticsAcquireRelease", fnCandidate.getName().c_str(), "");
2059             }
2060         }
2061         if (semantics2 & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease)) {
2062             if (!IsPow2(semantics2 & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
2063                 error(loc, "semUnequal must not include multiple of gl_SemanticsRelease, gl_SemanticsAcquire, or "
2064                            "gl_SemanticsAcquireRelease", fnCandidate.getName().c_str(), "");
2065             }
2066         }
2067     }
2068     if (callNode.getOp() == EOpMemoryBarrier) {
2069         if (storageClassSemantics == 0) {
2070             error(loc, "Storage class semantics must not be zero", fnCandidate.getName().c_str(), "");
2071         }
2072     }
2073     if (callNode.getOp() == EOpBarrier && semantics != 0 && storageClassSemantics == 0) {
2074         error(loc, "Storage class semantics must not be zero", fnCandidate.getName().c_str(), "");
2075     }
2076     if ((callNode.getOp() == EOpAtomicCompSwap || callNode.getOp() == EOpImageAtomicCompSwap) &&
2077         (semantics2 & (gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
2078         error(loc, "semUnequal must not be gl_SemanticsRelease or gl_SemanticsAcquireRelease",
2079               fnCandidate.getName().c_str(), "");
2080     }
2081     if ((semantics & gl_SemanticsMakeAvailable) &&
2082         !(semantics & (gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
2083         error(loc, "gl_SemanticsMakeAvailable requires gl_SemanticsRelease or gl_SemanticsAcquireRelease",
2084               fnCandidate.getName().c_str(), "");
2085     }
2086     if ((semantics & gl_SemanticsMakeVisible) &&
2087         !(semantics & (gl_SemanticsAcquire | gl_SemanticsAcquireRelease))) {
2088         error(loc, "gl_SemanticsMakeVisible requires gl_SemanticsAcquire or gl_SemanticsAcquireRelease",
2089               fnCandidate.getName().c_str(), "");
2090     }
2091     if ((semantics & gl_SemanticsVolatile) &&
2092         (callNode.getOp() == EOpMemoryBarrier || callNode.getOp() == EOpBarrier)) {
2093         error(loc, "gl_SemanticsVolatile must not be used with memoryBarrier or controlBarrier",
2094               fnCandidate.getName().c_str(), "");
2095     }
2096     if ((callNode.getOp() == EOpAtomicCompSwap || callNode.getOp() == EOpImageAtomicCompSwap) &&
2097         ((semantics ^ semantics2) & gl_SemanticsVolatile)) {
2098         error(loc, "semEqual and semUnequal must either both include gl_SemanticsVolatile or neither",
2099               fnCandidate.getName().c_str(), "");
2100     }
2101 }
2102
2103 //
2104 // Do additional checking of built-in function calls that is not caught
2105 // by normal semantic checks on argument type, extension tagging, etc.
2106 //
2107 // Assumes there has been a semantically correct match to a built-in function prototype.
2108 //
2109 void TParseContext::builtInOpCheck(const TSourceLoc& loc, const TFunction& fnCandidate, TIntermOperator& callNode)
2110 {
2111     // Set up convenience accessors to the argument(s).  There is almost always
2112     // multiple arguments for the cases below, but when there might be one,
2113     // check the unaryArg first.
2114     const TIntermSequence* argp = nullptr;   // confusing to use [] syntax on a pointer, so this is to help get a reference
2115     const TIntermTyped* unaryArg = nullptr;
2116     const TIntermTyped* arg0 = nullptr;
2117     if (callNode.getAsAggregate()) {
2118         argp = &callNode.getAsAggregate()->getSequence();
2119         if (argp->size() > 0)
2120             arg0 = (*argp)[0]->getAsTyped();
2121     } else {
2122         assert(callNode.getAsUnaryNode());
2123         unaryArg = callNode.getAsUnaryNode()->getOperand();
2124         arg0 = unaryArg;
2125     }
2126
2127     TString featureString;
2128     const char* feature = nullptr;
2129     switch (callNode.getOp()) {
2130 #ifndef GLSLANG_WEB
2131     case EOpTextureGather:
2132     case EOpTextureGatherOffset:
2133     case EOpTextureGatherOffsets:
2134     {
2135         // Figure out which variants are allowed by what extensions,
2136         // and what arguments must be constant for which situations.
2137
2138         featureString = fnCandidate.getName();
2139         featureString += "(...)";
2140         feature = featureString.c_str();
2141         profileRequires(loc, EEsProfile, 310, nullptr, feature);
2142         int compArg = -1;  // track which argument, if any, is the constant component argument
2143         switch (callNode.getOp()) {
2144         case EOpTextureGather:
2145             // More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5,
2146             // otherwise, need GL_ARB_texture_gather.
2147             if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect || fnCandidate[0].type->getSampler().shadow) {
2148                 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
2149                 if (! fnCandidate[0].type->getSampler().shadow)
2150                     compArg = 2;
2151             } else
2152                 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_texture_gather, feature);
2153             break;
2154         case EOpTextureGatherOffset:
2155             // GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument
2156             if (fnCandidate[0].type->getSampler().dim == Esd2D && ! fnCandidate[0].type->getSampler().shadow && fnCandidate.getParamCount() == 3)
2157                 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_texture_gather, feature);
2158             else
2159                 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
2160             if (! (*argp)[fnCandidate[0].type->getSampler().shadow ? 3 : 2]->getAsConstantUnion())
2161                 profileRequires(loc, EEsProfile, 320, Num_AEP_gpu_shader5, AEP_gpu_shader5,
2162                                 "non-constant offset argument");
2163             if (! fnCandidate[0].type->getSampler().shadow)
2164                 compArg = 3;
2165             break;
2166         case EOpTextureGatherOffsets:
2167             profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
2168             if (! fnCandidate[0].type->getSampler().shadow)
2169                 compArg = 3;
2170             // check for constant offsets
2171             if (! (*argp)[fnCandidate[0].type->getSampler().shadow ? 3 : 2]->getAsConstantUnion())
2172                 error(loc, "must be a compile-time constant:", feature, "offsets argument");
2173             break;
2174         default:
2175             break;
2176         }
2177
2178         if (compArg > 0 && compArg < fnCandidate.getParamCount()) {
2179             if ((*argp)[compArg]->getAsConstantUnion()) {
2180                 int value = (*argp)[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst();
2181                 if (value < 0 || value > 3)
2182                     error(loc, "must be 0, 1, 2, or 3:", feature, "component argument");
2183             } else
2184                 error(loc, "must be a compile-time constant:", feature, "component argument");
2185         }
2186
2187         bool bias = false;
2188         if (callNode.getOp() == EOpTextureGather)
2189             bias = fnCandidate.getParamCount() > 3;
2190         else if (callNode.getOp() == EOpTextureGatherOffset ||
2191                  callNode.getOp() == EOpTextureGatherOffsets)
2192             bias = fnCandidate.getParamCount() > 4;
2193
2194         if (bias) {
2195             featureString = fnCandidate.getName();
2196             featureString += "with bias argument";
2197             feature = featureString.c_str();
2198             profileRequires(loc, ~EEsProfile, 450, nullptr, feature);
2199             requireExtensions(loc, 1, &E_GL_AMD_texture_gather_bias_lod, feature);
2200         }
2201         break;
2202     }
2203     case EOpSparseTextureGather:
2204     case EOpSparseTextureGatherOffset:
2205     case EOpSparseTextureGatherOffsets:
2206     {
2207         bool bias = false;
2208         if (callNode.getOp() == EOpSparseTextureGather)
2209             bias = fnCandidate.getParamCount() > 4;
2210         else if (callNode.getOp() == EOpSparseTextureGatherOffset ||
2211                  callNode.getOp() == EOpSparseTextureGatherOffsets)
2212             bias = fnCandidate.getParamCount() > 5;
2213
2214         if (bias) {
2215             featureString = fnCandidate.getName();
2216             featureString += "with bias argument";
2217             feature = featureString.c_str();
2218             profileRequires(loc, ~EEsProfile, 450, nullptr, feature);
2219             requireExtensions(loc, 1, &E_GL_AMD_texture_gather_bias_lod, feature);
2220         }
2221         // As per GL_ARB_sparse_texture2 extension "Offsets" parameter must be constant integral expression
2222         // for sparseTextureGatherOffsetsARB just as textureGatherOffsets
2223         if (callNode.getOp() == EOpSparseTextureGatherOffsets) {
2224             int offsetsArg = arg0->getType().getSampler().shadow ? 3 : 2;
2225             if (!(*argp)[offsetsArg]->getAsConstantUnion())
2226                 error(loc, "argument must be compile-time constant", "offsets", "");
2227         }
2228         break;
2229     }
2230
2231     case EOpSparseTextureGatherLod:
2232     case EOpSparseTextureGatherLodOffset:
2233     case EOpSparseTextureGatherLodOffsets:
2234     {
2235         requireExtensions(loc, 1, &E_GL_ARB_sparse_texture2, fnCandidate.getName().c_str());
2236         break;
2237     }
2238
2239     case EOpSwizzleInvocations:
2240     {
2241         if (! (*argp)[1]->getAsConstantUnion())
2242             error(loc, "argument must be compile-time constant", "offset", "");
2243         else {
2244             unsigned offset[4] = {};
2245             offset[0] = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getUConst();
2246             offset[1] = (*argp)[1]->getAsConstantUnion()->getConstArray()[1].getUConst();
2247             offset[2] = (*argp)[1]->getAsConstantUnion()->getConstArray()[2].getUConst();
2248             offset[3] = (*argp)[1]->getAsConstantUnion()->getConstArray()[3].getUConst();
2249             if (offset[0] > 3 || offset[1] > 3 || offset[2] > 3 || offset[3] > 3)
2250                 error(loc, "components must be in the range [0, 3]", "offset", "");
2251         }
2252
2253         break;
2254     }
2255
2256     case EOpSwizzleInvocationsMasked:
2257     {
2258         if (! (*argp)[1]->getAsConstantUnion())
2259             error(loc, "argument must be compile-time constant", "mask", "");
2260         else {
2261             unsigned mask[3] = {};
2262             mask[0] = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getUConst();
2263             mask[1] = (*argp)[1]->getAsConstantUnion()->getConstArray()[1].getUConst();
2264             mask[2] = (*argp)[1]->getAsConstantUnion()->getConstArray()[2].getUConst();
2265             if (mask[0] > 31 || mask[1] > 31 || mask[2] > 31)
2266                 error(loc, "components must be in the range [0, 31]", "mask", "");
2267         }
2268
2269         break;
2270     }
2271 #endif
2272
2273     case EOpTextureOffset:
2274     case EOpTextureFetchOffset:
2275     case EOpTextureProjOffset:
2276     case EOpTextureLodOffset:
2277     case EOpTextureProjLodOffset:
2278     case EOpTextureGradOffset:
2279     case EOpTextureProjGradOffset:
2280     {
2281         // Handle texture-offset limits checking
2282         // Pick which argument has to hold constant offsets
2283         int arg = -1;
2284         switch (callNode.getOp()) {
2285         case EOpTextureOffset:          arg = 2;  break;
2286         case EOpTextureFetchOffset:     arg = (arg0->getType().getSampler().isRect()) ? 2 : 3; break;
2287         case EOpTextureProjOffset:      arg = 2;  break;
2288         case EOpTextureLodOffset:       arg = 3;  break;
2289         case EOpTextureProjLodOffset:   arg = 3;  break;
2290         case EOpTextureGradOffset:      arg = 4;  break;
2291         case EOpTextureProjGradOffset:  arg = 4;  break;
2292         default:
2293             assert(0);
2294             break;
2295         }
2296
2297         if (arg > 0) {
2298
2299 #ifndef GLSLANG_WEB
2300             bool f16ShadowCompare = (*argp)[1]->getAsTyped()->getBasicType() == EbtFloat16 &&
2301                                     arg0->getType().getSampler().shadow;
2302             if (f16ShadowCompare)
2303                 ++arg;
2304 #endif
2305             if (! (*argp)[arg]->getAsTyped()->getQualifier().isConstant())
2306                 error(loc, "argument must be compile-time constant", "texel offset", "");
2307             else if ((*argp)[arg]->getAsConstantUnion()) {
2308                 const TType& type = (*argp)[arg]->getAsTyped()->getType();
2309                 for (int c = 0; c < type.getVectorSize(); ++c) {
2310                     int offset = (*argp)[arg]->getAsConstantUnion()->getConstArray()[c].getIConst();
2311                     if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset)
2312                         error(loc, "value is out of range:", "texel offset",
2313                               "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]");
2314                 }
2315             }
2316
2317             if (callNode.getOp() == EOpTextureOffset) {
2318                 TSampler s = arg0->getType().getSampler();
2319                 if (s.is2D() && s.isArrayed() && s.isShadow()) {
2320                     if (isEsProfile())
2321                         error(loc, "TextureOffset does not support sampler2DArrayShadow : ", "sampler", "ES Profile");
2322                     else if (version <= 420)
2323                         error(loc, "TextureOffset does not support sampler2DArrayShadow : ", "sampler", "version <= 420");
2324                 }
2325             }
2326         }
2327
2328         break;
2329     }
2330
2331 #ifndef GLSLANG_WEB
2332     case EOpTraceNV:
2333         if (!(*argp)[10]->getAsConstantUnion())
2334             error(loc, "argument must be compile-time constant", "payload number", "a");
2335         break;
2336     case EOpTraceRayMotionNV:
2337         if (!(*argp)[11]->getAsConstantUnion())
2338             error(loc, "argument must be compile-time constant", "payload number", "a");
2339         break;
2340     case EOpTraceKHR:
2341         if (!(*argp)[10]->getAsConstantUnion())
2342             error(loc, "argument must be compile-time constant", "payload number", "a");
2343         else {
2344             unsigned int location = (*argp)[10]->getAsConstantUnion()->getAsConstantUnion()->getConstArray()[0].getUConst();
2345             if (!extensionTurnedOn(E_GL_EXT_spirv_intrinsics) && intermediate.checkLocationRT(0, location) < 0)
2346                 error(loc, "with layout(location =", "no rayPayloadEXT/rayPayloadInEXT declared", "%d)", location);
2347         }
2348         break;
2349     case EOpExecuteCallableNV:
2350         if (!(*argp)[1]->getAsConstantUnion())
2351             error(loc, "argument must be compile-time constant", "callable data number", "");
2352         break;
2353     case EOpExecuteCallableKHR:
2354         if (!(*argp)[1]->getAsConstantUnion())
2355             error(loc, "argument must be compile-time constant", "callable data number", "");
2356         else {
2357             unsigned int location = (*argp)[1]->getAsConstantUnion()->getAsConstantUnion()->getConstArray()[0].getUConst();
2358             if (!extensionTurnedOn(E_GL_EXT_spirv_intrinsics) && intermediate.checkLocationRT(1, location) < 0)
2359                 error(loc, "with layout(location =", "no callableDataEXT/callableDataInEXT declared", "%d)", location);
2360         }
2361         break;
2362
2363     case EOpRayQueryGetIntersectionType:
2364     case EOpRayQueryGetIntersectionT:
2365     case EOpRayQueryGetIntersectionInstanceCustomIndex:
2366     case EOpRayQueryGetIntersectionInstanceId:
2367     case EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2368     case EOpRayQueryGetIntersectionGeometryIndex:
2369     case EOpRayQueryGetIntersectionPrimitiveIndex:
2370     case EOpRayQueryGetIntersectionBarycentrics:
2371     case EOpRayQueryGetIntersectionFrontFace:
2372     case EOpRayQueryGetIntersectionObjectRayDirection:
2373     case EOpRayQueryGetIntersectionObjectRayOrigin:
2374     case EOpRayQueryGetIntersectionObjectToWorld:
2375     case EOpRayQueryGetIntersectionWorldToObject:
2376         if (!(*argp)[1]->getAsConstantUnion())
2377             error(loc, "argument must be compile-time constant", "committed", "");
2378         break;
2379
2380     case EOpTextureQuerySamples:
2381     case EOpImageQuerySamples:
2382         // GL_ARB_shader_texture_image_samples
2383         profileRequires(loc, ~EEsProfile, 450, E_GL_ARB_shader_texture_image_samples, "textureSamples and imageSamples");
2384         break;
2385
2386     case EOpImageAtomicAdd:
2387     case EOpImageAtomicMin:
2388     case EOpImageAtomicMax:
2389     case EOpImageAtomicAnd:
2390     case EOpImageAtomicOr:
2391     case EOpImageAtomicXor:
2392     case EOpImageAtomicExchange:
2393     case EOpImageAtomicCompSwap:
2394     case EOpImageAtomicLoad:
2395     case EOpImageAtomicStore:
2396     {
2397         // Make sure the image types have the correct layout() format and correct argument types
2398         const TType& imageType = arg0->getType();
2399         if (imageType.getSampler().type == EbtInt || imageType.getSampler().type == EbtUint ||
2400             imageType.getSampler().type == EbtInt64 || imageType.getSampler().type == EbtUint64) {
2401             if (imageType.getQualifier().getFormat() != ElfR32i && imageType.getQualifier().getFormat() != ElfR32ui &&
2402                 imageType.getQualifier().getFormat() != ElfR64i && imageType.getQualifier().getFormat() != ElfR64ui)
2403                 error(loc, "only supported on image with format r32i or r32ui", fnCandidate.getName().c_str(), "");
2404             if (callNode.getType().getBasicType() == EbtInt64 && imageType.getQualifier().getFormat() != ElfR64i)
2405                 error(loc, "only supported on image with format r64i", fnCandidate.getName().c_str(), "");
2406             else if (callNode.getType().getBasicType() == EbtUint64 && imageType.getQualifier().getFormat() != ElfR64ui)
2407                 error(loc, "only supported on image with format r64ui", fnCandidate.getName().c_str(), "");
2408         } else if (imageType.getSampler().type == EbtFloat) {
2409             if (fnCandidate.getName().compare(0, 19, "imageAtomicExchange") == 0) {
2410                 // imageAtomicExchange doesn't require an extension
2411             } else if ((fnCandidate.getName().compare(0, 14, "imageAtomicAdd") == 0) ||
2412                        (fnCandidate.getName().compare(0, 15, "imageAtomicLoad") == 0) ||
2413                        (fnCandidate.getName().compare(0, 16, "imageAtomicStore") == 0)) {
2414                 requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float, fnCandidate.getName().c_str());
2415             } else if ((fnCandidate.getName().compare(0, 14, "imageAtomicMin") == 0) ||
2416                        (fnCandidate.getName().compare(0, 14, "imageAtomicMax") == 0)) {
2417                 requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float2, fnCandidate.getName().c_str());
2418             } else {
2419                 error(loc, "only supported on integer images", fnCandidate.getName().c_str(), "");
2420             }
2421             if (imageType.getQualifier().getFormat() != ElfR32f && isEsProfile())
2422                 error(loc, "only supported on image with format r32f", fnCandidate.getName().c_str(), "");
2423         } else {
2424             error(loc, "not supported on this image type", fnCandidate.getName().c_str(), "");
2425         }
2426
2427         const size_t maxArgs = imageType.getSampler().isMultiSample() ? 5 : 4;
2428         if (argp->size() > maxArgs) {
2429             requireExtensions(loc, 1, &E_GL_KHR_memory_scope_semantics, fnCandidate.getName().c_str());
2430             memorySemanticsCheck(loc, fnCandidate, callNode);
2431         }
2432
2433         break;
2434     }
2435
2436     case EOpAtomicAdd:
2437     case EOpAtomicSubtract:
2438     case EOpAtomicMin:
2439     case EOpAtomicMax:
2440     case EOpAtomicAnd:
2441     case EOpAtomicOr:
2442     case EOpAtomicXor:
2443     case EOpAtomicExchange:
2444     case EOpAtomicCompSwap:
2445     case EOpAtomicLoad:
2446     case EOpAtomicStore:
2447     {
2448         if (argp->size() > 3) {
2449             requireExtensions(loc, 1, &E_GL_KHR_memory_scope_semantics, fnCandidate.getName().c_str());
2450             memorySemanticsCheck(loc, fnCandidate, callNode);
2451             if ((callNode.getOp() == EOpAtomicAdd || callNode.getOp() == EOpAtomicExchange ||
2452                 callNode.getOp() == EOpAtomicLoad || callNode.getOp() == EOpAtomicStore) &&
2453                 (arg0->getType().getBasicType() == EbtFloat ||
2454                  arg0->getType().getBasicType() == EbtDouble)) {
2455                 requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float, fnCandidate.getName().c_str());
2456             } else if ((callNode.getOp() == EOpAtomicAdd || callNode.getOp() == EOpAtomicExchange ||
2457                         callNode.getOp() == EOpAtomicLoad || callNode.getOp() == EOpAtomicStore ||
2458                         callNode.getOp() == EOpAtomicMin || callNode.getOp() == EOpAtomicMax) &&
2459                        arg0->getType().isFloatingDomain()) {
2460                 requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float2, fnCandidate.getName().c_str());
2461             }
2462         } else if (arg0->getType().getBasicType() == EbtInt64 || arg0->getType().getBasicType() == EbtUint64) {
2463             const char* const extensions[2] = { E_GL_NV_shader_atomic_int64,
2464                                                 E_GL_EXT_shader_atomic_int64 };
2465             requireExtensions(loc, 2, extensions, fnCandidate.getName().c_str());
2466         } else if ((callNode.getOp() == EOpAtomicAdd || callNode.getOp() == EOpAtomicExchange) &&
2467                    (arg0->getType().getBasicType() == EbtFloat ||
2468                     arg0->getType().getBasicType() == EbtDouble)) {
2469             requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float, fnCandidate.getName().c_str());
2470         } else if ((callNode.getOp() == EOpAtomicAdd || callNode.getOp() == EOpAtomicExchange ||
2471                     callNode.getOp() == EOpAtomicLoad || callNode.getOp() == EOpAtomicStore ||
2472                     callNode.getOp() == EOpAtomicMin || callNode.getOp() == EOpAtomicMax) &&
2473                    arg0->getType().isFloatingDomain()) {
2474             requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float2, fnCandidate.getName().c_str());
2475         }
2476
2477         const TIntermTyped* base = TIntermediate::findLValueBase(arg0, true , true);
2478         const TType* refType = (base->getType().isReference()) ? base->getType().getReferentType() : nullptr;
2479         const TQualifier& qualifier = (refType != nullptr) ? refType->getQualifier() : base->getType().getQualifier();
2480         if (qualifier.storage != EvqShared && qualifier.storage != EvqBuffer && qualifier.storage != EvqtaskPayloadSharedEXT)
2481             error(loc,"Atomic memory function can only be used for shader storage block member or shared variable.",
2482             fnCandidate.getName().c_str(), "");
2483
2484         break;
2485     }
2486
2487     case EOpInterpolateAtCentroid:
2488     case EOpInterpolateAtSample:
2489     case EOpInterpolateAtOffset:
2490     case EOpInterpolateAtVertex:
2491         // Make sure the first argument is an interpolant, or an array element of an interpolant
2492         if (arg0->getType().getQualifier().storage != EvqVaryingIn) {
2493             // It might still be an array element.
2494             //
2495             // We could check more, but the semantics of the first argument are already met; the
2496             // only way to turn an array into a float/vec* is array dereference and swizzle.
2497             //
2498             // ES and desktop 4.3 and earlier:  swizzles may not be used
2499             // desktop 4.4 and later: swizzles may be used
2500             bool swizzleOkay = (!isEsProfile()) && (version >= 440);
2501             const TIntermTyped* base = TIntermediate::findLValueBase(arg0, swizzleOkay);
2502             if (base == nullptr || base->getType().getQualifier().storage != EvqVaryingIn)
2503                 error(loc, "first argument must be an interpolant, or interpolant-array element", fnCandidate.getName().c_str(), "");
2504         }
2505
2506         if (callNode.getOp() == EOpInterpolateAtVertex) {
2507             if (!arg0->getType().getQualifier().isExplicitInterpolation())
2508                 error(loc, "argument must be qualified as __explicitInterpAMD in", "interpolant", "");
2509             else {
2510                 if (! (*argp)[1]->getAsConstantUnion())
2511                     error(loc, "argument must be compile-time constant", "vertex index", "");
2512                 else {
2513                     unsigned vertexIdx = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getUConst();
2514                     if (vertexIdx > 2)
2515                         error(loc, "must be in the range [0, 2]", "vertex index", "");
2516                 }
2517             }
2518         }
2519         break;
2520
2521     case EOpEmitStreamVertex:
2522     case EOpEndStreamPrimitive:
2523         if (version == 150)
2524             requireExtensions(loc, 1, &E_GL_ARB_gpu_shader5, "if the verison is 150 , the EmitStreamVertex and EndStreamPrimitive only support at extension GL_ARB_gpu_shader5");
2525         intermediate.setMultiStream();
2526         break;
2527
2528     case EOpSubgroupClusteredAdd:
2529     case EOpSubgroupClusteredMul:
2530     case EOpSubgroupClusteredMin:
2531     case EOpSubgroupClusteredMax:
2532     case EOpSubgroupClusteredAnd:
2533     case EOpSubgroupClusteredOr:
2534     case EOpSubgroupClusteredXor:
2535         // The <clusterSize> as used in the subgroupClustered<op>() operations must be:
2536         // - An integral constant expression.
2537         // - At least 1.
2538         // - A power of 2.
2539         if ((*argp)[1]->getAsConstantUnion() == nullptr)
2540             error(loc, "argument must be compile-time constant", "cluster size", "");
2541         else {
2542             int size = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getIConst();
2543             if (size < 1)
2544                 error(loc, "argument must be at least 1", "cluster size", "");
2545             else if (!IsPow2(size))
2546                 error(loc, "argument must be a power of 2", "cluster size", "");
2547         }
2548         break;
2549
2550     case EOpSubgroupBroadcast:
2551     case EOpSubgroupQuadBroadcast:
2552         if (spvVersion.spv < EShTargetSpv_1_5) {
2553             // <id> must be an integral constant expression.
2554             if ((*argp)[1]->getAsConstantUnion() == nullptr)
2555                 error(loc, "argument must be compile-time constant", "id", "");
2556         }
2557         break;
2558
2559     case EOpBarrier:
2560     case EOpMemoryBarrier:
2561         if (argp->size() > 0) {
2562             requireExtensions(loc, 1, &E_GL_KHR_memory_scope_semantics, fnCandidate.getName().c_str());
2563             memorySemanticsCheck(loc, fnCandidate, callNode);
2564         }
2565         break;
2566
2567     case EOpMix:
2568         if (profile == EEsProfile && version < 310) {
2569             // Look for specific signatures
2570             if ((*argp)[0]->getAsTyped()->getBasicType() != EbtFloat &&
2571                 (*argp)[1]->getAsTyped()->getBasicType() != EbtFloat &&
2572                 (*argp)[2]->getAsTyped()->getBasicType() == EbtBool) {
2573                 requireExtensions(loc, 1, &E_GL_EXT_shader_integer_mix, "specific signature of builtin mix");
2574             }
2575         }
2576
2577         if (profile != EEsProfile && version < 450) {
2578             if ((*argp)[0]->getAsTyped()->getBasicType() != EbtFloat &&
2579                 (*argp)[0]->getAsTyped()->getBasicType() != EbtDouble &&
2580                 (*argp)[1]->getAsTyped()->getBasicType() != EbtFloat &&
2581                 (*argp)[1]->getAsTyped()->getBasicType() != EbtDouble &&
2582                 (*argp)[2]->getAsTyped()->getBasicType() == EbtBool) {
2583                 requireExtensions(loc, 1, &E_GL_EXT_shader_integer_mix, fnCandidate.getName().c_str());
2584             }
2585         }
2586
2587         break;
2588 #endif
2589
2590     default:
2591         break;
2592     }
2593
2594     // Texture operations on texture objects (aside from texelFetch on a
2595     // textureBuffer) require EXT_samplerless_texture_functions.
2596     switch (callNode.getOp()) {
2597     case EOpTextureQuerySize:
2598     case EOpTextureQueryLevels:
2599     case EOpTextureQuerySamples:
2600     case EOpTextureFetch:
2601     case EOpTextureFetchOffset:
2602     {
2603         const TSampler& sampler = fnCandidate[0].type->getSampler();
2604
2605         const bool isTexture = sampler.isTexture() && !sampler.isCombined();
2606         const bool isBuffer = sampler.isBuffer();
2607         const bool isFetch = callNode.getOp() == EOpTextureFetch || callNode.getOp() == EOpTextureFetchOffset;
2608
2609         if (isTexture && (!isBuffer || !isFetch))
2610             requireExtensions(loc, 1, &E_GL_EXT_samplerless_texture_functions, fnCandidate.getName().c_str());
2611
2612         break;
2613     }
2614
2615     default:
2616         break;
2617     }
2618
2619     if (callNode.isSubgroup()) {
2620         // these require SPIR-V 1.3
2621         if (spvVersion.spv > 0 && spvVersion.spv < EShTargetSpv_1_3)
2622             error(loc, "requires SPIR-V 1.3", "subgroup op", "");
2623
2624         // Check that if extended types are being used that the correct extensions are enabled.
2625         if (arg0 != nullptr) {
2626             const TType& type = arg0->getType();
2627             bool enhanced = intermediate.getEnhancedMsgs();
2628             switch (type.getBasicType()) {
2629             default:
2630                 break;
2631             case EbtInt8:
2632             case EbtUint8:
2633                 requireExtensions(loc, 1, &E_GL_EXT_shader_subgroup_extended_types_int8, type.getCompleteString(enhanced).c_str());
2634                 break;
2635             case EbtInt16:
2636             case EbtUint16:
2637                 requireExtensions(loc, 1, &E_GL_EXT_shader_subgroup_extended_types_int16, type.getCompleteString(enhanced).c_str());
2638                 break;
2639             case EbtInt64:
2640             case EbtUint64:
2641                 requireExtensions(loc, 1, &E_GL_EXT_shader_subgroup_extended_types_int64, type.getCompleteString(enhanced).c_str());
2642                 break;
2643             case EbtFloat16:
2644                 requireExtensions(loc, 1, &E_GL_EXT_shader_subgroup_extended_types_float16, type.getCompleteString(enhanced).c_str());
2645                 break;
2646             }
2647         }
2648     }
2649 }
2650
2651 #ifndef GLSLANG_WEB
2652
2653 extern bool PureOperatorBuiltins;
2654
2655 // Deprecated!  Use PureOperatorBuiltins == true instead, in which case this
2656 // functionality is handled in builtInOpCheck() instead of here.
2657 //
2658 // Do additional checking of built-in function calls that were not mapped
2659 // to built-in operations (e.g., texturing functions).
2660 //
2661 // Assumes there has been a semantically correct match to a built-in function.
2662 //
2663 void TParseContext::nonOpBuiltInCheck(const TSourceLoc& loc, const TFunction& fnCandidate, TIntermAggregate& callNode)
2664 {
2665     // Further maintenance of this function is deprecated, because the "correct"
2666     // future-oriented design is to not have to do string compares on function names.
2667
2668     // If PureOperatorBuiltins == true, then all built-ins should be mapped
2669     // to a TOperator, and this function would then never get called.
2670
2671     assert(PureOperatorBuiltins == false);
2672
2673     // built-in texturing functions get their return value precision from the precision of the sampler
2674     if (fnCandidate.getType().getQualifier().precision == EpqNone &&
2675         fnCandidate.getParamCount() > 0 && fnCandidate[0].type->getBasicType() == EbtSampler)
2676         callNode.getQualifier().precision = callNode.getSequence()[0]->getAsTyped()->getQualifier().precision;
2677
2678     if (fnCandidate.getName().compare(0, 7, "texture") == 0) {
2679         if (fnCandidate.getName().compare(0, 13, "textureGather") == 0) {
2680             TString featureString = fnCandidate.getName() + "(...)";
2681             const char* feature = featureString.c_str();
2682             profileRequires(loc, EEsProfile, 310, nullptr, feature);
2683
2684             int compArg = -1;  // track which argument, if any, is the constant component argument
2685             if (fnCandidate.getName().compare("textureGatherOffset") == 0) {
2686                 // GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument
2687                 if (fnCandidate[0].type->getSampler().dim == Esd2D && ! fnCandidate[0].type->getSampler().shadow && fnCandidate.getParamCount() == 3)
2688                     profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_texture_gather, feature);
2689                 else
2690                     profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
2691                 int offsetArg = fnCandidate[0].type->getSampler().shadow ? 3 : 2;
2692                 if (! callNode.getSequence()[offsetArg]->getAsConstantUnion())
2693                     profileRequires(loc, EEsProfile, 320, Num_AEP_gpu_shader5, AEP_gpu_shader5,
2694                                     "non-constant offset argument");
2695                 if (! fnCandidate[0].type->getSampler().shadow)
2696                     compArg = 3;
2697             } else if (fnCandidate.getName().compare("textureGatherOffsets") == 0) {
2698                 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
2699                 if (! fnCandidate[0].type->getSampler().shadow)
2700                     compArg = 3;
2701                 // check for constant offsets
2702                 int offsetArg = fnCandidate[0].type->getSampler().shadow ? 3 : 2;
2703                 if (! callNode.getSequence()[offsetArg]->getAsConstantUnion())
2704                     error(loc, "must be a compile-time constant:", feature, "offsets argument");
2705             } else if (fnCandidate.getName().compare("textureGather") == 0) {
2706                 // More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5,
2707                 // otherwise, need GL_ARB_texture_gather.
2708                 if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect || fnCandidate[0].type->getSampler().shadow) {
2709                     profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
2710                     if (! fnCandidate[0].type->getSampler().shadow)
2711                         compArg = 2;
2712                 } else
2713                     profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_texture_gather, feature);
2714             }
2715
2716             if (compArg > 0 && compArg < fnCandidate.getParamCount()) {
2717                 if (callNode.getSequence()[compArg]->getAsConstantUnion()) {
2718                     int value = callNode.getSequence()[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst();
2719                     if (value < 0 || value > 3)
2720                         error(loc, "must be 0, 1, 2, or 3:", feature, "component argument");
2721                 } else
2722                     error(loc, "must be a compile-time constant:", feature, "component argument");
2723             }
2724         } else {
2725             // this is only for functions not starting "textureGather"...
2726             if (fnCandidate.getName().find("Offset") != TString::npos) {
2727
2728                 // Handle texture-offset limits checking
2729                 int arg = -1;
2730                 if (fnCandidate.getName().compare("textureOffset") == 0)
2731                     arg = 2;
2732                 else if (fnCandidate.getName().compare("texelFetchOffset") == 0)
2733                     arg = 3;
2734                 else if (fnCandidate.getName().compare("textureProjOffset") == 0)
2735                     arg = 2;
2736                 else if (fnCandidate.getName().compare("textureLodOffset") == 0)
2737                     arg = 3;
2738                 else if (fnCandidate.getName().compare("textureProjLodOffset") == 0)
2739                     arg = 3;
2740                 else if (fnCandidate.getName().compare("textureGradOffset") == 0)
2741                     arg = 4;
2742                 else if (fnCandidate.getName().compare("textureProjGradOffset") == 0)
2743                     arg = 4;
2744
2745                 if (arg > 0) {
2746                     if (! callNode.getSequence()[arg]->getAsConstantUnion())
2747                         error(loc, "argument must be compile-time constant", "texel offset", "");
2748                     else {
2749                         const TType& type = callNode.getSequence()[arg]->getAsTyped()->getType();
2750                         for (int c = 0; c < type.getVectorSize(); ++c) {
2751                             int offset = callNode.getSequence()[arg]->getAsConstantUnion()->getConstArray()[c].getIConst();
2752                             if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset)
2753                                 error(loc, "value is out of range:", "texel offset", "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]");
2754                         }
2755                     }
2756                 }
2757             }
2758         }
2759     }
2760
2761     // GL_ARB_shader_texture_image_samples
2762     if (fnCandidate.getName().compare(0, 14, "textureSamples") == 0 || fnCandidate.getName().compare(0, 12, "imageSamples") == 0)
2763         profileRequires(loc, ~EEsProfile, 450, E_GL_ARB_shader_texture_image_samples, "textureSamples and imageSamples");
2764
2765     if (fnCandidate.getName().compare(0, 11, "imageAtomic") == 0) {
2766         const TType& imageType = callNode.getSequence()[0]->getAsTyped()->getType();
2767         if (imageType.getSampler().type == EbtInt || imageType.getSampler().type == EbtUint) {
2768             if (imageType.getQualifier().getFormat() != ElfR32i && imageType.getQualifier().getFormat() != ElfR32ui)
2769                 error(loc, "only supported on image with format r32i or r32ui", fnCandidate.getName().c_str(), "");
2770         } else {
2771             if (fnCandidate.getName().compare(0, 19, "imageAtomicExchange") != 0)
2772                 error(loc, "only supported on integer images", fnCandidate.getName().c_str(), "");
2773             else if (imageType.getQualifier().getFormat() != ElfR32f && isEsProfile())
2774                 error(loc, "only supported on image with format r32f", fnCandidate.getName().c_str(), "");
2775         }
2776     }
2777 }
2778
2779 #endif
2780
2781 //
2782 // Do any extra checking for a user function call.
2783 //
2784 void TParseContext::userFunctionCallCheck(const TSourceLoc& loc, TIntermAggregate& callNode)
2785 {
2786     TIntermSequence& arguments = callNode.getSequence();
2787
2788     for (int i = 0; i < (int)arguments.size(); ++i)
2789         samplerConstructorLocationCheck(loc, "call argument", arguments[i]);
2790 }
2791
2792 //
2793 // Emit an error if this is a sampler constructor
2794 //
2795 void TParseContext::samplerConstructorLocationCheck(const TSourceLoc& loc, const char* token, TIntermNode* node)
2796 {
2797     if (node->getAsOperator() && node->getAsOperator()->getOp() == EOpConstructTextureSampler)
2798         error(loc, "sampler constructor must appear at point of use", token, "");
2799 }
2800
2801 //
2802 // Handle seeing a built-in constructor in a grammar production.
2803 //
2804 TFunction* TParseContext::handleConstructorCall(const TSourceLoc& loc, const TPublicType& publicType)
2805 {
2806     TType type(publicType);
2807     type.getQualifier().precision = EpqNone;
2808
2809     if (type.isArray()) {
2810         profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, "arrayed constructor");
2811         profileRequires(loc, EEsProfile, 300, nullptr, "arrayed constructor");
2812     }
2813
2814     TOperator op = intermediate.mapTypeToConstructorOp(type);
2815
2816     if (op == EOpNull) {
2817       if (intermediate.getEnhancedMsgs() && type.getBasicType() == EbtSampler)
2818             error(loc, "function not supported in this version; use texture() instead", "texture*D*", "");
2819         else
2820             error(loc, "cannot construct this type", type.getBasicString(), "");
2821         op = EOpConstructFloat;
2822         TType errorType(EbtFloat);
2823         type.shallowCopy(errorType);
2824     }
2825
2826     TString empty("");
2827
2828     return new TFunction(&empty, type, op);
2829 }
2830
2831 // Handle seeing a precision qualifier in the grammar.
2832 void TParseContext::handlePrecisionQualifier(const TSourceLoc& /*loc*/, TQualifier& qualifier, TPrecisionQualifier precision)
2833 {
2834     if (obeyPrecisionQualifiers())
2835         qualifier.precision = precision;
2836 }
2837
2838 // Check for messages to give on seeing a precision qualifier used in a
2839 // declaration in the grammar.
2840 void TParseContext::checkPrecisionQualifier(const TSourceLoc& loc, TPrecisionQualifier)
2841 {
2842     if (precisionManager.shouldWarnAboutDefaults()) {
2843         warn(loc, "all default precisions are highp; use precision statements to quiet warning, e.g.:\n"
2844                   "         \"precision mediump int; precision highp float;\"", "", "");
2845         precisionManager.defaultWarningGiven();
2846     }
2847 }
2848
2849 //
2850 // Same error message for all places assignments don't work.
2851 //
2852 void TParseContext::assignError(const TSourceLoc& loc, const char* op, TString left, TString right)
2853 {
2854     error(loc, "", op, "cannot convert from '%s' to '%s'",
2855           right.c_str(), left.c_str());
2856 }
2857
2858 //
2859 // Same error message for all places unary operations don't work.
2860 //
2861 void TParseContext::unaryOpError(const TSourceLoc& loc, const char* op, TString operand)
2862 {
2863    error(loc, " wrong operand type", op,
2864           "no operation '%s' exists that takes an operand of type %s (or there is no acceptable conversion)",
2865           op, operand.c_str());
2866 }
2867
2868 //
2869 // Same error message for all binary operations don't work.
2870 //
2871 void TParseContext::binaryOpError(const TSourceLoc& loc, const char* op, TString left, TString right)
2872 {
2873     error(loc, " wrong operand types:", op,
2874             "no operation '%s' exists that takes a left-hand operand of type '%s' and "
2875             "a right operand of type '%s' (or there is no acceptable conversion)",
2876             op, left.c_str(), right.c_str());
2877 }
2878
2879 //
2880 // A basic type of EbtVoid is a key that the name string was seen in the source, but
2881 // it was not found as a variable in the symbol table.  If so, give the error
2882 // message and insert a dummy variable in the symbol table to prevent future errors.
2883 //
2884 void TParseContext::variableCheck(TIntermTyped*& nodePtr)
2885 {
2886     TIntermSymbol* symbol = nodePtr->getAsSymbolNode();
2887     if (! symbol)
2888         return;
2889
2890     if (symbol->getType().getBasicType() == EbtVoid) {
2891         const char *extraInfoFormat = "";
2892         if (spvVersion.vulkan != 0 && symbol->getName() == "gl_VertexID") {
2893           extraInfoFormat = "(Did you mean gl_VertexIndex?)";
2894         } else if (spvVersion.vulkan != 0 && symbol->getName() == "gl_InstanceID") {
2895           extraInfoFormat = "(Did you mean gl_InstanceIndex?)";
2896         }
2897         error(symbol->getLoc(), "undeclared identifier", symbol->getName().c_str(), extraInfoFormat);
2898
2899         // Add to symbol table to prevent future error messages on the same name
2900         if (symbol->getName().size() > 0) {
2901             TVariable* fakeVariable = new TVariable(&symbol->getName(), TType(EbtFloat));
2902             symbolTable.insert(*fakeVariable);
2903
2904             // substitute a symbol node for this new variable
2905             nodePtr = intermediate.addSymbol(*fakeVariable, symbol->getLoc());
2906         }
2907     } else {
2908         switch (symbol->getQualifier().storage) {
2909         case EvqPointCoord:
2910             profileRequires(symbol->getLoc(), ENoProfile, 120, nullptr, "gl_PointCoord");
2911             break;
2912         default: break; // some compilers want this
2913         }
2914     }
2915 }
2916
2917 //
2918 // Both test and if necessary, spit out an error, to see if the node is really
2919 // an l-value that can be operated on this way.
2920 //
2921 // Returns true if there was an error.
2922 //
2923 bool TParseContext::lValueErrorCheck(const TSourceLoc& loc, const char* op, TIntermTyped* node)
2924 {
2925     TIntermBinary* binaryNode = node->getAsBinaryNode();
2926
2927     if (binaryNode) {
2928         bool errorReturn = false;
2929
2930         switch(binaryNode->getOp()) {
2931 #ifndef GLSLANG_WEB
2932         case EOpIndexDirect:
2933         case EOpIndexIndirect:
2934             // ...  tessellation control shader ...
2935             // If a per-vertex output variable is used as an l-value, it is a
2936             // compile-time or link-time error if the expression indicating the
2937             // vertex index is not the identifier gl_InvocationID.
2938             if (language == EShLangTessControl) {
2939                 const TType& leftType = binaryNode->getLeft()->getType();
2940                 if (leftType.getQualifier().storage == EvqVaryingOut && ! leftType.getQualifier().patch && binaryNode->getLeft()->getAsSymbolNode()) {
2941                     // we have a per-vertex output
2942                     const TIntermSymbol* rightSymbol = binaryNode->getRight()->getAsSymbolNode();
2943                     if (! rightSymbol || rightSymbol->getQualifier().builtIn != EbvInvocationId)
2944                         error(loc, "tessellation-control per-vertex output l-value must be indexed with gl_InvocationID", "[]", "");
2945                 }
2946             }
2947             break; // left node is checked by base class
2948 #endif
2949         case EOpVectorSwizzle:
2950             errorReturn = lValueErrorCheck(loc, op, binaryNode->getLeft());
2951             if (!errorReturn) {
2952                 int offset[4] = {0,0,0,0};
2953
2954                 TIntermTyped* rightNode = binaryNode->getRight();
2955                 TIntermAggregate *aggrNode = rightNode->getAsAggregate();
2956
2957                 for (TIntermSequence::iterator p = aggrNode->getSequence().begin();
2958                                                p != aggrNode->getSequence().end(); p++) {
2959                     int value = (*p)->getAsTyped()->getAsConstantUnion()->getConstArray()[0].getIConst();
2960                     offset[value]++;
2961                     if (offset[value] > 1) {
2962                         error(loc, " l-value of swizzle cannot have duplicate components", op, "", "");
2963
2964                         return true;
2965                     }
2966                 }
2967             }
2968
2969             return errorReturn;
2970         default:
2971             break;
2972         }
2973
2974         if (errorReturn) {
2975             error(loc, " l-value required", op, "", "");
2976             return true;
2977         }
2978     }
2979
2980     if (binaryNode && binaryNode->getOp() == EOpIndexDirectStruct && binaryNode->getLeft()->isReference())
2981         return false;
2982
2983     // Let the base class check errors
2984     if (TParseContextBase::lValueErrorCheck(loc, op, node))
2985         return true;
2986
2987     const char* symbol = nullptr;
2988     TIntermSymbol* symNode = node->getAsSymbolNode();
2989     if (symNode != nullptr)
2990         symbol = symNode->getName().c_str();
2991
2992     const char* message = nullptr;
2993     switch (node->getQualifier().storage) {
2994     case EvqVaryingIn:      message = "can't modify shader input";   break;
2995     case EvqInstanceId:     message = "can't modify gl_InstanceID";  break;
2996     case EvqVertexId:       message = "can't modify gl_VertexID";    break;
2997     case EvqFace:           message = "can't modify gl_FrontFace";   break;
2998     case EvqFragCoord:      message = "can't modify gl_FragCoord";   break;
2999     case EvqPointCoord:     message = "can't modify gl_PointCoord";  break;
3000     case EvqFragDepth:
3001         intermediate.setDepthReplacing();
3002         // "In addition, it is an error to statically write to gl_FragDepth in the fragment shader."
3003         if (isEsProfile() && intermediate.getEarlyFragmentTests())
3004             message = "can't modify gl_FragDepth if using early_fragment_tests";
3005         break;
3006     case EvqFragStencil:
3007         intermediate.setStencilReplacing();
3008         // "In addition, it is an error to statically write to gl_FragDepth in the fragment shader."
3009         if (isEsProfile() && intermediate.getEarlyFragmentTests())
3010             message = "can't modify EvqFragStencil if using early_fragment_tests";
3011         break;
3012
3013     case EvqtaskPayloadSharedEXT:
3014         if (language == EShLangMesh)
3015             message = "can't modify variable with storage qualifier taskPayloadSharedEXT in mesh shaders";
3016         break;
3017     default:
3018         break;
3019     }
3020
3021     if (message == nullptr && binaryNode == nullptr && symNode == nullptr) {
3022         error(loc, " l-value required", op, "", "");
3023
3024         return true;
3025     }
3026
3027     //
3028     // Everything else is okay, no error.
3029     //
3030     if (message == nullptr)
3031         return false;
3032
3033     //
3034     // If we get here, we have an error and a message.
3035     //
3036     if (symNode)
3037         error(loc, " l-value required", op, "\"%s\" (%s)", symbol, message);
3038     else
3039         error(loc, " l-value required", op, "(%s)", message);
3040
3041     return true;
3042 }
3043
3044 // Test for and give an error if the node can't be read from.
3045 void TParseContext::rValueErrorCheck(const TSourceLoc& loc, const char* op, TIntermTyped* node)
3046 {
3047     // Let the base class check errors
3048     TParseContextBase::rValueErrorCheck(loc, op, node);
3049
3050     TIntermSymbol* symNode = node->getAsSymbolNode();
3051     if (!(symNode && symNode->getQualifier().isWriteOnly())) // base class checks
3052         if (symNode && symNode->getQualifier().isExplicitInterpolation())
3053             error(loc, "can't read from explicitly-interpolated object: ", op, symNode->getName().c_str());
3054
3055     // local_size_{xyz} must be assigned or specialized before gl_WorkGroupSize can be assigned.
3056     if(node->getQualifier().builtIn == EbvWorkGroupSize &&
3057        !(intermediate.isLocalSizeSet() || intermediate.isLocalSizeSpecialized()))
3058         error(loc, "can't read from gl_WorkGroupSize before a fixed workgroup size has been declared", op, "");
3059 }
3060
3061 //
3062 // Both test, and if necessary spit out an error, to see if the node is really
3063 // a constant.
3064 //
3065 void TParseContext::constantValueCheck(TIntermTyped* node, const char* token)
3066 {
3067     if (! node->getQualifier().isConstant())
3068         error(node->getLoc(), "constant expression required", token, "");
3069 }
3070
3071 //
3072 // Both test, and if necessary spit out an error, to see if the node is really
3073 // a 32-bit integer or can implicitly convert to one.
3074 //
3075 void TParseContext::integerCheck(const TIntermTyped* node, const char* token)
3076 {
3077     auto from_type = node->getBasicType();
3078     if ((from_type == EbtInt || from_type == EbtUint ||
3079          intermediate.canImplicitlyPromote(from_type, EbtInt, EOpNull) ||
3080          intermediate.canImplicitlyPromote(from_type, EbtUint, EOpNull)) && node->isScalar())
3081         return;
3082
3083     error(node->getLoc(), "scalar integer expression required", token, "");
3084 }
3085
3086 //
3087 // Both test, and if necessary spit out an error, to see if we are currently
3088 // globally scoped.
3089 //
3090 void TParseContext::globalCheck(const TSourceLoc& loc, const char* token)
3091 {
3092     if (! symbolTable.atGlobalLevel())
3093         error(loc, "not allowed in nested scope", token, "");
3094 }
3095
3096 //
3097 // Reserved errors for GLSL.
3098 //
3099 void TParseContext::reservedErrorCheck(const TSourceLoc& loc, const TString& identifier)
3100 {
3101     // "Identifiers starting with "gl_" are reserved for use by OpenGL, and may not be
3102     // declared in a shader; this results in a compile-time error."
3103     if (! symbolTable.atBuiltInLevel()) {
3104         if (builtInName(identifier) && !extensionTurnedOn(E_GL_EXT_spirv_intrinsics))
3105             // The extension GL_EXT_spirv_intrinsics allows us to declare identifiers starting with "gl_".
3106             error(loc, "identifiers starting with \"gl_\" are reserved", identifier.c_str(), "");
3107
3108         // "__" are not supposed to be an error.  ES 300 (and desktop) added the clarification:
3109         // "In addition, all identifiers containing two consecutive underscores (__) are
3110         // reserved; using such a name does not itself result in an error, but may result
3111         // in undefined behavior."
3112         // however, before that, ES tests required an error.
3113         if (identifier.find("__") != TString::npos && !extensionTurnedOn(E_GL_EXT_spirv_intrinsics)) {
3114             // The extension GL_EXT_spirv_intrinsics allows us to declare identifiers starting with "__".
3115             if (isEsProfile() && version < 300)
3116                 error(loc, "identifiers containing consecutive underscores (\"__\") are reserved, and an error if version < 300", identifier.c_str(), "");
3117             else
3118                 warn(loc, "identifiers containing consecutive underscores (\"__\") are reserved", identifier.c_str(), "");
3119         }
3120     }
3121 }
3122
3123 //
3124 // Reserved errors for the preprocessor.
3125 //
3126 void TParseContext::reservedPpErrorCheck(const TSourceLoc& loc, const char* identifier, const char* op)
3127 {
3128     // "__" are not supposed to be an error.  ES 300 (and desktop) added the clarification:
3129     // "All macro names containing two consecutive underscores ( __ ) are reserved;
3130     // defining such a name does not itself result in an error, but may result in
3131     // undefined behavior.  All macro names prefixed with "GL_" ("GL" followed by a
3132     // single underscore) are also reserved, and defining such a name results in a
3133     // compile-time error."
3134     // however, before that, ES tests required an error.
3135     if (strncmp(identifier, "GL_", 3) == 0 && !extensionTurnedOn(E_GL_EXT_spirv_intrinsics))
3136         // The extension GL_EXT_spirv_intrinsics allows us to declare macros prefixed with "GL_".
3137         ppError(loc, "names beginning with \"GL_\" can't be (un)defined:", op,  identifier);
3138     else if (strncmp(identifier, "defined", 8) == 0)
3139         if (relaxedErrors())
3140             ppWarn(loc, "\"defined\" is (un)defined:", op,  identifier);
3141         else
3142             ppError(loc, "\"defined\" can't be (un)defined:", op,  identifier);
3143     else if (strstr(identifier, "__") != 0 && !extensionTurnedOn(E_GL_EXT_spirv_intrinsics)) {
3144         // The extension GL_EXT_spirv_intrinsics allows us to declare macros prefixed with "__".
3145         if (isEsProfile() && version >= 300 &&
3146             (strcmp(identifier, "__LINE__") == 0 ||
3147              strcmp(identifier, "__FILE__") == 0 ||
3148              strcmp(identifier, "__VERSION__") == 0))
3149             ppError(loc, "predefined names can't be (un)defined:", op,  identifier);
3150         else {
3151             if (isEsProfile() && version < 300 && !relaxedErrors())
3152                 ppError(loc, "names containing consecutive underscores are reserved, and an error if version < 300:", op, identifier);
3153             else
3154                 ppWarn(loc, "names containing consecutive underscores are reserved:", op, identifier);
3155         }
3156     }
3157 }
3158
3159 //
3160 // See if this version/profile allows use of the line-continuation character '\'.
3161 //
3162 // Returns true if a line continuation should be done.
3163 //
3164 bool TParseContext::lineContinuationCheck(const TSourceLoc& loc, bool endOfComment)
3165 {
3166 #ifdef GLSLANG_WEB
3167     return true;
3168 #endif
3169
3170     const char* message = "line continuation";
3171
3172     bool lineContinuationAllowed = (isEsProfile() && version >= 300) ||
3173                                    (!isEsProfile() && (version >= 420 || extensionTurnedOn(E_GL_ARB_shading_language_420pack)));
3174
3175     if (endOfComment) {
3176         if (lineContinuationAllowed)
3177             warn(loc, "used at end of comment; the following line is still part of the comment", message, "");
3178         else
3179             warn(loc, "used at end of comment, but this version does not provide line continuation", message, "");
3180
3181         return lineContinuationAllowed;
3182     }
3183
3184     if (relaxedErrors()) {
3185         if (! lineContinuationAllowed)
3186             warn(loc, "not allowed in this version", message, "");
3187         return true;
3188     } else {
3189         profileRequires(loc, EEsProfile, 300, nullptr, message);
3190         profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, message);
3191     }
3192
3193     return lineContinuationAllowed;
3194 }
3195
3196 bool TParseContext::builtInName(const TString& identifier)
3197 {
3198     return identifier.compare(0, 3, "gl_") == 0;
3199 }
3200
3201 //
3202 // Make sure there is enough data and not too many arguments provided to the
3203 // constructor to build something of the type of the constructor.  Also returns
3204 // the type of the constructor.
3205 //
3206 // Part of establishing type is establishing specialization-constness.
3207 // We don't yet know "top down" whether type is a specialization constant,
3208 // but a const constructor can becomes a specialization constant if any of
3209 // its children are, subject to KHR_vulkan_glsl rules:
3210 //
3211 //     - int(), uint(), and bool() constructors for type conversions
3212 //       from any of the following types to any of the following types:
3213 //         * int
3214 //         * uint
3215 //         * bool
3216 //     - vector versions of the above conversion constructors
3217 //
3218 // Returns true if there was an error in construction.
3219 //
3220 bool TParseContext::constructorError(const TSourceLoc& loc, TIntermNode* node, TFunction& function, TOperator op, TType& type)
3221 {
3222     // See if the constructor does not establish the main type, only requalifies
3223     // it, in which case the type comes from the argument instead of from the
3224     // constructor function.
3225     switch (op) {
3226 #ifndef GLSLANG_WEB
3227     case EOpConstructNonuniform:
3228         if (node != nullptr && node->getAsTyped() != nullptr) {
3229             type.shallowCopy(node->getAsTyped()->getType());
3230             type.getQualifier().makeTemporary();
3231             type.getQualifier().nonUniform = true;
3232         }
3233         break;
3234 #endif
3235     default:
3236         type.shallowCopy(function.getType());
3237         break;
3238     }
3239
3240     TString constructorString;
3241     if (intermediate.getEnhancedMsgs())
3242         constructorString.append(type.getCompleteString(true, false, false, true)).append(" constructor");
3243     else
3244         constructorString.append("constructor");
3245
3246     // See if it's a matrix
3247     bool constructingMatrix = false;
3248     switch (op) {
3249     case EOpConstructTextureSampler:
3250         return constructorTextureSamplerError(loc, function);
3251     case EOpConstructMat2x2:
3252     case EOpConstructMat2x3:
3253     case EOpConstructMat2x4:
3254     case EOpConstructMat3x2:
3255     case EOpConstructMat3x3:
3256     case EOpConstructMat3x4:
3257     case EOpConstructMat4x2:
3258     case EOpConstructMat4x3:
3259     case EOpConstructMat4x4:
3260 #ifndef GLSLANG_WEB
3261     case EOpConstructDMat2x2:
3262     case EOpConstructDMat2x3:
3263     case EOpConstructDMat2x4:
3264     case EOpConstructDMat3x2:
3265     case EOpConstructDMat3x3:
3266     case EOpConstructDMat3x4:
3267     case EOpConstructDMat4x2:
3268     case EOpConstructDMat4x3:
3269     case EOpConstructDMat4x4:
3270     case EOpConstructF16Mat2x2:
3271     case EOpConstructF16Mat2x3:
3272     case EOpConstructF16Mat2x4:
3273     case EOpConstructF16Mat3x2:
3274     case EOpConstructF16Mat3x3:
3275     case EOpConstructF16Mat3x4:
3276     case EOpConstructF16Mat4x2:
3277     case EOpConstructF16Mat4x3:
3278     case EOpConstructF16Mat4x4:
3279 #endif
3280         constructingMatrix = true;
3281         break;
3282     default:
3283         break;
3284     }
3285
3286     //
3287     // Walk the arguments for first-pass checks and collection of information.
3288     //
3289
3290     int size = 0;
3291     bool constType = true;
3292     bool specConstType = false;   // value is only valid if constType is true
3293     bool full = false;
3294     bool overFull = false;
3295     bool matrixInMatrix = false;
3296     bool arrayArg = false;
3297     bool floatArgument = false;
3298     bool intArgument = false;
3299     for (int arg = 0; arg < function.getParamCount(); ++arg) {
3300         if (function[arg].type->isArray()) {
3301             if (function[arg].type->isUnsizedArray()) {
3302                 // Can't construct from an unsized array.
3303                 error(loc, "array argument must be sized", constructorString.c_str(), "");
3304                 return true;
3305             }
3306             arrayArg = true;
3307         }
3308         if (constructingMatrix && function[arg].type->isMatrix())
3309             matrixInMatrix = true;
3310
3311         // 'full' will go to true when enough args have been seen.  If we loop
3312         // again, there is an extra argument.
3313         if (full) {
3314             // For vectors and matrices, it's okay to have too many components
3315             // available, but not okay to have unused arguments.
3316             overFull = true;
3317         }
3318
3319         size += function[arg].type->computeNumComponents();
3320         if (op != EOpConstructStruct && ! type.isArray() && size >= type.computeNumComponents())
3321             full = true;
3322
3323         if (! function[arg].type->getQualifier().isConstant())
3324             constType = false;
3325         if (function[arg].type->getQualifier().isSpecConstant())
3326             specConstType = true;
3327         if (function[arg].type->isFloatingDomain())
3328             floatArgument = true;
3329         if (function[arg].type->isIntegerDomain())
3330             intArgument = true;
3331         if (type.isStruct()) {
3332             if (function[arg].type->contains16BitFloat()) {
3333                 requireFloat16Arithmetic(loc, constructorString.c_str(), "can't construct structure containing 16-bit type");
3334             }
3335             if (function[arg].type->contains16BitInt()) {
3336                 requireInt16Arithmetic(loc, constructorString.c_str(), "can't construct structure containing 16-bit type");
3337             }
3338             if (function[arg].type->contains8BitInt()) {
3339                 requireInt8Arithmetic(loc, constructorString.c_str(), "can't construct structure containing 8-bit type");
3340             }
3341         }
3342     }
3343     if (op == EOpConstructNonuniform)
3344         constType = false;
3345
3346 #ifndef GLSLANG_WEB
3347     switch (op) {
3348     case EOpConstructFloat16:
3349     case EOpConstructF16Vec2:
3350     case EOpConstructF16Vec3:
3351     case EOpConstructF16Vec4:
3352         if (type.isArray())
3353             requireFloat16Arithmetic(loc, constructorString.c_str(), "16-bit arrays not supported");
3354         if (type.isVector() && function.getParamCount() != 1)
3355             requireFloat16Arithmetic(loc, constructorString.c_str(), "16-bit vectors only take vector types");
3356         break;
3357     case EOpConstructUint16:
3358     case EOpConstructU16Vec2:
3359     case EOpConstructU16Vec3:
3360     case EOpConstructU16Vec4:
3361     case EOpConstructInt16:
3362     case EOpConstructI16Vec2:
3363     case EOpConstructI16Vec3:
3364     case EOpConstructI16Vec4:
3365         if (type.isArray())
3366             requireInt16Arithmetic(loc, constructorString.c_str(), "16-bit arrays not supported");
3367         if (type.isVector() && function.getParamCount() != 1)
3368             requireInt16Arithmetic(loc, constructorString.c_str(), "16-bit vectors only take vector types");
3369         break;
3370     case EOpConstructUint8:
3371     case EOpConstructU8Vec2:
3372     case EOpConstructU8Vec3:
3373     case EOpConstructU8Vec4:
3374     case EOpConstructInt8:
3375     case EOpConstructI8Vec2:
3376     case EOpConstructI8Vec3:
3377     case EOpConstructI8Vec4:
3378         if (type.isArray())
3379             requireInt8Arithmetic(loc, constructorString.c_str(), "8-bit arrays not supported");
3380         if (type.isVector() && function.getParamCount() != 1)
3381             requireInt8Arithmetic(loc, constructorString.c_str(), "8-bit vectors only take vector types");
3382         break;
3383     default:
3384         break;
3385     }
3386 #endif
3387
3388     // inherit constness from children
3389     if (constType) {
3390         bool makeSpecConst;
3391         // Finish pinning down spec-const semantics
3392         if (specConstType) {
3393             switch (op) {
3394             case EOpConstructInt8:
3395             case EOpConstructInt:
3396             case EOpConstructUint:
3397             case EOpConstructBool:
3398             case EOpConstructBVec2:
3399             case EOpConstructBVec3:
3400             case EOpConstructBVec4:
3401             case EOpConstructIVec2:
3402             case EOpConstructIVec3:
3403             case EOpConstructIVec4:
3404             case EOpConstructUVec2:
3405             case EOpConstructUVec3:
3406             case EOpConstructUVec4:
3407 #ifndef GLSLANG_WEB
3408             case EOpConstructUint8:
3409             case EOpConstructInt16:
3410             case EOpConstructUint16:
3411             case EOpConstructInt64:
3412             case EOpConstructUint64:
3413             case EOpConstructI8Vec2:
3414             case EOpConstructI8Vec3:
3415             case EOpConstructI8Vec4:
3416             case EOpConstructU8Vec2:
3417             case EOpConstructU8Vec3:
3418             case EOpConstructU8Vec4:
3419             case EOpConstructI16Vec2:
3420             case EOpConstructI16Vec3:
3421             case EOpConstructI16Vec4:
3422             case EOpConstructU16Vec2:
3423             case EOpConstructU16Vec3:
3424             case EOpConstructU16Vec4:
3425             case EOpConstructI64Vec2:
3426             case EOpConstructI64Vec3:
3427             case EOpConstructI64Vec4:
3428             case EOpConstructU64Vec2:
3429             case EOpConstructU64Vec3:
3430             case EOpConstructU64Vec4:
3431 #endif
3432                 // This was the list of valid ones, if they aren't converting from float
3433                 // and aren't making an array.
3434                 makeSpecConst = ! floatArgument && ! type.isArray();
3435                 break;
3436
3437             case EOpConstructVec2:
3438             case EOpConstructVec3:
3439             case EOpConstructVec4:
3440                 // This was the list of valid ones, if they aren't converting from int
3441                 // and aren't making an array.
3442                 makeSpecConst = ! intArgument && !type.isArray();
3443                 break;
3444
3445             default:
3446                 // anything else wasn't white-listed in the spec as a conversion
3447                 makeSpecConst = false;
3448                 break;
3449             }
3450         } else
3451             makeSpecConst = false;
3452
3453         if (makeSpecConst)
3454             type.getQualifier().makeSpecConstant();
3455         else if (specConstType)
3456             type.getQualifier().makeTemporary();
3457         else
3458             type.getQualifier().storage = EvqConst;
3459     }
3460
3461     if (type.isArray()) {
3462         if (function.getParamCount() == 0) {
3463             error(loc, "array constructor must have at least one argument", constructorString.c_str(), "");
3464             return true;
3465         }
3466
3467         if (type.isUnsizedArray()) {
3468             // auto adapt the constructor type to the number of arguments
3469             type.changeOuterArraySize(function.getParamCount());
3470         } else if (type.getOuterArraySize() != function.getParamCount()) {
3471             error(loc, "array constructor needs one argument per array element", constructorString.c_str(), "");
3472             return true;
3473         }
3474
3475         if (type.isArrayOfArrays()) {
3476             // Types have to match, but we're still making the type.
3477             // Finish making the type, and the comparison is done later
3478             // when checking for conversion.
3479             TArraySizes& arraySizes = *type.getArraySizes();
3480
3481             // At least the dimensionalities have to match.
3482             if (! function[0].type->isArray() ||
3483                     arraySizes.getNumDims() != function[0].type->getArraySizes()->getNumDims() + 1) {
3484                 error(loc, "array constructor argument not correct type to construct array element", constructorString.c_str(), "");
3485                 return true;
3486             }
3487
3488             if (arraySizes.isInnerUnsized()) {
3489                 // "Arrays of arrays ..., and the size for any dimension is optional"
3490                 // That means we need to adopt (from the first argument) the other array sizes into the type.
3491                 for (int d = 1; d < arraySizes.getNumDims(); ++d) {
3492                     if (arraySizes.getDimSize(d) == UnsizedArraySize) {
3493                         arraySizes.setDimSize(d, function[0].type->getArraySizes()->getDimSize(d - 1));
3494                     }
3495                 }
3496             }
3497         }
3498     }
3499
3500     if (arrayArg && op != EOpConstructStruct && ! type.isArrayOfArrays()) {
3501         error(loc, "constructing non-array constituent from array argument", constructorString.c_str(), "");
3502         return true;
3503     }
3504
3505     if (matrixInMatrix && ! type.isArray()) {
3506         profileRequires(loc, ENoProfile, 120, nullptr, "constructing matrix from matrix");
3507
3508         // "If a matrix argument is given to a matrix constructor,
3509         // it is a compile-time error to have any other arguments."
3510         if (function.getParamCount() != 1)
3511             error(loc, "matrix constructed from matrix can only have one argument", constructorString.c_str(), "");
3512         return false;
3513     }
3514
3515     if (overFull) {
3516         error(loc, "too many arguments", constructorString.c_str(), "");
3517         return true;
3518     }
3519
3520     if (op == EOpConstructStruct && ! type.isArray() && (int)type.getStruct()->size() != function.getParamCount()) {
3521         error(loc, "Number of constructor parameters does not match the number of structure fields", constructorString.c_str(), "");
3522         return true;
3523     }
3524
3525     if ((op != EOpConstructStruct && size != 1 && size < type.computeNumComponents()) ||
3526         (op == EOpConstructStruct && size < type.computeNumComponents())) {
3527         error(loc, "not enough data provided for construction", constructorString.c_str(), "");
3528         return true;
3529     }
3530
3531     if (type.isCoopMat() && function.getParamCount() != 1) {
3532         error(loc, "wrong number of arguments", constructorString.c_str(), "");
3533         return true;
3534     }
3535     if (type.isCoopMat() &&
3536         !(function[0].type->isScalar() || function[0].type->isCoopMat())) {
3537         error(loc, "Cooperative matrix constructor argument must be scalar or cooperative matrix", constructorString.c_str(), "");
3538         return true;
3539     }
3540
3541     TIntermTyped* typed = node->getAsTyped();
3542     if (typed == nullptr) {
3543         error(loc, "constructor argument does not have a type", constructorString.c_str(), "");
3544         return true;
3545     }
3546     if (op != EOpConstructStruct && op != EOpConstructNonuniform && typed->getBasicType() == EbtSampler) {
3547         error(loc, "cannot convert a sampler", constructorString.c_str(), "");
3548         return true;
3549     }
3550     if (op != EOpConstructStruct && typed->isAtomic()) {
3551         error(loc, "cannot convert an atomic_uint", constructorString.c_str(), "");
3552         return true;
3553     }
3554     if (typed->getBasicType() == EbtVoid) {
3555         error(loc, "cannot convert a void", constructorString.c_str(), "");
3556         return true;
3557     }
3558
3559     return false;
3560 }
3561
3562 // Verify all the correct semantics for constructing a combined texture/sampler.
3563 // Return true if the semantics are incorrect.
3564 bool TParseContext::constructorTextureSamplerError(const TSourceLoc& loc, const TFunction& function)
3565 {
3566     TString constructorName = function.getType().getBasicTypeString();  // TODO: performance: should not be making copy; interface needs to change
3567     const char* token = constructorName.c_str();
3568
3569     // exactly two arguments needed
3570     if (function.getParamCount() != 2) {
3571         error(loc, "sampler-constructor requires two arguments", token, "");
3572         return true;
3573     }
3574
3575     // For now, not allowing arrayed constructors, the rest of this function
3576     // is set up to allow them, if this test is removed:
3577     if (function.getType().isArray()) {
3578         error(loc, "sampler-constructor cannot make an array of samplers", token, "");
3579         return true;
3580     }
3581
3582     // first argument
3583     //  * the constructor's first argument must be a texture type
3584     //  * the dimensionality (1D, 2D, 3D, Cube, Rect, Buffer, MS, and Array)
3585     //    of the texture type must match that of the constructed sampler type
3586     //    (that is, the suffixes of the type of the first argument and the
3587     //    type of the constructor will be spelled the same way)
3588     if (function[0].type->getBasicType() != EbtSampler ||
3589         ! function[0].type->getSampler().isTexture() ||
3590         function[0].type->isArray()) {
3591         error(loc, "sampler-constructor first argument must be a scalar *texture* type", token, "");
3592         return true;
3593     }
3594     // simulate the first argument's impact on the result type, so it can be compared with the encapsulated operator!=()
3595     TSampler texture = function.getType().getSampler();
3596     texture.setCombined(false);
3597     texture.shadow = false;
3598     if (texture != function[0].type->getSampler()) {
3599         error(loc, "sampler-constructor first argument must be a *texture* type"
3600                    " matching the dimensionality and sampled type of the constructor", token, "");
3601         return true;
3602     }
3603
3604     // second argument
3605     //   * the constructor's second argument must be a scalar of type
3606     //     *sampler* or *samplerShadow*
3607     if (  function[1].type->getBasicType() != EbtSampler ||
3608         ! function[1].type->getSampler().isPureSampler() ||
3609           function[1].type->isArray()) {
3610         error(loc, "sampler-constructor second argument must be a scalar sampler or samplerShadow", token, "");
3611         return true;
3612     }
3613
3614     return false;
3615 }
3616
3617 // Checks to see if a void variable has been declared and raise an error message for such a case
3618 //
3619 // returns true in case of an error
3620 //
3621 bool TParseContext::voidErrorCheck(const TSourceLoc& loc, const TString& identifier, const TBasicType basicType)
3622 {
3623     if (basicType == EbtVoid) {
3624         error(loc, "illegal use of type 'void'", identifier.c_str(), "");
3625         return true;
3626     }
3627
3628     return false;
3629 }
3630
3631 // Checks to see if the node (for the expression) contains a scalar boolean expression or not
3632 void TParseContext::boolCheck(const TSourceLoc& loc, const TIntermTyped* type)
3633 {
3634     if (type->getBasicType() != EbtBool || type->isArray() || type->isMatrix() || type->isVector())
3635         error(loc, "boolean expression expected", "", "");
3636 }
3637
3638 // This function checks to see if the node (for the expression) contains a scalar boolean expression or not
3639 void TParseContext::boolCheck(const TSourceLoc& loc, const TPublicType& pType)
3640 {
3641     if (pType.basicType != EbtBool || pType.arraySizes || pType.matrixCols > 1 || (pType.vectorSize > 1))
3642         error(loc, "boolean expression expected", "", "");
3643 }
3644
3645 void TParseContext::samplerCheck(const TSourceLoc& loc, const TType& type, const TString& identifier, TIntermTyped* /*initializer*/)
3646 {
3647     // Check that the appropriate extension is enabled if external sampler is used.
3648     // There are two extensions. The correct one must be used based on GLSL version.
3649     if (type.getBasicType() == EbtSampler && type.getSampler().isExternal()) {
3650         if (version < 300) {
3651             requireExtensions(loc, 1, &E_GL_OES_EGL_image_external, "samplerExternalOES");
3652         } else {
3653             requireExtensions(loc, 1, &E_GL_OES_EGL_image_external_essl3, "samplerExternalOES");
3654         }
3655     }
3656     if (type.getSampler().isYuv()) {
3657         requireExtensions(loc, 1, &E_GL_EXT_YUV_target, "__samplerExternal2DY2YEXT");
3658     }
3659
3660     if (type.getQualifier().storage == EvqUniform)
3661         return;
3662
3663     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtSampler))
3664         error(loc, "non-uniform struct contains a sampler or image:", type.getBasicTypeString().c_str(), identifier.c_str());
3665     else if (type.getBasicType() == EbtSampler && type.getQualifier().storage != EvqUniform) {
3666         // non-uniform sampler
3667         // not yet:  okay if it has an initializer
3668         // if (! initializer)
3669         error(loc, "sampler/image types can only be used in uniform variables or function parameters:", type.getBasicTypeString().c_str(), identifier.c_str());
3670     }
3671 }
3672
3673 #ifndef GLSLANG_WEB
3674
3675 void TParseContext::atomicUintCheck(const TSourceLoc& loc, const TType& type, const TString& identifier)
3676 {
3677     if (type.getQualifier().storage == EvqUniform)
3678         return;
3679
3680     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtAtomicUint))
3681         error(loc, "non-uniform struct contains an atomic_uint:", type.getBasicTypeString().c_str(), identifier.c_str());
3682     else if (type.getBasicType() == EbtAtomicUint && type.getQualifier().storage != EvqUniform)
3683         error(loc, "atomic_uints can only be used in uniform variables or function parameters:", type.getBasicTypeString().c_str(), identifier.c_str());
3684 }
3685
3686 void TParseContext::accStructCheck(const TSourceLoc& loc, const TType& type, const TString& identifier)
3687 {
3688     if (type.getQualifier().storage == EvqUniform)
3689         return;
3690
3691     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtAccStruct))
3692         error(loc, "non-uniform struct contains an accelerationStructureNV:", type.getBasicTypeString().c_str(), identifier.c_str());
3693     else if (type.getBasicType() == EbtAccStruct && type.getQualifier().storage != EvqUniform)
3694         error(loc, "accelerationStructureNV can only be used in uniform variables or function parameters:",
3695             type.getBasicTypeString().c_str(), identifier.c_str());
3696
3697 }
3698
3699 #endif // GLSLANG_WEB
3700
3701 void TParseContext::transparentOpaqueCheck(const TSourceLoc& loc, const TType& type, const TString& identifier)
3702 {
3703     if (parsingBuiltins)
3704         return;
3705
3706     if (type.getQualifier().storage != EvqUniform)
3707         return;
3708
3709     if (type.containsNonOpaque()) {
3710         // Vulkan doesn't allow transparent uniforms outside of blocks
3711         if (spvVersion.vulkan > 0 && !spvVersion.vulkanRelaxed)
3712             vulkanRemoved(loc, "non-opaque uniforms outside a block");
3713         // OpenGL wants locations on these (unless they are getting automapped)
3714         if (spvVersion.openGl > 0 && !type.getQualifier().hasLocation() && !intermediate.getAutoMapLocations())
3715             error(loc, "non-opaque uniform variables need a layout(location=L)", identifier.c_str(), "");
3716     }
3717 }
3718
3719 //
3720 // Qualifier checks knowing the qualifier and that it is a member of a struct/block.
3721 //
3722 void TParseContext::memberQualifierCheck(glslang::TPublicType& publicType)
3723 {
3724     globalQualifierFixCheck(publicType.loc, publicType.qualifier, true);
3725     checkNoShaderLayouts(publicType.loc, publicType.shaderQualifiers);
3726     if (publicType.qualifier.isNonUniform()) {
3727         error(publicType.loc, "not allowed on block or structure members", "nonuniformEXT", "");
3728         publicType.qualifier.nonUniform = false;
3729     }
3730 }
3731
3732 //
3733 // Check/fix just a full qualifier (no variables or types yet, but qualifier is complete) at global level.
3734 //
3735 void TParseContext::globalQualifierFixCheck(const TSourceLoc& loc, TQualifier& qualifier, bool isMemberCheck)
3736 {
3737     bool nonuniformOkay = false;
3738
3739     // move from parameter/unknown qualifiers to pipeline in/out qualifiers
3740     switch (qualifier.storage) {
3741     case EvqIn:
3742         profileRequires(loc, ENoProfile, 130, nullptr, "in for stage inputs");
3743         profileRequires(loc, EEsProfile, 300, nullptr, "in for stage inputs");
3744         qualifier.storage = EvqVaryingIn;
3745         nonuniformOkay = true;
3746         break;
3747     case EvqOut:
3748         profileRequires(loc, ENoProfile, 130, nullptr, "out for stage outputs");
3749         profileRequires(loc, EEsProfile, 300, nullptr, "out for stage outputs");
3750         qualifier.storage = EvqVaryingOut;
3751         if (intermediate.isInvariantAll())
3752             qualifier.invariant = true;
3753         break;
3754     case EvqInOut:
3755         qualifier.storage = EvqVaryingIn;
3756         error(loc, "cannot use 'inout' at global scope", "", "");
3757         break;
3758     case EvqGlobal:
3759     case EvqTemporary:
3760         nonuniformOkay = true;
3761         break;
3762     case EvqUniform:
3763         // According to GLSL spec: The std430 qualifier is supported only for shader storage blocks; a shader using
3764         // the std430 qualifier on a uniform block will fail to compile.
3765         // Only check the global declaration: layout(std430) uniform;
3766         if (blockName == nullptr &&
3767             qualifier.layoutPacking == ElpStd430)
3768         {
3769             requireExtensions(loc, 1, &E_GL_EXT_scalar_block_layout, "default std430 layout for uniform");
3770         }
3771         break;
3772     default:
3773         break;
3774     }
3775
3776     if (!nonuniformOkay && qualifier.isNonUniform())
3777         error(loc, "for non-parameter, can only apply to 'in' or no storage qualifier", "nonuniformEXT", "");
3778
3779 #ifndef GLSLANG_WEB
3780     if (qualifier.isSpirvByReference())
3781         error(loc, "can only apply to parameter", "spirv_by_reference", "");
3782
3783     if (qualifier.isSpirvLiteral())
3784         error(loc, "can only apply to parameter", "spirv_literal", "");
3785 #endif
3786
3787     // Storage qualifier isn't ready for memberQualifierCheck, we should skip invariantCheck for it.
3788     if (!isMemberCheck || structNestingLevel > 0)
3789         invariantCheck(loc, qualifier);
3790 }
3791
3792 //
3793 // Check a full qualifier and type (no variable yet) at global level.
3794 //
3795 void TParseContext::globalQualifierTypeCheck(const TSourceLoc& loc, const TQualifier& qualifier, const TPublicType& publicType)
3796 {
3797     if (! symbolTable.atGlobalLevel())
3798         return;
3799
3800     if (!(publicType.userDef && publicType.userDef->isReference()) && !parsingBuiltins) {
3801         if (qualifier.isMemoryQualifierImageAndSSBOOnly() && ! publicType.isImage() && publicType.qualifier.storage != EvqBuffer) {
3802             error(loc, "memory qualifiers cannot be used on this type", "", "");
3803         } else if (qualifier.isMemory() && (publicType.basicType != EbtSampler) && !publicType.qualifier.isUniformOrBuffer()) {
3804             error(loc, "memory qualifiers cannot be used on this type", "", "");
3805         }
3806     }
3807
3808     if (qualifier.storage == EvqBuffer &&
3809         publicType.basicType != EbtBlock &&
3810         !qualifier.hasBufferReference())
3811         error(loc, "buffers can be declared only as blocks", "buffer", "");
3812
3813     if (qualifier.storage != EvqVaryingIn && publicType.basicType == EbtDouble &&
3814         extensionTurnedOn(E_GL_ARB_vertex_attrib_64bit) && language == EShLangVertex &&
3815         version < 400) {
3816         profileRequires(loc, ECoreProfile | ECompatibilityProfile, 410, E_GL_ARB_gpu_shader_fp64, "vertex-shader `double` type");
3817     }
3818     if (qualifier.storage != EvqVaryingIn && qualifier.storage != EvqVaryingOut)
3819         return;
3820
3821     if (publicType.shaderQualifiers.hasBlendEquation())
3822         error(loc, "can only be applied to a standalone 'out'", "blend equation", "");
3823
3824     // now, knowing it is a shader in/out, do all the in/out semantic checks
3825
3826     if (publicType.basicType == EbtBool && !parsingBuiltins) {
3827         error(loc, "cannot be bool", GetStorageQualifierString(qualifier.storage), "");
3828         return;
3829     }
3830
3831     if (isTypeInt(publicType.basicType) || publicType.basicType == EbtDouble)
3832         profileRequires(loc, EEsProfile, 300, nullptr, "shader input/output");
3833
3834     if (!qualifier.flat && !qualifier.isExplicitInterpolation() && !qualifier.isPervertexNV() && !qualifier.isPervertexEXT()) {
3835         if (isTypeInt(publicType.basicType) ||
3836             publicType.basicType == EbtDouble ||
3837             (publicType.userDef && (   publicType.userDef->containsBasicType(EbtInt)
3838                                     || publicType.userDef->containsBasicType(EbtUint)
3839                                     || publicType.userDef->contains16BitInt()
3840                                     || publicType.userDef->contains8BitInt()
3841                                     || publicType.userDef->contains64BitInt()
3842                                     || publicType.userDef->containsDouble()))) {
3843             if (qualifier.storage == EvqVaryingIn && language == EShLangFragment)
3844                 error(loc, "must be qualified as flat", TType::getBasicString(publicType.basicType), GetStorageQualifierString(qualifier.storage));
3845             else if (qualifier.storage == EvqVaryingOut && language == EShLangVertex && version == 300)
3846                 error(loc, "must be qualified as flat", TType::getBasicString(publicType.basicType), GetStorageQualifierString(qualifier.storage));
3847         }
3848     }
3849
3850     if (qualifier.isPatch() && qualifier.isInterpolation())
3851         error(loc, "cannot use interpolation qualifiers with patch", "patch", "");
3852
3853     if (qualifier.isTaskPayload() && publicType.basicType == EbtBlock)
3854         error(loc, "taskPayloadSharedEXT variables should not be declared as interface blocks", "taskPayloadSharedEXT", "");
3855
3856     if (qualifier.isTaskMemory() && publicType.basicType != EbtBlock)
3857         error(loc, "taskNV variables can be declared only as blocks", "taskNV", "");
3858
3859     if (qualifier.storage == EvqVaryingIn) {
3860         switch (language) {
3861         case EShLangVertex:
3862             if (publicType.basicType == EbtStruct) {
3863                 error(loc, "cannot be a structure or array", GetStorageQualifierString(qualifier.storage), "");
3864                 return;
3865             }
3866             if (publicType.arraySizes) {
3867                 requireProfile(loc, ~EEsProfile, "vertex input arrays");
3868                 profileRequires(loc, ENoProfile, 150, nullptr, "vertex input arrays");
3869             }
3870             if (publicType.basicType == EbtDouble)
3871                 profileRequires(loc, ~EEsProfile, 410, E_GL_ARB_vertex_attrib_64bit, "vertex-shader `double` type input");
3872             if (qualifier.isAuxiliary() || qualifier.isInterpolation() || qualifier.isMemory() || qualifier.invariant)
3873                 error(loc, "vertex input cannot be further qualified", "", "");
3874             break;
3875         case EShLangFragment:
3876             if (publicType.userDef) {
3877                 profileRequires(loc, EEsProfile, 300, nullptr, "fragment-shader struct input");
3878                 profileRequires(loc, ~EEsProfile, 150, nullptr, "fragment-shader struct input");
3879                 if (publicType.userDef->containsStructure())
3880                     requireProfile(loc, ~EEsProfile, "fragment-shader struct input containing structure");
3881                 if (publicType.userDef->containsArray())
3882                     requireProfile(loc, ~EEsProfile, "fragment-shader struct input containing an array");
3883             }
3884             break;
3885        case EShLangCompute:
3886             if (! symbolTable.atBuiltInLevel())
3887                 error(loc, "global storage input qualifier cannot be used in a compute shader", "in", "");
3888             break;
3889 #ifndef GLSLANG_WEB
3890        case EShLangTessControl:
3891             if (qualifier.patch)
3892                 error(loc, "can only use on output in tessellation-control shader", "patch", "");
3893             break;
3894 #endif
3895         default:
3896             break;
3897         }
3898     } else {
3899         // qualifier.storage == EvqVaryingOut
3900         switch (language) {
3901         case EShLangVertex:
3902             if (publicType.userDef) {
3903                 profileRequires(loc, EEsProfile, 300, nullptr, "vertex-shader struct output");
3904                 profileRequires(loc, ~EEsProfile, 150, nullptr, "vertex-shader struct output");
3905                 if (publicType.userDef->containsStructure())
3906                     requireProfile(loc, ~EEsProfile, "vertex-shader struct output containing structure");
3907                 if (publicType.userDef->containsArray())
3908                     requireProfile(loc, ~EEsProfile, "vertex-shader struct output containing an array");
3909             }
3910
3911             break;
3912         case EShLangFragment:
3913             profileRequires(loc, EEsProfile, 300, nullptr, "fragment shader output");
3914             if (publicType.basicType == EbtStruct) {
3915                 error(loc, "cannot be a structure", GetStorageQualifierString(qualifier.storage), "");
3916                 return;
3917             }
3918             if (publicType.matrixRows > 0) {
3919                 error(loc, "cannot be a matrix", GetStorageQualifierString(qualifier.storage), "");
3920                 return;
3921             }
3922             if (qualifier.isAuxiliary())
3923                 error(loc, "can't use auxiliary qualifier on a fragment output", "centroid/sample/patch", "");
3924             if (qualifier.isInterpolation())
3925                 error(loc, "can't use interpolation qualifier on a fragment output", "flat/smooth/noperspective", "");
3926             if (publicType.basicType == EbtDouble || publicType.basicType == EbtInt64 || publicType.basicType == EbtUint64)
3927                 error(loc, "cannot contain a double, int64, or uint64", GetStorageQualifierString(qualifier.storage), "");
3928         break;
3929
3930         case EShLangCompute:
3931             error(loc, "global storage output qualifier cannot be used in a compute shader", "out", "");
3932             break;
3933 #ifndef GLSLANG_WEB
3934         case EShLangTessEvaluation:
3935             if (qualifier.patch)
3936                 error(loc, "can only use on input in tessellation-evaluation shader", "patch", "");
3937             break;
3938 #endif
3939         default:
3940             break;
3941         }
3942     }
3943 }
3944
3945 //
3946 // Merge characteristics of the 'src' qualifier into the 'dst'.
3947 // If there is duplication, issue error messages, unless 'force'
3948 // is specified, which means to just override default settings.
3949 //
3950 // Also, when force is false, it will be assumed that 'src' follows
3951 // 'dst', for the purpose of error checking order for versions
3952 // that require specific orderings of qualifiers.
3953 //
3954 void TParseContext::mergeQualifiers(const TSourceLoc& loc, TQualifier& dst, const TQualifier& src, bool force)
3955 {
3956     // Multiple auxiliary qualifiers (mostly done later by 'individual qualifiers')
3957     if (src.isAuxiliary() && dst.isAuxiliary())
3958         error(loc, "can only have one auxiliary qualifier (centroid, patch, and sample)", "", "");
3959
3960     // Multiple interpolation qualifiers (mostly done later by 'individual qualifiers')
3961     if (src.isInterpolation() && dst.isInterpolation())
3962         error(loc, "can only have one interpolation qualifier (flat, smooth, noperspective, __explicitInterpAMD)", "", "");
3963
3964     // Ordering
3965     if (! force && ((!isEsProfile() && version < 420) ||
3966                     (isEsProfile() && version < 310))
3967                 && ! extensionTurnedOn(E_GL_ARB_shading_language_420pack)) {
3968         // non-function parameters
3969         if (src.isNoContraction() && (dst.invariant || dst.isInterpolation() || dst.isAuxiliary() || dst.storage != EvqTemporary || dst.precision != EpqNone))
3970             error(loc, "precise qualifier must appear first", "", "");
3971         if (src.invariant && (dst.isInterpolation() || dst.isAuxiliary() || dst.storage != EvqTemporary || dst.precision != EpqNone))
3972             error(loc, "invariant qualifier must appear before interpolation, storage, and precision qualifiers ", "", "");
3973         else if (src.isInterpolation() && (dst.isAuxiliary() || dst.storage != EvqTemporary || dst.precision != EpqNone))
3974             error(loc, "interpolation qualifiers must appear before storage and precision qualifiers", "", "");
3975         else if (src.isAuxiliary() && (dst.storage != EvqTemporary || dst.precision != EpqNone))
3976             error(loc, "Auxiliary qualifiers (centroid, patch, and sample) must appear before storage and precision qualifiers", "", "");
3977         else if (src.storage != EvqTemporary && (dst.precision != EpqNone))
3978             error(loc, "precision qualifier must appear as last qualifier", "", "");
3979
3980         // function parameters
3981         if (src.isNoContraction() && (dst.storage == EvqConst || dst.storage == EvqIn || dst.storage == EvqOut))
3982             error(loc, "precise qualifier must appear first", "", "");
3983         if (src.storage == EvqConst && (dst.storage == EvqIn || dst.storage == EvqOut))
3984             error(loc, "in/out must appear before const", "", "");
3985     }
3986
3987     // Storage qualification
3988     if (dst.storage == EvqTemporary || dst.storage == EvqGlobal)
3989         dst.storage = src.storage;
3990     else if ((dst.storage == EvqIn  && src.storage == EvqOut) ||
3991              (dst.storage == EvqOut && src.storage == EvqIn))
3992         dst.storage = EvqInOut;
3993     else if ((dst.storage == EvqIn    && src.storage == EvqConst) ||
3994              (dst.storage == EvqConst && src.storage == EvqIn))
3995         dst.storage = EvqConstReadOnly;
3996     else if (src.storage != EvqTemporary &&
3997              src.storage != EvqGlobal)
3998         error(loc, "too many storage qualifiers", GetStorageQualifierString(src.storage), "");
3999
4000     // Precision qualifiers
4001     if (! force && src.precision != EpqNone && dst.precision != EpqNone)
4002         error(loc, "only one precision qualifier allowed", GetPrecisionQualifierString(src.precision), "");
4003     if (dst.precision == EpqNone || (force && src.precision != EpqNone))
4004         dst.precision = src.precision;
4005
4006 #ifndef GLSLANG_WEB
4007     if (!force && ((src.coherent && (dst.devicecoherent || dst.queuefamilycoherent || dst.workgroupcoherent || dst.subgroupcoherent || dst.shadercallcoherent)) ||
4008                    (src.devicecoherent && (dst.coherent || dst.queuefamilycoherent || dst.workgroupcoherent || dst.subgroupcoherent || dst.shadercallcoherent)) ||
4009                    (src.queuefamilycoherent && (dst.coherent || dst.devicecoherent || dst.workgroupcoherent || dst.subgroupcoherent || dst.shadercallcoherent)) ||
4010                    (src.workgroupcoherent && (dst.coherent || dst.devicecoherent || dst.queuefamilycoherent || dst.subgroupcoherent || dst.shadercallcoherent)) ||
4011                    (src.subgroupcoherent  && (dst.coherent || dst.devicecoherent || dst.queuefamilycoherent || dst.workgroupcoherent || dst.shadercallcoherent)) ||
4012                    (src.shadercallcoherent && (dst.coherent || dst.devicecoherent || dst.queuefamilycoherent || dst.workgroupcoherent || dst.subgroupcoherent)))) {
4013         error(loc, "only one coherent/devicecoherent/queuefamilycoherent/workgroupcoherent/subgroupcoherent/shadercallcoherent qualifier allowed",
4014             GetPrecisionQualifierString(src.precision), "");
4015     }
4016 #endif
4017     // Layout qualifiers
4018     mergeObjectLayoutQualifiers(dst, src, false);
4019
4020     // individual qualifiers
4021     bool repeated = false;
4022     #define MERGE_SINGLETON(field) repeated |= dst.field && src.field; dst.field |= src.field;
4023     MERGE_SINGLETON(invariant);
4024     MERGE_SINGLETON(centroid);
4025     MERGE_SINGLETON(smooth);
4026     MERGE_SINGLETON(flat);
4027     MERGE_SINGLETON(specConstant);
4028 #ifndef GLSLANG_WEB
4029     MERGE_SINGLETON(noContraction);
4030     MERGE_SINGLETON(nopersp);
4031     MERGE_SINGLETON(explicitInterp);
4032     MERGE_SINGLETON(perPrimitiveNV);
4033     MERGE_SINGLETON(perViewNV);
4034     MERGE_SINGLETON(perTaskNV);
4035     MERGE_SINGLETON(patch);
4036     MERGE_SINGLETON(sample);
4037     MERGE_SINGLETON(coherent);
4038     MERGE_SINGLETON(devicecoherent);
4039     MERGE_SINGLETON(queuefamilycoherent);
4040     MERGE_SINGLETON(workgroupcoherent);
4041     MERGE_SINGLETON(subgroupcoherent);
4042     MERGE_SINGLETON(shadercallcoherent);
4043     MERGE_SINGLETON(nonprivate);
4044     MERGE_SINGLETON(volatil);
4045     MERGE_SINGLETON(restrict);
4046     MERGE_SINGLETON(readonly);
4047     MERGE_SINGLETON(writeonly);
4048     MERGE_SINGLETON(nonUniform);
4049 #endif
4050
4051 #ifndef GLSLANG_WEB
4052     // SPIR-V storage class qualifier (GL_EXT_spirv_intrinsics)
4053     dst.spirvStorageClass = src.spirvStorageClass;
4054
4055     // SPIR-V decorate qualifiers (GL_EXT_spirv_intrinsics)
4056     if (src.hasSprivDecorate()) {
4057         if (dst.hasSprivDecorate()) {
4058             const TSpirvDecorate& srcSpirvDecorate = src.getSpirvDecorate();
4059             TSpirvDecorate& dstSpirvDecorate = dst.getSpirvDecorate();
4060             for (auto& decorate : srcSpirvDecorate.decorates) {
4061                 if (dstSpirvDecorate.decorates.find(decorate.first) != dstSpirvDecorate.decorates.end())
4062                     error(loc, "too many SPIR-V decorate qualifiers", "spirv_decorate", "(decoration=%u)", decorate.first);
4063                 else
4064                     dstSpirvDecorate.decorates.insert(decorate);
4065             }
4066
4067             for (auto& decorateId : srcSpirvDecorate.decorateIds) {
4068                 if (dstSpirvDecorate.decorateIds.find(decorateId.first) != dstSpirvDecorate.decorateIds.end())
4069                     error(loc, "too many SPIR-V decorate qualifiers", "spirv_decorate_id", "(decoration=%u)", decorateId.first);
4070                 else
4071                     dstSpirvDecorate.decorateIds.insert(decorateId);
4072             }
4073
4074             for (auto& decorateString : srcSpirvDecorate.decorateStrings) {
4075                 if (dstSpirvDecorate.decorates.find(decorateString.first) != dstSpirvDecorate.decorates.end())
4076                     error(loc, "too many SPIR-V decorate qualifiers", "spirv_decorate_string", "(decoration=%u)", decorateString.first);
4077                 else
4078                     dstSpirvDecorate.decorates.insert(decorateString);
4079             }
4080         } else {
4081             dst.spirvDecorate = src.spirvDecorate;
4082         }
4083     }
4084 #endif
4085
4086     if (repeated)
4087         error(loc, "replicated qualifiers", "", "");
4088 }
4089
4090 void TParseContext::setDefaultPrecision(const TSourceLoc& loc, TPublicType& publicType, TPrecisionQualifier qualifier)
4091 {
4092     TBasicType basicType = publicType.basicType;
4093
4094     if (basicType == EbtSampler) {
4095         defaultSamplerPrecision[computeSamplerTypeIndex(publicType.sampler)] = qualifier;
4096
4097         return;  // all is well
4098     }
4099
4100     if (basicType == EbtInt || basicType == EbtFloat) {
4101         if (publicType.isScalar()) {
4102             defaultPrecision[basicType] = qualifier;
4103             if (basicType == EbtInt) {
4104                 defaultPrecision[EbtUint] = qualifier;
4105                 precisionManager.explicitIntDefaultSeen();
4106             } else
4107                 precisionManager.explicitFloatDefaultSeen();
4108
4109             return;  // all is well
4110         }
4111     }
4112
4113     if (basicType == EbtAtomicUint) {
4114         if (qualifier != EpqHigh)
4115             error(loc, "can only apply highp to atomic_uint", "precision", "");
4116
4117         return;
4118     }
4119
4120     error(loc, "cannot apply precision statement to this type; use 'float', 'int' or a sampler type", TType::getBasicString(basicType), "");
4121 }
4122
4123 // used to flatten the sampler type space into a single dimension
4124 // correlates with the declaration of defaultSamplerPrecision[]
4125 int TParseContext::computeSamplerTypeIndex(TSampler& sampler)
4126 {
4127     int arrayIndex    = sampler.arrayed         ? 1 : 0;
4128     int shadowIndex   = sampler.shadow          ? 1 : 0;
4129     int externalIndex = sampler.isExternal()    ? 1 : 0;
4130     int imageIndex    = sampler.isImageClass()  ? 1 : 0;
4131     int msIndex       = sampler.isMultiSample() ? 1 : 0;
4132
4133     int flattened = EsdNumDims * (EbtNumTypes * (2 * (2 * (2 * (2 * arrayIndex + msIndex) + imageIndex) + shadowIndex) +
4134                                                  externalIndex) + sampler.type) + sampler.dim;
4135     assert(flattened < maxSamplerIndex);
4136
4137     return flattened;
4138 }
4139
4140 TPrecisionQualifier TParseContext::getDefaultPrecision(TPublicType& publicType)
4141 {
4142     if (publicType.basicType == EbtSampler)
4143         return defaultSamplerPrecision[computeSamplerTypeIndex(publicType.sampler)];
4144     else
4145         return defaultPrecision[publicType.basicType];
4146 }
4147
4148 void TParseContext::precisionQualifierCheck(const TSourceLoc& loc, TBasicType baseType, TQualifier& qualifier)
4149 {
4150     // Built-in symbols are allowed some ambiguous precisions, to be pinned down
4151     // later by context.
4152     if (! obeyPrecisionQualifiers() || parsingBuiltins)
4153         return;
4154
4155 #ifndef GLSLANG_WEB
4156     if (baseType == EbtAtomicUint && qualifier.precision != EpqNone && qualifier.precision != EpqHigh)
4157         error(loc, "atomic counters can only be highp", "atomic_uint", "");
4158 #endif
4159
4160     if (baseType == EbtFloat || baseType == EbtUint || baseType == EbtInt || baseType == EbtSampler || baseType == EbtAtomicUint) {
4161         if (qualifier.precision == EpqNone) {
4162             if (relaxedErrors())
4163                 warn(loc, "type requires declaration of default precision qualifier", TType::getBasicString(baseType), "substituting 'mediump'");
4164             else
4165                 error(loc, "type requires declaration of default precision qualifier", TType::getBasicString(baseType), "");
4166             qualifier.precision = EpqMedium;
4167             defaultPrecision[baseType] = EpqMedium;
4168         }
4169     } else if (qualifier.precision != EpqNone)
4170         error(loc, "type cannot have precision qualifier", TType::getBasicString(baseType), "");
4171 }
4172
4173 void TParseContext::parameterTypeCheck(const TSourceLoc& loc, TStorageQualifier qualifier, const TType& type)
4174 {
4175     if ((qualifier == EvqOut || qualifier == EvqInOut) && type.isOpaque())
4176         error(loc, "samplers and atomic_uints cannot be output parameters", type.getBasicTypeString().c_str(), "");
4177     if (!parsingBuiltins && type.contains16BitFloat())
4178         requireFloat16Arithmetic(loc, type.getBasicTypeString().c_str(), "float16 types can only be in uniform block or buffer storage");
4179     if (!parsingBuiltins && type.contains16BitInt())
4180         requireInt16Arithmetic(loc, type.getBasicTypeString().c_str(), "(u)int16 types can only be in uniform block or buffer storage");
4181     if (!parsingBuiltins && type.contains8BitInt())
4182         requireInt8Arithmetic(loc, type.getBasicTypeString().c_str(), "(u)int8 types can only be in uniform block or buffer storage");
4183 }
4184
4185 bool TParseContext::containsFieldWithBasicType(const TType& type, TBasicType basicType)
4186 {
4187     if (type.getBasicType() == basicType)
4188         return true;
4189
4190     if (type.getBasicType() == EbtStruct) {
4191         const TTypeList& structure = *type.getStruct();
4192         for (unsigned int i = 0; i < structure.size(); ++i) {
4193             if (containsFieldWithBasicType(*structure[i].type, basicType))
4194                 return true;
4195         }
4196     }
4197
4198     return false;
4199 }
4200
4201 //
4202 // Do size checking for an array type's size.
4203 //
4204 void TParseContext::arraySizeCheck(const TSourceLoc& loc, TIntermTyped* expr, TArraySize& sizePair, const char *sizeType)
4205 {
4206     bool isConst = false;
4207     sizePair.node = nullptr;
4208
4209     int size = 1;
4210
4211     TIntermConstantUnion* constant = expr->getAsConstantUnion();
4212     if (constant) {
4213         // handle true (non-specialization) constant
4214         size = constant->getConstArray()[0].getIConst();
4215         isConst = true;
4216     } else {
4217         // see if it's a specialization constant instead
4218         if (expr->getQualifier().isSpecConstant()) {
4219             isConst = true;
4220             sizePair.node = expr;
4221             TIntermSymbol* symbol = expr->getAsSymbolNode();
4222             if (symbol && symbol->getConstArray().size() > 0)
4223                 size = symbol->getConstArray()[0].getIConst();
4224         } else if (expr->getAsUnaryNode() &&
4225                    expr->getAsUnaryNode()->getOp() == glslang::EOpArrayLength &&
4226                    expr->getAsUnaryNode()->getOperand()->getType().isCoopMat()) {
4227             isConst = true;
4228             size = 1;
4229             sizePair.node = expr->getAsUnaryNode();
4230         }
4231     }
4232
4233     sizePair.size = size;
4234
4235     if (! isConst || (expr->getBasicType() != EbtInt && expr->getBasicType() != EbtUint)) {
4236         error(loc, sizeType, "", "must be a constant integer expression");
4237         return;
4238     }
4239
4240     if (size <= 0) {
4241         error(loc, sizeType, "", "must be a positive integer");
4242         return;
4243     }
4244 }
4245
4246 //
4247 // See if this qualifier can be an array.
4248 //
4249 // Returns true if there is an error.
4250 //
4251 bool TParseContext::arrayQualifierError(const TSourceLoc& loc, const TQualifier& qualifier)
4252 {
4253     if (qualifier.storage == EvqConst) {
4254         profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, "const array");
4255         profileRequires(loc, EEsProfile, 300, nullptr, "const array");
4256     }
4257
4258     if (qualifier.storage == EvqVaryingIn && language == EShLangVertex) {
4259         requireProfile(loc, ~EEsProfile, "vertex input arrays");
4260         profileRequires(loc, ENoProfile, 150, nullptr, "vertex input arrays");
4261     }
4262
4263     return false;
4264 }
4265
4266 //
4267 // See if this qualifier and type combination can be an array.
4268 // Assumes arrayQualifierError() was also called to catch the type-invariant tests.
4269 //
4270 // Returns true if there is an error.
4271 //
4272 bool TParseContext::arrayError(const TSourceLoc& loc, const TType& type)
4273 {
4274     if (type.getQualifier().storage == EvqVaryingOut && language == EShLangVertex) {
4275         if (type.isArrayOfArrays())
4276             requireProfile(loc, ~EEsProfile, "vertex-shader array-of-array output");
4277         else if (type.isStruct())
4278             requireProfile(loc, ~EEsProfile, "vertex-shader array-of-struct output");
4279     }
4280     if (type.getQualifier().storage == EvqVaryingIn && language == EShLangFragment) {
4281         if (type.isArrayOfArrays())
4282             requireProfile(loc, ~EEsProfile, "fragment-shader array-of-array input");
4283         else if (type.isStruct())
4284             requireProfile(loc, ~EEsProfile, "fragment-shader array-of-struct input");
4285     }
4286     if (type.getQualifier().storage == EvqVaryingOut && language == EShLangFragment) {
4287         if (type.isArrayOfArrays())
4288             requireProfile(loc, ~EEsProfile, "fragment-shader array-of-array output");
4289     }
4290
4291     return false;
4292 }
4293
4294 //
4295 // Require array to be completely sized
4296 //
4297 void TParseContext::arraySizeRequiredCheck(const TSourceLoc& loc, const TArraySizes& arraySizes)
4298 {
4299     if (!parsingBuiltins && arraySizes.hasUnsized())
4300         error(loc, "array size required", "", "");
4301 }
4302
4303 void TParseContext::structArrayCheck(const TSourceLoc& /*loc*/, const TType& type)
4304 {
4305     const TTypeList& structure = *type.getStruct();
4306     for (int m = 0; m < (int)structure.size(); ++m) {
4307         const TType& member = *structure[m].type;
4308         if (member.isArray())
4309             arraySizeRequiredCheck(structure[m].loc, *member.getArraySizes());
4310     }
4311 }
4312
4313 void TParseContext::arraySizesCheck(const TSourceLoc& loc, const TQualifier& qualifier, TArraySizes* arraySizes,
4314     const TIntermTyped* initializer, bool lastMember)
4315 {
4316     assert(arraySizes);
4317
4318     // always allow special built-in ins/outs sized to topologies
4319     if (parsingBuiltins)
4320         return;
4321
4322     // initializer must be a sized array, in which case
4323     // allow the initializer to set any unknown array sizes
4324     if (initializer != nullptr) {
4325         if (initializer->getType().isUnsizedArray())
4326             error(loc, "array initializer must be sized", "[]", "");
4327         return;
4328     }
4329
4330     // No environment allows any non-outer-dimension to be implicitly sized
4331     if (arraySizes->isInnerUnsized()) {
4332         error(loc, "only outermost dimension of an array of arrays can be implicitly sized", "[]", "");
4333         arraySizes->clearInnerUnsized();
4334     }
4335
4336     if (arraySizes->isInnerSpecialization() &&
4337         (qualifier.storage != EvqTemporary && qualifier.storage != EvqGlobal && qualifier.storage != EvqShared && qualifier.storage != EvqConst))
4338         error(loc, "only outermost dimension of an array of arrays can be a specialization constant", "[]", "");
4339
4340 #ifndef GLSLANG_WEB
4341
4342     // desktop always allows outer-dimension-unsized variable arrays,
4343     if (!isEsProfile())
4344         return;
4345
4346     // for ES, if size isn't coming from an initializer, it has to be explicitly declared now,
4347     // with very few exceptions
4348
4349     // implicitly-sized io exceptions:
4350     switch (language) {
4351     case EShLangGeometry:
4352         if (qualifier.storage == EvqVaryingIn)
4353             if ((isEsProfile() && version >= 320) ||
4354                 extensionsTurnedOn(Num_AEP_geometry_shader, AEP_geometry_shader))
4355                 return;
4356         break;
4357     case EShLangTessControl:
4358         if ( qualifier.storage == EvqVaryingIn ||
4359             (qualifier.storage == EvqVaryingOut && ! qualifier.isPatch()))
4360             if ((isEsProfile() && version >= 320) ||
4361                 extensionsTurnedOn(Num_AEP_tessellation_shader, AEP_tessellation_shader))
4362                 return;
4363         break;
4364     case EShLangTessEvaluation:
4365         if ((qualifier.storage == EvqVaryingIn && ! qualifier.isPatch()) ||
4366              qualifier.storage == EvqVaryingOut)
4367             if ((isEsProfile() && version >= 320) ||
4368                 extensionsTurnedOn(Num_AEP_tessellation_shader, AEP_tessellation_shader))
4369                 return;
4370         break;
4371     case EShLangMesh:
4372         if (qualifier.storage == EvqVaryingOut)
4373             if ((isEsProfile() && version >= 320) ||
4374                 extensionsTurnedOn(Num_AEP_mesh_shader, AEP_mesh_shader))
4375                 return;
4376         break;
4377     default:
4378         break;
4379     }
4380
4381 #endif
4382
4383     // last member of ssbo block exception:
4384     if (qualifier.storage == EvqBuffer && lastMember)
4385         return;
4386
4387     arraySizeRequiredCheck(loc, *arraySizes);
4388 }
4389
4390 void TParseContext::arrayOfArrayVersionCheck(const TSourceLoc& loc, const TArraySizes* sizes)
4391 {
4392     if (sizes == nullptr || sizes->getNumDims() == 1)
4393         return;
4394
4395     const char* feature = "arrays of arrays";
4396
4397     requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, feature);
4398     profileRequires(loc, EEsProfile, 310, nullptr, feature);
4399     profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, nullptr, feature);
4400 }
4401
4402 //
4403 // Do all the semantic checking for declaring or redeclaring an array, with and
4404 // without a size, and make the right changes to the symbol table.
4405 //
4406 void TParseContext::declareArray(const TSourceLoc& loc, const TString& identifier, const TType& type, TSymbol*& symbol)
4407 {
4408     if (symbol == nullptr) {
4409         bool currentScope;
4410         symbol = symbolTable.find(identifier, nullptr, &currentScope);
4411
4412         if (symbol && builtInName(identifier) && ! symbolTable.atBuiltInLevel()) {
4413             // bad shader (errors already reported) trying to redeclare a built-in name as an array
4414             symbol = nullptr;
4415             return;
4416         }
4417         if (symbol == nullptr || ! currentScope) {
4418             //
4419             // Successfully process a new definition.
4420             // (Redeclarations have to take place at the same scope; otherwise they are hiding declarations)
4421             //
4422             symbol = new TVariable(&identifier, type);
4423             symbolTable.insert(*symbol);
4424             if (symbolTable.atGlobalLevel())
4425                 trackLinkage(*symbol);
4426
4427 #ifndef GLSLANG_WEB
4428             if (! symbolTable.atBuiltInLevel()) {
4429                 if (isIoResizeArray(type)) {
4430                     ioArraySymbolResizeList.push_back(symbol);
4431                     checkIoArraysConsistency(loc, true);
4432                 } else
4433                     fixIoArraySize(loc, symbol->getWritableType());
4434             }
4435 #endif
4436
4437             return;
4438         }
4439         if (symbol->getAsAnonMember()) {
4440             error(loc, "cannot redeclare a user-block member array", identifier.c_str(), "");
4441             symbol = nullptr;
4442             return;
4443         }
4444     }
4445
4446     //
4447     // Process a redeclaration.
4448     //
4449
4450     if (symbol == nullptr) {
4451         error(loc, "array variable name expected", identifier.c_str(), "");
4452         return;
4453     }
4454
4455     // redeclareBuiltinVariable() should have already done the copyUp()
4456     TType& existingType = symbol->getWritableType();
4457
4458     if (! existingType.isArray()) {
4459         error(loc, "redeclaring non-array as array", identifier.c_str(), "");
4460         return;
4461     }
4462
4463     if (! existingType.sameElementType(type)) {
4464         error(loc, "redeclaration of array with a different element type", identifier.c_str(), "");
4465         return;
4466     }
4467
4468     if (! existingType.sameInnerArrayness(type)) {
4469         error(loc, "redeclaration of array with a different array dimensions or sizes", identifier.c_str(), "");
4470         return;
4471     }
4472
4473 #ifndef GLSLANG_WEB
4474     if (existingType.isSizedArray()) {
4475         // be more leniant for input arrays to geometry shaders and tessellation control outputs, where the redeclaration is the same size
4476         if (! (isIoResizeArray(type) && existingType.getOuterArraySize() == type.getOuterArraySize()))
4477             error(loc, "redeclaration of array with size", identifier.c_str(), "");
4478         return;
4479     }
4480
4481     arrayLimitCheck(loc, identifier, type.getOuterArraySize());
4482
4483     existingType.updateArraySizes(type);
4484
4485     if (isIoResizeArray(type))
4486         checkIoArraysConsistency(loc);
4487 #endif
4488 }
4489
4490 #ifndef GLSLANG_WEB
4491
4492 // Policy and error check for needing a runtime sized array.
4493 void TParseContext::checkRuntimeSizable(const TSourceLoc& loc, const TIntermTyped& base)
4494 {
4495     // runtime length implies runtime sizeable, so no problem
4496     if (isRuntimeLength(base))
4497         return;
4498
4499     if (base.getType().getQualifier().builtIn == EbvSampleMask)
4500         return;
4501
4502     // Check for last member of a bufferreference type, which is runtime sizeable
4503     // but doesn't support runtime length
4504     if (base.getType().getQualifier().storage == EvqBuffer) {
4505         const TIntermBinary* binary = base.getAsBinaryNode();
4506         if (binary != nullptr &&
4507             binary->getOp() == EOpIndexDirectStruct &&
4508             binary->getLeft()->isReference()) {
4509
4510             const int index = binary->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
4511             const int memberCount = (int)binary->getLeft()->getType().getReferentType()->getStruct()->size();
4512             if (index == memberCount - 1)
4513                 return;
4514         }
4515     }
4516
4517     // check for additional things allowed by GL_EXT_nonuniform_qualifier
4518     if (base.getBasicType() == EbtSampler || base.getBasicType() == EbtAccStruct || base.getBasicType() == EbtRayQuery ||
4519         (base.getBasicType() == EbtBlock && base.getType().getQualifier().isUniformOrBuffer()))
4520         requireExtensions(loc, 1, &E_GL_EXT_nonuniform_qualifier, "variable index");
4521     else
4522         error(loc, "", "[", "array must be redeclared with a size before being indexed with a variable");
4523 }
4524
4525 // Policy decision for whether a run-time .length() is allowed.
4526 bool TParseContext::isRuntimeLength(const TIntermTyped& base) const
4527 {
4528     if (base.getType().getQualifier().storage == EvqBuffer) {
4529         // in a buffer block
4530         const TIntermBinary* binary = base.getAsBinaryNode();
4531         if (binary != nullptr && binary->getOp() == EOpIndexDirectStruct) {
4532             // is it the last member?
4533             const int index = binary->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
4534
4535             if (binary->getLeft()->isReference())
4536                 return false;
4537
4538             const int memberCount = (int)binary->getLeft()->getType().getStruct()->size();
4539             if (index == memberCount - 1)
4540                 return true;
4541         }
4542     }
4543
4544     return false;
4545 }
4546
4547 // Check if mesh perviewNV attributes have a view dimension
4548 // and resize it to gl_MaxMeshViewCountNV when implicitly sized.
4549 void TParseContext::checkAndResizeMeshViewDim(const TSourceLoc& loc, TType& type, bool isBlockMember)
4550 {
4551     // see if member is a per-view attribute
4552     if (!type.getQualifier().isPerView())
4553         return;
4554
4555     if ((isBlockMember && type.isArray()) || (!isBlockMember && type.isArrayOfArrays())) {
4556         // since we don't have the maxMeshViewCountNV set during parsing builtins, we hardcode the value.
4557         int maxViewCount = parsingBuiltins ? 4 : resources.maxMeshViewCountNV;
4558         // For block members, outermost array dimension is the view dimension.
4559         // For non-block members, outermost array dimension is the vertex/primitive dimension
4560         // and 2nd outermost is the view dimension.
4561         int viewDim = isBlockMember ? 0 : 1;
4562         int viewDimSize = type.getArraySizes()->getDimSize(viewDim);
4563
4564         if (viewDimSize != UnsizedArraySize && viewDimSize != maxViewCount)
4565             error(loc, "mesh view output array size must be gl_MaxMeshViewCountNV or implicitly sized", "[]", "");
4566         else if (viewDimSize == UnsizedArraySize)
4567             type.getArraySizes()->setDimSize(viewDim, maxViewCount);
4568     }
4569     else {
4570         error(loc, "requires a view array dimension", "perviewNV", "");
4571     }
4572 }
4573
4574 #endif // GLSLANG_WEB
4575
4576 // Returns true if the first argument to the #line directive is the line number for the next line.
4577 //
4578 // Desktop, pre-version 3.30:  "After processing this directive
4579 // (including its new-line), the implementation will behave as if it is compiling at line number line+1 and
4580 // source string number source-string-number."
4581 //
4582 // Desktop, version 3.30 and later, and ES:  "After processing this directive
4583 // (including its new-line), the implementation will behave as if it is compiling at line number line and
4584 // source string number source-string-number.
4585 bool TParseContext::lineDirectiveShouldSetNextLine() const
4586 {
4587     return isEsProfile() || version >= 330;
4588 }
4589
4590 //
4591 // Enforce non-initializer type/qualifier rules.
4592 //
4593 void TParseContext::nonInitConstCheck(const TSourceLoc& loc, TString& identifier, TType& type)
4594 {
4595     //
4596     // Make the qualifier make sense, given that there is not an initializer.
4597     //
4598     if (type.getQualifier().storage == EvqConst ||
4599         type.getQualifier().storage == EvqConstReadOnly) {
4600         type.getQualifier().makeTemporary();
4601         error(loc, "variables with qualifier 'const' must be initialized", identifier.c_str(), "");
4602     }
4603 }
4604
4605 //
4606 // See if the identifier is a built-in symbol that can be redeclared, and if so,
4607 // copy the symbol table's read-only built-in variable to the current
4608 // global level, where it can be modified based on the passed in type.
4609 //
4610 // Returns nullptr if no redeclaration took place; meaning a normal declaration still
4611 // needs to occur for it, not necessarily an error.
4612 //
4613 // Returns a redeclared and type-modified variable if a redeclarated occurred.
4614 //
4615 TSymbol* TParseContext::redeclareBuiltinVariable(const TSourceLoc& loc, const TString& identifier,
4616                                                  const TQualifier& qualifier, const TShaderQualifiers& publicType)
4617 {
4618 #ifndef GLSLANG_WEB
4619     if (! builtInName(identifier) || symbolTable.atBuiltInLevel() || ! symbolTable.atGlobalLevel())
4620         return nullptr;
4621
4622     bool nonEsRedecls = (!isEsProfile() && (version >= 130 || identifier == "gl_TexCoord"));
4623     bool    esRedecls = (isEsProfile() &&
4624                          (version >= 320 || extensionsTurnedOn(Num_AEP_shader_io_blocks, AEP_shader_io_blocks)));
4625     if (! esRedecls && ! nonEsRedecls)
4626         return nullptr;
4627
4628     // Special case when using GL_ARB_separate_shader_objects
4629     bool ssoPre150 = false;  // means the only reason this variable is redeclared is due to this combination
4630     if (!isEsProfile() && version <= 140 && extensionTurnedOn(E_GL_ARB_separate_shader_objects)) {
4631         if (identifier == "gl_Position"     ||
4632             identifier == "gl_PointSize"    ||
4633             identifier == "gl_ClipVertex"   ||
4634             identifier == "gl_FogFragCoord")
4635             ssoPre150 = true;
4636     }
4637
4638     // Potentially redeclaring a built-in variable...
4639
4640     if (ssoPre150 ||
4641         (identifier == "gl_FragDepth"           && ((nonEsRedecls && version >= 420) || esRedecls)) ||
4642         (identifier == "gl_FragCoord"           && ((nonEsRedecls && version >= 140) || esRedecls)) ||
4643          identifier == "gl_ClipDistance"                                                            ||
4644          identifier == "gl_CullDistance"                                                            ||
4645          identifier == "gl_ShadingRateEXT"                                                          ||
4646          identifier == "gl_PrimitiveShadingRateEXT"                                                 ||
4647          identifier == "gl_FrontColor"                                                              ||
4648          identifier == "gl_BackColor"                                                               ||
4649          identifier == "gl_FrontSecondaryColor"                                                     ||
4650          identifier == "gl_BackSecondaryColor"                                                      ||
4651          identifier == "gl_SecondaryColor"                                                          ||
4652         (identifier == "gl_Color"               && language == EShLangFragment)                     ||
4653         (identifier == "gl_FragStencilRefARB"   && (nonEsRedecls && version >= 140)
4654                                                 && language == EShLangFragment)                     ||
4655          identifier == "gl_SampleMask"                                                              ||
4656          identifier == "gl_Layer"                                                                   ||
4657          identifier == "gl_PrimitiveIndicesNV"                                                      ||
4658          identifier == "gl_PrimitivePointIndicesEXT"                                                ||
4659          identifier == "gl_PrimitiveLineIndicesEXT"                                                 ||
4660          identifier == "gl_PrimitiveTriangleIndicesEXT"                                             ||
4661          identifier == "gl_TexCoord") {
4662
4663         // Find the existing symbol, if any.
4664         bool builtIn;
4665         TSymbol* symbol = symbolTable.find(identifier, &builtIn);
4666
4667         // If the symbol was not found, this must be a version/profile/stage
4668         // that doesn't have it.
4669         if (! symbol)
4670             return nullptr;
4671
4672         // If it wasn't at a built-in level, then it's already been redeclared;
4673         // that is, this is a redeclaration of a redeclaration; reuse that initial
4674         // redeclaration.  Otherwise, make the new one.
4675         if (builtIn) {
4676             makeEditable(symbol);
4677             symbolTable.amendSymbolIdLevel(*symbol);
4678         }
4679
4680         // Now, modify the type of the copy, as per the type of the current redeclaration.
4681
4682         TQualifier& symbolQualifier = symbol->getWritableType().getQualifier();
4683         if (ssoPre150) {
4684             if (intermediate.inIoAccessed(identifier))
4685                 error(loc, "cannot redeclare after use", identifier.c_str(), "");
4686             if (qualifier.hasLayout())
4687                 error(loc, "cannot apply layout qualifier to", "redeclaration", symbol->getName().c_str());
4688             if (qualifier.isMemory() || qualifier.isAuxiliary() || (language == EShLangVertex   && qualifier.storage != EvqVaryingOut) ||
4689                                                                    (language == EShLangFragment && qualifier.storage != EvqVaryingIn))
4690                 error(loc, "cannot change storage, memory, or auxiliary qualification of", "redeclaration", symbol->getName().c_str());
4691             if (! qualifier.smooth)
4692                 error(loc, "cannot change interpolation qualification of", "redeclaration", symbol->getName().c_str());
4693         } else if (identifier == "gl_FrontColor"          ||
4694                    identifier == "gl_BackColor"           ||
4695                    identifier == "gl_FrontSecondaryColor" ||
4696                    identifier == "gl_BackSecondaryColor"  ||
4697                    identifier == "gl_SecondaryColor"      ||
4698                    identifier == "gl_Color") {
4699             symbolQualifier.flat = qualifier.flat;
4700             symbolQualifier.smooth = qualifier.smooth;
4701             symbolQualifier.nopersp = qualifier.nopersp;
4702             if (qualifier.hasLayout())
4703                 error(loc, "cannot apply layout qualifier to", "redeclaration", symbol->getName().c_str());
4704             if (qualifier.isMemory() || qualifier.isAuxiliary() || symbol->getType().getQualifier().storage != qualifier.storage)
4705                 error(loc, "cannot change storage, memory, or auxiliary qualification of", "redeclaration", symbol->getName().c_str());
4706         } else if (identifier == "gl_TexCoord"     ||
4707                    identifier == "gl_ClipDistance" ||
4708                    identifier == "gl_CullDistance") {
4709             if (qualifier.hasLayout() || qualifier.isMemory() || qualifier.isAuxiliary() ||
4710                 qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat ||
4711                 symbolQualifier.storage != qualifier.storage)
4712                 error(loc, "cannot change qualification of", "redeclaration", symbol->getName().c_str());
4713         } else if (identifier == "gl_FragCoord") {
4714             if (!intermediate.getTexCoordRedeclared() && intermediate.inIoAccessed("gl_FragCoord"))
4715                 error(loc, "cannot redeclare after use", "gl_FragCoord", "");
4716             if (qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat ||
4717                 qualifier.isMemory() || qualifier.isAuxiliary())
4718                 error(loc, "can only change layout qualification of", "redeclaration", symbol->getName().c_str());
4719             if (qualifier.storage != EvqVaryingIn)
4720                 error(loc, "cannot change input storage qualification of", "redeclaration", symbol->getName().c_str());
4721             if (! builtIn && (publicType.pixelCenterInteger != intermediate.getPixelCenterInteger() ||
4722                               publicType.originUpperLeft != intermediate.getOriginUpperLeft()))
4723                 error(loc, "cannot redeclare with different qualification:", "redeclaration", symbol->getName().c_str());
4724
4725
4726             intermediate.setTexCoordRedeclared();
4727             if (publicType.pixelCenterInteger)
4728                 intermediate.setPixelCenterInteger();
4729             if (publicType.originUpperLeft)
4730                 intermediate.setOriginUpperLeft();
4731         } else if (identifier == "gl_FragDepth") {
4732             if (qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat ||
4733                 qualifier.isMemory() || qualifier.isAuxiliary())
4734                 error(loc, "can only change layout qualification of", "redeclaration", symbol->getName().c_str());
4735             if (qualifier.storage != EvqVaryingOut)
4736                 error(loc, "cannot change output storage qualification of", "redeclaration", symbol->getName().c_str());
4737             if (publicType.layoutDepth != EldNone) {
4738                 if (intermediate.inIoAccessed("gl_FragDepth"))
4739                     error(loc, "cannot redeclare after use", "gl_FragDepth", "");
4740                 if (! intermediate.setDepth(publicType.layoutDepth))
4741                     error(loc, "all redeclarations must use the same depth layout on", "redeclaration", symbol->getName().c_str());
4742             }
4743         } else if (identifier == "gl_FragStencilRefARB") {
4744             if (qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat ||
4745                 qualifier.isMemory() || qualifier.isAuxiliary())
4746                 error(loc, "can only change layout qualification of", "redeclaration", symbol->getName().c_str());
4747             if (qualifier.storage != EvqVaryingOut)
4748                 error(loc, "cannot change output storage qualification of", "redeclaration", symbol->getName().c_str());
4749             if (publicType.layoutStencil != ElsNone) {
4750                 if (intermediate.inIoAccessed("gl_FragStencilRefARB"))
4751                     error(loc, "cannot redeclare after use", "gl_FragStencilRefARB", "");
4752                 if (!intermediate.setStencil(publicType.layoutStencil))
4753                     error(loc, "all redeclarations must use the same stencil layout on", "redeclaration",
4754                           symbol->getName().c_str());
4755             }
4756         }
4757         else if (
4758             identifier == "gl_PrimitiveIndicesNV") {
4759             if (qualifier.hasLayout())
4760                 error(loc, "cannot apply layout qualifier to", "redeclaration", symbol->getName().c_str());
4761             if (qualifier.storage != EvqVaryingOut)
4762                 error(loc, "cannot change output storage qualification of", "redeclaration", symbol->getName().c_str());
4763         }
4764         else if (identifier == "gl_SampleMask") {
4765             if (!publicType.layoutOverrideCoverage) {
4766                 error(loc, "redeclaration only allowed for override_coverage layout", "redeclaration", symbol->getName().c_str());
4767             }
4768             intermediate.setLayoutOverrideCoverage();
4769         }
4770         else if (identifier == "gl_Layer") {
4771             if (!qualifier.layoutViewportRelative && qualifier.layoutSecondaryViewportRelativeOffset == -2048)
4772                 error(loc, "redeclaration only allowed for viewport_relative or secondary_view_offset layout", "redeclaration", symbol->getName().c_str());
4773             symbolQualifier.layoutViewportRelative = qualifier.layoutViewportRelative;
4774             symbolQualifier.layoutSecondaryViewportRelativeOffset = qualifier.layoutSecondaryViewportRelativeOffset;
4775         }
4776
4777         // TODO: semantics quality: separate smooth from nothing declared, then use IsInterpolation for several tests above
4778
4779         return symbol;
4780     }
4781 #endif
4782
4783     return nullptr;
4784 }
4785
4786 //
4787 // Either redeclare the requested block, or give an error message why it can't be done.
4788 //
4789 // TODO: functionality: explicitly sizing members of redeclared blocks is not giving them an explicit size
4790 void TParseContext::redeclareBuiltinBlock(const TSourceLoc& loc, TTypeList& newTypeList, const TString& blockName,
4791     const TString* instanceName, TArraySizes* arraySizes)
4792 {
4793 #ifndef GLSLANG_WEB
4794     const char* feature = "built-in block redeclaration";
4795     profileRequires(loc, EEsProfile, 320, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, feature);
4796     profileRequires(loc, ~EEsProfile, 410, E_GL_ARB_separate_shader_objects, feature);
4797
4798     if (blockName != "gl_PerVertex" && blockName != "gl_PerFragment" &&
4799         blockName != "gl_MeshPerVertexNV" && blockName != "gl_MeshPerPrimitiveNV" &&
4800         blockName != "gl_MeshPerVertexEXT" && blockName != "gl_MeshPerPrimitiveEXT") {
4801         error(loc, "cannot redeclare block: ", "block declaration", blockName.c_str());
4802         return;
4803     }
4804
4805     // Redeclaring a built-in block...
4806
4807     if (instanceName && ! builtInName(*instanceName)) {
4808         error(loc, "cannot redeclare a built-in block with a user name", instanceName->c_str(), "");
4809         return;
4810     }
4811
4812     // Blocks with instance names are easy to find, lookup the instance name,
4813     // Anonymous blocks need to be found via a member.
4814     bool builtIn;
4815     TSymbol* block;
4816     if (instanceName)
4817         block = symbolTable.find(*instanceName, &builtIn);
4818     else
4819         block = symbolTable.find(newTypeList.front().type->getFieldName(), &builtIn);
4820
4821     // If the block was not found, this must be a version/profile/stage
4822     // that doesn't have it, or the instance name is wrong.
4823     const char* errorName = instanceName ? instanceName->c_str() : newTypeList.front().type->getFieldName().c_str();
4824     if (! block) {
4825         error(loc, "no declaration found for redeclaration", errorName, "");
4826         return;
4827     }
4828     // Built-in blocks cannot be redeclared more than once, which if happened,
4829     // we'd be finding the already redeclared one here, rather than the built in.
4830     if (! builtIn) {
4831         error(loc, "can only redeclare a built-in block once, and before any use", blockName.c_str(), "");
4832         return;
4833     }
4834
4835     // Copy the block to make a writable version, to insert into the block table after editing.
4836     block = symbolTable.copyUpDeferredInsert(block);
4837
4838     if (block->getType().getBasicType() != EbtBlock) {
4839         error(loc, "cannot redeclare a non block as a block", errorName, "");
4840         return;
4841     }
4842
4843     // Fix XFB stuff up, it applies to the order of the redeclaration, not
4844     // the order of the original members.
4845     if (currentBlockQualifier.storage == EvqVaryingOut && globalOutputDefaults.hasXfbBuffer()) {
4846         if (!currentBlockQualifier.hasXfbBuffer())
4847             currentBlockQualifier.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
4848         if (!currentBlockQualifier.hasStream())
4849             currentBlockQualifier.layoutStream = globalOutputDefaults.layoutStream;
4850         fixXfbOffsets(currentBlockQualifier, newTypeList);
4851     }
4852
4853     // Edit and error check the container against the redeclaration
4854     //  - remove unused members
4855     //  - ensure remaining qualifiers/types match
4856
4857     TType& type = block->getWritableType();
4858
4859     // if gl_PerVertex is redeclared for the purpose of passing through "gl_Position"
4860     // for passthrough purpose, the redeclared block should have the same qualifers as
4861     // the current one
4862     if (currentBlockQualifier.layoutPassthrough) {
4863         type.getQualifier().layoutPassthrough = currentBlockQualifier.layoutPassthrough;
4864         type.getQualifier().storage = currentBlockQualifier.storage;
4865         type.getQualifier().layoutStream = currentBlockQualifier.layoutStream;
4866         type.getQualifier().layoutXfbBuffer = currentBlockQualifier.layoutXfbBuffer;
4867     }
4868
4869     TTypeList::iterator member = type.getWritableStruct()->begin();
4870     size_t numOriginalMembersFound = 0;
4871     while (member != type.getStruct()->end()) {
4872         // look for match
4873         bool found = false;
4874         TTypeList::const_iterator newMember;
4875         TSourceLoc memberLoc;
4876         memberLoc.init();
4877         for (newMember = newTypeList.begin(); newMember != newTypeList.end(); ++newMember) {
4878             if (member->type->getFieldName() == newMember->type->getFieldName()) {
4879                 found = true;
4880                 memberLoc = newMember->loc;
4881                 break;
4882             }
4883         }
4884
4885         if (found) {
4886             ++numOriginalMembersFound;
4887             // - ensure match between redeclared members' types
4888             // - check for things that can't be changed
4889             // - update things that can be changed
4890             TType& oldType = *member->type;
4891             const TType& newType = *newMember->type;
4892             if (! newType.sameElementType(oldType))
4893                 error(memberLoc, "cannot redeclare block member with a different type", member->type->getFieldName().c_str(), "");
4894             if (oldType.isArray() != newType.isArray())
4895                 error(memberLoc, "cannot change arrayness of redeclared block member", member->type->getFieldName().c_str(), "");
4896             else if (! oldType.getQualifier().isPerView() && ! oldType.sameArrayness(newType) && oldType.isSizedArray())
4897                 error(memberLoc, "cannot change array size of redeclared block member", member->type->getFieldName().c_str(), "");
4898             else if (! oldType.getQualifier().isPerView() && newType.isArray())
4899                 arrayLimitCheck(loc, member->type->getFieldName(), newType.getOuterArraySize());
4900             if (oldType.getQualifier().isPerView() && ! newType.getQualifier().isPerView())
4901                 error(memberLoc, "missing perviewNV qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
4902             else if (! oldType.getQualifier().isPerView() && newType.getQualifier().isPerView())
4903                 error(memberLoc, "cannot add perviewNV qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
4904             else if (newType.getQualifier().isPerView()) {
4905                 if (oldType.getArraySizes()->getNumDims() != newType.getArraySizes()->getNumDims())
4906                     error(memberLoc, "cannot change arrayness of redeclared block member", member->type->getFieldName().c_str(), "");
4907                 else if (! newType.isUnsizedArray() && newType.getOuterArraySize() != resources.maxMeshViewCountNV)
4908                     error(loc, "mesh view output array size must be gl_MaxMeshViewCountNV or implicitly sized", "[]", "");
4909                 else if (newType.getArraySizes()->getNumDims() == 2) {
4910                     int innerDimSize = newType.getArraySizes()->getDimSize(1);
4911                     arrayLimitCheck(memberLoc, member->type->getFieldName(), innerDimSize);
4912                     oldType.getArraySizes()->setDimSize(1, innerDimSize);
4913                 }
4914             }
4915             if (oldType.getQualifier().isPerPrimitive() && ! newType.getQualifier().isPerPrimitive())
4916                 error(memberLoc, "missing perprimitiveNV qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
4917             else if (! oldType.getQualifier().isPerPrimitive() && newType.getQualifier().isPerPrimitive())
4918                 error(memberLoc, "cannot add perprimitiveNV qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
4919             if (newType.getQualifier().isMemory())
4920                 error(memberLoc, "cannot add memory qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
4921             if (newType.getQualifier().hasNonXfbLayout())
4922                 error(memberLoc, "cannot add non-XFB layout to redeclared block member", member->type->getFieldName().c_str(), "");
4923             if (newType.getQualifier().patch)
4924                 error(memberLoc, "cannot add patch to redeclared block member", member->type->getFieldName().c_str(), "");
4925             if (newType.getQualifier().hasXfbBuffer() &&
4926                 newType.getQualifier().layoutXfbBuffer != currentBlockQualifier.layoutXfbBuffer)
4927                 error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_buffer", "");
4928             if (newType.getQualifier().hasStream() &&
4929                 newType.getQualifier().layoutStream != currentBlockQualifier.layoutStream)
4930                 error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_stream", "");
4931             oldType.getQualifier().centroid = newType.getQualifier().centroid;
4932             oldType.getQualifier().sample = newType.getQualifier().sample;
4933             oldType.getQualifier().invariant = newType.getQualifier().invariant;
4934             oldType.getQualifier().noContraction = newType.getQualifier().noContraction;
4935             oldType.getQualifier().smooth = newType.getQualifier().smooth;
4936             oldType.getQualifier().flat = newType.getQualifier().flat;
4937             oldType.getQualifier().nopersp = newType.getQualifier().nopersp;
4938             oldType.getQualifier().layoutXfbOffset = newType.getQualifier().layoutXfbOffset;
4939             oldType.getQualifier().layoutXfbBuffer = newType.getQualifier().layoutXfbBuffer;
4940             oldType.getQualifier().layoutXfbStride = newType.getQualifier().layoutXfbStride;
4941             if (oldType.getQualifier().layoutXfbOffset != TQualifier::layoutXfbBufferEnd) {
4942                 // If any member has an xfb_offset, then the block's xfb_buffer inherents current xfb_buffer,
4943                 // and for xfb processing, the member needs it as well, along with xfb_stride.
4944                 type.getQualifier().layoutXfbBuffer = currentBlockQualifier.layoutXfbBuffer;
4945                 oldType.getQualifier().layoutXfbBuffer = currentBlockQualifier.layoutXfbBuffer;
4946             }
4947             if (oldType.isUnsizedArray() && newType.isSizedArray())
4948                 oldType.changeOuterArraySize(newType.getOuterArraySize());
4949
4950             //  check and process the member's type, which will include managing xfb information
4951             layoutTypeCheck(loc, oldType);
4952
4953             // go to next member
4954             ++member;
4955         } else {
4956             // For missing members of anonymous blocks that have been redeclared,
4957             // hide the original (shared) declaration.
4958             // Instance-named blocks can just have the member removed.
4959             if (instanceName)
4960                 member = type.getWritableStruct()->erase(member);
4961             else {
4962                 member->type->hideMember();
4963                 ++member;
4964             }
4965         }
4966     }
4967
4968     if (spvVersion.vulkan > 0) {
4969         // ...then streams apply to built-in blocks, instead of them being only on stream 0
4970         type.getQualifier().layoutStream = currentBlockQualifier.layoutStream;
4971     }
4972
4973     if (numOriginalMembersFound < newTypeList.size())
4974         error(loc, "block redeclaration has extra members", blockName.c_str(), "");
4975     if (type.isArray() != (arraySizes != nullptr) ||
4976         (type.isArray() && arraySizes != nullptr && type.getArraySizes()->getNumDims() != arraySizes->getNumDims()))
4977         error(loc, "cannot change arrayness of redeclared block", blockName.c_str(), "");
4978     else if (type.isArray()) {
4979         // At this point, we know both are arrays and both have the same number of dimensions.
4980
4981         // It is okay for a built-in block redeclaration to be unsized, and keep the size of the
4982         // original block declaration.
4983         if (!arraySizes->isSized() && type.isSizedArray())
4984             arraySizes->changeOuterSize(type.getOuterArraySize());
4985
4986         // And, okay to be giving a size to the array, by the redeclaration
4987         if (!type.isSizedArray() && arraySizes->isSized())
4988             type.changeOuterArraySize(arraySizes->getOuterSize());
4989
4990         // Now, they must match in all dimensions.
4991         if (type.isSizedArray() && *type.getArraySizes() != *arraySizes)
4992             error(loc, "cannot change array size of redeclared block", blockName.c_str(), "");
4993     }
4994
4995     symbolTable.insert(*block);
4996
4997     // Check for general layout qualifier errors
4998     layoutObjectCheck(loc, *block);
4999
5000     // Tracking for implicit sizing of array
5001     if (isIoResizeArray(block->getType())) {
5002         ioArraySymbolResizeList.push_back(block);
5003         checkIoArraysConsistency(loc, true);
5004     } else if (block->getType().isArray())
5005         fixIoArraySize(loc, block->getWritableType());
5006
5007     // Save it in the AST for linker use.
5008     trackLinkage(*block);
5009 #endif // GLSLANG_WEB
5010 }
5011
5012 void TParseContext::paramCheckFixStorage(const TSourceLoc& loc, const TStorageQualifier& qualifier, TType& type)
5013 {
5014     switch (qualifier) {
5015     case EvqConst:
5016     case EvqConstReadOnly:
5017         type.getQualifier().storage = EvqConstReadOnly;
5018         break;
5019     case EvqIn:
5020     case EvqOut:
5021     case EvqInOut:
5022         type.getQualifier().storage = qualifier;
5023         break;
5024     case EvqGlobal:
5025     case EvqTemporary:
5026         type.getQualifier().storage = EvqIn;
5027         break;
5028     default:
5029         type.getQualifier().storage = EvqIn;
5030         error(loc, "storage qualifier not allowed on function parameter", GetStorageQualifierString(qualifier), "");
5031         break;
5032     }
5033 }
5034
5035 void TParseContext::paramCheckFix(const TSourceLoc& loc, const TQualifier& qualifier, TType& type)
5036 {
5037 #ifndef GLSLANG_WEB
5038     if (qualifier.isMemory()) {
5039         type.getQualifier().volatil   = qualifier.volatil;
5040         type.getQualifier().coherent  = qualifier.coherent;
5041         type.getQualifier().devicecoherent  = qualifier.devicecoherent ;
5042         type.getQualifier().queuefamilycoherent  = qualifier.queuefamilycoherent;
5043         type.getQualifier().workgroupcoherent  = qualifier.workgroupcoherent;
5044         type.getQualifier().subgroupcoherent  = qualifier.subgroupcoherent;
5045         type.getQualifier().shadercallcoherent = qualifier.shadercallcoherent;
5046         type.getQualifier().nonprivate = qualifier.nonprivate;
5047         type.getQualifier().readonly  = qualifier.readonly;
5048         type.getQualifier().writeonly = qualifier.writeonly;
5049         type.getQualifier().restrict  = qualifier.restrict;
5050     }
5051 #endif
5052
5053     if (qualifier.isAuxiliary() ||
5054         qualifier.isInterpolation())
5055         error(loc, "cannot use auxiliary or interpolation qualifiers on a function parameter", "", "");
5056     if (qualifier.hasLayout())
5057         error(loc, "cannot use layout qualifiers on a function parameter", "", "");
5058     if (qualifier.invariant)
5059         error(loc, "cannot use invariant qualifier on a function parameter", "", "");
5060     if (qualifier.isNoContraction()) {
5061         if (qualifier.isParamOutput())
5062             type.getQualifier().setNoContraction();
5063         else
5064             warn(loc, "qualifier has no effect on non-output parameters", "precise", "");
5065     }
5066     if (qualifier.isNonUniform())
5067         type.getQualifier().nonUniform = qualifier.nonUniform;
5068 #ifndef GLSLANG_WEB
5069     if (qualifier.isSpirvByReference())
5070         type.getQualifier().setSpirvByReference();
5071     if (qualifier.isSpirvLiteral()) {
5072         if (type.getBasicType() == EbtFloat || type.getBasicType() == EbtInt || type.getBasicType() == EbtUint ||
5073             type.getBasicType() == EbtBool)
5074             type.getQualifier().setSpirvLiteral();
5075         else
5076             error(loc, "cannot use spirv_literal qualifier", type.getBasicTypeString().c_str(), "");
5077 #endif
5078     }
5079
5080     paramCheckFixStorage(loc, qualifier.storage, type);
5081 }
5082
5083 void TParseContext::nestedBlockCheck(const TSourceLoc& loc)
5084 {
5085     if (structNestingLevel > 0 || blockNestingLevel > 0)
5086         error(loc, "cannot nest a block definition inside a structure or block", "", "");
5087     ++blockNestingLevel;
5088 }
5089
5090 void TParseContext::nestedStructCheck(const TSourceLoc& loc)
5091 {
5092     if (structNestingLevel > 0 || blockNestingLevel > 0)
5093         error(loc, "cannot nest a structure definition inside a structure or block", "", "");
5094     ++structNestingLevel;
5095 }
5096
5097 void TParseContext::arrayObjectCheck(const TSourceLoc& loc, const TType& type, const char* op)
5098 {
5099     // Some versions don't allow comparing arrays or structures containing arrays
5100     if (type.containsArray()) {
5101         profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, op);
5102         profileRequires(loc, EEsProfile, 300, nullptr, op);
5103     }
5104 }
5105
5106 void TParseContext::opaqueCheck(const TSourceLoc& loc, const TType& type, const char* op)
5107 {
5108     if (containsFieldWithBasicType(type, EbtSampler))
5109         error(loc, "can't use with samplers or structs containing samplers", op, "");
5110 }
5111
5112 void TParseContext::referenceCheck(const TSourceLoc& loc, const TType& type, const char* op)
5113 {
5114 #ifndef GLSLANG_WEB
5115     if (containsFieldWithBasicType(type, EbtReference))
5116         error(loc, "can't use with reference types", op, "");
5117 #endif
5118 }
5119
5120 void TParseContext::storage16BitAssignmentCheck(const TSourceLoc& loc, const TType& type, const char* op)
5121 {
5122 #ifndef GLSLANG_WEB
5123     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtFloat16))
5124         requireFloat16Arithmetic(loc, op, "can't use with structs containing float16");
5125
5126     if (type.isArray() && type.getBasicType() == EbtFloat16)
5127         requireFloat16Arithmetic(loc, op, "can't use with arrays containing float16");
5128
5129     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtInt16))
5130         requireInt16Arithmetic(loc, op, "can't use with structs containing int16");
5131
5132     if (type.isArray() && type.getBasicType() == EbtInt16)
5133         requireInt16Arithmetic(loc, op, "can't use with arrays containing int16");
5134
5135     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtUint16))
5136         requireInt16Arithmetic(loc, op, "can't use with structs containing uint16");
5137
5138     if (type.isArray() && type.getBasicType() == EbtUint16)
5139         requireInt16Arithmetic(loc, op, "can't use with arrays containing uint16");
5140
5141     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtInt8))
5142         requireInt8Arithmetic(loc, op, "can't use with structs containing int8");
5143
5144     if (type.isArray() && type.getBasicType() == EbtInt8)
5145         requireInt8Arithmetic(loc, op, "can't use with arrays containing int8");
5146
5147     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtUint8))
5148         requireInt8Arithmetic(loc, op, "can't use with structs containing uint8");
5149
5150     if (type.isArray() && type.getBasicType() == EbtUint8)
5151         requireInt8Arithmetic(loc, op, "can't use with arrays containing uint8");
5152 #endif
5153 }
5154
5155 void TParseContext::specializationCheck(const TSourceLoc& loc, const TType& type, const char* op)
5156 {
5157     if (type.containsSpecializationSize())
5158         error(loc, "can't use with types containing arrays sized with a specialization constant", op, "");
5159 }
5160
5161 void TParseContext::structTypeCheck(const TSourceLoc& /*loc*/, TPublicType& publicType)
5162 {
5163     const TTypeList& typeList = *publicType.userDef->getStruct();
5164
5165     // fix and check for member storage qualifiers and types that don't belong within a structure
5166     for (unsigned int member = 0; member < typeList.size(); ++member) {
5167         TQualifier& memberQualifier = typeList[member].type->getQualifier();
5168         const TSourceLoc& memberLoc = typeList[member].loc;
5169         if (memberQualifier.isAuxiliary() ||
5170             memberQualifier.isInterpolation() ||
5171             (memberQualifier.storage != EvqTemporary && memberQualifier.storage != EvqGlobal))
5172             error(memberLoc, "cannot use storage or interpolation qualifiers on structure members", typeList[member].type->getFieldName().c_str(), "");
5173         if (memberQualifier.isMemory())
5174             error(memberLoc, "cannot use memory qualifiers on structure members", typeList[member].type->getFieldName().c_str(), "");
5175         if (memberQualifier.hasLayout()) {
5176             error(memberLoc, "cannot use layout qualifiers on structure members", typeList[member].type->getFieldName().c_str(), "");
5177             memberQualifier.clearLayout();
5178         }
5179         if (memberQualifier.invariant)
5180             error(memberLoc, "cannot use invariant qualifier on structure members", typeList[member].type->getFieldName().c_str(), "");
5181     }
5182 }
5183
5184 //
5185 // See if this loop satisfies the limitations for ES 2.0 (version 100) for loops in Appendex A:
5186 //
5187 // "The loop index has type int or float.
5188 //
5189 // "The for statement has the form:
5190 //     for ( init-declaration ; condition ; expression )
5191 //     init-declaration has the form: type-specifier identifier = constant-expression
5192 //     condition has the form:  loop-index relational_operator constant-expression
5193 //         where relational_operator is one of: > >= < <= == or !=
5194 //     expression [sic] has one of the following forms:
5195 //         loop-index++
5196 //         loop-index--
5197 //         loop-index += constant-expression
5198 //         loop-index -= constant-expression
5199 //
5200 // The body is handled in an AST traversal.
5201 //
5202 void TParseContext::inductiveLoopCheck(const TSourceLoc& loc, TIntermNode* init, TIntermLoop* loop)
5203 {
5204 #ifndef GLSLANG_WEB
5205     // loop index init must exist and be a declaration, which shows up in the AST as an aggregate of size 1 of the declaration
5206     bool badInit = false;
5207     if (! init || ! init->getAsAggregate() || init->getAsAggregate()->getSequence().size() != 1)
5208         badInit = true;
5209     TIntermBinary* binaryInit = 0;
5210     if (! badInit) {
5211         // get the declaration assignment
5212         binaryInit = init->getAsAggregate()->getSequence()[0]->getAsBinaryNode();
5213         if (! binaryInit)
5214             badInit = true;
5215     }
5216     if (badInit) {
5217         error(loc, "inductive-loop init-declaration requires the form \"type-specifier loop-index = constant-expression\"", "limitations", "");
5218         return;
5219     }
5220
5221     // loop index must be type int or float
5222     if (! binaryInit->getType().isScalar() || (binaryInit->getBasicType() != EbtInt && binaryInit->getBasicType() != EbtFloat)) {
5223         error(loc, "inductive loop requires a scalar 'int' or 'float' loop index", "limitations", "");
5224         return;
5225     }
5226
5227     // init is the form "loop-index = constant"
5228     if (binaryInit->getOp() != EOpAssign || ! binaryInit->getLeft()->getAsSymbolNode() || ! binaryInit->getRight()->getAsConstantUnion()) {
5229         error(loc, "inductive-loop init-declaration requires the form \"type-specifier loop-index = constant-expression\"", "limitations", "");
5230         return;
5231     }
5232
5233     // get the unique id of the loop index
5234     long long loopIndex = binaryInit->getLeft()->getAsSymbolNode()->getId();
5235     inductiveLoopIds.insert(loopIndex);
5236
5237     // condition's form must be "loop-index relational-operator constant-expression"
5238     bool badCond = ! loop->getTest();
5239     if (! badCond) {
5240         TIntermBinary* binaryCond = loop->getTest()->getAsBinaryNode();
5241         badCond = ! binaryCond;
5242         if (! badCond) {
5243             switch (binaryCond->getOp()) {
5244             case EOpGreaterThan:
5245             case EOpGreaterThanEqual:
5246             case EOpLessThan:
5247             case EOpLessThanEqual:
5248             case EOpEqual:
5249             case EOpNotEqual:
5250                 break;
5251             default:
5252                 badCond = true;
5253             }
5254         }
5255         if (binaryCond && (! binaryCond->getLeft()->getAsSymbolNode() ||
5256                            binaryCond->getLeft()->getAsSymbolNode()->getId() != loopIndex ||
5257                            ! binaryCond->getRight()->getAsConstantUnion()))
5258             badCond = true;
5259     }
5260     if (badCond) {
5261         error(loc, "inductive-loop condition requires the form \"loop-index <comparison-op> constant-expression\"", "limitations", "");
5262         return;
5263     }
5264
5265     // loop-index++
5266     // loop-index--
5267     // loop-index += constant-expression
5268     // loop-index -= constant-expression
5269     bool badTerminal = ! loop->getTerminal();
5270     if (! badTerminal) {
5271         TIntermUnary* unaryTerminal = loop->getTerminal()->getAsUnaryNode();
5272         TIntermBinary* binaryTerminal = loop->getTerminal()->getAsBinaryNode();
5273         if (unaryTerminal || binaryTerminal) {
5274             switch(loop->getTerminal()->getAsOperator()->getOp()) {
5275             case EOpPostDecrement:
5276             case EOpPostIncrement:
5277             case EOpAddAssign:
5278             case EOpSubAssign:
5279                 break;
5280             default:
5281                 badTerminal = true;
5282             }
5283         } else
5284             badTerminal = true;
5285         if (binaryTerminal && (! binaryTerminal->getLeft()->getAsSymbolNode() ||
5286                                binaryTerminal->getLeft()->getAsSymbolNode()->getId() != loopIndex ||
5287                                ! binaryTerminal->getRight()->getAsConstantUnion()))
5288             badTerminal = true;
5289         if (unaryTerminal && (! unaryTerminal->getOperand()->getAsSymbolNode() ||
5290                               unaryTerminal->getOperand()->getAsSymbolNode()->getId() != loopIndex))
5291             badTerminal = true;
5292     }
5293     if (badTerminal) {
5294         error(loc, "inductive-loop termination requires the form \"loop-index++, loop-index--, loop-index += constant-expression, or loop-index -= constant-expression\"", "limitations", "");
5295         return;
5296     }
5297
5298     // the body
5299     inductiveLoopBodyCheck(loop->getBody(), loopIndex, symbolTable);
5300 #endif
5301 }
5302
5303 #ifndef GLSLANG_WEB
5304 // Do limit checks for built-in arrays.
5305 void TParseContext::arrayLimitCheck(const TSourceLoc& loc, const TString& identifier, int size)
5306 {
5307     if (identifier.compare("gl_TexCoord") == 0)
5308         limitCheck(loc, size, "gl_MaxTextureCoords", "gl_TexCoord array size");
5309     else if (identifier.compare("gl_ClipDistance") == 0)
5310         limitCheck(loc, size, "gl_MaxClipDistances", "gl_ClipDistance array size");
5311     else if (identifier.compare("gl_CullDistance") == 0)
5312         limitCheck(loc, size, "gl_MaxCullDistances", "gl_CullDistance array size");
5313     else if (identifier.compare("gl_ClipDistancePerViewNV") == 0)
5314         limitCheck(loc, size, "gl_MaxClipDistances", "gl_ClipDistancePerViewNV array size");
5315     else if (identifier.compare("gl_CullDistancePerViewNV") == 0)
5316         limitCheck(loc, size, "gl_MaxCullDistances", "gl_CullDistancePerViewNV array size");
5317 }
5318 #endif // GLSLANG_WEB
5319
5320 // See if the provided value is less than or equal to the symbol indicated by limit,
5321 // which should be a constant in the symbol table.
5322 void TParseContext::limitCheck(const TSourceLoc& loc, int value, const char* limit, const char* feature)
5323 {
5324     TSymbol* symbol = symbolTable.find(limit);
5325     assert(symbol->getAsVariable());
5326     const TConstUnionArray& constArray = symbol->getAsVariable()->getConstArray();
5327     assert(! constArray.empty());
5328     if (value > constArray[0].getIConst())
5329         error(loc, "must be less than or equal to", feature, "%s (%d)", limit, constArray[0].getIConst());
5330 }
5331
5332 #ifndef GLSLANG_WEB
5333
5334 //
5335 // Do any additional error checking, etc., once we know the parsing is done.
5336 //
5337 void TParseContext::finish()
5338 {
5339     TParseContextBase::finish();
5340
5341     if (parsingBuiltins)
5342         return;
5343
5344     // Check on array indexes for ES 2.0 (version 100) limitations.
5345     for (size_t i = 0; i < needsIndexLimitationChecking.size(); ++i)
5346         constantIndexExpressionCheck(needsIndexLimitationChecking[i]);
5347
5348     // Check for stages that are enabled by extension.
5349     // Can't do this at the beginning, it is chicken and egg to add a stage by
5350     // extension.
5351     // Stage-specific features were correctly tested for already, this is just
5352     // about the stage itself.
5353     switch (language) {
5354     case EShLangGeometry:
5355         if (isEsProfile() && version == 310)
5356             requireExtensions(getCurrentLoc(), Num_AEP_geometry_shader, AEP_geometry_shader, "geometry shaders");
5357         break;
5358     case EShLangTessControl:
5359     case EShLangTessEvaluation:
5360         if (isEsProfile() && version == 310)
5361             requireExtensions(getCurrentLoc(), Num_AEP_tessellation_shader, AEP_tessellation_shader, "tessellation shaders");
5362         else if (!isEsProfile() && version < 400)
5363             requireExtensions(getCurrentLoc(), 1, &E_GL_ARB_tessellation_shader, "tessellation shaders");
5364         break;
5365     case EShLangCompute:
5366         if (!isEsProfile() && version < 430)
5367             requireExtensions(getCurrentLoc(), 1, &E_GL_ARB_compute_shader, "compute shaders");
5368         break;
5369     case EShLangTask:
5370         requireExtensions(getCurrentLoc(), Num_AEP_mesh_shader, AEP_mesh_shader, "task shaders");
5371         break;
5372     case EShLangMesh:
5373         requireExtensions(getCurrentLoc(), Num_AEP_mesh_shader, AEP_mesh_shader, "mesh shaders");
5374         break;
5375     default:
5376         break;
5377     }
5378
5379     // Set default outputs for GL_NV_geometry_shader_passthrough
5380     if (language == EShLangGeometry && extensionTurnedOn(E_SPV_NV_geometry_shader_passthrough)) {
5381         if (intermediate.getOutputPrimitive() == ElgNone) {
5382             switch (intermediate.getInputPrimitive()) {
5383             case ElgPoints:      intermediate.setOutputPrimitive(ElgPoints);    break;
5384             case ElgLines:       intermediate.setOutputPrimitive(ElgLineStrip); break;
5385             case ElgTriangles:   intermediate.setOutputPrimitive(ElgTriangleStrip); break;
5386             default: break;
5387             }
5388         }
5389         if (intermediate.getVertices() == TQualifier::layoutNotSet) {
5390             switch (intermediate.getInputPrimitive()) {
5391             case ElgPoints:      intermediate.setVertices(1); break;
5392             case ElgLines:       intermediate.setVertices(2); break;
5393             case ElgTriangles:   intermediate.setVertices(3); break;
5394             default: break;
5395             }
5396         }
5397     }
5398 }
5399 #endif // GLSLANG_WEB
5400
5401 //
5402 // Layout qualifier stuff.
5403 //
5404
5405 // Put the id's layout qualification into the public type, for qualifiers not having a number set.
5406 // This is before we know any type information for error checking.
5407 void TParseContext::setLayoutQualifier(const TSourceLoc& loc, TPublicType& publicType, TString& id)
5408 {
5409     std::transform(id.begin(), id.end(), id.begin(), ::tolower);
5410
5411     if (id == TQualifier::getLayoutMatrixString(ElmColumnMajor)) {
5412         publicType.qualifier.layoutMatrix = ElmColumnMajor;
5413         return;
5414     }
5415     if (id == TQualifier::getLayoutMatrixString(ElmRowMajor)) {
5416         publicType.qualifier.layoutMatrix = ElmRowMajor;
5417         return;
5418     }
5419     if (id == TQualifier::getLayoutPackingString(ElpPacked)) {
5420         if (spvVersion.spv != 0) {
5421             if (spvVersion.vulkanRelaxed)
5422                 return; // silently ignore qualifier
5423             else
5424                 spvRemoved(loc, "packed");
5425         }
5426         publicType.qualifier.layoutPacking = ElpPacked;
5427         return;
5428     }
5429     if (id == TQualifier::getLayoutPackingString(ElpShared)) {
5430         if (spvVersion.spv != 0) {
5431             if (spvVersion.vulkanRelaxed)
5432                 return; // silently ignore qualifier
5433             else
5434                 spvRemoved(loc, "shared");
5435         }
5436         publicType.qualifier.layoutPacking = ElpShared;
5437         return;
5438     }
5439     if (id == TQualifier::getLayoutPackingString(ElpStd140)) {
5440         publicType.qualifier.layoutPacking = ElpStd140;
5441         return;
5442     }
5443 #ifndef GLSLANG_WEB
5444     if (id == TQualifier::getLayoutPackingString(ElpStd430)) {
5445         requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, "std430");
5446         profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, E_GL_ARB_shader_storage_buffer_object, "std430");
5447         profileRequires(loc, EEsProfile, 310, nullptr, "std430");
5448         publicType.qualifier.layoutPacking = ElpStd430;
5449         return;
5450     }
5451     if (id == TQualifier::getLayoutPackingString(ElpScalar)) {
5452         requireVulkan(loc, "scalar");
5453         requireExtensions(loc, 1, &E_GL_EXT_scalar_block_layout, "scalar block layout");
5454         publicType.qualifier.layoutPacking = ElpScalar;
5455         return;
5456     }
5457     // TODO: compile-time performance: may need to stop doing linear searches
5458     for (TLayoutFormat format = (TLayoutFormat)(ElfNone + 1); format < ElfCount; format = (TLayoutFormat)(format + 1)) {
5459         if (id == TQualifier::getLayoutFormatString(format)) {
5460             if ((format > ElfEsFloatGuard && format < ElfFloatGuard) ||
5461                 (format > ElfEsIntGuard && format < ElfIntGuard) ||
5462                 (format > ElfEsUintGuard && format < ElfCount))
5463                 requireProfile(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, "image load-store format");
5464             profileRequires(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, 420, E_GL_ARB_shader_image_load_store, "image load store");
5465             profileRequires(loc, EEsProfile, 310, E_GL_ARB_shader_image_load_store, "image load store");
5466             publicType.qualifier.layoutFormat = format;
5467             return;
5468         }
5469     }
5470     if (id == "push_constant") {
5471         requireVulkan(loc, "push_constant");
5472         publicType.qualifier.layoutPushConstant = true;
5473         return;
5474     }
5475     if (id == "buffer_reference") {
5476         requireVulkan(loc, "buffer_reference");
5477         requireExtensions(loc, 1, &E_GL_EXT_buffer_reference, "buffer_reference");
5478         publicType.qualifier.layoutBufferReference = true;
5479         intermediate.setUseStorageBuffer();
5480         intermediate.setUsePhysicalStorageBuffer();
5481         return;
5482     }
5483     if (language == EShLangGeometry || language == EShLangTessEvaluation || language == EShLangMesh) {
5484         if (id == TQualifier::getGeometryString(ElgTriangles)) {
5485             publicType.shaderQualifiers.geometry = ElgTriangles;
5486             return;
5487         }
5488         if (language == EShLangGeometry || language == EShLangMesh) {
5489             if (id == TQualifier::getGeometryString(ElgPoints)) {
5490                 publicType.shaderQualifiers.geometry = ElgPoints;
5491                 return;
5492             }
5493             if (id == TQualifier::getGeometryString(ElgLines)) {
5494                 publicType.shaderQualifiers.geometry = ElgLines;
5495                 return;
5496             }
5497             if (language == EShLangGeometry) {
5498                 if (id == TQualifier::getGeometryString(ElgLineStrip)) {
5499                     publicType.shaderQualifiers.geometry = ElgLineStrip;
5500                     return;
5501                 }
5502                 if (id == TQualifier::getGeometryString(ElgLinesAdjacency)) {
5503                     publicType.shaderQualifiers.geometry = ElgLinesAdjacency;
5504                     return;
5505                 }
5506                 if (id == TQualifier::getGeometryString(ElgTrianglesAdjacency)) {
5507                     publicType.shaderQualifiers.geometry = ElgTrianglesAdjacency;
5508                     return;
5509                 }
5510                 if (id == TQualifier::getGeometryString(ElgTriangleStrip)) {
5511                     publicType.shaderQualifiers.geometry = ElgTriangleStrip;
5512                     return;
5513                 }
5514                 if (id == "passthrough") {
5515                     requireExtensions(loc, 1, &E_SPV_NV_geometry_shader_passthrough, "geometry shader passthrough");
5516                     publicType.qualifier.layoutPassthrough = true;
5517                     intermediate.setGeoPassthroughEXT();
5518                     return;
5519                 }
5520             }
5521         } else {
5522             assert(language == EShLangTessEvaluation);
5523
5524             // input primitive
5525             if (id == TQualifier::getGeometryString(ElgTriangles)) {
5526                 publicType.shaderQualifiers.geometry = ElgTriangles;
5527                 return;
5528             }
5529             if (id == TQualifier::getGeometryString(ElgQuads)) {
5530                 publicType.shaderQualifiers.geometry = ElgQuads;
5531                 return;
5532             }
5533             if (id == TQualifier::getGeometryString(ElgIsolines)) {
5534                 publicType.shaderQualifiers.geometry = ElgIsolines;
5535                 return;
5536             }
5537
5538             // vertex spacing
5539             if (id == TQualifier::getVertexSpacingString(EvsEqual)) {
5540                 publicType.shaderQualifiers.spacing = EvsEqual;
5541                 return;
5542             }
5543             if (id == TQualifier::getVertexSpacingString(EvsFractionalEven)) {
5544                 publicType.shaderQualifiers.spacing = EvsFractionalEven;
5545                 return;
5546             }
5547             if (id == TQualifier::getVertexSpacingString(EvsFractionalOdd)) {
5548                 publicType.shaderQualifiers.spacing = EvsFractionalOdd;
5549                 return;
5550             }
5551
5552             // triangle order
5553             if (id == TQualifier::getVertexOrderString(EvoCw)) {
5554                 publicType.shaderQualifiers.order = EvoCw;
5555                 return;
5556             }
5557             if (id == TQualifier::getVertexOrderString(EvoCcw)) {
5558                 publicType.shaderQualifiers.order = EvoCcw;
5559                 return;
5560             }
5561
5562             // point mode
5563             if (id == "point_mode") {
5564                 publicType.shaderQualifiers.pointMode = true;
5565                 return;
5566             }
5567         }
5568     }
5569     if (language == EShLangFragment) {
5570         if (id == "origin_upper_left") {
5571             requireProfile(loc, ECoreProfile | ECompatibilityProfile | ENoProfile, "origin_upper_left");
5572             if (profile == ENoProfile) {
5573                 profileRequires(loc,ECoreProfile | ECompatibilityProfile, 140, E_GL_ARB_fragment_coord_conventions, "origin_upper_left");
5574             }
5575
5576             publicType.shaderQualifiers.originUpperLeft = true;
5577             return;
5578         }
5579         if (id == "pixel_center_integer") {
5580             requireProfile(loc, ECoreProfile | ECompatibilityProfile | ENoProfile, "pixel_center_integer");
5581             if (profile == ENoProfile) {
5582                 profileRequires(loc,ECoreProfile | ECompatibilityProfile, 140, E_GL_ARB_fragment_coord_conventions, "pixel_center_integer");
5583             }
5584             publicType.shaderQualifiers.pixelCenterInteger = true;
5585             return;
5586         }
5587         if (id == "early_fragment_tests") {
5588             profileRequires(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, 420, E_GL_ARB_shader_image_load_store, "early_fragment_tests");
5589             profileRequires(loc, EEsProfile, 310, nullptr, "early_fragment_tests");
5590             publicType.shaderQualifiers.earlyFragmentTests = true;
5591             return;
5592         }
5593         if (id == "early_and_late_fragment_tests_amd") {
5594             profileRequires(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, 420, E_GL_AMD_shader_early_and_late_fragment_tests, "early_and_late_fragment_tests_amd");
5595             profileRequires(loc, EEsProfile, 310, nullptr, "early_and_late_fragment_tests_amd");
5596             publicType.shaderQualifiers.earlyAndLateFragmentTestsAMD = true;
5597             return;
5598         }
5599         if (id == "post_depth_coverage") {
5600             requireExtensions(loc, Num_post_depth_coverageEXTs, post_depth_coverageEXTs, "post depth coverage");
5601             if (extensionTurnedOn(E_GL_ARB_post_depth_coverage)) {
5602                 publicType.shaderQualifiers.earlyFragmentTests = true;
5603             }
5604             publicType.shaderQualifiers.postDepthCoverage = true;
5605             return;
5606         }
5607         for (TLayoutDepth depth = (TLayoutDepth)(EldNone + 1); depth < EldCount; depth = (TLayoutDepth)(depth+1)) {
5608             if (id == TQualifier::getLayoutDepthString(depth)) {
5609                 requireProfile(loc, ECoreProfile | ECompatibilityProfile, "depth layout qualifier");
5610                 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 420, nullptr, "depth layout qualifier");
5611                 publicType.shaderQualifiers.layoutDepth = depth;
5612                 return;
5613             }
5614         }
5615         for (TLayoutStencil stencil = (TLayoutStencil)(ElsNone + 1); stencil < ElsCount; stencil = (TLayoutStencil)(stencil+1)) {
5616             if (id == TQualifier::getLayoutStencilString(stencil)) {
5617                 requireProfile(loc, ECoreProfile | ECompatibilityProfile, "stencil layout qualifier");
5618                 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 420, nullptr, "stencil layout qualifier");
5619                 publicType.shaderQualifiers.layoutStencil = stencil;
5620                 return;
5621             }
5622         }
5623         for (TInterlockOrdering order = (TInterlockOrdering)(EioNone + 1); order < EioCount; order = (TInterlockOrdering)(order+1)) {
5624             if (id == TQualifier::getInterlockOrderingString(order)) {
5625                 requireProfile(loc, ECoreProfile | ECompatibilityProfile, "fragment shader interlock layout qualifier");
5626                 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 450, nullptr, "fragment shader interlock layout qualifier");
5627                 requireExtensions(loc, 1, &E_GL_ARB_fragment_shader_interlock, TQualifier::getInterlockOrderingString(order));
5628                 if (order == EioShadingRateInterlockOrdered || order == EioShadingRateInterlockUnordered)
5629                     requireExtensions(loc, 1, &E_GL_NV_shading_rate_image, TQualifier::getInterlockOrderingString(order));
5630                 publicType.shaderQualifiers.interlockOrdering = order;
5631                 return;
5632             }
5633         }
5634         if (id.compare(0, 13, "blend_support") == 0) {
5635             bool found = false;
5636             for (TBlendEquationShift be = (TBlendEquationShift)0; be < EBlendCount; be = (TBlendEquationShift)(be + 1)) {
5637                 if (id == TQualifier::getBlendEquationString(be)) {
5638                     profileRequires(loc, EEsProfile, 320, E_GL_KHR_blend_equation_advanced, "blend equation");
5639                     profileRequires(loc, ~EEsProfile, 0, E_GL_KHR_blend_equation_advanced, "blend equation");
5640                     intermediate.addBlendEquation(be);
5641                     publicType.shaderQualifiers.blendEquation = true;
5642                     found = true;
5643                     break;
5644                 }
5645             }
5646             if (! found)
5647                 error(loc, "unknown blend equation", "blend_support", "");
5648             return;
5649         }
5650         if (id == "override_coverage") {
5651             requireExtensions(loc, 1, &E_GL_NV_sample_mask_override_coverage, "sample mask override coverage");
5652             publicType.shaderQualifiers.layoutOverrideCoverage = true;
5653             return;
5654         }
5655     }
5656     if (language == EShLangVertex ||
5657         language == EShLangTessControl ||
5658         language == EShLangTessEvaluation ||
5659         language == EShLangGeometry ) {
5660         if (id == "viewport_relative") {
5661             requireExtensions(loc, 1, &E_GL_NV_viewport_array2, "view port array2");
5662             publicType.qualifier.layoutViewportRelative = true;
5663             return;
5664         }
5665     } else {
5666         if (language == EShLangRayGen || language == EShLangIntersect ||
5667         language == EShLangAnyHit || language == EShLangClosestHit ||
5668         language == EShLangMiss || language == EShLangCallable) {
5669             if (id == "shaderrecordnv" || id == "shaderrecordext") {
5670                 if (id == "shaderrecordnv") {
5671                     requireExtensions(loc, 1, &E_GL_NV_ray_tracing, "shader record NV");
5672                 } else {
5673                     requireExtensions(loc, 1, &E_GL_EXT_ray_tracing, "shader record EXT");
5674                 }
5675                 publicType.qualifier.layoutShaderRecord = true;
5676                 return;
5677             }
5678
5679         }
5680     }
5681     if (language == EShLangCompute) {
5682         if (id.compare(0, 17, "derivative_group_") == 0) {
5683             requireExtensions(loc, 1, &E_GL_NV_compute_shader_derivatives, "compute shader derivatives");
5684             if (id == "derivative_group_quadsnv") {
5685                 publicType.shaderQualifiers.layoutDerivativeGroupQuads = true;
5686                 return;
5687             } else if (id == "derivative_group_linearnv") {
5688                 publicType.shaderQualifiers.layoutDerivativeGroupLinear = true;
5689                 return;
5690             }
5691         }
5692     }
5693
5694     if (id == "primitive_culling") {
5695         requireExtensions(loc, 1, &E_GL_EXT_ray_flags_primitive_culling, "primitive culling");
5696         publicType.shaderQualifiers.layoutPrimitiveCulling = true;
5697         return;
5698     }
5699 #endif
5700
5701     error(loc, "unrecognized layout identifier, or qualifier requires assignment (e.g., binding = 4)", id.c_str(), "");
5702 }
5703
5704 // Put the id's layout qualifier value into the public type, for qualifiers having a number set.
5705 // This is before we know any type information for error checking.
5706 void TParseContext::setLayoutQualifier(const TSourceLoc& loc, TPublicType& publicType, TString& id, const TIntermTyped* node)
5707 {
5708     const char* feature = "layout-id value";
5709     const char* nonLiteralFeature = "non-literal layout-id value";
5710
5711     integerCheck(node, feature);
5712     const TIntermConstantUnion* constUnion = node->getAsConstantUnion();
5713     int value;
5714     bool nonLiteral = false;
5715     if (constUnion) {
5716         value = constUnion->getConstArray()[0].getIConst();
5717         if (! constUnion->isLiteral()) {
5718             requireProfile(loc, ECoreProfile | ECompatibilityProfile, nonLiteralFeature);
5719             profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, nonLiteralFeature);
5720         }
5721     } else {
5722         // grammar should have give out the error message
5723         value = 0;
5724         nonLiteral = true;
5725     }
5726
5727     if (value < 0) {
5728         error(loc, "cannot be negative", feature, "");
5729         return;
5730     }
5731
5732     std::transform(id.begin(), id.end(), id.begin(), ::tolower);
5733
5734     if (id == "offset") {
5735         // "offset" can be for either
5736         //  - uniform offsets
5737         //  - atomic_uint offsets
5738         const char* feature = "offset";
5739         if (spvVersion.spv == 0) {
5740             requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, feature);
5741             const char* exts[2] = { E_GL_ARB_enhanced_layouts, E_GL_ARB_shader_atomic_counters };
5742             profileRequires(loc, ECoreProfile | ECompatibilityProfile, 420, 2, exts, feature);
5743             profileRequires(loc, EEsProfile, 310, nullptr, feature);
5744         }
5745         publicType.qualifier.layoutOffset = value;
5746         publicType.qualifier.explicitOffset = true;
5747         if (nonLiteral)
5748             error(loc, "needs a literal integer", "offset", "");
5749         return;
5750     } else if (id == "align") {
5751         const char* feature = "uniform buffer-member align";
5752         if (spvVersion.spv == 0) {
5753             requireProfile(loc, ECoreProfile | ECompatibilityProfile, feature);
5754             profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, feature);
5755         }
5756         // "The specified alignment must be a power of 2, or a compile-time error results."
5757         if (! IsPow2(value))
5758             error(loc, "must be a power of 2", "align", "");
5759         else
5760             publicType.qualifier.layoutAlign = value;
5761         if (nonLiteral)
5762             error(loc, "needs a literal integer", "align", "");
5763         return;
5764     } else if (id == "location") {
5765         profileRequires(loc, EEsProfile, 300, nullptr, "location");
5766         const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location };
5767         // GL_ARB_explicit_uniform_location requires 330 or GL_ARB_explicit_attrib_location we do not need to add it here
5768         profileRequires(loc, ~EEsProfile, 330, 2, exts, "location");
5769         if ((unsigned int)value >= TQualifier::layoutLocationEnd)
5770             error(loc, "location is too large", id.c_str(), "");
5771         else
5772             publicType.qualifier.layoutLocation = value;
5773         if (nonLiteral)
5774             error(loc, "needs a literal integer", "location", "");
5775         return;
5776     } else if (id == "set") {
5777         if ((unsigned int)value >= TQualifier::layoutSetEnd)
5778             error(loc, "set is too large", id.c_str(), "");
5779         else
5780             publicType.qualifier.layoutSet = value;
5781         if (value != 0)
5782             requireVulkan(loc, "descriptor set");
5783         if (nonLiteral)
5784             error(loc, "needs a literal integer", "set", "");
5785         return;
5786     } else if (id == "binding") {
5787 #ifndef GLSLANG_WEB
5788         profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, "binding");
5789         profileRequires(loc, EEsProfile, 310, nullptr, "binding");
5790 #endif
5791         if ((unsigned int)value >= TQualifier::layoutBindingEnd)
5792             error(loc, "binding is too large", id.c_str(), "");
5793         else
5794             publicType.qualifier.layoutBinding = value;
5795         if (nonLiteral)
5796             error(loc, "needs a literal integer", "binding", "");
5797         return;
5798     }
5799     if (id == "constant_id") {
5800         requireSpv(loc, "constant_id");
5801         if (value >= (int)TQualifier::layoutSpecConstantIdEnd) {
5802             error(loc, "specialization-constant id is too large", id.c_str(), "");
5803         } else {
5804             publicType.qualifier.layoutSpecConstantId = value;
5805             publicType.qualifier.specConstant = true;
5806             if (! intermediate.addUsedConstantId(value))
5807                 error(loc, "specialization-constant id already used", id.c_str(), "");
5808         }
5809         if (nonLiteral)
5810             error(loc, "needs a literal integer", "constant_id", "");
5811         return;
5812     }
5813 #ifndef GLSLANG_WEB
5814     if (id == "component") {
5815         requireProfile(loc, ECoreProfile | ECompatibilityProfile, "component");
5816         profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, "component");
5817         if ((unsigned)value >= TQualifier::layoutComponentEnd)
5818             error(loc, "component is too large", id.c_str(), "");
5819         else
5820             publicType.qualifier.layoutComponent = value;
5821         if (nonLiteral)
5822             error(loc, "needs a literal integer", "component", "");
5823         return;
5824     }
5825     if (id.compare(0, 4, "xfb_") == 0) {
5826         // "Any shader making any static use (after preprocessing) of any of these
5827         // *xfb_* qualifiers will cause the shader to be in a transform feedback
5828         // capturing mode and hence responsible for describing the transform feedback
5829         // setup."
5830         intermediate.setXfbMode();
5831         const char* feature = "transform feedback qualifier";
5832         requireStage(loc, (EShLanguageMask)(EShLangVertexMask | EShLangGeometryMask | EShLangTessControlMask | EShLangTessEvaluationMask), feature);
5833         requireProfile(loc, ECoreProfile | ECompatibilityProfile, feature);
5834         profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, feature);
5835         if (id == "xfb_buffer") {
5836             // "It is a compile-time error to specify an *xfb_buffer* that is greater than
5837             // the implementation-dependent constant gl_MaxTransformFeedbackBuffers."
5838             if (value >= resources.maxTransformFeedbackBuffers)
5839                 error(loc, "buffer is too large:", id.c_str(), "gl_MaxTransformFeedbackBuffers is %d", resources.maxTransformFeedbackBuffers);
5840             if (value >= (int)TQualifier::layoutXfbBufferEnd)
5841                 error(loc, "buffer is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbBufferEnd-1);
5842             else
5843                 publicType.qualifier.layoutXfbBuffer = value;
5844             if (nonLiteral)
5845                 error(loc, "needs a literal integer", "xfb_buffer", "");
5846             return;
5847         } else if (id == "xfb_offset") {
5848             if (value >= (int)TQualifier::layoutXfbOffsetEnd)
5849                 error(loc, "offset is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbOffsetEnd-1);
5850             else
5851                 publicType.qualifier.layoutXfbOffset = value;
5852             if (nonLiteral)
5853                 error(loc, "needs a literal integer", "xfb_offset", "");
5854             return;
5855         } else if (id == "xfb_stride") {
5856             // "The resulting stride (implicit or explicit), when divided by 4, must be less than or equal to the
5857             // implementation-dependent constant gl_MaxTransformFeedbackInterleavedComponents."
5858             if (value > 4 * resources.maxTransformFeedbackInterleavedComponents) {
5859                 error(loc, "1/4 stride is too large:", id.c_str(), "gl_MaxTransformFeedbackInterleavedComponents is %d",
5860                     resources.maxTransformFeedbackInterleavedComponents);
5861             }
5862             if (value >= (int)TQualifier::layoutXfbStrideEnd)
5863                 error(loc, "stride is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbStrideEnd-1);
5864             else
5865                 publicType.qualifier.layoutXfbStride = value;
5866             if (nonLiteral)
5867                 error(loc, "needs a literal integer", "xfb_stride", "");
5868             return;
5869         }
5870     }
5871     if (id == "input_attachment_index") {
5872         requireVulkan(loc, "input_attachment_index");
5873         if (value >= (int)TQualifier::layoutAttachmentEnd)
5874             error(loc, "attachment index is too large", id.c_str(), "");
5875         else
5876             publicType.qualifier.layoutAttachment = value;
5877         if (nonLiteral)
5878             error(loc, "needs a literal integer", "input_attachment_index", "");
5879         return;
5880     }
5881     if (id == "num_views") {
5882         requireExtensions(loc, Num_OVR_multiview_EXTs, OVR_multiview_EXTs, "num_views");
5883         publicType.shaderQualifiers.numViews = value;
5884         if (nonLiteral)
5885             error(loc, "needs a literal integer", "num_views", "");
5886         return;
5887     }
5888     if (language == EShLangVertex ||
5889         language == EShLangTessControl ||
5890         language == EShLangTessEvaluation ||
5891         language == EShLangGeometry) {
5892         if (id == "secondary_view_offset") {
5893             requireExtensions(loc, 1, &E_GL_NV_stereo_view_rendering, "stereo view rendering");
5894             publicType.qualifier.layoutSecondaryViewportRelativeOffset = value;
5895             if (nonLiteral)
5896                 error(loc, "needs a literal integer", "secondary_view_offset", "");
5897             return;
5898         }
5899     }
5900
5901     if (id == "buffer_reference_align") {
5902         requireExtensions(loc, 1, &E_GL_EXT_buffer_reference, "buffer_reference_align");
5903         if (! IsPow2(value))
5904             error(loc, "must be a power of 2", "buffer_reference_align", "");
5905         else
5906             publicType.qualifier.layoutBufferReferenceAlign = IntLog2(value);
5907         if (nonLiteral)
5908             error(loc, "needs a literal integer", "buffer_reference_align", "");
5909         return;
5910     }
5911 #endif
5912
5913     switch (language) {
5914 #ifndef GLSLANG_WEB
5915     case EShLangTessControl:
5916         if (id == "vertices") {
5917             if (value == 0)
5918                 error(loc, "must be greater than 0", "vertices", "");
5919             else
5920                 publicType.shaderQualifiers.vertices = value;
5921             if (nonLiteral)
5922                 error(loc, "needs a literal integer", "vertices", "");
5923             return;
5924         }
5925         break;
5926
5927     case EShLangGeometry:
5928         if (id == "invocations") {
5929             profileRequires(loc, ECompatibilityProfile | ECoreProfile, 400, nullptr, "invocations");
5930             if (value == 0)
5931                 error(loc, "must be at least 1", "invocations", "");
5932             else
5933                 publicType.shaderQualifiers.invocations = value;
5934             if (nonLiteral)
5935                 error(loc, "needs a literal integer", "invocations", "");
5936             return;
5937         }
5938         if (id == "max_vertices") {
5939             publicType.shaderQualifiers.vertices = value;
5940             if (value > resources.maxGeometryOutputVertices)
5941                 error(loc, "too large, must be less than gl_MaxGeometryOutputVertices", "max_vertices", "");
5942             if (nonLiteral)
5943                 error(loc, "needs a literal integer", "max_vertices", "");
5944             return;
5945         }
5946         if (id == "stream") {
5947             requireProfile(loc, ~EEsProfile, "selecting output stream");
5948             publicType.qualifier.layoutStream = value;
5949             if (value > 0)
5950                 intermediate.setMultiStream();
5951             if (nonLiteral)
5952                 error(loc, "needs a literal integer", "stream", "");
5953             return;
5954         }
5955         break;
5956
5957     case EShLangFragment:
5958         if (id == "index") {
5959             requireProfile(loc, ECompatibilityProfile | ECoreProfile | EEsProfile, "index layout qualifier on fragment output");
5960             const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location };
5961             profileRequires(loc, ECompatibilityProfile | ECoreProfile, 330, 2, exts, "index layout qualifier on fragment output");
5962             profileRequires(loc, EEsProfile ,310, E_GL_EXT_blend_func_extended, "index layout qualifier on fragment output");
5963             // "It is also a compile-time error if a fragment shader sets a layout index to less than 0 or greater than 1."
5964             if (value < 0 || value > 1) {
5965                 value = 0;
5966                 error(loc, "value must be 0 or 1", "index", "");
5967             }
5968
5969             publicType.qualifier.layoutIndex = value;
5970             if (nonLiteral)
5971                 error(loc, "needs a literal integer", "index", "");
5972             return;
5973         }
5974         break;
5975
5976     case EShLangMesh:
5977         if (id == "max_vertices") {
5978             requireExtensions(loc, Num_AEP_mesh_shader, AEP_mesh_shader, "max_vertices");
5979             publicType.shaderQualifiers.vertices = value;
5980             int max = extensionTurnedOn(E_GL_EXT_mesh_shader) ? resources.maxMeshOutputVerticesEXT
5981                                                               : resources.maxMeshOutputVerticesNV;
5982             if (value > max) {
5983                 TString maxsErrtring = "too large, must be less than ";
5984                 maxsErrtring.append(extensionTurnedOn(E_GL_EXT_mesh_shader) ? "gl_MaxMeshOutputVerticesEXT"
5985                                                                             : "gl_MaxMeshOutputVerticesNV");
5986                 error(loc, maxsErrtring.c_str(), "max_vertices", "");
5987             }
5988             if (nonLiteral)
5989                 error(loc, "needs a literal integer", "max_vertices", "");
5990             return;
5991         }
5992         if (id == "max_primitives") {
5993             requireExtensions(loc, Num_AEP_mesh_shader, AEP_mesh_shader, "max_primitives");
5994             publicType.shaderQualifiers.primitives = value;
5995             int max = extensionTurnedOn(E_GL_EXT_mesh_shader) ? resources.maxMeshOutputPrimitivesEXT
5996                                                               : resources.maxMeshOutputPrimitivesNV;
5997             if (value > max) {
5998                 TString maxsErrtring = "too large, must be less than ";
5999                 maxsErrtring.append(extensionTurnedOn(E_GL_EXT_mesh_shader) ? "gl_MaxMeshOutputPrimitivesEXT"
6000                                                                             : "gl_MaxMeshOutputPrimitivesNV");
6001                 error(loc, maxsErrtring.c_str(), "max_primitives", "");
6002             }
6003             if (nonLiteral)
6004                 error(loc, "needs a literal integer", "max_primitives", "");
6005             return;
6006         }
6007         // Fall through
6008
6009     case EShLangTask:
6010         // Fall through
6011 #endif
6012     case EShLangCompute:
6013         if (id.compare(0, 11, "local_size_") == 0) {
6014 #ifndef GLSLANG_WEB
6015             if (language == EShLangMesh || language == EShLangTask) {
6016                 requireExtensions(loc, Num_AEP_mesh_shader, AEP_mesh_shader, "gl_WorkGroupSize");
6017             } else {
6018                 profileRequires(loc, EEsProfile, 310, 0, "gl_WorkGroupSize");
6019                 profileRequires(loc, ~EEsProfile, 430, E_GL_ARB_compute_shader, "gl_WorkGroupSize");
6020             }
6021 #endif
6022             if (nonLiteral)
6023                 error(loc, "needs a literal integer", "local_size", "");
6024             if (id.size() == 12 && value == 0) {
6025                 error(loc, "must be at least 1", id.c_str(), "");
6026                 return;
6027             }
6028             if (id == "local_size_x") {
6029                 publicType.shaderQualifiers.localSize[0] = value;
6030                 publicType.shaderQualifiers.localSizeNotDefault[0] = true;
6031                 return;
6032             }
6033             if (id == "local_size_y") {
6034                 publicType.shaderQualifiers.localSize[1] = value;
6035                 publicType.shaderQualifiers.localSizeNotDefault[1] = true;
6036                 return;
6037             }
6038             if (id == "local_size_z") {
6039                 publicType.shaderQualifiers.localSize[2] = value;
6040                 publicType.shaderQualifiers.localSizeNotDefault[2] = true;
6041                 return;
6042             }
6043             if (spvVersion.spv != 0) {
6044                 if (id == "local_size_x_id") {
6045                     publicType.shaderQualifiers.localSizeSpecId[0] = value;
6046                     return;
6047                 }
6048                 if (id == "local_size_y_id") {
6049                     publicType.shaderQualifiers.localSizeSpecId[1] = value;
6050                     return;
6051                 }
6052                 if (id == "local_size_z_id") {
6053                     publicType.shaderQualifiers.localSizeSpecId[2] = value;
6054                     return;
6055                 }
6056             }
6057         }
6058         break;
6059
6060     default:
6061         break;
6062     }
6063
6064     error(loc, "there is no such layout identifier for this stage taking an assigned value", id.c_str(), "");
6065 }
6066
6067 // Merge any layout qualifier information from src into dst, leaving everything else in dst alone
6068 //
6069 // "More than one layout qualifier may appear in a single declaration.
6070 // Additionally, the same layout-qualifier-name can occur multiple times
6071 // within a layout qualifier or across multiple layout qualifiers in the
6072 // same declaration. When the same layout-qualifier-name occurs
6073 // multiple times, in a single declaration, the last occurrence overrides
6074 // the former occurrence(s).  Further, if such a layout-qualifier-name
6075 // will effect subsequent declarations or other observable behavior, it
6076 // is only the last occurrence that will have any effect, behaving as if
6077 // the earlier occurrence(s) within the declaration are not present.
6078 // This is also true for overriding layout-qualifier-names, where one
6079 // overrides the other (e.g., row_major vs. column_major); only the last
6080 // occurrence has any effect."
6081 void TParseContext::mergeObjectLayoutQualifiers(TQualifier& dst, const TQualifier& src, bool inheritOnly)
6082 {
6083     if (src.hasMatrix())
6084         dst.layoutMatrix = src.layoutMatrix;
6085     if (src.hasPacking())
6086         dst.layoutPacking = src.layoutPacking;
6087
6088 #ifndef GLSLANG_WEB
6089     if (src.hasStream())
6090         dst.layoutStream = src.layoutStream;
6091     if (src.hasFormat())
6092         dst.layoutFormat = src.layoutFormat;
6093     if (src.hasXfbBuffer())
6094         dst.layoutXfbBuffer = src.layoutXfbBuffer;
6095     if (src.hasBufferReferenceAlign())
6096         dst.layoutBufferReferenceAlign = src.layoutBufferReferenceAlign;
6097 #endif
6098
6099     if (src.hasAlign())
6100         dst.layoutAlign = src.layoutAlign;
6101
6102     if (! inheritOnly) {
6103         if (src.hasLocation())
6104             dst.layoutLocation = src.layoutLocation;
6105         if (src.hasOffset())
6106             dst.layoutOffset = src.layoutOffset;
6107         if (src.hasSet())
6108             dst.layoutSet = src.layoutSet;
6109         if (src.layoutBinding != TQualifier::layoutBindingEnd)
6110             dst.layoutBinding = src.layoutBinding;
6111
6112         if (src.hasSpecConstantId())
6113             dst.layoutSpecConstantId = src.layoutSpecConstantId;
6114
6115 #ifndef GLSLANG_WEB
6116         if (src.hasComponent())
6117             dst.layoutComponent = src.layoutComponent;
6118         if (src.hasIndex())
6119             dst.layoutIndex = src.layoutIndex;
6120         if (src.hasXfbStride())
6121             dst.layoutXfbStride = src.layoutXfbStride;
6122         if (src.hasXfbOffset())
6123             dst.layoutXfbOffset = src.layoutXfbOffset;
6124         if (src.hasAttachment())
6125             dst.layoutAttachment = src.layoutAttachment;
6126         if (src.layoutPushConstant)
6127             dst.layoutPushConstant = true;
6128
6129         if (src.layoutBufferReference)
6130             dst.layoutBufferReference = true;
6131
6132         if (src.layoutPassthrough)
6133             dst.layoutPassthrough = true;
6134         if (src.layoutViewportRelative)
6135             dst.layoutViewportRelative = true;
6136         if (src.layoutSecondaryViewportRelativeOffset != -2048)
6137             dst.layoutSecondaryViewportRelativeOffset = src.layoutSecondaryViewportRelativeOffset;
6138         if (src.layoutShaderRecord)
6139             dst.layoutShaderRecord = true;
6140         if (src.pervertexNV)
6141             dst.pervertexNV = true;
6142         if (src.pervertexEXT)
6143             dst.pervertexEXT = true;
6144 #endif
6145     }
6146 }
6147
6148 // Do error layout error checking given a full variable/block declaration.
6149 void TParseContext::layoutObjectCheck(const TSourceLoc& loc, const TSymbol& symbol)
6150 {
6151     const TType& type = symbol.getType();
6152     const TQualifier& qualifier = type.getQualifier();
6153
6154     // first, cross check WRT to just the type
6155     layoutTypeCheck(loc, type);
6156
6157     // now, any remaining error checking based on the object itself
6158
6159     if (qualifier.hasAnyLocation()) {
6160         switch (qualifier.storage) {
6161         case EvqUniform:
6162         case EvqBuffer:
6163             if (symbol.getAsVariable() == nullptr)
6164                 error(loc, "can only be used on variable declaration", "location", "");
6165             break;
6166         default:
6167             break;
6168         }
6169     }
6170
6171     // user-variable location check, which are required for SPIR-V in/out:
6172     //  - variables have it directly,
6173     //  - blocks have it on each member (already enforced), so check first one
6174     if (spvVersion.spv > 0 && !parsingBuiltins && qualifier.builtIn == EbvNone &&
6175         !qualifier.hasLocation() && !intermediate.getAutoMapLocations()) {
6176
6177         switch (qualifier.storage) {
6178         case EvqVaryingIn:
6179         case EvqVaryingOut:
6180             if (!type.getQualifier().isTaskMemory() &&
6181 #ifndef GLSLANG_WEB
6182                 !type.getQualifier().hasSprivDecorate() &&
6183 #endif
6184                 (type.getBasicType() != EbtBlock ||
6185                  (!(*type.getStruct())[0].type->getQualifier().hasLocation() &&
6186                    (*type.getStruct())[0].type->getQualifier().builtIn == EbvNone)))
6187                 error(loc, "SPIR-V requires location for user input/output", "location", "");
6188             break;
6189         default:
6190             break;
6191         }
6192     }
6193
6194     // Check packing and matrix
6195     if (qualifier.hasUniformLayout()) {
6196         switch (qualifier.storage) {
6197         case EvqUniform:
6198         case EvqBuffer:
6199             if (type.getBasicType() != EbtBlock) {
6200                 if (qualifier.hasMatrix())
6201                     error(loc, "cannot specify matrix layout on a variable declaration", "layout", "");
6202                 if (qualifier.hasPacking())
6203                     error(loc, "cannot specify packing on a variable declaration", "layout", "");
6204                 // "The offset qualifier can only be used on block members of blocks..."
6205                 if (qualifier.hasOffset() && !type.isAtomic())
6206                     error(loc, "cannot specify on a variable declaration", "offset", "");
6207                 // "The align qualifier can only be used on blocks or block members..."
6208                 if (qualifier.hasAlign())
6209                     error(loc, "cannot specify on a variable declaration", "align", "");
6210                 if (qualifier.isPushConstant())
6211                     error(loc, "can only specify on a uniform block", "push_constant", "");
6212                 if (qualifier.isShaderRecord())
6213                     error(loc, "can only specify on a buffer block", "shaderRecordNV", "");
6214                 if (qualifier.hasLocation() && type.isAtomic())
6215                     error(loc, "cannot specify on atomic counter", "location", "");
6216             }
6217             break;
6218         default:
6219             // these were already filtered by layoutTypeCheck() (or its callees)
6220             break;
6221         }
6222     }
6223 }
6224
6225 // "For some blocks declared as arrays, the location can only be applied at the block level:
6226 // When a block is declared as an array where additional locations are needed for each member
6227 // for each block array element, it is a compile-time error to specify locations on the block
6228 // members.  That is, when locations would be under specified by applying them on block members,
6229 // they are not allowed on block members.  For arrayed interfaces (those generally having an
6230 // extra level of arrayness due to interface expansion), the outer array is stripped before
6231 // applying this rule."
6232 void TParseContext::layoutMemberLocationArrayCheck(const TSourceLoc& loc, bool memberWithLocation,
6233     TArraySizes* arraySizes)
6234 {
6235     if (memberWithLocation && arraySizes != nullptr) {
6236         if (arraySizes->getNumDims() > (currentBlockQualifier.isArrayedIo(language) ? 1 : 0))
6237             error(loc, "cannot use in a block array where new locations are needed for each block element",
6238                        "location", "");
6239     }
6240 }
6241
6242 // Do layout error checking with respect to a type.
6243 void TParseContext::layoutTypeCheck(const TSourceLoc& loc, const TType& type)
6244 {
6245 #ifndef GLSLANG_WEB
6246     if (extensionTurnedOn(E_GL_EXT_spirv_intrinsics))
6247         return; // Skip any check if GL_EXT_spirv_intrinsics is turned on
6248 #endif
6249
6250     const TQualifier& qualifier = type.getQualifier();
6251
6252     // first, intra-layout qualifier-only error checking
6253     layoutQualifierCheck(loc, qualifier);
6254
6255     // now, error checking combining type and qualifier
6256
6257     if (qualifier.hasAnyLocation()) {
6258         if (qualifier.hasLocation()) {
6259             if (qualifier.storage == EvqVaryingOut && language == EShLangFragment) {
6260                 if (qualifier.layoutLocation >= (unsigned int)resources.maxDrawBuffers)
6261                     error(loc, "too large for fragment output", "location", "");
6262             }
6263         }
6264         if (qualifier.hasComponent()) {
6265             // "It is a compile-time error if this sequence of components gets larger than 3."
6266             if (qualifier.layoutComponent + type.getVectorSize() * (type.getBasicType() == EbtDouble ? 2 : 1) > 4)
6267                 error(loc, "type overflows the available 4 components", "component", "");
6268
6269             // "It is a compile-time error to apply the component qualifier to a matrix, a structure, a block, or an array containing any of these."
6270             if (type.isMatrix() || type.getBasicType() == EbtBlock || type.getBasicType() == EbtStruct)
6271                 error(loc, "cannot apply to a matrix, structure, or block", "component", "");
6272
6273             // " It is a compile-time error to use component 1 or 3 as the beginning of a double or dvec2."
6274             if (type.getBasicType() == EbtDouble)
6275                 if (qualifier.layoutComponent & 1)
6276                     error(loc, "doubles cannot start on an odd-numbered component", "component", "");
6277         }
6278
6279         switch (qualifier.storage) {
6280         case EvqVaryingIn:
6281         case EvqVaryingOut:
6282             if (type.getBasicType() == EbtBlock)
6283                 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, "location qualifier on in/out block");
6284             if (type.getQualifier().isTaskMemory())
6285                 error(loc, "cannot apply to taskNV in/out blocks", "location", "");
6286             break;
6287         case EvqUniform:
6288         case EvqBuffer:
6289             if (type.getBasicType() == EbtBlock)
6290                 error(loc, "cannot apply to uniform or buffer block", "location", "");
6291             break;
6292         case EvqtaskPayloadSharedEXT:
6293             error(loc, "cannot apply to taskPayloadSharedEXT", "location", "");
6294             break;
6295 #ifndef GLSLANG_WEB
6296         case EvqPayload:
6297         case EvqPayloadIn:
6298         case EvqHitAttr:
6299         case EvqCallableData:
6300         case EvqCallableDataIn:
6301             break;
6302 #endif
6303         default:
6304             error(loc, "can only apply to uniform, buffer, in, or out storage qualifiers", "location", "");
6305             break;
6306         }
6307
6308         bool typeCollision;
6309         int repeated = intermediate.addUsedLocation(qualifier, type, typeCollision);
6310         if (repeated >= 0 && ! typeCollision)
6311             error(loc, "overlapping use of location", "location", "%d", repeated);
6312         // "fragment-shader outputs ... if two variables are placed within the same
6313         // location, they must have the same underlying type (floating-point or integer)"
6314         if (typeCollision && language == EShLangFragment && qualifier.isPipeOutput())
6315             error(loc, "fragment outputs sharing the same location must be the same basic type", "location", "%d", repeated);
6316     }
6317
6318 #ifndef GLSLANG_WEB
6319     if (qualifier.hasXfbOffset() && qualifier.hasXfbBuffer()) {
6320         if (type.isUnsizedArray()) {
6321             error(loc, "unsized array", "xfb_offset", "in buffer %d", qualifier.layoutXfbBuffer);
6322         } else {
6323             int repeated = intermediate.addXfbBufferOffset(type);
6324             if (repeated >= 0)
6325                 error(loc, "overlapping offsets at", "xfb_offset", "offset %d in buffer %d", repeated, qualifier.layoutXfbBuffer);
6326         }
6327
6328         // "The offset must be a multiple of the size of the first component of the first
6329         // qualified variable or block member, or a compile-time error results. Further, if applied to an aggregate
6330         // containing a double or 64-bit integer, the offset must also be a multiple of 8..."
6331         if ((type.containsBasicType(EbtDouble) || type.containsBasicType(EbtInt64) || type.containsBasicType(EbtUint64)) &&
6332             ! IsMultipleOfPow2(qualifier.layoutXfbOffset, 8))
6333             error(loc, "type contains double or 64-bit integer; xfb_offset must be a multiple of 8", "xfb_offset", "");
6334         else if ((type.containsBasicType(EbtBool) || type.containsBasicType(EbtFloat) ||
6335                   type.containsBasicType(EbtInt) || type.containsBasicType(EbtUint)) &&
6336                  ! IsMultipleOfPow2(qualifier.layoutXfbOffset, 4))
6337             error(loc, "must be a multiple of size of first component", "xfb_offset", "");
6338         // ..., if applied to an aggregate containing a half float or 16-bit integer, the offset must also be a multiple of 2..."
6339         else if ((type.contains16BitFloat() || type.containsBasicType(EbtInt16) || type.containsBasicType(EbtUint16)) &&
6340                  !IsMultipleOfPow2(qualifier.layoutXfbOffset, 2))
6341             error(loc, "type contains half float or 16-bit integer; xfb_offset must be a multiple of 2", "xfb_offset", "");
6342     }
6343     if (qualifier.hasXfbStride() && qualifier.hasXfbBuffer()) {
6344         if (! intermediate.setXfbBufferStride(qualifier.layoutXfbBuffer, qualifier.layoutXfbStride))
6345             error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d", qualifier.layoutXfbBuffer);
6346     }
6347 #endif
6348
6349     if (qualifier.hasBinding()) {
6350         // Binding checking, from the spec:
6351         //
6352         // "If the binding point for any uniform or shader storage block instance is less than zero, or greater than or
6353         // equal to the implementation-dependent maximum number of uniform buffer bindings, a compile-time
6354         // error will occur. When the binding identifier is used with a uniform or shader storage block instanced as
6355         // an array of size N, all elements of the array from binding through binding + N - 1 must be within this
6356         // range."
6357         //
6358         if (! type.isOpaque() && type.getBasicType() != EbtBlock)
6359             error(loc, "requires block, or sampler/image, or atomic-counter type", "binding", "");
6360         if (type.getBasicType() == EbtSampler) {
6361             int lastBinding = qualifier.layoutBinding;
6362             if (type.isArray()) {
6363                 if (spvVersion.vulkan == 0) {
6364                     if (type.isSizedArray())
6365                         lastBinding += (type.getCumulativeArraySize() - 1);
6366                     else {
6367 #ifndef GLSLANG_WEB
6368                         warn(loc, "assuming binding count of one for compile-time checking of binding numbers for unsized array", "[]", "");
6369 #endif
6370                     }
6371                 }
6372             }
6373 #ifndef GLSLANG_WEB
6374             if (spvVersion.vulkan == 0 && lastBinding >= resources.maxCombinedTextureImageUnits)
6375                 error(loc, "sampler binding not less than gl_MaxCombinedTextureImageUnits", "binding", type.isArray() ? "(using array)" : "");
6376 #endif
6377         }
6378         if (type.isAtomic() && !spvVersion.vulkanRelaxed) {
6379             if (qualifier.layoutBinding >= (unsigned int)resources.maxAtomicCounterBindings) {
6380                 error(loc, "atomic_uint binding is too large; see gl_MaxAtomicCounterBindings", "binding", "");
6381                 return;
6382             }
6383         }
6384     } else if (!intermediate.getAutoMapBindings()) {
6385         // some types require bindings
6386
6387         // atomic_uint
6388         if (type.isAtomic())
6389             error(loc, "layout(binding=X) is required", "atomic_uint", "");
6390
6391         // SPIR-V
6392         if (spvVersion.spv > 0) {
6393             if (qualifier.isUniformOrBuffer()) {
6394                 if (type.getBasicType() == EbtBlock && !qualifier.isPushConstant() &&
6395                        !qualifier.isShaderRecord() &&
6396                        !qualifier.hasAttachment() &&
6397                        !qualifier.hasBufferReference())
6398                     error(loc, "uniform/buffer blocks require layout(binding=X)", "binding", "");
6399                 else if (spvVersion.vulkan > 0 && type.getBasicType() == EbtSampler)
6400                     error(loc, "sampler/texture/image requires layout(binding=X)", "binding", "");
6401             }
6402         }
6403     }
6404
6405     // some things can't have arrays of arrays
6406     if (type.isArrayOfArrays()) {
6407         if (spvVersion.vulkan > 0) {
6408             if (type.isOpaque() || (type.getQualifier().isUniformOrBuffer() && type.getBasicType() == EbtBlock))
6409                 warn(loc, "Generating SPIR-V array-of-arrays, but Vulkan only supports single array level for this resource", "[][]", "");
6410         }
6411     }
6412
6413     // "The offset qualifier can only be used on block members of blocks..."
6414     if (qualifier.hasOffset()) {
6415         if (type.getBasicType() == EbtBlock)
6416             error(loc, "only applies to block members, not blocks", "offset", "");
6417     }
6418
6419     // Image format
6420     if (qualifier.hasFormat()) {
6421         if (! type.isImage())
6422             error(loc, "only apply to images", TQualifier::getLayoutFormatString(qualifier.getFormat()), "");
6423         else {
6424             if (type.getSampler().type == EbtFloat && qualifier.getFormat() > ElfFloatGuard)
6425                 error(loc, "does not apply to floating point images", TQualifier::getLayoutFormatString(qualifier.getFormat()), "");
6426             if (type.getSampler().type == EbtInt && (qualifier.getFormat() < ElfFloatGuard || qualifier.getFormat() > ElfIntGuard))
6427                 error(loc, "does not apply to signed integer images", TQualifier::getLayoutFormatString(qualifier.getFormat()), "");
6428             if (type.getSampler().type == EbtUint && qualifier.getFormat() < ElfIntGuard)
6429                 error(loc, "does not apply to unsigned integer images", TQualifier::getLayoutFormatString(qualifier.getFormat()), "");
6430
6431             if (isEsProfile()) {
6432                 // "Except for image variables qualified with the format qualifiers r32f, r32i, and r32ui, image variables must
6433                 // specify either memory qualifier readonly or the memory qualifier writeonly."
6434                 if (! (qualifier.getFormat() == ElfR32f || qualifier.getFormat() == ElfR32i || qualifier.getFormat() == ElfR32ui)) {
6435                     if (! qualifier.isReadOnly() && ! qualifier.isWriteOnly())
6436                         error(loc, "format requires readonly or writeonly memory qualifier", TQualifier::getLayoutFormatString(qualifier.getFormat()), "");
6437                 }
6438             }
6439         }
6440     } else if (type.isImage() && ! qualifier.isWriteOnly()) {
6441         const char *explanation = "image variables not declared 'writeonly' and without a format layout qualifier";
6442         requireProfile(loc, ECoreProfile | ECompatibilityProfile, explanation);
6443         profileRequires(loc, ECoreProfile | ECompatibilityProfile, 0, E_GL_EXT_shader_image_load_formatted, explanation);
6444     }
6445
6446     if (qualifier.isPushConstant()) {
6447         if (type.getBasicType() != EbtBlock)
6448             error(loc, "can only be used with a block", "push_constant", "");
6449         if (type.isArray())
6450             error(loc, "Push constants blocks can't be an array", "push_constant", "");
6451     }
6452
6453     if (qualifier.hasBufferReference() && type.getBasicType() != EbtBlock)
6454         error(loc, "can only be used with a block", "buffer_reference", "");
6455
6456     if (qualifier.isShaderRecord() && type.getBasicType() != EbtBlock)
6457         error(loc, "can only be used with a block", "shaderRecordNV", "");
6458
6459     // input attachment
6460     if (type.isSubpass()) {
6461         if (! qualifier.hasAttachment())
6462             error(loc, "requires an input_attachment_index layout qualifier", "subpass", "");
6463     } else {
6464         if (qualifier.hasAttachment())
6465             error(loc, "can only be used with a subpass", "input_attachment_index", "");
6466     }
6467
6468     // specialization-constant id
6469     if (qualifier.hasSpecConstantId()) {
6470         if (type.getQualifier().storage != EvqConst)
6471             error(loc, "can only be applied to 'const'-qualified scalar", "constant_id", "");
6472         if (! type.isScalar())
6473             error(loc, "can only be applied to a scalar", "constant_id", "");
6474         switch (type.getBasicType())
6475         {
6476         case EbtInt8:
6477         case EbtUint8:
6478         case EbtInt16:
6479         case EbtUint16:
6480         case EbtInt:
6481         case EbtUint:
6482         case EbtInt64:
6483         case EbtUint64:
6484         case EbtBool:
6485         case EbtFloat:
6486         case EbtDouble:
6487         case EbtFloat16:
6488             break;
6489         default:
6490             error(loc, "cannot be applied to this type", "constant_id", "");
6491             break;
6492         }
6493     }
6494 }
6495
6496 static bool storageCanHaveLayoutInBlock(const enum TStorageQualifier storage)
6497 {
6498     switch (storage) {
6499     case EvqUniform:
6500     case EvqBuffer:
6501     case EvqShared:
6502         return true;
6503     default:
6504         return false;
6505     }
6506 }
6507
6508 // Do layout error checking that can be done within a layout qualifier proper, not needing to know
6509 // if there are blocks, atomic counters, variables, etc.
6510 void TParseContext::layoutQualifierCheck(const TSourceLoc& loc, const TQualifier& qualifier)
6511 {
6512     if (qualifier.storage == EvqShared && qualifier.hasLayout()) {
6513         if (spvVersion.spv > 0 && spvVersion.spv < EShTargetSpv_1_4) {
6514             error(loc, "shared block requires at least SPIR-V 1.4", "shared block", "");
6515         }
6516         profileRequires(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, 0, E_GL_EXT_shared_memory_block, "shared block");
6517     }
6518
6519     // "It is a compile-time error to use *component* without also specifying the location qualifier (order does not matter)."
6520     if (qualifier.hasComponent() && ! qualifier.hasLocation())
6521         error(loc, "must specify 'location' to use 'component'", "component", "");
6522
6523     if (qualifier.hasAnyLocation()) {
6524
6525         // "As with input layout qualifiers, all shaders except compute shaders
6526         // allow *location* layout qualifiers on output variable declarations,
6527         // output block declarations, and output block member declarations."
6528
6529         switch (qualifier.storage) {
6530 #ifndef GLSLANG_WEB
6531         case EvqVaryingIn:
6532         {
6533             const char* feature = "location qualifier on input";
6534             if (isEsProfile() && version < 310)
6535                 requireStage(loc, EShLangVertex, feature);
6536             else
6537                 requireStage(loc, (EShLanguageMask)~EShLangComputeMask, feature);
6538             if (language == EShLangVertex) {
6539                 const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location };
6540                 profileRequires(loc, ~EEsProfile, 330, 2, exts, feature);
6541                 profileRequires(loc, EEsProfile, 300, nullptr, feature);
6542             } else {
6543                 profileRequires(loc, ~EEsProfile, 410, E_GL_ARB_separate_shader_objects, feature);
6544                 profileRequires(loc, EEsProfile, 310, nullptr, feature);
6545             }
6546             break;
6547         }
6548         case EvqVaryingOut:
6549         {
6550             const char* feature = "location qualifier on output";
6551             if (isEsProfile() && version < 310)
6552                 requireStage(loc, EShLangFragment, feature);
6553             else
6554                 requireStage(loc, (EShLanguageMask)~EShLangComputeMask, feature);
6555             if (language == EShLangFragment) {
6556                 const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location };
6557                 profileRequires(loc, ~EEsProfile, 330, 2, exts, feature);
6558                 profileRequires(loc, EEsProfile, 300, nullptr, feature);
6559             } else {
6560                 profileRequires(loc, ~EEsProfile, 410, E_GL_ARB_separate_shader_objects, feature);
6561                 profileRequires(loc, EEsProfile, 310, nullptr, feature);
6562             }
6563             break;
6564         }
6565 #endif
6566         case EvqUniform:
6567         case EvqBuffer:
6568         {
6569             const char* feature = "location qualifier on uniform or buffer";
6570             requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile | ENoProfile, feature);
6571             profileRequires(loc, ~EEsProfile, 330, E_GL_ARB_explicit_attrib_location, feature);
6572             profileRequires(loc, ~EEsProfile, 430, E_GL_ARB_explicit_uniform_location, feature);
6573             profileRequires(loc, EEsProfile, 310, nullptr, feature);
6574             break;
6575         }
6576         default:
6577             break;
6578         }
6579         if (qualifier.hasIndex()) {
6580             if (qualifier.storage != EvqVaryingOut)
6581                 error(loc, "can only be used on an output", "index", "");
6582             if (! qualifier.hasLocation())
6583                 error(loc, "can only be used with an explicit location", "index", "");
6584         }
6585     }
6586
6587     if (qualifier.hasBinding()) {
6588         if (! qualifier.isUniformOrBuffer() && !qualifier.isTaskMemory())
6589             error(loc, "requires uniform or buffer storage qualifier", "binding", "");
6590     }
6591     if (qualifier.hasStream()) {
6592         if (!qualifier.isPipeOutput())
6593             error(loc, "can only be used on an output", "stream", "");
6594     }
6595     if (qualifier.hasXfb()) {
6596         if (!qualifier.isPipeOutput())
6597             error(loc, "can only be used on an output", "xfb layout qualifier", "");
6598     }
6599     if (qualifier.hasUniformLayout()) {
6600         if (!storageCanHaveLayoutInBlock(qualifier.storage) && !qualifier.isTaskMemory()) {
6601             if (qualifier.hasMatrix() || qualifier.hasPacking())
6602                 error(loc, "matrix or packing qualifiers can only be used on a uniform or buffer", "layout", "");
6603             if (qualifier.hasOffset() || qualifier.hasAlign())
6604                 error(loc, "offset/align can only be used on a uniform or buffer", "layout", "");
6605         }
6606     }
6607     if (qualifier.isPushConstant()) {
6608         if (qualifier.storage != EvqUniform)
6609             error(loc, "can only be used with a uniform", "push_constant", "");
6610         if (qualifier.hasSet())
6611             error(loc, "cannot be used with push_constant", "set", "");
6612         if (qualifier.hasBinding())
6613             error(loc, "cannot be used with push_constant", "binding", "");
6614     }
6615     if (qualifier.hasBufferReference()) {
6616         if (qualifier.storage != EvqBuffer)
6617             error(loc, "can only be used with buffer", "buffer_reference", "");
6618     }
6619     if (qualifier.isShaderRecord()) {
6620         if (qualifier.storage != EvqBuffer)
6621             error(loc, "can only be used with a buffer", "shaderRecordNV", "");
6622         if (qualifier.hasBinding())
6623             error(loc, "cannot be used with shaderRecordNV", "binding", "");
6624         if (qualifier.hasSet())
6625             error(loc, "cannot be used with shaderRecordNV", "set", "");
6626
6627     }
6628     if (qualifier.storage == EvqHitAttr && qualifier.hasLayout()) {
6629         error(loc, "cannot apply layout qualifiers to hitAttributeNV variable", "hitAttributeNV", "");
6630     }
6631 }
6632
6633 // For places that can't have shader-level layout qualifiers
6634 void TParseContext::checkNoShaderLayouts(const TSourceLoc& loc, const TShaderQualifiers& shaderQualifiers)
6635 {
6636 #ifndef GLSLANG_WEB
6637     const char* message = "can only apply to a standalone qualifier";
6638
6639     if (shaderQualifiers.geometry != ElgNone)
6640         error(loc, message, TQualifier::getGeometryString(shaderQualifiers.geometry), "");
6641     if (shaderQualifiers.spacing != EvsNone)
6642         error(loc, message, TQualifier::getVertexSpacingString(shaderQualifiers.spacing), "");
6643     if (shaderQualifiers.order != EvoNone)
6644         error(loc, message, TQualifier::getVertexOrderString(shaderQualifiers.order), "");
6645     if (shaderQualifiers.pointMode)
6646         error(loc, message, "point_mode", "");
6647     if (shaderQualifiers.invocations != TQualifier::layoutNotSet)
6648         error(loc, message, "invocations", "");
6649     for (int i = 0; i < 3; ++i) {
6650         if (shaderQualifiers.localSize[i] > 1)
6651             error(loc, message, "local_size", "");
6652         if (shaderQualifiers.localSizeSpecId[i] != TQualifier::layoutNotSet)
6653             error(loc, message, "local_size id", "");
6654     }
6655     if (shaderQualifiers.vertices != TQualifier::layoutNotSet) {
6656         if (language == EShLangGeometry || language == EShLangMesh)
6657             error(loc, message, "max_vertices", "");
6658         else if (language == EShLangTessControl)
6659             error(loc, message, "vertices", "");
6660         else
6661             assert(0);
6662     }
6663     if (shaderQualifiers.earlyFragmentTests)
6664         error(loc, message, "early_fragment_tests", "");
6665     if (shaderQualifiers.postDepthCoverage)
6666         error(loc, message, "post_depth_coverage", "");
6667     if (shaderQualifiers.primitives != TQualifier::layoutNotSet) {
6668         if (language == EShLangMesh)
6669             error(loc, message, "max_primitives", "");
6670         else
6671             assert(0);
6672     }
6673     if (shaderQualifiers.hasBlendEquation())
6674         error(loc, message, "blend equation", "");
6675     if (shaderQualifiers.numViews != TQualifier::layoutNotSet)
6676         error(loc, message, "num_views", "");
6677     if (shaderQualifiers.interlockOrdering != EioNone)
6678         error(loc, message, TQualifier::getInterlockOrderingString(shaderQualifiers.interlockOrdering), "");
6679     if (shaderQualifiers.layoutPrimitiveCulling)
6680         error(loc, "can only be applied as standalone", "primitive_culling", "");
6681 #endif
6682 }
6683
6684 // Correct and/or advance an object's offset layout qualifier.
6685 void TParseContext::fixOffset(const TSourceLoc& loc, TSymbol& symbol)
6686 {
6687     const TQualifier& qualifier = symbol.getType().getQualifier();
6688 #ifndef GLSLANG_WEB
6689     if (symbol.getType().isAtomic()) {
6690         if (qualifier.hasBinding() && (int)qualifier.layoutBinding < resources.maxAtomicCounterBindings) {
6691
6692             // Set the offset
6693             int offset;
6694             if (qualifier.hasOffset())
6695                 offset = qualifier.layoutOffset;
6696             else
6697                 offset = atomicUintOffsets[qualifier.layoutBinding];
6698
6699             if (offset % 4 != 0)
6700                 error(loc, "atomic counters offset should align based on 4:", "offset", "%d", offset);
6701
6702             symbol.getWritableType().getQualifier().layoutOffset = offset;
6703
6704             // Check for overlap
6705             int numOffsets = 4;
6706             if (symbol.getType().isArray()) {
6707                 if (symbol.getType().isSizedArray() && !symbol.getType().getArraySizes()->isInnerUnsized())
6708                     numOffsets *= symbol.getType().getCumulativeArraySize();
6709                 else {
6710                     // "It is a compile-time error to declare an unsized array of atomic_uint."
6711                     error(loc, "array must be explicitly sized", "atomic_uint", "");
6712                 }
6713             }
6714             int repeated = intermediate.addUsedOffsets(qualifier.layoutBinding, offset, numOffsets);
6715             if (repeated >= 0)
6716                 error(loc, "atomic counters sharing the same offset:", "offset", "%d", repeated);
6717
6718             // Bump the default offset
6719             atomicUintOffsets[qualifier.layoutBinding] = offset + numOffsets;
6720         }
6721     }
6722 #endif
6723 }
6724
6725 //
6726 // Look up a function name in the symbol table, and make sure it is a function.
6727 //
6728 // Return the function symbol if found, otherwise nullptr.
6729 //
6730 const TFunction* TParseContext::findFunction(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
6731 {
6732     if (symbolTable.isFunctionNameVariable(call.getName())) {
6733         error(loc, "can't use function syntax on variable", call.getName().c_str(), "");
6734         return nullptr;
6735     }
6736
6737 #ifdef GLSLANG_WEB
6738     return findFunctionExact(loc, call, builtIn);
6739 #endif
6740
6741     const TFunction* function = nullptr;
6742
6743     // debugPrintfEXT has var args and is in the symbol table as "debugPrintfEXT()",
6744     // mangled to "debugPrintfEXT("
6745     if (call.getName() == "debugPrintfEXT") {
6746         TSymbol* symbol = symbolTable.find("debugPrintfEXT(", &builtIn);
6747         if (symbol)
6748             return symbol->getAsFunction();
6749     }
6750
6751     bool explicitTypesEnabled = extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types) ||
6752                                 extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_int8) ||
6753                                 extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_int16) ||
6754                                 extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_int32) ||
6755                                 extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_int64) ||
6756                                 extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_float16) ||
6757                                 extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_float32) ||
6758                                 extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_float64);
6759
6760     if (isEsProfile())
6761         function = (explicitTypesEnabled && version >= 310)
6762                    ? findFunctionExplicitTypes(loc, call, builtIn)
6763                    : ((extensionTurnedOn(E_GL_EXT_shader_implicit_conversions) && version >= 310)
6764                       ? findFunction120(loc, call, builtIn)
6765                       : findFunctionExact(loc, call, builtIn));
6766     else if (version < 120)
6767         function = findFunctionExact(loc, call, builtIn);
6768     else if (version < 400) {
6769         bool needfindFunction400 = extensionTurnedOn(E_GL_ARB_gpu_shader_fp64) || extensionTurnedOn(E_GL_ARB_gpu_shader5);
6770         function = needfindFunction400 ? findFunction400(loc, call, builtIn) : findFunction120(loc, call, builtIn);
6771     }
6772     else if (explicitTypesEnabled)
6773         function = findFunctionExplicitTypes(loc, call, builtIn);
6774     else
6775         function = findFunction400(loc, call, builtIn);
6776
6777     return function;
6778 }
6779
6780 // Function finding algorithm for ES and desktop 110.
6781 const TFunction* TParseContext::findFunctionExact(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
6782 {
6783     TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
6784     if (symbol == nullptr) {
6785         error(loc, "no matching overloaded function found", call.getName().c_str(), "");
6786
6787         return nullptr;
6788     }
6789
6790     return symbol->getAsFunction();
6791 }
6792
6793 // Function finding algorithm for desktop versions 120 through 330.
6794 const TFunction* TParseContext::findFunction120(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
6795 {
6796     // first, look for an exact match
6797     TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
6798     if (symbol)
6799         return symbol->getAsFunction();
6800
6801     // exact match not found, look through a list of overloaded functions of the same name
6802
6803     // "If no exact match is found, then [implicit conversions] will be applied to find a match. Mismatched types
6804     // on input parameters (in or inout or default) must have a conversion from the calling argument type to the
6805     // formal parameter type. Mismatched types on output parameters (out or inout) must have a conversion
6806     // from the formal parameter type to the calling argument type.  When argument conversions are used to find
6807     // a match, it is a semantic error if there are multiple ways to apply these conversions to make the call match
6808     // more than one function."
6809
6810     const TFunction* candidate = nullptr;
6811     TVector<const TFunction*> candidateList;
6812     symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
6813
6814     for (auto it = candidateList.begin(); it != candidateList.end(); ++it) {
6815         const TFunction& function = *(*it);
6816
6817         // to even be a potential match, number of arguments has to match
6818         if (call.getParamCount() != function.getParamCount())
6819             continue;
6820
6821         bool possibleMatch = true;
6822         for (int i = 0; i < function.getParamCount(); ++i) {
6823             // same types is easy
6824             if (*function[i].type == *call[i].type)
6825                 continue;
6826
6827             // We have a mismatch in type, see if it is implicitly convertible
6828
6829             if (function[i].type->isArray() || call[i].type->isArray() ||
6830                 ! function[i].type->sameElementShape(*call[i].type))
6831                 possibleMatch = false;
6832             else {
6833                 // do direction-specific checks for conversion of basic type
6834                 if (function[i].type->getQualifier().isParamInput()) {
6835                     if (! intermediate.canImplicitlyPromote(call[i].type->getBasicType(), function[i].type->getBasicType()))
6836                         possibleMatch = false;
6837                 }
6838                 if (function[i].type->getQualifier().isParamOutput()) {
6839                     if (! intermediate.canImplicitlyPromote(function[i].type->getBasicType(), call[i].type->getBasicType()))
6840                         possibleMatch = false;
6841                 }
6842             }
6843             if (! possibleMatch)
6844                 break;
6845         }
6846         if (possibleMatch) {
6847             if (candidate) {
6848                 // our second match, meaning ambiguity
6849                 error(loc, "ambiguous function signature match: multiple signatures match under implicit type conversion", call.getName().c_str(), "");
6850             } else
6851                 candidate = &function;
6852         }
6853     }
6854
6855     if (candidate == nullptr)
6856         error(loc, "no matching overloaded function found", call.getName().c_str(), "");
6857
6858     return candidate;
6859 }
6860
6861 // Function finding algorithm for desktop version 400 and above.
6862 //
6863 // "When function calls are resolved, an exact type match for all the arguments
6864 // is sought. If an exact match is found, all other functions are ignored, and
6865 // the exact match is used. If no exact match is found, then the implicit
6866 // conversions in section 4.1.10 Implicit Conversions will be applied to find
6867 // a match. Mismatched types on input parameters (in or inout or default) must
6868 // have a conversion from the calling argument type to the formal parameter type.
6869 // Mismatched types on output parameters (out or inout) must have a conversion
6870 // from the formal parameter type to the calling argument type.
6871 //
6872 // "If implicit conversions can be used to find more than one matching function,
6873 // a single best-matching function is sought. To determine a best match, the
6874 // conversions between calling argument and formal parameter types are compared
6875 // for each function argument and pair of matching functions. After these
6876 // comparisons are performed, each pair of matching functions are compared.
6877 // A function declaration A is considered a better match than function
6878 // declaration B if
6879 //
6880 //  * for at least one function argument, the conversion for that argument in A
6881 //    is better than the corresponding conversion in B; and
6882 //  * there is no function argument for which the conversion in B is better than
6883 //    the corresponding conversion in A.
6884 //
6885 // "If a single function declaration is considered a better match than every
6886 // other matching function declaration, it will be used. Otherwise, a
6887 // compile-time semantic error for an ambiguous overloaded function call occurs.
6888 //
6889 // "To determine whether the conversion for a single argument in one match is
6890 // better than that for another match, the following rules are applied, in order:
6891 //
6892 //  1. An exact match is better than a match involving any implicit conversion.
6893 //  2. A match involving an implicit conversion from float to double is better
6894 //     than a match involving any other implicit conversion.
6895 //  3. A match involving an implicit conversion from either int or uint to float
6896 //     is better than a match involving an implicit conversion from either int
6897 //     or uint to double.
6898 //
6899 // "If none of the rules above apply to a particular pair of conversions, neither
6900 // conversion is considered better than the other."
6901 //
6902 const TFunction* TParseContext::findFunction400(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
6903 {
6904     // first, look for an exact match
6905     TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
6906     if (symbol)
6907         return symbol->getAsFunction();
6908
6909     // no exact match, use the generic selector, parameterized by the GLSL rules
6910
6911     // create list of candidates to send
6912     TVector<const TFunction*> candidateList;
6913     symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
6914
6915     // can 'from' convert to 'to'?
6916     const auto convertible = [this,builtIn](const TType& from, const TType& to, TOperator, int) -> bool {
6917         if (from == to)
6918             return true;
6919         if (from.coopMatParameterOK(to))
6920             return true;
6921         // Allow a sized array to be passed through an unsized array parameter, for coopMatLoad/Store functions
6922         if (builtIn && from.isArray() && to.isUnsizedArray()) {
6923             TType fromElementType(from, 0);
6924             TType toElementType(to, 0);
6925             if (fromElementType == toElementType)
6926                 return true;
6927         }
6928         if (from.isArray() || to.isArray() || ! from.sameElementShape(to))
6929             return false;
6930         if (from.isCoopMat() && to.isCoopMat())
6931             return from.sameCoopMatBaseType(to);
6932         return intermediate.canImplicitlyPromote(from.getBasicType(), to.getBasicType());
6933     };
6934
6935     // Is 'to2' a better conversion than 'to1'?
6936     // Ties should not be considered as better.
6937     // Assumes 'convertible' already said true.
6938     const auto better = [](const TType& from, const TType& to1, const TType& to2) -> bool {
6939         // 1. exact match
6940         if (from == to2)
6941             return from != to1;
6942         if (from == to1)
6943             return false;
6944
6945         // 2. float -> double is better
6946         if (from.getBasicType() == EbtFloat) {
6947             if (to2.getBasicType() == EbtDouble && to1.getBasicType() != EbtDouble)
6948                 return true;
6949         }
6950
6951         // 3. -> float is better than -> double
6952         return to2.getBasicType() == EbtFloat && to1.getBasicType() == EbtDouble;
6953     };
6954
6955     // for ambiguity reporting
6956     bool tie = false;
6957
6958     // send to the generic selector
6959     const TFunction* bestMatch = selectFunction(candidateList, call, convertible, better, tie);
6960
6961     if (bestMatch == nullptr)
6962         error(loc, "no matching overloaded function found", call.getName().c_str(), "");
6963     else if (tie)
6964         error(loc, "ambiguous best function under implicit type conversion", call.getName().c_str(), "");
6965
6966     return bestMatch;
6967 }
6968
6969 // "To determine whether the conversion for a single argument in one match
6970 //  is better than that for another match, the conversion is assigned of the
6971 //  three ranks ordered from best to worst:
6972 //   1. Exact match: no conversion.
6973 //    2. Promotion: integral or floating-point promotion.
6974 //    3. Conversion: integral conversion, floating-point conversion,
6975 //       floating-integral conversion.
6976 //  A conversion C1 is better than a conversion C2 if the rank of C1 is
6977 //  better than the rank of C2."
6978 const TFunction* TParseContext::findFunctionExplicitTypes(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
6979 {
6980     // first, look for an exact match
6981     TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
6982     if (symbol)
6983         return symbol->getAsFunction();
6984
6985     // no exact match, use the generic selector, parameterized by the GLSL rules
6986
6987     // create list of candidates to send
6988     TVector<const TFunction*> candidateList;
6989     symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
6990
6991     // can 'from' convert to 'to'?
6992     const auto convertible = [this,builtIn](const TType& from, const TType& to, TOperator, int) -> bool {
6993         if (from == to)
6994             return true;
6995         if (from.coopMatParameterOK(to))
6996             return true;
6997         // Allow a sized array to be passed through an unsized array parameter, for coopMatLoad/Store functions
6998         if (builtIn && from.isArray() && to.isUnsizedArray()) {
6999             TType fromElementType(from, 0);
7000             TType toElementType(to, 0);
7001             if (fromElementType == toElementType)
7002                 return true;
7003         }
7004         if (from.isArray() || to.isArray() || ! from.sameElementShape(to))
7005             return false;
7006         if (from.isCoopMat() && to.isCoopMat())
7007             return from.sameCoopMatBaseType(to);
7008         return intermediate.canImplicitlyPromote(from.getBasicType(), to.getBasicType());
7009     };
7010
7011     // Is 'to2' a better conversion than 'to1'?
7012     // Ties should not be considered as better.
7013     // Assumes 'convertible' already said true.
7014     const auto better = [this](const TType& from, const TType& to1, const TType& to2) -> bool {
7015         // 1. exact match
7016         if (from == to2)
7017             return from != to1;
7018         if (from == to1)
7019             return false;
7020
7021         // 2. Promotion (integral, floating-point) is better
7022         TBasicType from_type = from.getBasicType();
7023         TBasicType to1_type = to1.getBasicType();
7024         TBasicType to2_type = to2.getBasicType();
7025         bool isPromotion1 = (intermediate.isIntegralPromotion(from_type, to1_type) ||
7026                              intermediate.isFPPromotion(from_type, to1_type));
7027         bool isPromotion2 = (intermediate.isIntegralPromotion(from_type, to2_type) ||
7028                              intermediate.isFPPromotion(from_type, to2_type));
7029         if (isPromotion2)
7030             return !isPromotion1;
7031         if(isPromotion1)
7032             return false;
7033
7034         // 3. Conversion (integral, floating-point , floating-integral)
7035         bool isConversion1 = (intermediate.isIntegralConversion(from_type, to1_type) ||
7036                               intermediate.isFPConversion(from_type, to1_type) ||
7037                               intermediate.isFPIntegralConversion(from_type, to1_type));
7038         bool isConversion2 = (intermediate.isIntegralConversion(from_type, to2_type) ||
7039                               intermediate.isFPConversion(from_type, to2_type) ||
7040                               intermediate.isFPIntegralConversion(from_type, to2_type));
7041
7042         return isConversion2 && !isConversion1;
7043     };
7044
7045     // for ambiguity reporting
7046     bool tie = false;
7047
7048     // send to the generic selector
7049     const TFunction* bestMatch = selectFunction(candidateList, call, convertible, better, tie);
7050
7051     if (bestMatch == nullptr)
7052         error(loc, "no matching overloaded function found", call.getName().c_str(), "");
7053     else if (tie)
7054         error(loc, "ambiguous best function under implicit type conversion", call.getName().c_str(), "");
7055
7056     return bestMatch;
7057 }
7058
7059 //
7060 // Adjust function calls that aren't declared in Vulkan to a
7061 // calls with equivalent effects
7062 //
7063 TIntermTyped* TParseContext::vkRelaxedRemapFunctionCall(const TSourceLoc& loc, TFunction* function, TIntermNode* arguments)
7064 {
7065     TIntermTyped* result = nullptr;
7066
7067 #ifndef GLSLANG_WEB
7068     if (function->getBuiltInOp() != EOpNull) {
7069         return nullptr;
7070     }
7071
7072     if (function->getName() == "atomicCounterIncrement") {
7073         // change atomicCounterIncrement into an atomicAdd of 1
7074         TString name("atomicAdd");
7075         TType uintType(EbtUint);
7076
7077         TFunction realFunc(&name, function->getType());
7078
7079         // Use copyParam to avoid shared ownership of the 'type' field
7080         // of the parameter.
7081         for (int i = 0; i < function->getParamCount(); ++i) {
7082             realFunc.addParameter(TParameter().copyParam((*function)[i]));
7083         }
7084
7085         TParameter tmpP = { 0, &uintType };
7086         realFunc.addParameter(TParameter().copyParam(tmpP));
7087         arguments = intermediate.growAggregate(arguments, intermediate.addConstantUnion(1, loc, true));
7088
7089         result = handleFunctionCall(loc, &realFunc, arguments);
7090     } else if (function->getName() == "atomicCounterDecrement") {
7091         // change atomicCounterDecrement into an atomicAdd with -1
7092         // and subtract 1 from result, to return post-decrement value
7093         TString name("atomicAdd");
7094         TType uintType(EbtUint);
7095
7096         TFunction realFunc(&name, function->getType());
7097
7098         for (int i = 0; i < function->getParamCount(); ++i) {
7099             realFunc.addParameter(TParameter().copyParam((*function)[i]));
7100         }
7101
7102         TParameter tmpP = { 0, &uintType };
7103         realFunc.addParameter(TParameter().copyParam(tmpP));
7104         arguments = intermediate.growAggregate(arguments, intermediate.addConstantUnion(-1, loc, true));
7105
7106         result = handleFunctionCall(loc, &realFunc, arguments);
7107
7108         // post decrement, so that it matches AtomicCounterDecrement semantics
7109         if (result) {
7110             result = handleBinaryMath(loc, "-", EOpSub, result, intermediate.addConstantUnion(1, loc, true));
7111         }
7112     } else if (function->getName() == "atomicCounter") {
7113         // change atomicCounter into a direct read of the variable
7114         if (arguments->getAsTyped()) {
7115             result = arguments->getAsTyped();
7116         }
7117     }
7118 #endif
7119
7120     return result;
7121 }
7122
7123 // When a declaration includes a type, but not a variable name, it can be used
7124 // to establish defaults.
7125 void TParseContext::declareTypeDefaults(const TSourceLoc& loc, const TPublicType& publicType)
7126 {
7127 #ifndef GLSLANG_WEB
7128     if (publicType.basicType == EbtAtomicUint && publicType.qualifier.hasBinding()) {
7129         if (publicType.qualifier.layoutBinding >= (unsigned int)resources.maxAtomicCounterBindings) {
7130             error(loc, "atomic_uint binding is too large", "binding", "");
7131             return;
7132         }
7133         if (publicType.qualifier.hasOffset())
7134             atomicUintOffsets[publicType.qualifier.layoutBinding] = publicType.qualifier.layoutOffset;
7135         return;
7136     }
7137
7138     if (publicType.arraySizes) {
7139         error(loc, "expect an array name", "", "");
7140     }
7141
7142     if (publicType.qualifier.hasLayout() && !publicType.qualifier.hasBufferReference())
7143         warn(loc, "useless application of layout qualifier", "layout", "");
7144 #endif
7145 }
7146
7147 bool TParseContext::vkRelaxedRemapUniformVariable(const TSourceLoc& loc, TString& identifier, const TPublicType&,
7148     TArraySizes*, TIntermTyped* initializer, TType& type)
7149 {
7150     if (parsingBuiltins || symbolTable.atBuiltInLevel() || !symbolTable.atGlobalLevel() ||
7151         type.getQualifier().storage != EvqUniform ||
7152         !(type.containsNonOpaque()
7153 #ifndef GLSLANG_WEB
7154             || type.getBasicType() == EbtAtomicUint
7155 #endif
7156         )) {
7157         return false;
7158     }
7159
7160     if (type.getQualifier().hasLocation()) {
7161         warn(loc, "ignoring layout qualifier for uniform", identifier.c_str(), "location");
7162         type.getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
7163     }
7164
7165     if (initializer) {
7166         warn(loc, "Ignoring initializer for uniform", identifier.c_str(), "");
7167         initializer = nullptr;
7168     }
7169
7170     if (type.isArray()) {
7171         // do array size checks here
7172         arraySizesCheck(loc, type.getQualifier(), type.getArraySizes(), initializer, false);
7173
7174         if (arrayQualifierError(loc, type.getQualifier()) || arrayError(loc, type)) {
7175             error(loc, "array param error", identifier.c_str(), "");
7176         }
7177     }
7178
7179     // do some checking on the type as it was declared
7180     layoutTypeCheck(loc, type);
7181
7182     int bufferBinding = TQualifier::layoutBindingEnd;
7183     TVariable* updatedBlock = nullptr;
7184
7185 #ifndef GLSLANG_WEB
7186     // Convert atomic_uint into members of a buffer block
7187     if (type.isAtomic()) {
7188         type.setBasicType(EbtUint);
7189         type.getQualifier().storage = EvqBuffer;
7190
7191         type.getQualifier().volatil = true;
7192         type.getQualifier().coherent = true;
7193
7194         // xxTODO: use logic from fixOffset() to apply explicit member offset
7195         bufferBinding = type.getQualifier().layoutBinding;
7196         type.getQualifier().layoutBinding = TQualifier::layoutBindingEnd;
7197         type.getQualifier().explicitOffset = false;
7198         growAtomicCounterBlock(bufferBinding, loc, type, identifier, nullptr);
7199         updatedBlock = atomicCounterBuffers[bufferBinding];
7200     }
7201 #endif
7202
7203     if (!updatedBlock) {
7204         growGlobalUniformBlock(loc, type, identifier, nullptr);
7205         updatedBlock = globalUniformBlock;
7206     }
7207
7208     //
7209     //      don't assign explicit member offsets here
7210     //      if any are assigned, need to be updated here and in the merge/link step
7211     // fixBlockUniformOffsets(updatedBlock->getWritableType().getQualifier(), *updatedBlock->getWritableType().getWritableStruct());
7212
7213     // checks on update buffer object
7214     layoutObjectCheck(loc, *updatedBlock);
7215
7216     TSymbol* symbol = symbolTable.find(identifier);
7217
7218     if (!symbol) {
7219         if (updatedBlock == globalUniformBlock)
7220             error(loc, "error adding uniform to default uniform block", identifier.c_str(), "");
7221         else
7222             error(loc, "error adding atomic counter to atomic counter block", identifier.c_str(), "");
7223         return false;
7224     }
7225
7226     // merge qualifiers
7227     mergeObjectLayoutQualifiers(updatedBlock->getWritableType().getQualifier(), type.getQualifier(), true);
7228
7229     return true;
7230 }
7231
7232 //
7233 // Do everything necessary to handle a variable (non-block) declaration.
7234 // Either redeclaring a variable, or making a new one, updating the symbol
7235 // table, and all error checking.
7236 //
7237 // Returns a subtree node that computes an initializer, if needed.
7238 // Returns nullptr if there is no code to execute for initialization.
7239 //
7240 // 'publicType' is the type part of the declaration (to the left)
7241 // 'arraySizes' is the arrayness tagged on the identifier (to the right)
7242 //
7243 TIntermNode* TParseContext::declareVariable(const TSourceLoc& loc, TString& identifier, const TPublicType& publicType,
7244     TArraySizes* arraySizes, TIntermTyped* initializer)
7245 {
7246     // Make a fresh type that combines the characteristics from the individual
7247     // identifier syntax and the declaration-type syntax.
7248     TType type(publicType);
7249     type.transferArraySizes(arraySizes);
7250     type.copyArrayInnerSizes(publicType.arraySizes);
7251     arrayOfArrayVersionCheck(loc, type.getArraySizes());
7252
7253     if (initializer) {
7254         if (type.getBasicType() == EbtRayQuery) {
7255             error(loc, "ray queries can only be initialized by using the rayQueryInitializeEXT intrinsic:", "=", identifier.c_str());
7256         }
7257     }
7258
7259     if (type.isCoopMat()) {
7260         intermediate.setUseVulkanMemoryModel();
7261         intermediate.setUseStorageBuffer();
7262
7263         if (!publicType.typeParameters || publicType.typeParameters->getNumDims() != 4) {
7264             error(loc, "expected four type parameters", identifier.c_str(), "");
7265         }
7266         if (publicType.typeParameters) {
7267             if (isTypeFloat(publicType.basicType) &&
7268                 publicType.typeParameters->getDimSize(0) != 16 &&
7269                 publicType.typeParameters->getDimSize(0) != 32 &&
7270                 publicType.typeParameters->getDimSize(0) != 64) {
7271                 error(loc, "expected 16, 32, or 64 bits for first type parameter", identifier.c_str(), "");
7272             }
7273             if (isTypeInt(publicType.basicType) &&
7274                 publicType.typeParameters->getDimSize(0) != 8 &&
7275                 publicType.typeParameters->getDimSize(0) != 32) {
7276                 error(loc, "expected 8 or 32 bits for first type parameter", identifier.c_str(), "");
7277             }
7278         }
7279
7280     } else {
7281         if (publicType.typeParameters && publicType.typeParameters->getNumDims() != 0) {
7282             error(loc, "unexpected type parameters", identifier.c_str(), "");
7283         }
7284     }
7285
7286     if (voidErrorCheck(loc, identifier, type.getBasicType()))
7287         return nullptr;
7288
7289     if (initializer)
7290         rValueErrorCheck(loc, "initializer", initializer);
7291     else
7292         nonInitConstCheck(loc, identifier, type);
7293
7294     samplerCheck(loc, type, identifier, initializer);
7295     transparentOpaqueCheck(loc, type, identifier);
7296 #ifndef GLSLANG_WEB
7297     atomicUintCheck(loc, type, identifier);
7298     accStructCheck(loc, type, identifier);
7299     checkAndResizeMeshViewDim(loc, type, /*isBlockMember*/ false);
7300 #endif
7301     if (type.getQualifier().storage == EvqConst && type.containsReference()) {
7302         error(loc, "variables with reference type can't have qualifier 'const'", "qualifier", "");
7303     }
7304
7305     if (type.getQualifier().storage != EvqUniform && type.getQualifier().storage != EvqBuffer) {
7306         if (type.contains16BitFloat())
7307             requireFloat16Arithmetic(loc, "qualifier", "float16 types can only be in uniform block or buffer storage");
7308         if (type.contains16BitInt())
7309             requireInt16Arithmetic(loc, "qualifier", "(u)int16 types can only be in uniform block or buffer storage");
7310         if (type.contains8BitInt())
7311             requireInt8Arithmetic(loc, "qualifier", "(u)int8 types can only be in uniform block or buffer storage");
7312     }
7313
7314     if (type.getQualifier().storage == EvqtaskPayloadSharedEXT)
7315         intermediate.addTaskPayloadEXTCount();
7316     if (type.getQualifier().storage == EvqShared && type.containsCoopMat())
7317         error(loc, "qualifier", "Cooperative matrix types must not be used in shared memory", "");
7318
7319     if (profile == EEsProfile) {
7320         if (type.getQualifier().isPipeInput() && type.getBasicType() == EbtStruct) {
7321             if (type.getQualifier().isArrayedIo(language)) {
7322                 TType perVertexType(type, 0);
7323                 if (perVertexType.containsArray() && perVertexType.containsBuiltIn() == false) {
7324                     error(loc, "A per vertex structure containing an array is not allowed as input in ES", type.getTypeName().c_str(), "");
7325                 }
7326             }
7327             else if (type.containsArray() && type.containsBuiltIn() == false) {
7328                 error(loc, "A structure containing an array is not allowed as input in ES", type.getTypeName().c_str(), "");
7329             }
7330             if (type.containsStructure())
7331                 error(loc, "A structure containing an struct is not allowed as input in ES", type.getTypeName().c_str(), "");
7332         }
7333     }
7334
7335     if (identifier != "gl_FragCoord" && (publicType.shaderQualifiers.originUpperLeft || publicType.shaderQualifiers.pixelCenterInteger))
7336         error(loc, "can only apply origin_upper_left and pixel_center_origin to gl_FragCoord", "layout qualifier", "");
7337     if (identifier != "gl_FragDepth" && publicType.shaderQualifiers.getDepth() != EldNone)
7338         error(loc, "can only apply depth layout to gl_FragDepth", "layout qualifier", "");
7339     if (identifier != "gl_FragStencilRefARB" && publicType.shaderQualifiers.getStencil() != ElsNone)
7340         error(loc, "can only apply depth layout to gl_FragStencilRefARB", "layout qualifier", "");
7341
7342     // Check for redeclaration of built-ins and/or attempting to declare a reserved name
7343     TSymbol* symbol = redeclareBuiltinVariable(loc, identifier, type.getQualifier(), publicType.shaderQualifiers);
7344     if (symbol == nullptr)
7345         reservedErrorCheck(loc, identifier);
7346
7347     if (symbol == nullptr && spvVersion.vulkan > 0 && spvVersion.vulkanRelaxed) {
7348         bool remapped = vkRelaxedRemapUniformVariable(loc, identifier, publicType, arraySizes, initializer, type);
7349
7350         if (remapped) {
7351             return nullptr;
7352         }
7353     }
7354
7355     inheritGlobalDefaults(type.getQualifier());
7356
7357     // Declare the variable
7358     if (type.isArray()) {
7359         // Check that implicit sizing is only where allowed.
7360         arraySizesCheck(loc, type.getQualifier(), type.getArraySizes(), initializer, false);
7361
7362         if (! arrayQualifierError(loc, type.getQualifier()) && ! arrayError(loc, type))
7363             declareArray(loc, identifier, type, symbol);
7364
7365         if (initializer) {
7366             profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, "initializer");
7367             profileRequires(loc, EEsProfile, 300, nullptr, "initializer");
7368         }
7369     } else {
7370         // non-array case
7371         if (symbol == nullptr)
7372             symbol = declareNonArray(loc, identifier, type);
7373         else if (type != symbol->getType())
7374             error(loc, "cannot change the type of", "redeclaration", symbol->getName().c_str());
7375     }
7376
7377     if (symbol == nullptr)
7378         return nullptr;
7379
7380     // Deal with initializer
7381     TIntermNode* initNode = nullptr;
7382     if (symbol != nullptr && initializer) {
7383         TVariable* variable = symbol->getAsVariable();
7384         if (! variable) {
7385             error(loc, "initializer requires a variable, not a member", identifier.c_str(), "");
7386             return nullptr;
7387         }
7388         initNode = executeInitializer(loc, initializer, variable);
7389     }
7390
7391     // look for errors in layout qualifier use
7392     layoutObjectCheck(loc, *symbol);
7393
7394     // fix up
7395     fixOffset(loc, *symbol);
7396
7397     return initNode;
7398 }
7399
7400 // Pick up global defaults from the provide global defaults into dst.
7401 void TParseContext::inheritGlobalDefaults(TQualifier& dst) const
7402 {
7403 #ifndef GLSLANG_WEB
7404     if (dst.storage == EvqVaryingOut) {
7405         if (! dst.hasStream() && language == EShLangGeometry)
7406             dst.layoutStream = globalOutputDefaults.layoutStream;
7407         if (! dst.hasXfbBuffer())
7408             dst.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
7409     }
7410 #endif
7411 }
7412
7413 //
7414 // Make an internal-only variable whose name is for debug purposes only
7415 // and won't be searched for.  Callers will only use the return value to use
7416 // the variable, not the name to look it up.  It is okay if the name
7417 // is the same as other names; there won't be any conflict.
7418 //
7419 TVariable* TParseContext::makeInternalVariable(const char* name, const TType& type) const
7420 {
7421     TString* nameString = NewPoolTString(name);
7422     TVariable* variable = new TVariable(nameString, type);
7423     symbolTable.makeInternalVariable(*variable);
7424
7425     return variable;
7426 }
7427
7428 //
7429 // Declare a non-array variable, the main point being there is no redeclaration
7430 // for resizing allowed.
7431 //
7432 // Return the successfully declared variable.
7433 //
7434 TVariable* TParseContext::declareNonArray(const TSourceLoc& loc, const TString& identifier, const TType& type)
7435 {
7436     // make a new variable
7437     TVariable* variable = new TVariable(&identifier, type);
7438
7439 #ifndef GLSLANG_WEB
7440     ioArrayCheck(loc, type, identifier);
7441 #endif
7442
7443     // add variable to symbol table
7444     if (symbolTable.insert(*variable)) {
7445         if (symbolTable.atGlobalLevel())
7446             trackLinkage(*variable);
7447         return variable;
7448     }
7449
7450     error(loc, "redefinition", variable->getName().c_str(), "");
7451     return nullptr;
7452 }
7453
7454 //
7455 // Handle all types of initializers from the grammar.
7456 //
7457 // Returning nullptr just means there is no code to execute to handle the
7458 // initializer, which will, for example, be the case for constant initializers.
7459 //
7460 TIntermNode* TParseContext::executeInitializer(const TSourceLoc& loc, TIntermTyped* initializer, TVariable* variable)
7461 {
7462     // A null initializer is an aggregate that hasn't had an op assigned yet
7463     // (still EOpNull, no relation to nullInit), and has no children.
7464     bool nullInit = initializer->getAsAggregate() && initializer->getAsAggregate()->getOp() == EOpNull &&
7465         initializer->getAsAggregate()->getSequence().size() == 0;
7466
7467     //
7468     // Identifier must be of type constant, a global, or a temporary, and
7469     // starting at version 120, desktop allows uniforms to have initializers.
7470     //
7471     TStorageQualifier qualifier = variable->getType().getQualifier().storage;
7472     if (! (qualifier == EvqTemporary || qualifier == EvqGlobal || qualifier == EvqConst ||
7473            (qualifier == EvqUniform && !isEsProfile() && version >= 120))) {
7474         if (qualifier == EvqShared) {
7475             // GL_EXT_null_initializer allows this for shared, if it's a null initializer
7476             if (nullInit) {
7477                 const char* feature = "initialization with shared qualifier";
7478                 profileRequires(loc, EEsProfile, 0, E_GL_EXT_null_initializer, feature);
7479                 profileRequires(loc, ~EEsProfile, 0, E_GL_EXT_null_initializer, feature);
7480             } else {
7481                 error(loc, "initializer can only be a null initializer ('{}')", "shared", "");
7482             }
7483         } else {
7484             error(loc, " cannot initialize this type of qualifier ",
7485                   variable->getType().getStorageQualifierString(), "");
7486             return nullptr;
7487         }
7488     }
7489
7490     if (nullInit) {
7491         // only some types can be null initialized
7492         if (variable->getType().containsUnsizedArray()) {
7493             error(loc, "null initializers can't size unsized arrays", "{}", "");
7494             return nullptr;
7495         }
7496         if (variable->getType().containsOpaque()) {
7497             error(loc, "null initializers can't be used on opaque values", "{}", "");
7498             return nullptr;
7499         }
7500         variable->getWritableType().getQualifier().setNullInit();
7501         return nullptr;
7502     }
7503
7504     arrayObjectCheck(loc, variable->getType(), "array initializer");
7505
7506     //
7507     // If the initializer was from braces { ... }, we convert the whole subtree to a
7508     // constructor-style subtree, allowing the rest of the code to operate
7509     // identically for both kinds of initializers.
7510     //
7511     // Type can't be deduced from the initializer list, so a skeletal type to
7512     // follow has to be passed in.  Constness and specialization-constness
7513     // should be deduced bottom up, not dictated by the skeletal type.
7514     //
7515     TType skeletalType;
7516     skeletalType.shallowCopy(variable->getType());
7517     skeletalType.getQualifier().makeTemporary();
7518 #ifndef GLSLANG_WEB
7519     initializer = convertInitializerList(loc, skeletalType, initializer);
7520 #endif
7521     if (! initializer) {
7522         // error recovery; don't leave const without constant values
7523         if (qualifier == EvqConst)
7524             variable->getWritableType().getQualifier().makeTemporary();
7525         return nullptr;
7526     }
7527
7528     // Fix outer arrayness if variable is unsized, getting size from the initializer
7529     if (initializer->getType().isSizedArray() && variable->getType().isUnsizedArray())
7530         variable->getWritableType().changeOuterArraySize(initializer->getType().getOuterArraySize());
7531
7532     // Inner arrayness can also get set by an initializer
7533     if (initializer->getType().isArrayOfArrays() && variable->getType().isArrayOfArrays() &&
7534         initializer->getType().getArraySizes()->getNumDims() ==
7535            variable->getType().getArraySizes()->getNumDims()) {
7536         // adopt unsized sizes from the initializer's sizes
7537         for (int d = 1; d < variable->getType().getArraySizes()->getNumDims(); ++d) {
7538             if (variable->getType().getArraySizes()->getDimSize(d) == UnsizedArraySize) {
7539                 variable->getWritableType().getArraySizes()->setDimSize(d,
7540                     initializer->getType().getArraySizes()->getDimSize(d));
7541             }
7542         }
7543     }
7544
7545     // Uniforms require a compile-time constant initializer
7546     if (qualifier == EvqUniform && ! initializer->getType().getQualifier().isFrontEndConstant()) {
7547         error(loc, "uniform initializers must be constant", "=", "'%s'",
7548               variable->getType().getCompleteString(intermediate.getEnhancedMsgs()).c_str());
7549         variable->getWritableType().getQualifier().makeTemporary();
7550         return nullptr;
7551     }
7552     // Global consts require a constant initializer (specialization constant is okay)
7553     if (qualifier == EvqConst && symbolTable.atGlobalLevel() && ! initializer->getType().getQualifier().isConstant()) {
7554         error(loc, "global const initializers must be constant", "=", "'%s'",
7555               variable->getType().getCompleteString(intermediate.getEnhancedMsgs()).c_str());
7556         variable->getWritableType().getQualifier().makeTemporary();
7557         return nullptr;
7558     }
7559
7560     // Const variables require a constant initializer, depending on version
7561     if (qualifier == EvqConst) {
7562         if (! initializer->getType().getQualifier().isConstant()) {
7563             const char* initFeature = "non-constant initializer";
7564             requireProfile(loc, ~EEsProfile, initFeature);
7565             profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, initFeature);
7566             variable->getWritableType().getQualifier().storage = EvqConstReadOnly;
7567             qualifier = EvqConstReadOnly;
7568         }
7569     } else {
7570         // Non-const global variables in ES need a const initializer.
7571         //
7572         // "In declarations of global variables with no storage qualifier or with a const
7573         // qualifier any initializer must be a constant expression."
7574         if (symbolTable.atGlobalLevel() && ! initializer->getType().getQualifier().isConstant()) {
7575             const char* initFeature =
7576                 "non-constant global initializer (needs GL_EXT_shader_non_constant_global_initializers)";
7577             if (isEsProfile()) {
7578                 if (relaxedErrors() && ! extensionTurnedOn(E_GL_EXT_shader_non_constant_global_initializers))
7579                     warn(loc, "not allowed in this version", initFeature, "");
7580                 else
7581                     profileRequires(loc, EEsProfile, 0, E_GL_EXT_shader_non_constant_global_initializers, initFeature);
7582             }
7583         }
7584     }
7585
7586     if (qualifier == EvqConst || qualifier == EvqUniform) {
7587         // Compile-time tagging of the variable with its constant value...
7588
7589         initializer = intermediate.addConversion(EOpAssign, variable->getType(), initializer);
7590         if (! initializer || ! initializer->getType().getQualifier().isConstant() ||
7591             variable->getType() != initializer->getType()) {
7592             error(loc, "non-matching or non-convertible constant type for const initializer",
7593                   variable->getType().getStorageQualifierString(), "");
7594             variable->getWritableType().getQualifier().makeTemporary();
7595             return nullptr;
7596         }
7597
7598         // We either have a folded constant in getAsConstantUnion, or we have to use
7599         // the initializer's subtree in the AST to represent the computation of a
7600         // specialization constant.
7601         assert(initializer->getAsConstantUnion() || initializer->getType().getQualifier().isSpecConstant());
7602         if (initializer->getAsConstantUnion())
7603             variable->setConstArray(initializer->getAsConstantUnion()->getConstArray());
7604         else {
7605             // It's a specialization constant.
7606             variable->getWritableType().getQualifier().makeSpecConstant();
7607
7608             // Keep the subtree that computes the specialization constant with the variable.
7609             // Later, a symbol node will adopt the subtree from the variable.
7610             variable->setConstSubtree(initializer);
7611         }
7612     } else {
7613         // normal assigning of a value to a variable...
7614         specializationCheck(loc, initializer->getType(), "initializer");
7615         TIntermSymbol* intermSymbol = intermediate.addSymbol(*variable, loc);
7616         TIntermTyped* initNode = intermediate.addAssign(EOpAssign, intermSymbol, initializer, loc);
7617         if (! initNode)
7618             assignError(loc, "=", intermSymbol->getCompleteString(intermediate.getEnhancedMsgs()), initializer->getCompleteString(intermediate.getEnhancedMsgs()));
7619
7620         return initNode;
7621     }
7622
7623     return nullptr;
7624 }
7625
7626 //
7627 // Reprocess any initializer-list (the  "{ ... }" syntax) parts of the
7628 // initializer.
7629 //
7630 // Need to hierarchically assign correct types and implicit
7631 // conversions. Will do this mimicking the same process used for
7632 // creating a constructor-style initializer, ensuring we get the
7633 // same form.  However, it has to in parallel walk the 'type'
7634 // passed in, as type cannot be deduced from an initializer list.
7635 //
7636 TIntermTyped* TParseContext::convertInitializerList(const TSourceLoc& loc, const TType& type, TIntermTyped* initializer)
7637 {
7638     // Will operate recursively.  Once a subtree is found that is constructor style,
7639     // everything below it is already good: Only the "top part" of the initializer
7640     // can be an initializer list, where "top part" can extend for several (or all) levels.
7641
7642     // see if we have bottomed out in the tree within the initializer-list part
7643     TIntermAggregate* initList = initializer->getAsAggregate();
7644     if (! initList || initList->getOp() != EOpNull)
7645         return initializer;
7646
7647     // Of the initializer-list set of nodes, need to process bottom up,
7648     // so recurse deep, then process on the way up.
7649
7650     // Go down the tree here...
7651     if (type.isArray()) {
7652         // The type's array might be unsized, which could be okay, so base sizes on the size of the aggregate.
7653         // Later on, initializer execution code will deal with array size logic.
7654         TType arrayType;
7655         arrayType.shallowCopy(type);                     // sharing struct stuff is fine
7656         arrayType.copyArraySizes(*type.getArraySizes());  // but get a fresh copy of the array information, to edit below
7657
7658         // edit array sizes to fill in unsized dimensions
7659         arrayType.changeOuterArraySize((int)initList->getSequence().size());
7660         TIntermTyped* firstInit = initList->getSequence()[0]->getAsTyped();
7661         if (arrayType.isArrayOfArrays() && firstInit->getType().isArray() &&
7662             arrayType.getArraySizes()->getNumDims() == firstInit->getType().getArraySizes()->getNumDims() + 1) {
7663             for (int d = 1; d < arrayType.getArraySizes()->getNumDims(); ++d) {
7664                 if (arrayType.getArraySizes()->getDimSize(d) == UnsizedArraySize)
7665                     arrayType.getArraySizes()->setDimSize(d, firstInit->getType().getArraySizes()->getDimSize(d - 1));
7666             }
7667         }
7668
7669         TType elementType(arrayType, 0); // dereferenced type
7670         for (size_t i = 0; i < initList->getSequence().size(); ++i) {
7671             initList->getSequence()[i] = convertInitializerList(loc, elementType, initList->getSequence()[i]->getAsTyped());
7672             if (initList->getSequence()[i] == nullptr)
7673                 return nullptr;
7674         }
7675
7676         return addConstructor(loc, initList, arrayType);
7677     } else if (type.isStruct()) {
7678         if (type.getStruct()->size() != initList->getSequence().size()) {
7679             error(loc, "wrong number of structure members", "initializer list", "");
7680             return nullptr;
7681         }
7682         for (size_t i = 0; i < type.getStruct()->size(); ++i) {
7683             initList->getSequence()[i] = convertInitializerList(loc, *(*type.getStruct())[i].type, initList->getSequence()[i]->getAsTyped());
7684             if (initList->getSequence()[i] == nullptr)
7685                 return nullptr;
7686         }
7687     } else if (type.isMatrix()) {
7688         if (type.getMatrixCols() != (int)initList->getSequence().size()) {
7689             error(loc, "wrong number of matrix columns:", "initializer list", type.getCompleteString(intermediate.getEnhancedMsgs()).c_str());
7690             return nullptr;
7691         }
7692         TType vectorType(type, 0); // dereferenced type
7693         for (int i = 0; i < type.getMatrixCols(); ++i) {
7694             initList->getSequence()[i] = convertInitializerList(loc, vectorType, initList->getSequence()[i]->getAsTyped());
7695             if (initList->getSequence()[i] == nullptr)
7696                 return nullptr;
7697         }
7698     } else if (type.isVector()) {
7699         if (type.getVectorSize() != (int)initList->getSequence().size()) {
7700             error(loc, "wrong vector size (or rows in a matrix column):", "initializer list", type.getCompleteString(intermediate.getEnhancedMsgs()).c_str());
7701             return nullptr;
7702         }
7703         TBasicType destType = type.getBasicType();
7704         for (int i = 0; i < type.getVectorSize(); ++i) {
7705             TBasicType initType = initList->getSequence()[i]->getAsTyped()->getBasicType();
7706             if (destType != initType && !intermediate.canImplicitlyPromote(initType, destType)) {
7707                 error(loc, "type mismatch in initializer list", "initializer list", type.getCompleteString(intermediate.getEnhancedMsgs()).c_str());
7708                 return nullptr;
7709             }
7710
7711         }
7712     } else {
7713         error(loc, "unexpected initializer-list type:", "initializer list", type.getCompleteString(intermediate.getEnhancedMsgs()).c_str());
7714         return nullptr;
7715     }
7716
7717     // Now that the subtree is processed, process this node as if the
7718     // initializer list is a set of arguments to a constructor.
7719     TIntermNode* emulatedConstructorArguments;
7720     if (initList->getSequence().size() == 1)
7721         emulatedConstructorArguments = initList->getSequence()[0];
7722     else
7723         emulatedConstructorArguments = initList;
7724     return addConstructor(loc, emulatedConstructorArguments, type);
7725 }
7726
7727 //
7728 // Test for the correctness of the parameters passed to various constructor functions
7729 // and also convert them to the right data type, if allowed and required.
7730 //
7731 // 'node' is what to construct from.
7732 // 'type' is what type to construct.
7733 //
7734 // Returns nullptr for an error or the constructed node (aggregate or typed) for no error.
7735 //
7736 TIntermTyped* TParseContext::addConstructor(const TSourceLoc& loc, TIntermNode* node, const TType& type)
7737 {
7738     if (node == nullptr || node->getAsTyped() == nullptr)
7739         return nullptr;
7740     rValueErrorCheck(loc, "constructor", node->getAsTyped());
7741
7742     TIntermAggregate* aggrNode = node->getAsAggregate();
7743     TOperator op = intermediate.mapTypeToConstructorOp(type);
7744
7745     // Combined texture-sampler constructors are completely semantic checked
7746     // in constructorTextureSamplerError()
7747     if (op == EOpConstructTextureSampler) {
7748         if (aggrNode->getSequence()[1]->getAsTyped()->getType().getSampler().shadow) {
7749             // Transfer depth into the texture (SPIR-V image) type, as a hint
7750             // for tools to know this texture/image is a depth image.
7751             aggrNode->getSequence()[0]->getAsTyped()->getWritableType().getSampler().shadow = true;
7752         }
7753         return intermediate.setAggregateOperator(aggrNode, op, type, loc);
7754     }
7755
7756     TTypeList::const_iterator memberTypes;
7757     if (op == EOpConstructStruct)
7758         memberTypes = type.getStruct()->begin();
7759
7760     TType elementType;
7761     if (type.isArray()) {
7762         TType dereferenced(type, 0);
7763         elementType.shallowCopy(dereferenced);
7764     } else
7765         elementType.shallowCopy(type);
7766
7767     bool singleArg;
7768     if (aggrNode) {
7769         if (aggrNode->getOp() != EOpNull)
7770             singleArg = true;
7771         else
7772             singleArg = false;
7773     } else
7774         singleArg = true;
7775
7776     TIntermTyped *newNode;
7777     if (singleArg) {
7778         // If structure constructor or array constructor is being called
7779         // for only one parameter inside the structure, we need to call constructAggregate function once.
7780         if (type.isArray())
7781             newNode = constructAggregate(node, elementType, 1, node->getLoc());
7782         else if (op == EOpConstructStruct)
7783             newNode = constructAggregate(node, *(*memberTypes).type, 1, node->getLoc());
7784         else
7785             newNode = constructBuiltIn(type, op, node->getAsTyped(), node->getLoc(), false);
7786
7787         if (newNode && (type.isArray() || op == EOpConstructStruct))
7788             newNode = intermediate.setAggregateOperator(newNode, EOpConstructStruct, type, loc);
7789
7790         return newNode;
7791     }
7792
7793     //
7794     // Handle list of arguments.
7795     //
7796     TIntermSequence &sequenceVector = aggrNode->getSequence();    // Stores the information about the parameter to the constructor
7797     // if the structure constructor contains more than one parameter, then construct
7798     // each parameter
7799
7800     int paramCount = 0;  // keeps track of the constructor parameter number being checked
7801
7802     // for each parameter to the constructor call, check to see if the right type is passed or convert them
7803     // to the right type if possible (and allowed).
7804     // for structure constructors, just check if the right type is passed, no conversion is allowed.
7805     for (TIntermSequence::iterator p = sequenceVector.begin();
7806                                    p != sequenceVector.end(); p++, paramCount++) {
7807         if (type.isArray())
7808             newNode = constructAggregate(*p, elementType, paramCount+1, node->getLoc());
7809         else if (op == EOpConstructStruct)
7810             newNode = constructAggregate(*p, *(memberTypes[paramCount]).type, paramCount+1, node->getLoc());
7811         else
7812             newNode = constructBuiltIn(type, op, (*p)->getAsTyped(), node->getLoc(), true);
7813
7814         if (newNode)
7815             *p = newNode;
7816         else
7817             return nullptr;
7818     }
7819
7820     TIntermTyped *ret_node = intermediate.setAggregateOperator(aggrNode, op, type, loc);
7821
7822     TIntermAggregate *agg_node = ret_node->getAsAggregate();
7823     if (agg_node && (agg_node->isVector() || agg_node->isArray() || agg_node->isMatrix()))
7824         agg_node->updatePrecision();
7825
7826     return ret_node;
7827 }
7828
7829 // Function for constructor implementation. Calls addUnaryMath with appropriate EOp value
7830 // for the parameter to the constructor (passed to this function). Essentially, it converts
7831 // the parameter types correctly. If a constructor expects an int (like ivec2) and is passed a
7832 // float, then float is converted to int.
7833 //
7834 // Returns nullptr for an error or the constructed node.
7835 //
7836 TIntermTyped* TParseContext::constructBuiltIn(const TType& type, TOperator op, TIntermTyped* node, const TSourceLoc& loc,
7837     bool subset)
7838 {
7839     // If we are changing a matrix in both domain of basic type and to a non matrix,
7840     // do the shape change first (by default, below, basic type is changed before shape).
7841     // This avoids requesting a matrix of a new type that is going to be discarded anyway.
7842     // TODO: This could be generalized to more type combinations, but that would require
7843     // more extensive testing and full algorithm rework. For now, the need to do two changes makes
7844     // the recursive call work, and avoids the most egregious case of creating integer matrices.
7845     if (node->getType().isMatrix() && (type.isScalar() || type.isVector()) &&
7846             type.isFloatingDomain() != node->getType().isFloatingDomain()) {
7847         TType transitionType(node->getBasicType(), glslang::EvqTemporary, type.getVectorSize(), 0, 0, node->isVector());
7848         TOperator transitionOp = intermediate.mapTypeToConstructorOp(transitionType);
7849         node = constructBuiltIn(transitionType, transitionOp, node, loc, false);
7850     }
7851
7852     TIntermTyped* newNode;
7853     TOperator basicOp;
7854
7855     //
7856     // First, convert types as needed.
7857     //
7858     switch (op) {
7859     case EOpConstructVec2:
7860     case EOpConstructVec3:
7861     case EOpConstructVec4:
7862     case EOpConstructMat2x2:
7863     case EOpConstructMat2x3:
7864     case EOpConstructMat2x4:
7865     case EOpConstructMat3x2:
7866     case EOpConstructMat3x3:
7867     case EOpConstructMat3x4:
7868     case EOpConstructMat4x2:
7869     case EOpConstructMat4x3:
7870     case EOpConstructMat4x4:
7871     case EOpConstructFloat:
7872         basicOp = EOpConstructFloat;
7873         break;
7874
7875     case EOpConstructIVec2:
7876     case EOpConstructIVec3:
7877     case EOpConstructIVec4:
7878     case EOpConstructInt:
7879         basicOp = EOpConstructInt;
7880         break;
7881
7882     case EOpConstructUVec2:
7883         if (node->getType().getBasicType() == EbtReference) {
7884             requireExtensions(loc, 1, &E_GL_EXT_buffer_reference_uvec2, "reference conversion to uvec2");
7885             TIntermTyped* newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvPtrToUvec2, true, node,
7886                 type);
7887             return newNode;
7888         }
7889     case EOpConstructUVec3:
7890     case EOpConstructUVec4:
7891     case EOpConstructUint:
7892         basicOp = EOpConstructUint;
7893         break;
7894
7895     case EOpConstructBVec2:
7896     case EOpConstructBVec3:
7897     case EOpConstructBVec4:
7898     case EOpConstructBool:
7899         basicOp = EOpConstructBool;
7900         break;
7901
7902 #ifndef GLSLANG_WEB
7903
7904     case EOpConstructDVec2:
7905     case EOpConstructDVec3:
7906     case EOpConstructDVec4:
7907     case EOpConstructDMat2x2:
7908     case EOpConstructDMat2x3:
7909     case EOpConstructDMat2x4:
7910     case EOpConstructDMat3x2:
7911     case EOpConstructDMat3x3:
7912     case EOpConstructDMat3x4:
7913     case EOpConstructDMat4x2:
7914     case EOpConstructDMat4x3:
7915     case EOpConstructDMat4x4:
7916     case EOpConstructDouble:
7917         basicOp = EOpConstructDouble;
7918         break;
7919
7920     case EOpConstructF16Vec2:
7921     case EOpConstructF16Vec3:
7922     case EOpConstructF16Vec4:
7923     case EOpConstructF16Mat2x2:
7924     case EOpConstructF16Mat2x3:
7925     case EOpConstructF16Mat2x4:
7926     case EOpConstructF16Mat3x2:
7927     case EOpConstructF16Mat3x3:
7928     case EOpConstructF16Mat3x4:
7929     case EOpConstructF16Mat4x2:
7930     case EOpConstructF16Mat4x3:
7931     case EOpConstructF16Mat4x4:
7932     case EOpConstructFloat16:
7933         basicOp = EOpConstructFloat16;
7934         // 8/16-bit storage extensions don't support constructing composites of 8/16-bit types,
7935         // so construct a 32-bit type and convert
7936         if (!intermediate.getArithemeticFloat16Enabled()) {
7937             TType tempType(EbtFloat, EvqTemporary, type.getVectorSize());
7938             newNode = node;
7939             if (tempType != newNode->getType()) {
7940                 TOperator aggregateOp;
7941                 if (op == EOpConstructFloat16)
7942                     aggregateOp = EOpConstructFloat;
7943                 else
7944                     aggregateOp = (TOperator)(EOpConstructVec2 + op - EOpConstructF16Vec2);
7945                 newNode = intermediate.setAggregateOperator(newNode, aggregateOp, tempType, node->getLoc());
7946             }
7947             newNode = intermediate.addConversion(EbtFloat16, newNode);
7948             return newNode;
7949         }
7950         break;
7951
7952     case EOpConstructI8Vec2:
7953     case EOpConstructI8Vec3:
7954     case EOpConstructI8Vec4:
7955     case EOpConstructInt8:
7956         basicOp = EOpConstructInt8;
7957         // 8/16-bit storage extensions don't support constructing composites of 8/16-bit types,
7958         // so construct a 32-bit type and convert
7959         if (!intermediate.getArithemeticInt8Enabled()) {
7960             TType tempType(EbtInt, EvqTemporary, type.getVectorSize());
7961             newNode = node;
7962             if (tempType != newNode->getType()) {
7963                 TOperator aggregateOp;
7964                 if (op == EOpConstructInt8)
7965                     aggregateOp = EOpConstructInt;
7966                 else
7967                     aggregateOp = (TOperator)(EOpConstructIVec2 + op - EOpConstructI8Vec2);
7968                 newNode = intermediate.setAggregateOperator(newNode, aggregateOp, tempType, node->getLoc());
7969             }
7970             newNode = intermediate.addConversion(EbtInt8, newNode);
7971             return newNode;
7972         }
7973         break;
7974
7975     case EOpConstructU8Vec2:
7976     case EOpConstructU8Vec3:
7977     case EOpConstructU8Vec4:
7978     case EOpConstructUint8:
7979         basicOp = EOpConstructUint8;
7980         // 8/16-bit storage extensions don't support constructing composites of 8/16-bit types,
7981         // so construct a 32-bit type and convert
7982         if (!intermediate.getArithemeticInt8Enabled()) {
7983             TType tempType(EbtUint, EvqTemporary, type.getVectorSize());
7984             newNode = node;
7985             if (tempType != newNode->getType()) {
7986                 TOperator aggregateOp;
7987                 if (op == EOpConstructUint8)
7988                     aggregateOp = EOpConstructUint;
7989                 else
7990                     aggregateOp = (TOperator)(EOpConstructUVec2 + op - EOpConstructU8Vec2);
7991                 newNode = intermediate.setAggregateOperator(newNode, aggregateOp, tempType, node->getLoc());
7992             }
7993             newNode = intermediate.addConversion(EbtUint8, newNode);
7994             return newNode;
7995         }
7996         break;
7997
7998     case EOpConstructI16Vec2:
7999     case EOpConstructI16Vec3:
8000     case EOpConstructI16Vec4:
8001     case EOpConstructInt16:
8002         basicOp = EOpConstructInt16;
8003         // 8/16-bit storage extensions don't support constructing composites of 8/16-bit types,
8004         // so construct a 32-bit type and convert
8005         if (!intermediate.getArithemeticInt16Enabled()) {
8006             TType tempType(EbtInt, EvqTemporary, type.getVectorSize());
8007             newNode = node;
8008             if (tempType != newNode->getType()) {
8009                 TOperator aggregateOp;
8010                 if (op == EOpConstructInt16)
8011                     aggregateOp = EOpConstructInt;
8012                 else
8013                     aggregateOp = (TOperator)(EOpConstructIVec2 + op - EOpConstructI16Vec2);
8014                 newNode = intermediate.setAggregateOperator(newNode, aggregateOp, tempType, node->getLoc());
8015             }
8016             newNode = intermediate.addConversion(EbtInt16, newNode);
8017             return newNode;
8018         }
8019         break;
8020
8021     case EOpConstructU16Vec2:
8022     case EOpConstructU16Vec3:
8023     case EOpConstructU16Vec4:
8024     case EOpConstructUint16:
8025         basicOp = EOpConstructUint16;
8026         // 8/16-bit storage extensions don't support constructing composites of 8/16-bit types,
8027         // so construct a 32-bit type and convert
8028         if (!intermediate.getArithemeticInt16Enabled()) {
8029             TType tempType(EbtUint, EvqTemporary, type.getVectorSize());
8030             newNode = node;
8031             if (tempType != newNode->getType()) {
8032                 TOperator aggregateOp;
8033                 if (op == EOpConstructUint16)
8034                     aggregateOp = EOpConstructUint;
8035                 else
8036                     aggregateOp = (TOperator)(EOpConstructUVec2 + op - EOpConstructU16Vec2);
8037                 newNode = intermediate.setAggregateOperator(newNode, aggregateOp, tempType, node->getLoc());
8038             }
8039             newNode = intermediate.addConversion(EbtUint16, newNode);
8040             return newNode;
8041         }
8042         break;
8043
8044     case EOpConstructI64Vec2:
8045     case EOpConstructI64Vec3:
8046     case EOpConstructI64Vec4:
8047     case EOpConstructInt64:
8048         basicOp = EOpConstructInt64;
8049         break;
8050
8051     case EOpConstructUint64:
8052         if (type.isScalar() && node->getType().isReference()) {
8053             TIntermTyped* newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvPtrToUint64, true, node, type);
8054             return newNode;
8055         }
8056         // fall through
8057     case EOpConstructU64Vec2:
8058     case EOpConstructU64Vec3:
8059     case EOpConstructU64Vec4:
8060         basicOp = EOpConstructUint64;
8061         break;
8062
8063     case EOpConstructNonuniform:
8064         // Make a nonuniform copy of node
8065         newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpCopyObject, true, node, type);
8066         return newNode;
8067
8068     case EOpConstructReference:
8069         // construct reference from reference
8070         if (node->getType().isReference()) {
8071             newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConstructReference, true, node, type);
8072             return newNode;
8073         // construct reference from uint64
8074         } else if (node->getType().isScalar() && node->getType().getBasicType() == EbtUint64) {
8075             TIntermTyped* newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvUint64ToPtr, true, node,
8076                 type);
8077             return newNode;
8078         // construct reference from uvec2
8079         } else if (node->getType().isVector() && node->getType().getBasicType() == EbtUint &&
8080                    node->getVectorSize() == 2) {
8081             requireExtensions(loc, 1, &E_GL_EXT_buffer_reference_uvec2, "uvec2 conversion to reference");
8082             TIntermTyped* newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvUvec2ToPtr, true, node,
8083                 type);
8084             return newNode;
8085         } else {
8086             return nullptr;
8087         }
8088
8089     case EOpConstructCooperativeMatrix:
8090         if (!node->getType().isCoopMat()) {
8091             if (type.getBasicType() != node->getType().getBasicType()) {
8092                 node = intermediate.addConversion(type.getBasicType(), node);
8093                 if (node == nullptr)
8094                     return nullptr;
8095             }
8096             node = intermediate.setAggregateOperator(node, EOpConstructCooperativeMatrix, type, node->getLoc());
8097         } else {
8098             TOperator op = EOpNull;
8099             switch (type.getBasicType()) {
8100             default:
8101                 assert(0);
8102                 break;
8103             case EbtInt:
8104                 switch (node->getType().getBasicType()) {
8105                     case EbtFloat:   op = EOpConvFloatToInt;    break;
8106                     case EbtFloat16: op = EOpConvFloat16ToInt;  break;
8107                     case EbtUint8:   op = EOpConvUint8ToInt;    break;
8108                     case EbtInt8:    op = EOpConvInt8ToInt;     break;
8109                     case EbtUint:    op = EOpConvUintToInt;     break;
8110                     default: assert(0);
8111                 }
8112                 break;
8113             case EbtUint:
8114                 switch (node->getType().getBasicType()) {
8115                     case EbtFloat:   op = EOpConvFloatToUint;    break;
8116                     case EbtFloat16: op = EOpConvFloat16ToUint;  break;
8117                     case EbtUint8:   op = EOpConvUint8ToUint;    break;
8118                     case EbtInt8:    op = EOpConvInt8ToUint;     break;
8119                     case EbtInt:     op = EOpConvIntToUint;      break;
8120                     case EbtUint:    op = EOpConvUintToInt8;     break;
8121                     default: assert(0);
8122                 }
8123                 break;
8124             case EbtInt8:
8125                 switch (node->getType().getBasicType()) {
8126                     case EbtFloat:   op = EOpConvFloatToInt8;    break;
8127                     case EbtFloat16: op = EOpConvFloat16ToInt8;  break;
8128                     case EbtUint8:   op = EOpConvUint8ToInt8;    break;
8129                     case EbtInt:     op = EOpConvIntToInt8;      break;
8130                     case EbtUint:    op = EOpConvUintToInt8;     break;
8131                     default: assert(0);
8132                 }
8133                 break;
8134             case EbtUint8:
8135                 switch (node->getType().getBasicType()) {
8136                     case EbtFloat:   op = EOpConvFloatToUint8;   break;
8137                     case EbtFloat16: op = EOpConvFloat16ToUint8; break;
8138                     case EbtInt8:    op = EOpConvInt8ToUint8;    break;
8139                     case EbtInt:     op = EOpConvIntToUint8;     break;
8140                     case EbtUint:    op = EOpConvUintToUint8;    break;
8141                     default: assert(0);
8142                 }
8143                 break;
8144             case EbtFloat:
8145                 switch (node->getType().getBasicType()) {
8146                     case EbtFloat16: op = EOpConvFloat16ToFloat;  break;
8147                     case EbtInt8:    op = EOpConvInt8ToFloat;     break;
8148                     case EbtUint8:   op = EOpConvUint8ToFloat;    break;
8149                     case EbtInt:     op = EOpConvIntToFloat;      break;
8150                     case EbtUint:    op = EOpConvUintToFloat;     break;
8151                     default: assert(0);
8152                 }
8153                 break;
8154             case EbtFloat16:
8155                 switch (node->getType().getBasicType()) {
8156                     case EbtFloat:  op = EOpConvFloatToFloat16;  break;
8157                     case EbtInt8:   op = EOpConvInt8ToFloat16;   break;
8158                     case EbtUint8:  op = EOpConvUint8ToFloat16;  break;
8159                     case EbtInt:    op = EOpConvIntToFloat16;    break;
8160                     case EbtUint:   op = EOpConvUintToFloat16;   break;
8161                     default: assert(0);
8162                 }
8163                 break;
8164             }
8165
8166             node = intermediate.addUnaryNode(op, node, node->getLoc(), type);
8167             // If it's a (non-specialization) constant, it must be folded.
8168             if (node->getAsUnaryNode()->getOperand()->getAsConstantUnion())
8169                 return node->getAsUnaryNode()->getOperand()->getAsConstantUnion()->fold(op, node->getType());
8170         }
8171
8172         return node;
8173
8174     case EOpConstructAccStruct:
8175         if ((node->getType().isScalar() && node->getType().getBasicType() == EbtUint64)) {
8176             // construct acceleration structure from uint64
8177             requireExtensions(loc, Num_ray_tracing_EXTs, ray_tracing_EXTs, "uint64_t conversion to acclerationStructureEXT");
8178             return intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvUint64ToAccStruct, true, node,
8179                 type);
8180         } else if (node->getType().isVector() && node->getType().getBasicType() == EbtUint && node->getVectorSize() == 2) {
8181             // construct acceleration structure from uint64
8182             requireExtensions(loc, Num_ray_tracing_EXTs, ray_tracing_EXTs, "uvec2 conversion to accelerationStructureEXT");
8183             return intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvUvec2ToAccStruct, true, node,
8184                 type);
8185         } else
8186             return nullptr;
8187 #endif // GLSLANG_WEB
8188
8189     default:
8190         error(loc, "unsupported construction", "", "");
8191
8192         return nullptr;
8193     }
8194     newNode = intermediate.addUnaryMath(basicOp, node, node->getLoc());
8195     if (newNode == nullptr) {
8196         error(loc, "can't convert", "constructor", "");
8197         return nullptr;
8198     }
8199
8200     //
8201     // Now, if there still isn't an operation to do the construction, and we need one, add one.
8202     //
8203
8204     // Otherwise, skip out early.
8205     if (subset || (newNode != node && newNode->getType() == type))
8206         return newNode;
8207
8208     // setAggregateOperator will insert a new node for the constructor, as needed.
8209     return intermediate.setAggregateOperator(newNode, op, type, loc);
8210 }
8211
8212 // This function tests for the type of the parameters to the structure or array constructor. Raises
8213 // an error message if the expected type does not match the parameter passed to the constructor.
8214 //
8215 // Returns nullptr for an error or the input node itself if the expected and the given parameter types match.
8216 //
8217 TIntermTyped* TParseContext::constructAggregate(TIntermNode* node, const TType& type, int paramCount, const TSourceLoc& loc)
8218 {
8219     TIntermTyped* converted = intermediate.addConversion(EOpConstructStruct, type, node->getAsTyped());
8220     if (! converted || converted->getType() != type) {
8221         bool enhanced = intermediate.getEnhancedMsgs();
8222         error(loc, "", "constructor", "cannot convert parameter %d from '%s' to '%s'", paramCount,
8223               node->getAsTyped()->getType().getCompleteString(enhanced).c_str(), type.getCompleteString(enhanced).c_str());
8224
8225         return nullptr;
8226     }
8227
8228     return converted;
8229 }
8230
8231 // If a memory qualifier is present in 'to', also make it present in 'from'.
8232 void TParseContext::inheritMemoryQualifiers(const TQualifier& from, TQualifier& to)
8233 {
8234 #ifndef GLSLANG_WEB
8235     if (from.isReadOnly())
8236         to.readonly = from.readonly;
8237     if (from.isWriteOnly())
8238         to.writeonly = from.writeonly;
8239     if (from.coherent)
8240         to.coherent = from.coherent;
8241     if (from.volatil)
8242         to.volatil = from.volatil;
8243     if (from.restrict)
8244         to.restrict = from.restrict;
8245 #endif
8246 }
8247
8248 //
8249 // Do everything needed to add an interface block.
8250 //
8251 void TParseContext::declareBlock(const TSourceLoc& loc, TTypeList& typeList, const TString* instanceName,
8252     TArraySizes* arraySizes)
8253 {
8254     if (spvVersion.vulkan > 0 && spvVersion.vulkanRelaxed)
8255         blockStorageRemap(loc, blockName, currentBlockQualifier);
8256     blockStageIoCheck(loc, currentBlockQualifier);
8257     blockQualifierCheck(loc, currentBlockQualifier, instanceName != nullptr);
8258     if (arraySizes != nullptr) {
8259         arraySizesCheck(loc, currentBlockQualifier, arraySizes, nullptr, false);
8260         arrayOfArrayVersionCheck(loc, arraySizes);
8261         if (arraySizes->getNumDims() > 1)
8262             requireProfile(loc, ~EEsProfile, "array-of-array of block");
8263     }
8264
8265     // Inherit and check member storage qualifiers WRT to the block-level qualifier.
8266     for (unsigned int member = 0; member < typeList.size(); ++member) {
8267         TType& memberType = *typeList[member].type;
8268         TQualifier& memberQualifier = memberType.getQualifier();
8269         const TSourceLoc& memberLoc = typeList[member].loc;
8270         if (memberQualifier.storage != EvqTemporary && memberQualifier.storage != EvqGlobal && memberQualifier.storage != currentBlockQualifier.storage)
8271             error(memberLoc, "member storage qualifier cannot contradict block storage qualifier", memberType.getFieldName().c_str(), "");
8272         memberQualifier.storage = currentBlockQualifier.storage;
8273         globalQualifierFixCheck(memberLoc, memberQualifier);
8274 #ifndef GLSLANG_WEB
8275         inheritMemoryQualifiers(currentBlockQualifier, memberQualifier);
8276         if (currentBlockQualifier.perPrimitiveNV)
8277             memberQualifier.perPrimitiveNV = currentBlockQualifier.perPrimitiveNV;
8278         if (currentBlockQualifier.perViewNV)
8279             memberQualifier.perViewNV = currentBlockQualifier.perViewNV;
8280         if (currentBlockQualifier.perTaskNV)
8281             memberQualifier.perTaskNV = currentBlockQualifier.perTaskNV;
8282         if (currentBlockQualifier.storage == EvqtaskPayloadSharedEXT)
8283             memberQualifier.storage = EvqtaskPayloadSharedEXT;
8284         if (memberQualifier.storage == EvqSpirvStorageClass)
8285             error(memberLoc, "member cannot have a spirv_storage_class qualifier", memberType.getFieldName().c_str(), "");
8286         if (memberQualifier.hasSprivDecorate() && !memberQualifier.getSpirvDecorate().decorateIds.empty())
8287             error(memberLoc, "member cannot have a spirv_decorate_id qualifier", memberType.getFieldName().c_str(), "");
8288 #endif
8289         if ((currentBlockQualifier.storage == EvqUniform || currentBlockQualifier.storage == EvqBuffer) && (memberQualifier.isInterpolation() || memberQualifier.isAuxiliary()))
8290             error(memberLoc, "member of uniform or buffer block cannot have an auxiliary or interpolation qualifier", memberType.getFieldName().c_str(), "");
8291         if (memberType.isArray())
8292             arraySizesCheck(memberLoc, currentBlockQualifier, memberType.getArraySizes(), nullptr, member == typeList.size() - 1);
8293         if (memberQualifier.hasOffset()) {
8294             if (spvVersion.spv == 0) {
8295                 profileRequires(memberLoc, ~EEsProfile, 440, E_GL_ARB_enhanced_layouts, "\"offset\" on block member");
8296                 profileRequires(memberLoc, EEsProfile, 300, E_GL_ARB_enhanced_layouts, "\"offset\" on block member");
8297             }
8298         }
8299
8300         if (memberType.containsOpaque())
8301             error(memberLoc, "member of block cannot be or contain a sampler, image, or atomic_uint type", typeList[member].type->getFieldName().c_str(), "");
8302
8303         if (memberType.containsCoopMat())
8304             error(memberLoc, "member of block cannot be or contain a cooperative matrix type", typeList[member].type->getFieldName().c_str(), "");
8305     }
8306
8307     // This might be a redeclaration of a built-in block.  If so, redeclareBuiltinBlock() will
8308     // do all the rest.
8309     if (! symbolTable.atBuiltInLevel() && builtInName(*blockName)) {
8310         redeclareBuiltinBlock(loc, typeList, *blockName, instanceName, arraySizes);
8311         return;
8312     }
8313
8314     // Not a redeclaration of a built-in; check that all names are user names.
8315     reservedErrorCheck(loc, *blockName);
8316     if (instanceName)
8317         reservedErrorCheck(loc, *instanceName);
8318     for (unsigned int member = 0; member < typeList.size(); ++member)
8319         reservedErrorCheck(typeList[member].loc, typeList[member].type->getFieldName());
8320
8321     // Make default block qualification, and adjust the member qualifications
8322
8323     TQualifier defaultQualification;
8324     switch (currentBlockQualifier.storage) {
8325     case EvqUniform:    defaultQualification = globalUniformDefaults;    break;
8326     case EvqBuffer:     defaultQualification = globalBufferDefaults;     break;
8327     case EvqVaryingIn:  defaultQualification = globalInputDefaults;      break;
8328     case EvqVaryingOut: defaultQualification = globalOutputDefaults;     break;
8329     case EvqShared:     defaultQualification = globalSharedDefaults;     break;
8330     default:            defaultQualification.clear();                    break;
8331     }
8332
8333     // Special case for "push_constant uniform", which has a default of std430,
8334     // contrary to normal uniform defaults, and can't have a default tracked for it.
8335     if ((currentBlockQualifier.isPushConstant() && !currentBlockQualifier.hasPacking()) ||
8336         (currentBlockQualifier.isShaderRecord() && !currentBlockQualifier.hasPacking()))
8337         currentBlockQualifier.layoutPacking = ElpStd430;
8338
8339     // Special case for "taskNV in/out", which has a default of std430,
8340     if (currentBlockQualifier.isTaskMemory() && !currentBlockQualifier.hasPacking())
8341         currentBlockQualifier.layoutPacking = ElpStd430;
8342
8343     // fix and check for member layout qualifiers
8344
8345     mergeObjectLayoutQualifiers(defaultQualification, currentBlockQualifier, true);
8346
8347     // "The align qualifier can only be used on blocks or block members, and only for blocks declared with std140 or std430 layouts."
8348     if (currentBlockQualifier.hasAlign()) {
8349         if (defaultQualification.layoutPacking != ElpStd140 &&
8350             defaultQualification.layoutPacking != ElpStd430 &&
8351             defaultQualification.layoutPacking != ElpScalar) {
8352             error(loc, "can only be used with std140, std430, or scalar layout packing", "align", "");
8353             defaultQualification.layoutAlign = -1;
8354         }
8355     }
8356
8357     bool memberWithLocation = false;
8358     bool memberWithoutLocation = false;
8359     bool memberWithPerViewQualifier = false;
8360     for (unsigned int member = 0; member < typeList.size(); ++member) {
8361         TQualifier& memberQualifier = typeList[member].type->getQualifier();
8362         const TSourceLoc& memberLoc = typeList[member].loc;
8363 #ifndef GLSLANG_WEB
8364         if (memberQualifier.hasStream()) {
8365             if (defaultQualification.layoutStream != memberQualifier.layoutStream)
8366                 error(memberLoc, "member cannot contradict block", "stream", "");
8367         }
8368
8369         // "This includes a block's inheritance of the
8370         // current global default buffer, a block member's inheritance of the block's
8371         // buffer, and the requirement that any *xfb_buffer* declared on a block
8372         // member must match the buffer inherited from the block."
8373         if (memberQualifier.hasXfbBuffer()) {
8374             if (defaultQualification.layoutXfbBuffer != memberQualifier.layoutXfbBuffer)
8375                 error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_buffer", "");
8376         }
8377 #endif
8378
8379         if (memberQualifier.hasPacking())
8380             error(memberLoc, "member of block cannot have a packing layout qualifier", typeList[member].type->getFieldName().c_str(), "");
8381         if (memberQualifier.hasLocation()) {
8382             const char* feature = "location on block member";
8383             switch (currentBlockQualifier.storage) {
8384 #ifndef GLSLANG_WEB
8385             case EvqVaryingIn:
8386             case EvqVaryingOut:
8387                 requireProfile(memberLoc, ECoreProfile | ECompatibilityProfile | EEsProfile, feature);
8388                 profileRequires(memberLoc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, feature);
8389                 profileRequires(memberLoc, EEsProfile, 320, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, feature);
8390                 memberWithLocation = true;
8391                 break;
8392 #endif
8393             default:
8394                 error(memberLoc, "can only use in an in/out block", feature, "");
8395                 break;
8396             }
8397         } else
8398             memberWithoutLocation = true;
8399
8400         // "The offset qualifier can only be used on block members of blocks declared with std140 or std430 layouts."
8401         // "The align qualifier can only be used on blocks or block members, and only for blocks declared with std140 or std430 layouts."
8402         if (memberQualifier.hasAlign() || memberQualifier.hasOffset()) {
8403             if (defaultQualification.layoutPacking != ElpStd140 &&
8404                 defaultQualification.layoutPacking != ElpStd430 &&
8405                 defaultQualification.layoutPacking != ElpScalar)
8406                 error(memberLoc, "can only be used with std140, std430, or scalar layout packing", "offset/align", "");
8407         }
8408
8409         if (memberQualifier.isPerView()) {
8410             memberWithPerViewQualifier = true;
8411         }
8412
8413         TQualifier newMemberQualification = defaultQualification;
8414         mergeQualifiers(memberLoc, newMemberQualification, memberQualifier, false);
8415         memberQualifier = newMemberQualification;
8416     }
8417
8418     layoutMemberLocationArrayCheck(loc, memberWithLocation, arraySizes);
8419
8420 #ifndef GLSLANG_WEB
8421     // Ensure that the block has an XfbBuffer assigned. This is needed
8422     // because if the block has a XfbOffset assigned, then it is
8423     // assumed that it has implicitly assigned the current global
8424     // XfbBuffer, and because it's members need to be assigned a
8425     // XfbOffset if they lack it.
8426     if (currentBlockQualifier.storage == EvqVaryingOut && globalOutputDefaults.hasXfbBuffer()) {
8427        if (!currentBlockQualifier.hasXfbBuffer() && currentBlockQualifier.hasXfbOffset())
8428           currentBlockQualifier.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
8429     }
8430 #endif
8431
8432     // Process the members
8433     fixBlockLocations(loc, currentBlockQualifier, typeList, memberWithLocation, memberWithoutLocation);
8434     fixXfbOffsets(currentBlockQualifier, typeList);
8435     fixBlockUniformOffsets(currentBlockQualifier, typeList);
8436     fixBlockUniformLayoutMatrix(currentBlockQualifier, &typeList, nullptr);
8437     fixBlockUniformLayoutPacking(currentBlockQualifier, &typeList, nullptr);
8438     for (unsigned int member = 0; member < typeList.size(); ++member)
8439         layoutTypeCheck(typeList[member].loc, *typeList[member].type);
8440
8441 #ifndef GLSLANG_WEB
8442     if (memberWithPerViewQualifier) {
8443         for (unsigned int member = 0; member < typeList.size(); ++member) {
8444             checkAndResizeMeshViewDim(typeList[member].loc, *typeList[member].type, /*isBlockMember*/ true);
8445         }
8446     }
8447 #endif
8448
8449     // reverse merge, so that currentBlockQualifier now has all layout information
8450     // (can't use defaultQualification directly, it's missing other non-layout-default-class qualifiers)
8451     mergeObjectLayoutQualifiers(currentBlockQualifier, defaultQualification, true);
8452
8453     //
8454     // Build and add the interface block as a new type named 'blockName'
8455     //
8456
8457     TType blockType(&typeList, *blockName, currentBlockQualifier);
8458     if (arraySizes != nullptr)
8459         blockType.transferArraySizes(arraySizes);
8460
8461 #ifndef GLSLANG_WEB
8462     if (arraySizes == nullptr)
8463         ioArrayCheck(loc, blockType, instanceName ? *instanceName : *blockName);
8464     if (currentBlockQualifier.hasBufferReference()) {
8465
8466         if (currentBlockQualifier.storage != EvqBuffer)
8467             error(loc, "can only be used with buffer", "buffer_reference", "");
8468
8469         // Create the block reference type. If it was forward-declared, detect that
8470         // as a referent struct type with no members. Replace the referent type with
8471         // blockType.
8472         TType blockNameType(EbtReference, blockType, *blockName);
8473         TVariable* blockNameVar = new TVariable(blockName, blockNameType, true);
8474         if (! symbolTable.insert(*blockNameVar)) {
8475             TSymbol* existingName = symbolTable.find(*blockName);
8476             if (existingName->getType().isReference() &&
8477                 existingName->getType().getReferentType()->getStruct() &&
8478                 existingName->getType().getReferentType()->getStruct()->size() == 0 &&
8479                 existingName->getType().getQualifier().storage == blockType.getQualifier().storage) {
8480                 existingName->getType().getReferentType()->deepCopy(blockType);
8481             } else {
8482                 error(loc, "block name cannot be redefined", blockName->c_str(), "");
8483             }
8484         }
8485         if (!instanceName) {
8486             return;
8487         }
8488     } else
8489 #endif
8490     {
8491         //
8492         // Don't make a user-defined type out of block name; that will cause an error
8493         // if the same block name gets reused in a different interface.
8494         //
8495         // "Block names have no other use within a shader
8496         // beyond interface matching; it is a compile-time error to use a block name at global scope for anything
8497         // other than as a block name (e.g., use of a block name for a global variable name or function name is
8498         // currently reserved)."
8499         //
8500         // Use the symbol table to prevent normal reuse of the block's name, as a variable entry,
8501         // whose type is EbtBlock, but without all the structure; that will come from the type
8502         // the instances point to.
8503         //
8504         TType blockNameType(EbtBlock, blockType.getQualifier().storage);
8505         TVariable* blockNameVar = new TVariable(blockName, blockNameType);
8506         if (! symbolTable.insert(*blockNameVar)) {
8507             TSymbol* existingName = symbolTable.find(*blockName);
8508             if (existingName->getType().getBasicType() == EbtBlock) {
8509                 if (existingName->getType().getQualifier().storage == blockType.getQualifier().storage) {
8510                     error(loc, "Cannot reuse block name within the same interface:", blockName->c_str(), blockType.getStorageQualifierString());
8511                     return;
8512                 }
8513             } else {
8514                 error(loc, "block name cannot redefine a non-block name", blockName->c_str(), "");
8515                 return;
8516             }
8517         }
8518     }
8519
8520     // Add the variable, as anonymous or named instanceName.
8521     // Make an anonymous variable if no name was provided.
8522     if (! instanceName)
8523         instanceName = NewPoolTString("");
8524
8525     TVariable& variable = *new TVariable(instanceName, blockType);
8526     if (! symbolTable.insert(variable)) {
8527         if (*instanceName == "")
8528             error(loc, "nameless block contains a member that already has a name at global scope", blockName->c_str(), "");
8529         else
8530             error(loc, "block instance name redefinition", variable.getName().c_str(), "");
8531
8532         return;
8533     }
8534
8535     // Check for general layout qualifier errors
8536     layoutObjectCheck(loc, variable);
8537
8538 #ifndef GLSLANG_WEB
8539     // fix up
8540     if (isIoResizeArray(blockType)) {
8541         ioArraySymbolResizeList.push_back(&variable);
8542         checkIoArraysConsistency(loc, true);
8543     } else
8544         fixIoArraySize(loc, variable.getWritableType());
8545 #endif
8546
8547     // Save it in the AST for linker use.
8548     trackLinkage(variable);
8549 }
8550
8551 //
8552 // allow storage type of block to be remapped at compile time
8553 //
8554 void TParseContext::blockStorageRemap(const TSourceLoc&, const TString* instanceName, TQualifier& qualifier)
8555 {
8556     TBlockStorageClass type = intermediate.getBlockStorageOverride(instanceName->c_str());
8557     if (type != EbsNone) {
8558         qualifier.setBlockStorage(type);
8559     }
8560 }
8561
8562 // Do all block-declaration checking regarding the combination of in/out/uniform/buffer
8563 // with a particular stage.
8564 void TParseContext::blockStageIoCheck(const TSourceLoc& loc, const TQualifier& qualifier)
8565 {
8566     const char *extsrt[2] = { E_GL_NV_ray_tracing, E_GL_EXT_ray_tracing };
8567     switch (qualifier.storage) {
8568     case EvqUniform:
8569         profileRequires(loc, EEsProfile, 300, nullptr, "uniform block");
8570         profileRequires(loc, ENoProfile, 140, E_GL_ARB_uniform_buffer_object, "uniform block");
8571         if (currentBlockQualifier.layoutPacking == ElpStd430 && ! currentBlockQualifier.isPushConstant())
8572             requireExtensions(loc, 1, &E_GL_EXT_scalar_block_layout, "std430 requires the buffer storage qualifier");
8573         break;
8574     case EvqBuffer:
8575         requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, "buffer block");
8576         profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, E_GL_ARB_shader_storage_buffer_object, "buffer block");
8577         profileRequires(loc, EEsProfile, 310, nullptr, "buffer block");
8578         break;
8579     case EvqVaryingIn:
8580         profileRequires(loc, ~EEsProfile, 150, E_GL_ARB_separate_shader_objects, "input block");
8581         // It is a compile-time error to have an input block in a vertex shader or an output block in a fragment shader
8582         // "Compute shaders do not permit user-defined input variables..."
8583         requireStage(loc, (EShLanguageMask)(EShLangTessControlMask|EShLangTessEvaluationMask|EShLangGeometryMask|
8584             EShLangFragmentMask|EShLangMeshMask), "input block");
8585         if (language == EShLangFragment) {
8586             profileRequires(loc, EEsProfile, 320, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, "fragment input block");
8587         } else if (language == EShLangMesh && ! qualifier.isTaskMemory()) {
8588             error(loc, "input blocks cannot be used in a mesh shader", "out", "");
8589         }
8590         break;
8591     case EvqVaryingOut:
8592         profileRequires(loc, ~EEsProfile, 150, E_GL_ARB_separate_shader_objects, "output block");
8593         requireStage(loc, (EShLanguageMask)(EShLangVertexMask|EShLangTessControlMask|EShLangTessEvaluationMask|
8594             EShLangGeometryMask|EShLangMeshMask|EShLangTaskMask), "output block");
8595         // ES 310 can have a block before shader_io is turned on, so skip this test for built-ins
8596         if (language == EShLangVertex && ! parsingBuiltins) {
8597             profileRequires(loc, EEsProfile, 320, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, "vertex output block");
8598         } else if (language == EShLangMesh && qualifier.isTaskMemory()) {
8599             error(loc, "can only use on input blocks in mesh shader", "taskNV", "");
8600         } else if (language == EShLangTask && ! qualifier.isTaskMemory()) {
8601             error(loc, "output blocks cannot be used in a task shader", "out", "");
8602         }
8603         break;
8604     case EvqShared:
8605         if (spvVersion.spv > 0 && spvVersion.spv < EShTargetSpv_1_4) {
8606             error(loc, "shared block requires at least SPIR-V 1.4", "shared block", "");
8607         }
8608         profileRequires(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, 0, E_GL_EXT_shared_memory_block, "shared block");
8609         break;
8610 #ifndef GLSLANG_WEB
8611     case EvqPayload:
8612         profileRequires(loc, ~EEsProfile, 460, 2, extsrt, "rayPayloadNV block");
8613         requireStage(loc, (EShLanguageMask)(EShLangRayGenMask | EShLangAnyHitMask | EShLangClosestHitMask | EShLangMissMask),
8614             "rayPayloadNV block");
8615         break;
8616     case EvqPayloadIn:
8617         profileRequires(loc, ~EEsProfile, 460, 2, extsrt, "rayPayloadInNV block");
8618         requireStage(loc, (EShLanguageMask)(EShLangAnyHitMask | EShLangClosestHitMask | EShLangMissMask),
8619             "rayPayloadInNV block");
8620         break;
8621     case EvqHitAttr:
8622         profileRequires(loc, ~EEsProfile, 460, 2, extsrt, "hitAttributeNV block");
8623         requireStage(loc, (EShLanguageMask)(EShLangIntersectMask | EShLangAnyHitMask | EShLangClosestHitMask), "hitAttributeNV block");
8624         break;
8625     case EvqCallableData:
8626         profileRequires(loc, ~EEsProfile, 460, 2, extsrt, "callableDataNV block");
8627         requireStage(loc, (EShLanguageMask)(EShLangRayGenMask | EShLangClosestHitMask | EShLangMissMask | EShLangCallableMask),
8628             "callableDataNV block");
8629         break;
8630     case EvqCallableDataIn:
8631         profileRequires(loc, ~EEsProfile, 460, 2, extsrt, "callableDataInNV block");
8632         requireStage(loc, (EShLanguageMask)(EShLangCallableMask), "callableDataInNV block");
8633         break;
8634 #endif
8635     default:
8636         error(loc, "only uniform, buffer, in, or out blocks are supported", blockName->c_str(), "");
8637         break;
8638     }
8639 }
8640
8641 // Do all block-declaration checking regarding its qualifiers.
8642 void TParseContext::blockQualifierCheck(const TSourceLoc& loc, const TQualifier& qualifier, bool /*instanceName*/)
8643 {
8644     // The 4.5 specification says:
8645     //
8646     // interface-block :
8647     //    layout-qualifieropt interface-qualifier  block-name { member-list } instance-nameopt ;
8648     //
8649     // interface-qualifier :
8650     //    in
8651     //    out
8652     //    patch in
8653     //    patch out
8654     //    uniform
8655     //    buffer
8656     //
8657     // Note however memory qualifiers aren't included, yet the specification also says
8658     //
8659     // "...memory qualifiers may also be used in the declaration of shader storage blocks..."
8660
8661     if (qualifier.isInterpolation())
8662         error(loc, "cannot use interpolation qualifiers on an interface block", "flat/smooth/noperspective", "");
8663     if (qualifier.centroid)
8664         error(loc, "cannot use centroid qualifier on an interface block", "centroid", "");
8665     if (qualifier.isSample())
8666         error(loc, "cannot use sample qualifier on an interface block", "sample", "");
8667     if (qualifier.invariant)
8668         error(loc, "cannot use invariant qualifier on an interface block", "invariant", "");
8669     if (qualifier.isPushConstant())
8670         intermediate.addPushConstantCount();
8671     if (qualifier.isShaderRecord())
8672         intermediate.addShaderRecordCount();
8673     if (qualifier.isTaskMemory())
8674         intermediate.addTaskNVCount();
8675 }
8676
8677 //
8678 // "For a block, this process applies to the entire block, or until the first member
8679 // is reached that has a location layout qualifier. When a block member is declared with a location
8680 // qualifier, its location comes from that qualifier: The member's location qualifier overrides the block-level
8681 // declaration. Subsequent members are again assigned consecutive locations, based on the newest location,
8682 // until the next member declared with a location qualifier. The values used for locations do not have to be
8683 // declared in increasing order."
8684 void TParseContext::fixBlockLocations(const TSourceLoc& loc, TQualifier& qualifier, TTypeList& typeList, bool memberWithLocation, bool memberWithoutLocation)
8685 {
8686     // "If a block has no block-level location layout qualifier, it is required that either all or none of its members
8687     // have a location layout qualifier, or a compile-time error results."
8688     if (! qualifier.hasLocation() && memberWithLocation && memberWithoutLocation)
8689         error(loc, "either the block needs a location, or all members need a location, or no members have a location", "location", "");
8690     else {
8691         if (memberWithLocation) {
8692             // remove any block-level location and make it per *every* member
8693             int nextLocation = 0;  // by the rule above, initial value is not relevant
8694             if (qualifier.hasAnyLocation()) {
8695                 nextLocation = qualifier.layoutLocation;
8696                 qualifier.layoutLocation = TQualifier::layoutLocationEnd;
8697                 if (qualifier.hasComponent()) {
8698                     // "It is a compile-time error to apply the *component* qualifier to a ... block"
8699                     error(loc, "cannot apply to a block", "component", "");
8700                 }
8701                 if (qualifier.hasIndex()) {
8702                     error(loc, "cannot apply to a block", "index", "");
8703                 }
8704             }
8705             for (unsigned int member = 0; member < typeList.size(); ++member) {
8706                 TQualifier& memberQualifier = typeList[member].type->getQualifier();
8707                 const TSourceLoc& memberLoc = typeList[member].loc;
8708                 if (! memberQualifier.hasLocation()) {
8709                     if (nextLocation >= (int)TQualifier::layoutLocationEnd)
8710                         error(memberLoc, "location is too large", "location", "");
8711                     memberQualifier.layoutLocation = nextLocation;
8712                     memberQualifier.layoutComponent = TQualifier::layoutComponentEnd;
8713                 }
8714                 nextLocation = memberQualifier.layoutLocation + intermediate.computeTypeLocationSize(
8715                                     *typeList[member].type, language);
8716             }
8717         }
8718     }
8719 }
8720
8721 void TParseContext::fixXfbOffsets(TQualifier& qualifier, TTypeList& typeList)
8722 {
8723 #ifndef GLSLANG_WEB
8724     // "If a block is qualified with xfb_offset, all its
8725     // members are assigned transform feedback buffer offsets. If a block is not qualified with xfb_offset, any
8726     // members of that block not qualified with an xfb_offset will not be assigned transform feedback buffer
8727     // offsets."
8728
8729     if (! qualifier.hasXfbBuffer() || ! qualifier.hasXfbOffset())
8730         return;
8731
8732     int nextOffset = qualifier.layoutXfbOffset;
8733     for (unsigned int member = 0; member < typeList.size(); ++member) {
8734         TQualifier& memberQualifier = typeList[member].type->getQualifier();
8735         bool contains64BitType = false;
8736         bool contains32BitType = false;
8737         bool contains16BitType = false;
8738         int memberSize = intermediate.computeTypeXfbSize(*typeList[member].type, contains64BitType, contains32BitType, contains16BitType);
8739         // see if we need to auto-assign an offset to this member
8740         if (! memberQualifier.hasXfbOffset()) {
8741             // "if applied to an aggregate containing a double or 64-bit integer, the offset must also be a multiple of 8"
8742             if (contains64BitType)
8743                 RoundToPow2(nextOffset, 8);
8744             else if (contains32BitType)
8745                 RoundToPow2(nextOffset, 4);
8746             else if (contains16BitType)
8747                 RoundToPow2(nextOffset, 2);
8748             memberQualifier.layoutXfbOffset = nextOffset;
8749         } else
8750             nextOffset = memberQualifier.layoutXfbOffset;
8751         nextOffset += memberSize;
8752     }
8753
8754     // The above gave all block members an offset, so we can take it off the block now,
8755     // which will avoid double counting the offset usage.
8756     qualifier.layoutXfbOffset = TQualifier::layoutXfbOffsetEnd;
8757 #endif
8758 }
8759
8760 // Calculate and save the offset of each block member, using the recursively
8761 // defined block offset rules and the user-provided offset and align.
8762 //
8763 // Also, compute and save the total size of the block. For the block's size, arrayness
8764 // is not taken into account, as each element is backed by a separate buffer.
8765 //
8766 void TParseContext::fixBlockUniformOffsets(TQualifier& qualifier, TTypeList& typeList)
8767 {
8768     if (!storageCanHaveLayoutInBlock(qualifier.storage) && !qualifier.isTaskMemory())
8769         return;
8770     if (qualifier.layoutPacking != ElpStd140 && qualifier.layoutPacking != ElpStd430 && qualifier.layoutPacking != ElpScalar)
8771         return;
8772
8773     int offset = 0;
8774     int memberSize;
8775     for (unsigned int member = 0; member < typeList.size(); ++member) {
8776         TQualifier& memberQualifier = typeList[member].type->getQualifier();
8777         const TSourceLoc& memberLoc = typeList[member].loc;
8778
8779         // "When align is applied to an array, it effects only the start of the array, not the array's internal stride."
8780
8781         // modify just the children's view of matrix layout, if there is one for this member
8782         TLayoutMatrix subMatrixLayout = typeList[member].type->getQualifier().layoutMatrix;
8783         int dummyStride;
8784         int memberAlignment = intermediate.getMemberAlignment(*typeList[member].type, memberSize, dummyStride, qualifier.layoutPacking,
8785                                                               subMatrixLayout != ElmNone ? subMatrixLayout == ElmRowMajor : qualifier.layoutMatrix == ElmRowMajor);
8786         if (memberQualifier.hasOffset()) {
8787             // "The specified offset must be a multiple
8788             // of the base alignment of the type of the block member it qualifies, or a compile-time error results."
8789             if (! IsMultipleOfPow2(memberQualifier.layoutOffset, memberAlignment))
8790                 error(memberLoc, "must be a multiple of the member's alignment", "offset", "");
8791
8792             // GLSL: "It is a compile-time error to specify an offset that is smaller than the offset of the previous
8793             // member in the block or that lies within the previous member of the block"
8794             if (spvVersion.spv == 0) {
8795                 if (memberQualifier.layoutOffset < offset)
8796                     error(memberLoc, "cannot lie in previous members", "offset", "");
8797
8798                 // "The offset qualifier forces the qualified member to start at or after the specified
8799                 // integral-constant expression, which will be its byte offset from the beginning of the buffer.
8800                 // "The actual offset of a member is computed as
8801                 // follows: If offset was declared, start with that offset, otherwise start with the next available offset."
8802                 offset = std::max(offset, memberQualifier.layoutOffset);
8803             } else {
8804                 // TODO: Vulkan: "It is a compile-time error to have any offset, explicit or assigned,
8805                 // that lies within another member of the block."
8806
8807                 offset = memberQualifier.layoutOffset;
8808             }
8809         }
8810
8811         // "The actual alignment of a member will be the greater of the specified align alignment and the standard
8812         // (e.g., std140) base alignment for the member's type."
8813         if (memberQualifier.hasAlign())
8814             memberAlignment = std::max(memberAlignment, memberQualifier.layoutAlign);
8815
8816         // "If the resulting offset is not a multiple of the actual alignment,
8817         // increase it to the first offset that is a multiple of
8818         // the actual alignment."
8819         RoundToPow2(offset, memberAlignment);
8820         typeList[member].type->getQualifier().layoutOffset = offset;
8821         offset += memberSize;
8822     }
8823 }
8824
8825 //
8826 // Spread LayoutMatrix to uniform block member, if a uniform block member is a struct,
8827 // we need spread LayoutMatrix to this struct member too. and keep this rule for recursive.
8828 //
8829 void TParseContext::fixBlockUniformLayoutMatrix(TQualifier& qualifier, TTypeList* originTypeList,
8830                                                 TTypeList* tmpTypeList)
8831 {
8832     assert(tmpTypeList == nullptr || originTypeList->size() == tmpTypeList->size());
8833     for (unsigned int member = 0; member < originTypeList->size(); ++member) {
8834         if (qualifier.layoutPacking != ElpNone) {
8835             if (tmpTypeList == nullptr) {
8836                 if (((*originTypeList)[member].type->isMatrix() ||
8837                      (*originTypeList)[member].type->getBasicType() == EbtStruct) &&
8838                     (*originTypeList)[member].type->getQualifier().layoutMatrix == ElmNone) {
8839                     (*originTypeList)[member].type->getQualifier().layoutMatrix = qualifier.layoutMatrix;
8840                 }
8841             } else {
8842                 if (((*tmpTypeList)[member].type->isMatrix() ||
8843                      (*tmpTypeList)[member].type->getBasicType() == EbtStruct) &&
8844                     (*tmpTypeList)[member].type->getQualifier().layoutMatrix == ElmNone) {
8845                     (*tmpTypeList)[member].type->getQualifier().layoutMatrix = qualifier.layoutMatrix;
8846                 }
8847             }
8848         }
8849
8850         if ((*originTypeList)[member].type->getBasicType() == EbtStruct) {
8851             TQualifier* memberQualifier = nullptr;
8852             // block member can be declare a matrix style, so it should be update to the member's style
8853             if ((*originTypeList)[member].type->getQualifier().layoutMatrix == ElmNone) {
8854                 memberQualifier = &qualifier;
8855             } else {
8856                 memberQualifier = &((*originTypeList)[member].type->getQualifier());
8857             }
8858
8859             const TType* tmpType = tmpTypeList == nullptr ?
8860                 (*originTypeList)[member].type->clone() : (*tmpTypeList)[member].type;
8861
8862             fixBlockUniformLayoutMatrix(*memberQualifier, (*originTypeList)[member].type->getWritableStruct(),
8863                                         tmpType->getWritableStruct());
8864
8865             const TTypeList* structure = recordStructCopy(matrixFixRecord, (*originTypeList)[member].type, tmpType);
8866
8867             if (tmpTypeList == nullptr) {
8868                 (*originTypeList)[member].type->setStruct(const_cast<TTypeList*>(structure));
8869             }
8870             if (tmpTypeList != nullptr) {
8871                 (*tmpTypeList)[member].type->setStruct(const_cast<TTypeList*>(structure));
8872             }
8873         }
8874     }
8875 }
8876
8877 //
8878 // Spread LayoutPacking to matrix or aggregate block members. If a block member is a struct or
8879 // array of struct, spread LayoutPacking recursively to its matrix or aggregate members.
8880 //
8881 void TParseContext::fixBlockUniformLayoutPacking(TQualifier& qualifier, TTypeList* originTypeList,
8882                                                  TTypeList* tmpTypeList)
8883 {
8884     assert(tmpTypeList == nullptr || originTypeList->size() == tmpTypeList->size());
8885     for (unsigned int member = 0; member < originTypeList->size(); ++member) {
8886         if (qualifier.layoutPacking != ElpNone) {
8887             if (tmpTypeList == nullptr) {
8888                 if ((*originTypeList)[member].type->getQualifier().layoutPacking == ElpNone &&
8889                     !(*originTypeList)[member].type->isScalarOrVector()) {
8890                     (*originTypeList)[member].type->getQualifier().layoutPacking = qualifier.layoutPacking;
8891                 }
8892             } else {
8893                 if ((*tmpTypeList)[member].type->getQualifier().layoutPacking == ElpNone &&
8894                     !(*tmpTypeList)[member].type->isScalarOrVector()) {
8895                     (*tmpTypeList)[member].type->getQualifier().layoutPacking = qualifier.layoutPacking;
8896                 }
8897             }
8898         }
8899
8900         if ((*originTypeList)[member].type->getBasicType() == EbtStruct) {
8901             // Deep copy the type in pool.
8902             // Because, struct use in different block may have different layout qualifier.
8903             // We have to new a object to distinguish between them.
8904             const TType* tmpType = tmpTypeList == nullptr ?
8905                 (*originTypeList)[member].type->clone() : (*tmpTypeList)[member].type;
8906
8907             fixBlockUniformLayoutPacking(qualifier, (*originTypeList)[member].type->getWritableStruct(),
8908                                          tmpType->getWritableStruct());
8909
8910             const TTypeList* structure = recordStructCopy(packingFixRecord, (*originTypeList)[member].type, tmpType);
8911
8912             if (tmpTypeList == nullptr) {
8913                 (*originTypeList)[member].type->setStruct(const_cast<TTypeList*>(structure));
8914             }
8915             if (tmpTypeList != nullptr) {
8916                 (*tmpTypeList)[member].type->setStruct(const_cast<TTypeList*>(structure));
8917             }
8918         }
8919     }
8920 }
8921
8922 // For an identifier that is already declared, add more qualification to it.
8923 void TParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, const TString& identifier)
8924 {
8925     TSymbol* symbol = symbolTable.find(identifier);
8926
8927     // A forward declaration of a block reference looks to the grammar like adding
8928     // a qualifier to an existing symbol. Detect this and create the block reference
8929     // type with an empty type list, which will be filled in later in
8930     // TParseContext::declareBlock.
8931     if (!symbol && qualifier.hasBufferReference()) {
8932         TTypeList typeList;
8933         TType blockType(&typeList, identifier, qualifier);;
8934         TType blockNameType(EbtReference, blockType, identifier);
8935         TVariable* blockNameVar = new TVariable(&identifier, blockNameType, true);
8936         if (! symbolTable.insert(*blockNameVar)) {
8937             error(loc, "block name cannot redefine a non-block name", blockName->c_str(), "");
8938         }
8939         return;
8940     }
8941
8942     if (! symbol) {
8943         error(loc, "identifier not previously declared", identifier.c_str(), "");
8944         return;
8945     }
8946     if (symbol->getAsFunction()) {
8947         error(loc, "cannot re-qualify a function name", identifier.c_str(), "");
8948         return;
8949     }
8950
8951     if (qualifier.isAuxiliary() ||
8952         qualifier.isMemory() ||
8953         qualifier.isInterpolation() ||
8954         qualifier.hasLayout() ||
8955         qualifier.storage != EvqTemporary ||
8956         qualifier.precision != EpqNone) {
8957         error(loc, "cannot add storage, auxiliary, memory, interpolation, layout, or precision qualifier to an existing variable", identifier.c_str(), "");
8958         return;
8959     }
8960
8961     // For read-only built-ins, add a new symbol for holding the modified qualifier.
8962     // This will bring up an entire block, if a block type has to be modified (e.g., gl_Position inside a block)
8963     if (symbol->isReadOnly())
8964         symbol = symbolTable.copyUp(symbol);
8965
8966     if (qualifier.invariant) {
8967         if (intermediate.inIoAccessed(identifier))
8968             error(loc, "cannot change qualification after use", "invariant", "");
8969         symbol->getWritableType().getQualifier().invariant = true;
8970         invariantCheck(loc, symbol->getType().getQualifier());
8971     } else if (qualifier.isNoContraction()) {
8972         if (intermediate.inIoAccessed(identifier))
8973             error(loc, "cannot change qualification after use", "precise", "");
8974         symbol->getWritableType().getQualifier().setNoContraction();
8975     } else if (qualifier.specConstant) {
8976         symbol->getWritableType().getQualifier().makeSpecConstant();
8977         if (qualifier.hasSpecConstantId())
8978             symbol->getWritableType().getQualifier().layoutSpecConstantId = qualifier.layoutSpecConstantId;
8979     } else
8980         warn(loc, "unknown requalification", "", "");
8981 }
8982
8983 void TParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, TIdentifierList& identifiers)
8984 {
8985     for (unsigned int i = 0; i < identifiers.size(); ++i)
8986         addQualifierToExisting(loc, qualifier, *identifiers[i]);
8987 }
8988
8989 // Make sure 'invariant' isn't being applied to a non-allowed object.
8990 void TParseContext::invariantCheck(const TSourceLoc& loc, const TQualifier& qualifier)
8991 {
8992     if (! qualifier.invariant)
8993         return;
8994
8995     bool pipeOut = qualifier.isPipeOutput();
8996     bool pipeIn = qualifier.isPipeInput();
8997     if ((version >= 300 && isEsProfile()) || (!isEsProfile() && version >= 420)) {
8998         if (! pipeOut)
8999             error(loc, "can only apply to an output", "invariant", "");
9000     } else {
9001         if ((language == EShLangVertex && pipeIn) || (! pipeOut && ! pipeIn))
9002             error(loc, "can only apply to an output, or to an input in a non-vertex stage\n", "invariant", "");
9003     }
9004 }
9005
9006 //
9007 // Updating default qualifier for the case of a declaration with just a qualifier,
9008 // no type, block, or identifier.
9009 //
9010 void TParseContext::updateStandaloneQualifierDefaults(const TSourceLoc& loc, const TPublicType& publicType)
9011 {
9012 #ifndef GLSLANG_WEB
9013     if (publicType.shaderQualifiers.vertices != TQualifier::layoutNotSet) {
9014         assert(language == EShLangTessControl || language == EShLangGeometry || language == EShLangMesh);
9015         const char* id = (language == EShLangTessControl) ? "vertices" : "max_vertices";
9016
9017         if (publicType.qualifier.storage != EvqVaryingOut)
9018             error(loc, "can only apply to 'out'", id, "");
9019         if (! intermediate.setVertices(publicType.shaderQualifiers.vertices))
9020             error(loc, "cannot change previously set layout value", id, "");
9021
9022         if (language == EShLangTessControl)
9023             checkIoArraysConsistency(loc);
9024     }
9025     if (publicType.shaderQualifiers.primitives != TQualifier::layoutNotSet) {
9026         assert(language == EShLangMesh);
9027         const char* id = "max_primitives";
9028
9029         if (publicType.qualifier.storage != EvqVaryingOut)
9030             error(loc, "can only apply to 'out'", id, "");
9031         if (! intermediate.setPrimitives(publicType.shaderQualifiers.primitives))
9032             error(loc, "cannot change previously set layout value", id, "");
9033     }
9034     if (publicType.shaderQualifiers.invocations != TQualifier::layoutNotSet) {
9035         if (publicType.qualifier.storage != EvqVaryingIn)
9036             error(loc, "can only apply to 'in'", "invocations", "");
9037         if (! intermediate.setInvocations(publicType.shaderQualifiers.invocations))
9038             error(loc, "cannot change previously set layout value", "invocations", "");
9039     }
9040     if (publicType.shaderQualifiers.geometry != ElgNone) {
9041         if (publicType.qualifier.storage == EvqVaryingIn) {
9042             switch (publicType.shaderQualifiers.geometry) {
9043             case ElgPoints:
9044             case ElgLines:
9045             case ElgLinesAdjacency:
9046             case ElgTriangles:
9047             case ElgTrianglesAdjacency:
9048             case ElgQuads:
9049             case ElgIsolines:
9050                 if (language == EShLangMesh) {
9051                     error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
9052                     break;
9053                 }
9054                 if (intermediate.setInputPrimitive(publicType.shaderQualifiers.geometry)) {
9055                     if (language == EShLangGeometry)
9056                         checkIoArraysConsistency(loc);
9057                 } else
9058                     error(loc, "cannot change previously set input primitive", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
9059                 break;
9060             default:
9061                 error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
9062             }
9063         } else if (publicType.qualifier.storage == EvqVaryingOut) {
9064             switch (publicType.shaderQualifiers.geometry) {
9065             case ElgLines:
9066             case ElgTriangles:
9067                 if (language != EShLangMesh) {
9068                     error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
9069                     break;
9070                 }
9071                 // Fall through
9072             case ElgPoints:
9073             case ElgLineStrip:
9074             case ElgTriangleStrip:
9075                 if (! intermediate.setOutputPrimitive(publicType.shaderQualifiers.geometry))
9076                     error(loc, "cannot change previously set output primitive", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
9077                 break;
9078             default:
9079                 error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
9080             }
9081         } else
9082             error(loc, "cannot apply to:", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), GetStorageQualifierString(publicType.qualifier.storage));
9083     }
9084     if (publicType.shaderQualifiers.spacing != EvsNone) {
9085         if (publicType.qualifier.storage == EvqVaryingIn) {
9086             if (! intermediate.setVertexSpacing(publicType.shaderQualifiers.spacing))
9087                 error(loc, "cannot change previously set vertex spacing", TQualifier::getVertexSpacingString(publicType.shaderQualifiers.spacing), "");
9088         } else
9089             error(loc, "can only apply to 'in'", TQualifier::getVertexSpacingString(publicType.shaderQualifiers.spacing), "");
9090     }
9091     if (publicType.shaderQualifiers.order != EvoNone) {
9092         if (publicType.qualifier.storage == EvqVaryingIn) {
9093             if (! intermediate.setVertexOrder(publicType.shaderQualifiers.order))
9094                 error(loc, "cannot change previously set vertex order", TQualifier::getVertexOrderString(publicType.shaderQualifiers.order), "");
9095         } else
9096             error(loc, "can only apply to 'in'", TQualifier::getVertexOrderString(publicType.shaderQualifiers.order), "");
9097     }
9098     if (publicType.shaderQualifiers.pointMode) {
9099         if (publicType.qualifier.storage == EvqVaryingIn)
9100             intermediate.setPointMode();
9101         else
9102             error(loc, "can only apply to 'in'", "point_mode", "");
9103     }
9104 #endif
9105     for (int i = 0; i < 3; ++i) {
9106         if (publicType.shaderQualifiers.localSizeNotDefault[i]) {
9107             if (publicType.qualifier.storage == EvqVaryingIn) {
9108                 if (! intermediate.setLocalSize(i, publicType.shaderQualifiers.localSize[i]))
9109                     error(loc, "cannot change previously set size", "local_size", "");
9110                 else {
9111                     int max = 0;
9112                     if (language == EShLangCompute) {
9113                         switch (i) {
9114                         case 0: max = resources.maxComputeWorkGroupSizeX; break;
9115                         case 1: max = resources.maxComputeWorkGroupSizeY; break;
9116                         case 2: max = resources.maxComputeWorkGroupSizeZ; break;
9117                         default: break;
9118                         }
9119                         if (intermediate.getLocalSize(i) > (unsigned int)max)
9120                             error(loc, "too large; see gl_MaxComputeWorkGroupSize", "local_size", "");
9121                     }
9122 #ifndef GLSLANG_WEB
9123                     else if (language == EShLangMesh) {
9124                         switch (i) {
9125                         case 0:
9126                             max = extensionTurnedOn(E_GL_EXT_mesh_shader) ?
9127                                     resources.maxMeshWorkGroupSizeX_EXT :
9128                                     resources.maxMeshWorkGroupSizeX_NV;
9129                             break;
9130                         case 1:
9131                             max = extensionTurnedOn(E_GL_EXT_mesh_shader) ?
9132                                     resources.maxMeshWorkGroupSizeY_EXT :
9133                                     resources.maxMeshWorkGroupSizeY_NV ;
9134                             break;
9135                         case 2:
9136                             max = extensionTurnedOn(E_GL_EXT_mesh_shader) ?
9137                                     resources.maxMeshWorkGroupSizeZ_EXT :
9138                                     resources.maxMeshWorkGroupSizeZ_NV ;
9139                             break;
9140                         default: break;
9141                         }
9142                         if (intermediate.getLocalSize(i) > (unsigned int)max) {
9143                             TString maxsErrtring = "too large, see ";
9144                             maxsErrtring.append(extensionTurnedOn(E_GL_EXT_mesh_shader) ?
9145                                                     "gl_MaxMeshWorkGroupSizeEXT" : "gl_MaxMeshWorkGroupSizeNV");
9146                             error(loc, maxsErrtring.c_str(), "local_size", "");
9147                         }
9148                     } else if (language == EShLangTask) {
9149                         switch (i) {
9150                         case 0:
9151                             max = extensionTurnedOn(E_GL_EXT_mesh_shader) ?
9152                                     resources.maxTaskWorkGroupSizeX_EXT :
9153                                     resources.maxTaskWorkGroupSizeX_NV;
9154                             break;
9155                         case 1:
9156                             max = extensionTurnedOn(E_GL_EXT_mesh_shader) ?
9157                                     resources.maxTaskWorkGroupSizeY_EXT:
9158                                     resources.maxTaskWorkGroupSizeY_NV;
9159                             break;
9160                         case 2:
9161                             max = extensionTurnedOn(E_GL_EXT_mesh_shader) ?
9162                                     resources.maxTaskWorkGroupSizeZ_EXT:
9163                                     resources.maxTaskWorkGroupSizeZ_NV;
9164                             break;
9165                         default: break;
9166                         }
9167                         if (intermediate.getLocalSize(i) > (unsigned int)max) {
9168                             TString maxsErrtring = "too large, see ";
9169                             maxsErrtring.append(extensionTurnedOn(E_GL_EXT_mesh_shader) ?
9170                                                     "gl_MaxTaskWorkGroupSizeEXT" : "gl_MaxTaskWorkGroupSizeNV");
9171                             error(loc, maxsErrtring.c_str(), "local_size", "");
9172                         }
9173                     }
9174 #endif
9175                     else {
9176                         assert(0);
9177                     }
9178
9179                     // Fix the existing constant gl_WorkGroupSize with this new information.
9180                     TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
9181                     if (workGroupSize != nullptr)
9182                         workGroupSize->getWritableConstArray()[i].setUConst(intermediate.getLocalSize(i));
9183                 }
9184             } else
9185                 error(loc, "can only apply to 'in'", "local_size", "");
9186         }
9187         if (publicType.shaderQualifiers.localSizeSpecId[i] != TQualifier::layoutNotSet) {
9188             if (publicType.qualifier.storage == EvqVaryingIn) {
9189                 if (! intermediate.setLocalSizeSpecId(i, publicType.shaderQualifiers.localSizeSpecId[i]))
9190                     error(loc, "cannot change previously set size", "local_size", "");
9191             } else
9192                 error(loc, "can only apply to 'in'", "local_size id", "");
9193             // Set the workgroup built-in variable as a specialization constant
9194             TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
9195             if (workGroupSize != nullptr)
9196                 workGroupSize->getWritableType().getQualifier().specConstant = true;
9197         }
9198     }
9199
9200 #ifndef GLSLANG_WEB
9201     if (publicType.shaderQualifiers.earlyFragmentTests) {
9202         if (publicType.qualifier.storage == EvqVaryingIn)
9203             intermediate.setEarlyFragmentTests();
9204         else
9205             error(loc, "can only apply to 'in'", "early_fragment_tests", "");
9206     }
9207     if (publicType.shaderQualifiers.earlyAndLateFragmentTestsAMD) {
9208         if (publicType.qualifier.storage == EvqVaryingIn)
9209             intermediate.setEarlyAndLateFragmentTestsAMD();
9210         else
9211             error(loc, "can only apply to 'in'", "early_and_late_fragment_tests_amd", "");
9212     }
9213     if (publicType.shaderQualifiers.postDepthCoverage) {
9214         if (publicType.qualifier.storage == EvqVaryingIn)
9215             intermediate.setPostDepthCoverage();
9216         else
9217             error(loc, "can only apply to 'in'", "post_coverage_coverage", "");
9218     }
9219     if (publicType.shaderQualifiers.hasBlendEquation()) {
9220         if (publicType.qualifier.storage != EvqVaryingOut)
9221             error(loc, "can only apply to 'out'", "blend equation", "");
9222     }
9223     if (publicType.shaderQualifiers.interlockOrdering) {
9224         if (publicType.qualifier.storage == EvqVaryingIn) {
9225             if (!intermediate.setInterlockOrdering(publicType.shaderQualifiers.interlockOrdering))
9226                 error(loc, "cannot change previously set fragment shader interlock ordering", TQualifier::getInterlockOrderingString(publicType.shaderQualifiers.interlockOrdering), "");
9227         }
9228         else
9229             error(loc, "can only apply to 'in'", TQualifier::getInterlockOrderingString(publicType.shaderQualifiers.interlockOrdering), "");
9230     }
9231
9232     if (publicType.shaderQualifiers.layoutDerivativeGroupQuads &&
9233         publicType.shaderQualifiers.layoutDerivativeGroupLinear) {
9234         error(loc, "cannot be both specified", "derivative_group_quadsNV and derivative_group_linearNV", "");
9235     }
9236
9237     if (publicType.shaderQualifiers.layoutDerivativeGroupQuads) {
9238         if (publicType.qualifier.storage == EvqVaryingIn) {
9239             if ((intermediate.getLocalSize(0) & 1) ||
9240                 (intermediate.getLocalSize(1) & 1))
9241                 error(loc, "requires local_size_x and local_size_y to be multiple of two", "derivative_group_quadsNV", "");
9242             else
9243                 intermediate.setLayoutDerivativeMode(LayoutDerivativeGroupQuads);
9244         }
9245         else
9246             error(loc, "can only apply to 'in'", "derivative_group_quadsNV", "");
9247     }
9248     if (publicType.shaderQualifiers.layoutDerivativeGroupLinear) {
9249         if (publicType.qualifier.storage == EvqVaryingIn) {
9250             if((intermediate.getLocalSize(0) *
9251                 intermediate.getLocalSize(1) *
9252                 intermediate.getLocalSize(2)) % 4 != 0)
9253                 error(loc, "requires total group size to be multiple of four", "derivative_group_linearNV", "");
9254             else
9255                 intermediate.setLayoutDerivativeMode(LayoutDerivativeGroupLinear);
9256         }
9257         else
9258             error(loc, "can only apply to 'in'", "derivative_group_linearNV", "");
9259     }
9260     // Check mesh out array sizes, once all the necessary out qualifiers are defined.
9261     if ((language == EShLangMesh) &&
9262         (intermediate.getVertices() != TQualifier::layoutNotSet) &&
9263         (intermediate.getPrimitives() != TQualifier::layoutNotSet) &&
9264         (intermediate.getOutputPrimitive() != ElgNone))
9265     {
9266         checkIoArraysConsistency(loc);
9267     }
9268
9269     if (publicType.shaderQualifiers.layoutPrimitiveCulling) {
9270         if (publicType.qualifier.storage != EvqTemporary)
9271             error(loc, "layout qualifier can not have storage qualifiers", "primitive_culling","", "");
9272         else {
9273             intermediate.setLayoutPrimitiveCulling();
9274         }
9275         // Exit early as further checks are not valid
9276         return;
9277     }
9278 #endif
9279     const TQualifier& qualifier = publicType.qualifier;
9280
9281     if (qualifier.isAuxiliary() ||
9282         qualifier.isMemory() ||
9283         qualifier.isInterpolation() ||
9284         qualifier.precision != EpqNone)
9285         error(loc, "cannot use auxiliary, memory, interpolation, or precision qualifier in a default qualifier declaration (declaration with no type)", "qualifier", "");
9286
9287     // "The offset qualifier can only be used on block members of blocks..."
9288     // "The align qualifier can only be used on blocks or block members..."
9289     if (qualifier.hasOffset() ||
9290         qualifier.hasAlign())
9291         error(loc, "cannot use offset or align qualifiers in a default qualifier declaration (declaration with no type)", "layout qualifier", "");
9292
9293     layoutQualifierCheck(loc, qualifier);
9294
9295     switch (qualifier.storage) {
9296     case EvqUniform:
9297         if (qualifier.hasMatrix())
9298             globalUniformDefaults.layoutMatrix = qualifier.layoutMatrix;
9299         if (qualifier.hasPacking())
9300             globalUniformDefaults.layoutPacking = qualifier.layoutPacking;
9301         break;
9302     case EvqBuffer:
9303         if (qualifier.hasMatrix())
9304             globalBufferDefaults.layoutMatrix = qualifier.layoutMatrix;
9305         if (qualifier.hasPacking())
9306             globalBufferDefaults.layoutPacking = qualifier.layoutPacking;
9307         break;
9308     case EvqVaryingIn:
9309         break;
9310     case EvqVaryingOut:
9311 #ifndef GLSLANG_WEB
9312         if (qualifier.hasStream())
9313             globalOutputDefaults.layoutStream = qualifier.layoutStream;
9314         if (qualifier.hasXfbBuffer())
9315             globalOutputDefaults.layoutXfbBuffer = qualifier.layoutXfbBuffer;
9316         if (globalOutputDefaults.hasXfbBuffer() && qualifier.hasXfbStride()) {
9317             if (! intermediate.setXfbBufferStride(globalOutputDefaults.layoutXfbBuffer, qualifier.layoutXfbStride))
9318                 error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d", qualifier.layoutXfbBuffer);
9319         }
9320 #endif
9321         break;
9322     case EvqShared:
9323         if (qualifier.hasMatrix())
9324             globalSharedDefaults.layoutMatrix = qualifier.layoutMatrix;
9325         if (qualifier.hasPacking())
9326             globalSharedDefaults.layoutPacking = qualifier.layoutPacking;
9327         break;
9328     default:
9329         error(loc, "default qualifier requires 'uniform', 'buffer', 'in', 'out' or 'shared' storage qualification", "", "");
9330         return;
9331     }
9332
9333     if (qualifier.hasBinding())
9334         error(loc, "cannot declare a default, include a type or full declaration", "binding", "");
9335     if (qualifier.hasAnyLocation())
9336         error(loc, "cannot declare a default, use a full declaration", "location/component/index", "");
9337     if (qualifier.hasXfbOffset())
9338         error(loc, "cannot declare a default, use a full declaration", "xfb_offset", "");
9339     if (qualifier.isPushConstant())
9340         error(loc, "cannot declare a default, can only be used on a block", "push_constant", "");
9341     if (qualifier.hasBufferReference())
9342         error(loc, "cannot declare a default, can only be used on a block", "buffer_reference", "");
9343     if (qualifier.hasSpecConstantId())
9344         error(loc, "cannot declare a default, can only be used on a scalar", "constant_id", "");
9345     if (qualifier.isShaderRecord())
9346         error(loc, "cannot declare a default, can only be used on a block", "shaderRecordNV", "");
9347 }
9348
9349 //
9350 // Take the sequence of statements that has been built up since the last case/default,
9351 // put it on the list of top-level nodes for the current (inner-most) switch statement,
9352 // and follow that by the case/default we are on now.  (See switch topology comment on
9353 // TIntermSwitch.)
9354 //
9355 void TParseContext::wrapupSwitchSubsequence(TIntermAggregate* statements, TIntermNode* branchNode)
9356 {
9357     TIntermSequence* switchSequence = switchSequenceStack.back();
9358
9359     if (statements) {
9360         if (switchSequence->size() == 0)
9361             error(statements->getLoc(), "cannot have statements before first case/default label", "switch", "");
9362         statements->setOperator(EOpSequence);
9363         switchSequence->push_back(statements);
9364     }
9365     if (branchNode) {
9366         // check all previous cases for the same label (or both are 'default')
9367         for (unsigned int s = 0; s < switchSequence->size(); ++s) {
9368             TIntermBranch* prevBranch = (*switchSequence)[s]->getAsBranchNode();
9369             if (prevBranch) {
9370                 TIntermTyped* prevExpression = prevBranch->getExpression();
9371                 TIntermTyped* newExpression = branchNode->getAsBranchNode()->getExpression();
9372                 if (prevExpression == nullptr && newExpression == nullptr)
9373                     error(branchNode->getLoc(), "duplicate label", "default", "");
9374                 else if (prevExpression != nullptr &&
9375                           newExpression != nullptr &&
9376                          prevExpression->getAsConstantUnion() &&
9377                           newExpression->getAsConstantUnion() &&
9378                          prevExpression->getAsConstantUnion()->getConstArray()[0].getIConst() ==
9379                           newExpression->getAsConstantUnion()->getConstArray()[0].getIConst())
9380                     error(branchNode->getLoc(), "duplicated value", "case", "");
9381             }
9382         }
9383         switchSequence->push_back(branchNode);
9384     }
9385 }
9386
9387 //
9388 // Turn the top-level node sequence built up of wrapupSwitchSubsequence9)
9389 // into a switch node.
9390 //
9391 TIntermNode* TParseContext::addSwitch(const TSourceLoc& loc, TIntermTyped* expression, TIntermAggregate* lastStatements)
9392 {
9393     profileRequires(loc, EEsProfile, 300, nullptr, "switch statements");
9394     profileRequires(loc, ENoProfile, 130, nullptr, "switch statements");
9395
9396     wrapupSwitchSubsequence(lastStatements, nullptr);
9397
9398     if (expression == nullptr ||
9399         (expression->getBasicType() != EbtInt && expression->getBasicType() != EbtUint) ||
9400         expression->getType().isArray() || expression->getType().isMatrix() || expression->getType().isVector())
9401             error(loc, "condition must be a scalar integer expression", "switch", "");
9402
9403     // If there is nothing to do, drop the switch but still execute the expression
9404     TIntermSequence* switchSequence = switchSequenceStack.back();
9405     if (switchSequence->size() == 0)
9406         return expression;
9407
9408     if (lastStatements == nullptr) {
9409         // This was originally an ERRROR, because early versions of the specification said
9410         // "it is an error to have no statement between a label and the end of the switch statement."
9411         // The specifications were updated to remove this (being ill-defined what a "statement" was),
9412         // so, this became a warning.  However, 3.0 tests still check for the error.
9413         if (isEsProfile() && (version <= 300 || version >= 320) && ! relaxedErrors())
9414             error(loc, "last case/default label not followed by statements", "switch", "");
9415         else if (!isEsProfile() && (version <= 430 || version >= 460))
9416             error(loc, "last case/default label not followed by statements", "switch", "");
9417         else
9418             warn(loc, "last case/default label not followed by statements", "switch", "");
9419
9420
9421         // emulate a break for error recovery
9422         lastStatements = intermediate.makeAggregate(intermediate.addBranch(EOpBreak, loc));
9423         lastStatements->setOperator(EOpSequence);
9424         switchSequence->push_back(lastStatements);
9425     }
9426
9427     TIntermAggregate* body = new TIntermAggregate(EOpSequence);
9428     body->getSequence() = *switchSequenceStack.back();
9429     body->setLoc(loc);
9430
9431     TIntermSwitch* switchNode = new TIntermSwitch(expression, body);
9432     switchNode->setLoc(loc);
9433
9434     return switchNode;
9435 }
9436
9437 //
9438 // When a struct used in block, and has it's own layout packing, layout matrix,
9439 // record the origin structure of a struct to map, and Record the structure copy to the copy table,
9440 //
9441 const TTypeList* TParseContext::recordStructCopy(TStructRecord& record, const TType* originType, const TType* tmpType)
9442 {
9443     size_t memberCount = tmpType->getStruct()->size();
9444     size_t originHash = 0, tmpHash = 0;
9445     std::hash<size_t> hasher;
9446     for (size_t i = 0; i < memberCount; i++) {
9447         size_t originMemberHash = hasher(originType->getStruct()->at(i).type->getQualifier().layoutPacking +
9448                                          originType->getStruct()->at(i).type->getQualifier().layoutMatrix);
9449         size_t tmpMemberHash = hasher(tmpType->getStruct()->at(i).type->getQualifier().layoutPacking +
9450                                       tmpType->getStruct()->at(i).type->getQualifier().layoutMatrix);
9451         originHash = hasher((originHash ^ originMemberHash) << 1);
9452         tmpHash = hasher((tmpHash ^ tmpMemberHash) << 1);
9453     }
9454     const TTypeList* originStruct = originType->getStruct();
9455     const TTypeList* tmpStruct = tmpType->getStruct();
9456     if (originHash != tmpHash) {
9457         auto fixRecords = record.find(originStruct);
9458         if (fixRecords != record.end()) {
9459             auto fixRecord = fixRecords->second.find(tmpHash);
9460             if (fixRecord != fixRecords->second.end()) {
9461                 return fixRecord->second;
9462             } else {
9463                 record[originStruct][tmpHash] = tmpStruct;
9464                 return tmpStruct;
9465             }
9466         } else {
9467             record[originStruct] = std::map<size_t, const TTypeList*>();
9468             record[originStruct][tmpHash] = tmpStruct;
9469             return tmpStruct;
9470         }
9471     }
9472     return originStruct;
9473 }
9474
9475 } // end namespace glslang