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