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