Implement atomic ops, bit conversions, fix fwidth stage mask, fix saturate dest modifier.
[platform/upstream/glslang.git] / hlsl / hlslParseHelper.cpp
1 //
2 //Copyright (C) 2016 Google, Inc.
3 //Copyright (C) 2016 LunarG, Inc.
4 //
5 //All rights reserved.
6 //
7 //Redistribution and use in source and binary forms, with or without
8 //modification, are permitted provided that the following conditions
9 //are met:
10 //
11 //    Redistributions of source code must retain the above copyright
12 //    notice, this list of conditions and the following disclaimer.
13 //
14 //    Redistributions in binary form must reproduce the above
15 //    copyright notice, this list of conditions and the following
16 //    disclaimer in the documentation and/or other materials provided
17 //    with the distribution.
18 //
19 //    Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20 //    contributors may be used to endorse or promote products derived
21 //    from this software without specific prior written permission.
22 //
23 //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 //"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25 //LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26 //FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27 //COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28 //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29 //BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30 //LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31 //CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 //LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33 //ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34 //POSSIBILITY OF SUCH DAMAGE.
35 //
36
37 #include "hlslParseHelper.h"
38 #include "hlslScanContext.h"
39 #include "hlslGrammar.h"
40
41 #include "../glslang/MachineIndependent/Scan.h"
42 #include "../glslang/MachineIndependent/preprocessor/PpContext.h"
43
44 #include "../glslang/OSDependent/osinclude.h"
45
46 #include <stdarg.h>
47 #include <algorithm>
48
49 namespace glslang {
50
51 HlslParseContext::HlslParseContext(TSymbolTable& symbolTable, TIntermediate& interm, bool /*parsingBuiltins*/,
52                                    int version, EProfile profile, int spv, int vulkan, EShLanguage language, TInfoSink& infoSink,
53                                    bool forwardCompatible, EShMessages messages) :
54     TParseContextBase(symbolTable, interm, version, profile, spv, vulkan, language, infoSink, forwardCompatible, messages),
55     contextPragma(true, false), loopNestingLevel(0), structNestingLevel(0), controlFlowNestingLevel(0),
56     postMainReturn(false),
57     limits(resources.limits),
58     afterEOF(false)
59 {
60     // ensure we always have a linkage node, even if empty, to simplify tree topology algorithms
61     linkage = new TIntermAggregate;
62
63     globalUniformDefaults.clear();
64     globalUniformDefaults.layoutMatrix = ElmColumnMajor;
65     globalUniformDefaults.layoutPacking = vulkan > 0 ? ElpStd140 : ElpShared;
66
67     globalBufferDefaults.clear();
68     globalBufferDefaults.layoutMatrix = ElmColumnMajor;
69     globalBufferDefaults.layoutPacking = vulkan > 0 ? ElpStd430 : ElpShared;
70
71     globalInputDefaults.clear();
72     globalOutputDefaults.clear();
73
74     // "Shaders in the transform 
75     // feedback capturing mode have an initial global default of
76     //     layout(xfb_buffer = 0) out;"
77     if (language == EShLangVertex ||
78         language == EShLangTessControl ||
79         language == EShLangTessEvaluation ||
80         language == EShLangGeometry)
81         globalOutputDefaults.layoutXfbBuffer = 0;
82
83     if (language == EShLangGeometry)
84         globalOutputDefaults.layoutStream = 0;
85 }
86
87 HlslParseContext::~HlslParseContext()
88 {
89 }
90
91 void HlslParseContext::setLimits(const TBuiltInResource& r)
92 {
93     resources = r;
94     intermediate.setLimits(resources);
95 }
96
97 //
98 // Parse an array of strings using the parser in HlslRules.
99 //
100 // Returns true for successful acceptance of the shader, false if any errors.
101 //
102 bool HlslParseContext::parseShaderStrings(TPpContext& ppContext, TInputScanner& input, bool versionWillBeError)
103 {
104     currentScanner = &input;
105     ppContext.setInput(input, versionWillBeError);
106
107     HlslScanContext::fillInKeywordMap();      // TODO: right place, and include the delete too
108
109     HlslScanContext scanContext(*this, ppContext);
110     HlslGrammar grammar(scanContext, *this);
111     if (! grammar.parse())
112         printf("HLSL translation failed.\n");
113
114     return numErrors == 0;
115 }
116
117 void HlslParseContext::handlePragma(const TSourceLoc& loc, const TVector<TString>& tokens)
118 {
119     if (pragmaCallback)
120         pragmaCallback(loc.line, tokens);
121
122     if (tokens.size() == 0)
123         return;
124 }
125
126 //
127 // Look at a '.' field selector string and change it into offsets
128 // for a vector or scalar
129 //
130 // Returns true if there is no error.
131 //
132 bool HlslParseContext::parseVectorFields(const TSourceLoc& loc, const TString& compString, int vecSize, TVectorFields& fields)
133 {
134     fields.num = (int)compString.size();
135     if (fields.num > 4) {
136         error(loc, "illegal vector field selection", compString.c_str(), "");
137         return false;
138     }
139
140     enum {
141         exyzw,
142         ergba,
143         estpq,
144     } fieldSet[4];
145
146         for (int i = 0; i < fields.num; ++i) {
147             switch (compString[i])  {
148             case 'x':
149                 fields.offsets[i] = 0;
150                 fieldSet[i] = exyzw;
151                 break;
152             case 'r':
153                 fields.offsets[i] = 0;
154                 fieldSet[i] = ergba;
155                 break;
156             case 's':
157                 fields.offsets[i] = 0;
158                 fieldSet[i] = estpq;
159                 break;
160             case 'y':
161                 fields.offsets[i] = 1;
162                 fieldSet[i] = exyzw;
163                 break;
164             case 'g':
165                 fields.offsets[i] = 1;
166                 fieldSet[i] = ergba;
167                 break;
168             case 't':
169                 fields.offsets[i] = 1;
170                 fieldSet[i] = estpq;
171                 break;
172             case 'z':
173                 fields.offsets[i] = 2;
174                 fieldSet[i] = exyzw;
175                 break;
176             case 'b':
177                 fields.offsets[i] = 2;
178                 fieldSet[i] = ergba;
179                 break;
180             case 'p':
181                 fields.offsets[i] = 2;
182                 fieldSet[i] = estpq;
183                 break;
184
185             case 'w':
186                 fields.offsets[i] = 3;
187                 fieldSet[i] = exyzw;
188                 break;
189             case 'a':
190                 fields.offsets[i] = 3;
191                 fieldSet[i] = ergba;
192                 break;
193             case 'q':
194                 fields.offsets[i] = 3;
195                 fieldSet[i] = estpq;
196                 break;
197             default:
198                 error(loc, "illegal vector field selection", compString.c_str(), "");
199                 return false;
200             }
201         }
202
203         for (int i = 0; i < fields.num; ++i) {
204             if (fields.offsets[i] >= vecSize) {
205                 error(loc, "vector field selection out of range", compString.c_str(), "");
206                 return false;
207             }
208
209             if (i > 0) {
210                 if (fieldSet[i] != fieldSet[i - 1]) {
211                     error(loc, "illegal - vector component fields not from the same set", compString.c_str(), "");
212                     return false;
213                 }
214             }
215         }
216
217         return true;
218 }
219
220 //
221 // Used to output syntax, parsing, and semantic errors.
222 //
223
224 void HlslParseContext::outputMessage(const TSourceLoc& loc, const char* szReason,
225     const char* szToken,
226     const char* szExtraInfoFormat,
227     TPrefixType prefix, va_list args)
228 {
229     const int maxSize = MaxTokenLength + 200;
230     char szExtraInfo[maxSize];
231
232     safe_vsprintf(szExtraInfo, maxSize, szExtraInfoFormat, args);
233
234     infoSink.info.prefix(prefix);
235     infoSink.info.location(loc);
236     infoSink.info << "'" << szToken << "' : " << szReason << " " << szExtraInfo << "\n";
237
238     if (prefix == EPrefixError) {
239         ++numErrors;
240     }
241 }
242
243 void C_DECL HlslParseContext::error(const TSourceLoc& loc, const char* szReason, const char* szToken,
244     const char* szExtraInfoFormat, ...)
245 {
246     if (messages & EShMsgOnlyPreprocessor)
247         return;
248     va_list args;
249     va_start(args, szExtraInfoFormat);
250     outputMessage(loc, szReason, szToken, szExtraInfoFormat, EPrefixError, args);
251     va_end(args);
252 }
253
254 void C_DECL HlslParseContext::warn(const TSourceLoc& loc, const char* szReason, const char* szToken,
255     const char* szExtraInfoFormat, ...)
256 {
257     if (suppressWarnings())
258         return;
259     va_list args;
260     va_start(args, szExtraInfoFormat);
261     outputMessage(loc, szReason, szToken, szExtraInfoFormat, EPrefixWarning, args);
262     va_end(args);
263 }
264
265 void C_DECL HlslParseContext::ppError(const TSourceLoc& loc, const char* szReason, const char* szToken,
266     const char* szExtraInfoFormat, ...)
267 {
268     va_list args;
269     va_start(args, szExtraInfoFormat);
270     outputMessage(loc, szReason, szToken, szExtraInfoFormat, EPrefixError, args);
271     va_end(args);
272 }
273
274 void C_DECL HlslParseContext::ppWarn(const TSourceLoc& loc, const char* szReason, const char* szToken,
275     const char* szExtraInfoFormat, ...)
276 {
277     va_list args;
278     va_start(args, szExtraInfoFormat);
279     outputMessage(loc, szReason, szToken, szExtraInfoFormat, EPrefixWarning, args);
280     va_end(args);
281 }
282
283 //
284 // Handle seeing a variable identifier in the grammar.
285 //
286 TIntermTyped* HlslParseContext::handleVariable(const TSourceLoc& loc, TSymbol* symbol, const TString* string)
287 {
288     if (symbol == nullptr)
289         symbol = symbolTable.find(*string);
290     if (symbol && symbol->getAsVariable() && symbol->getAsVariable()->isUserType()) {
291         error(loc, "expected symbol, not user-defined type", string->c_str(), "");
292         return nullptr;
293     }
294
295     // Error check for requiring specific extensions present.
296     if (symbol && symbol->getNumExtensions())
297         requireExtensions(loc, symbol->getNumExtensions(), symbol->getExtensions(), symbol->getName().c_str());
298
299     if (symbol && symbol->isReadOnly()) {
300         // All shared things containing an implicitly sized array must be copied up 
301         // on first use, so that all future references will share its array structure,
302         // so that editing the implicit size will effect all nodes consuming it,
303         // and so that editing the implicit size won't change the shared one.
304         //
305         // If this is a variable or a block, check it and all it contains, but if this 
306         // is a member of an anonymous block, check the whole block, as the whole block
307         // will need to be copied up if it contains an implicitly-sized array.
308         if (symbol->getType().containsImplicitlySizedArray() || (symbol->getAsAnonMember() && symbol->getAsAnonMember()->getAnonContainer().getType().containsImplicitlySizedArray()))
309             makeEditable(symbol);
310     }
311
312     const TVariable* variable;
313     const TAnonMember* anon = symbol ? symbol->getAsAnonMember() : nullptr;
314     TIntermTyped* node = nullptr;
315     if (anon) {
316         // It was a member of an anonymous container.
317
318         // Create a subtree for its dereference.
319         variable = anon->getAnonContainer().getAsVariable();
320         TIntermTyped* container = intermediate.addSymbol(*variable, loc);
321         TIntermTyped* constNode = intermediate.addConstantUnion(anon->getMemberNumber(), loc);
322         node = intermediate.addIndex(EOpIndexDirectStruct, container, constNode, loc);
323
324         node->setType(*(*variable->getType().getStruct())[anon->getMemberNumber()].type);
325         if (node->getType().hiddenMember())
326             error(loc, "member of nameless block was not redeclared", string->c_str(), "");
327     } else {
328         // Not a member of an anonymous container.
329
330         // The symbol table search was done in the lexical phase.
331         // See if it was a variable.
332         variable = symbol ? symbol->getAsVariable() : nullptr;
333         if (variable) {
334             if ((variable->getType().getBasicType() == EbtBlock ||
335                 variable->getType().getBasicType() == EbtStruct) && variable->getType().getStruct() == nullptr) {
336                 error(loc, "cannot be used (maybe an instance name is needed)", string->c_str(), "");
337                 variable = nullptr;
338             }
339         } else {
340             if (symbol)
341                 error(loc, "variable name expected", string->c_str(), "");
342         }
343
344         // Recovery, if it wasn't found or was not a variable.
345         if (! variable)
346             variable = new TVariable(string, TType(EbtVoid));
347
348         if (variable->getType().getQualifier().isFrontEndConstant())
349             node = intermediate.addConstantUnion(variable->getConstArray(), variable->getType(), loc);
350         else
351             node = intermediate.addSymbol(*variable, loc);
352     }
353
354     if (variable->getType().getQualifier().isIo())
355         intermediate.addIoAccessed(*string);
356
357     return node;
358 }
359
360 //
361 // Handle seeing a base[index] dereference in the grammar.
362 //
363 TIntermTyped* HlslParseContext::handleBracketDereference(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
364 {
365     TIntermTyped* result = nullptr;
366
367     int indexValue = 0;
368     if (index->getQualifier().storage == EvqConst) {
369         indexValue = index->getAsConstantUnion()->getConstArray()[0].getIConst();
370         checkIndex(loc, base->getType(), indexValue);
371     }
372
373     variableCheck(base);
374     if (! base->isArray() && ! base->isMatrix() && ! base->isVector()) {
375         if (base->getAsSymbolNode())
376             error(loc, " left of '[' is not of type array, matrix, or vector ", base->getAsSymbolNode()->getName().c_str(), "");
377         else
378             error(loc, " left of '[' is not of type array, matrix, or vector ", "expression", "");
379     } else if (base->getType().getQualifier().storage == EvqConst && index->getQualifier().storage == EvqConst)
380         return intermediate.foldDereference(base, indexValue, loc);
381     else {
382         // at least one of base and index is variable...
383
384         if (base->getAsSymbolNode() && isIoResizeArray(base->getType()))
385             handleIoResizeArrayAccess(loc, base);
386
387         if (index->getQualifier().storage == EvqConst) {
388             if (base->getType().isImplicitlySizedArray())
389                 updateImplicitArraySize(loc, base, indexValue);
390             result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
391         } else {
392             result = intermediate.addIndex(EOpIndexIndirect, base, index, loc);
393         }
394     }
395
396     if (result == nullptr) {
397         // Insert dummy error-recovery result
398         result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
399     } else {
400         // Insert valid dereferenced result
401         TType newType(base->getType(), 0);  // dereferenced type
402         if (base->getType().getQualifier().storage == EvqConst && index->getQualifier().storage == EvqConst)
403             newType.getQualifier().storage = EvqConst;
404         else
405             newType.getQualifier().storage = EvqTemporary;
406         result->setType(newType);
407     }
408
409     return result;
410 }
411
412 void HlslParseContext::checkIndex(const TSourceLoc& loc, const TType& type, int& index)
413 {
414     // HLSL todo: any rules for index fixups?
415 }
416
417 // Make a shared symbol have a non-shared version that can be edited by the current 
418 // compile, such that editing its type will not change the shared version and will
419 // effect all nodes sharing it.
420 void HlslParseContext::makeEditable(TSymbol*& symbol)
421 {
422     // copyUp() does a deep copy of the type.
423     symbol = symbolTable.copyUp(symbol);
424
425     // Also, see if it's tied to IO resizing
426     if (isIoResizeArray(symbol->getType()))
427         ioArraySymbolResizeList.push_back(symbol);
428
429     // Also, save it in the AST for linker use.
430     intermediate.addSymbolLinkageNode(linkage, *symbol);
431 }
432
433 TVariable* HlslParseContext::getEditableVariable(const char* name)
434 {
435     bool builtIn;
436     TSymbol* symbol = symbolTable.find(name, &builtIn);
437     if (builtIn)
438         makeEditable(symbol);
439
440     return symbol->getAsVariable();
441 }
442
443 // Return true if this is a geometry shader input array or tessellation control output array.
444 bool HlslParseContext::isIoResizeArray(const TType& type) const
445 {
446     return type.isArray() &&
447         ((language == EShLangGeometry    && type.getQualifier().storage == EvqVaryingIn) ||
448         (language == EShLangTessControl && type.getQualifier().storage == EvqVaryingOut && ! type.getQualifier().patch));
449 }
450
451 // If an array is not isIoResizeArray() but is an io array, make sure it has the right size
452 void HlslParseContext::fixIoArraySize(const TSourceLoc& loc, TType& type)
453 {
454     if (! type.isArray() || type.getQualifier().patch || symbolTable.atBuiltInLevel())
455         return;
456
457     assert(! isIoResizeArray(type));
458
459     if (type.getQualifier().storage != EvqVaryingIn || type.getQualifier().patch)
460         return;
461
462     if (language == EShLangTessControl || language == EShLangTessEvaluation) {
463         if (type.getOuterArraySize() != resources.maxPatchVertices) {
464             if (type.isExplicitlySizedArray())
465                 error(loc, "tessellation input array size must be gl_MaxPatchVertices or implicitly sized", "[]", "");
466             type.changeOuterArraySize(resources.maxPatchVertices);
467         }
468     }
469 }
470
471 // Handle a dereference of a geometry shader input array or tessellation control output array.
472 // See ioArraySymbolResizeList comment in ParseHelper.h.
473 //
474 void HlslParseContext::handleIoResizeArrayAccess(const TSourceLoc& /*loc*/, TIntermTyped* base)
475 {
476     TIntermSymbol* symbolNode = base->getAsSymbolNode();
477     assert(symbolNode);
478     if (! symbolNode)
479         return;
480
481     // fix array size, if it can be fixed and needs to be fixed (will allow variable indexing)
482     if (symbolNode->getType().isImplicitlySizedArray()) {
483         int newSize = getIoArrayImplicitSize();
484         if (newSize > 0)
485             symbolNode->getWritableType().changeOuterArraySize(newSize);
486     }
487 }
488
489 // If there has been an input primitive declaration (geometry shader) or an output
490 // number of vertices declaration(tessellation shader), make sure all input array types
491 // match it in size.  Types come either from nodes in the AST or symbols in the 
492 // symbol table.
493 //
494 // Types without an array size will be given one.
495 // Types already having a size that is wrong will get an error.
496 //
497 void HlslParseContext::checkIoArraysConsistency(const TSourceLoc& loc, bool tailOnly)
498 {
499     int requiredSize = getIoArrayImplicitSize();
500     if (requiredSize == 0)
501         return;
502
503     const char* feature;
504     if (language == EShLangGeometry)
505         feature = TQualifier::getGeometryString(intermediate.getInputPrimitive());
506     else if (language == EShLangTessControl)
507         feature = "vertices";
508     else
509         feature = "unknown";
510
511     if (tailOnly) {
512         checkIoArrayConsistency(loc, requiredSize, feature, ioArraySymbolResizeList.back()->getWritableType(), ioArraySymbolResizeList.back()->getName());
513         return;
514     }
515
516     for (size_t i = 0; i < ioArraySymbolResizeList.size(); ++i)
517         checkIoArrayConsistency(loc, requiredSize, feature, ioArraySymbolResizeList[i]->getWritableType(), ioArraySymbolResizeList[i]->getName());
518 }
519
520 int HlslParseContext::getIoArrayImplicitSize() const
521 {
522     if (language == EShLangGeometry)
523         return TQualifier::mapGeometryToSize(intermediate.getInputPrimitive());
524     else if (language == EShLangTessControl)
525         return intermediate.getVertices() != TQualifier::layoutNotSet ? intermediate.getVertices() : 0;
526     else
527         return 0;
528 }
529
530 void HlslParseContext::checkIoArrayConsistency(const TSourceLoc& loc, int requiredSize, const char* feature, TType& type, const TString& name)
531 {
532     if (type.isImplicitlySizedArray())
533         type.changeOuterArraySize(requiredSize);
534 }
535
536 // Handle seeing a binary node with a math operation.
537 TIntermTyped* HlslParseContext::handleBinaryMath(const TSourceLoc& loc, const char* str, TOperator op, TIntermTyped* left, TIntermTyped* right)
538 {
539     TIntermTyped* result = intermediate.addBinaryMath(op, left, right, loc);
540     if (! result)
541         binaryOpError(loc, str, left->getCompleteString(), right->getCompleteString());
542
543     return result;
544 }
545
546 // Handle seeing a unary node with a math operation.
547 TIntermTyped* HlslParseContext::handleUnaryMath(const TSourceLoc& loc, const char* str, TOperator op, TIntermTyped* childNode)
548 {
549     TIntermTyped* result = intermediate.addUnaryMath(op, childNode, loc);
550
551     if (result)
552         return result;
553     else
554         unaryOpError(loc, str, childNode->getCompleteString());
555
556     return childNode;
557 }
558
559 //
560 // Handle seeing a base.field dereference in the grammar.
561 //
562 TIntermTyped* HlslParseContext::handleDotDereference(const TSourceLoc& loc, TIntermTyped* base, const TString& field)
563 {
564     variableCheck(base);
565
566     //
567     // .length() can't be resolved until we later see the function-calling syntax.
568     // Save away the name in the AST for now.  Processing is completed in 
569     // handleLengthMethod().
570     //
571     if (field == "length") {
572         return intermediate.addMethod(base, TType(EbtInt), &field, loc);
573     }
574
575     // It's not .length() if we get to here.
576
577     if (base->isArray()) {
578         error(loc, "cannot apply to an array:", ".", field.c_str());
579
580         return base;
581     }
582
583     // It's neither an array nor .length() if we get here,
584     // leaving swizzles and struct/block dereferences.
585
586     TIntermTyped* result = base;
587     if (base->isVector() || base->isScalar()) {
588         TVectorFields fields;
589         if (! parseVectorFields(loc, field, base->getVectorSize(), fields)) {
590             fields.num = 1;
591             fields.offsets[0] = 0;
592         }
593
594         if (base->isScalar()) {
595             if (fields.num == 1)
596                 return result;
597             else {
598                 TType type(base->getBasicType(), EvqTemporary, fields.num);
599                 return addConstructor(loc, base, type, mapTypeToConstructorOp(type));
600             }
601         }
602
603         if (base->getType().getQualifier().isFrontEndConstant())
604             result = intermediate.foldSwizzle(base, fields, loc);
605         else {
606             if (fields.num == 1) {
607                 TIntermTyped* index = intermediate.addConstantUnion(fields.offsets[0], loc);
608                 result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
609                 result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision));
610             } else {
611                 TString vectorString = field;
612                 TIntermTyped* index = intermediate.addSwizzle(fields, loc);
613                 result = intermediate.addIndex(EOpVectorSwizzle, base, index, loc);
614                 result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision, (int)vectorString.size()));
615             }
616         }
617     } else if (base->getBasicType() == EbtStruct || base->getBasicType() == EbtBlock) {
618         const TTypeList* fields = base->getType().getStruct();
619         bool fieldFound = false;
620         int member;
621         for (member = 0; member < (int)fields->size(); ++member) {
622             if ((*fields)[member].type->getFieldName() == field) {
623                 fieldFound = true;
624                 break;
625             }
626         }
627         if (fieldFound) {
628             if (base->getType().getQualifier().storage == EvqConst)
629                 result = intermediate.foldDereference(base, member, loc);
630             else {
631                 TIntermTyped* index = intermediate.addConstantUnion(member, loc);
632                 result = intermediate.addIndex(EOpIndexDirectStruct, base, index, loc);
633                 result->setType(*(*fields)[member].type);
634             }
635         } else
636             error(loc, "no such field in structure", field.c_str(), "");
637     } else
638         error(loc, "does not apply to this type:", field.c_str(), base->getType().getCompleteString().c_str());
639
640     return result;
641 }
642
643 //
644 // Handle seeing a function declarator in the grammar.  This is the precursor
645 // to recognizing a function prototype or function definition.
646 //
647 TFunction* HlslParseContext::handleFunctionDeclarator(const TSourceLoc& loc, TFunction& function, bool prototype)
648 {
649     //
650     // Multiple declarations of the same function name are allowed.
651     //
652     // If this is a definition, the definition production code will check for redefinitions
653     // (we don't know at this point if it's a definition or not).
654     //
655     // Redeclarations (full signature match) are allowed.  But, return types and parameter qualifiers must also match.
656     //  - except ES 100, which only allows a single prototype
657     //
658     // ES 100 does not allow redefining, but does allow overloading of built-in functions.
659     // ES 300 does not allow redefining or overloading of built-in functions.
660     //
661     bool builtIn;
662     TSymbol* symbol = symbolTable.find(function.getMangledName(), &builtIn);
663     const TFunction* prevDec = symbol ? symbol->getAsFunction() : 0;
664
665     if (prototype) {
666         // All built-in functions are defined, even though they don't have a body.
667         // Count their prototype as a definition instead.
668         if (symbolTable.atBuiltInLevel())
669             function.setDefined();
670         else {
671             if (prevDec && ! builtIn)
672                 symbol->getAsFunction()->setPrototyped();  // need a writable one, but like having prevDec as a const
673             function.setPrototyped();
674         }
675     }
676
677     // This insert won't actually insert it if it's a duplicate signature, but it will still check for
678     // other forms of name collisions.
679     if (! symbolTable.insert(function))
680         error(loc, "function name is redeclaration of existing name", function.getName().c_str(), "");
681
682     //
683     // If this is a redeclaration, it could also be a definition,
684     // in which case, we need to use the parameter names from this one, and not the one that's
685     // being redeclared.  So, pass back this declaration, not the one in the symbol table.
686     //
687     return &function;
688 }
689
690 //
691 // Handle seeing the function prototype in front of a function definition in the grammar.  
692 // The body is handled after this function returns.
693 //
694 TIntermAggregate* HlslParseContext::handleFunctionDefinition(const TSourceLoc& loc, TFunction& function)
695 {
696     currentCaller = function.getMangledName();
697     TSymbol* symbol = symbolTable.find(function.getMangledName());
698     TFunction* prevDec = symbol ? symbol->getAsFunction() : nullptr;
699
700     if (! prevDec)
701         error(loc, "can't find function", function.getName().c_str(), "");
702     // Note:  'prevDec' could be 'function' if this is the first time we've seen function
703     // as it would have just been put in the symbol table.  Otherwise, we're looking up
704     // an earlier occurrence.
705
706     if (prevDec && prevDec->isDefined()) {
707         // Then this function already has a body.
708         error(loc, "function already has a body", function.getName().c_str(), "");
709     }
710     if (prevDec && ! prevDec->isDefined()) {
711         prevDec->setDefined();
712
713         // Remember the return type for later checking for RETURN statements.
714         currentFunctionType = &(prevDec->getType());
715     } else
716         currentFunctionType = new TType(EbtVoid);
717     functionReturnsValue = false;
718
719     inEntrypoint = (function.getName() == intermediate.getEntryPoint().c_str());
720
721     //
722     // New symbol table scope for body of function plus its arguments
723     //
724     pushScope();
725
726     //
727     // Insert parameters into the symbol table.
728     // If the parameter has no name, it's not an error, just don't insert it
729     // (could be used for unused args).
730     //
731     // Also, accumulate the list of parameters into the HIL, so lower level code
732     // knows where to find parameters.
733     //
734     TIntermAggregate* paramNodes = new TIntermAggregate;
735     for (int i = 0; i < function.getParamCount(); i++) {
736         TParameter& param = function[i];
737         if (param.name != nullptr) {
738             TVariable *variable = new TVariable(param.name, *param.type);
739
740             // Insert the parameters with name in the symbol table.
741             if (! symbolTable.insert(*variable))
742                 error(loc, "redefinition", variable->getName().c_str(), "");
743             else {
744                 // Transfer ownership of name pointer to symbol table.
745                 param.name = nullptr;
746
747                 // Add the parameter to the HIL
748                 paramNodes = intermediate.growAggregate(paramNodes,
749                     intermediate.addSymbol(*variable, loc),
750                     loc);
751             }
752         } else
753             paramNodes = intermediate.growAggregate(paramNodes, intermediate.addSymbol(*param.type, loc), loc);
754     }
755     intermediate.setAggregateOperator(paramNodes, EOpParameters, TType(EbtVoid), loc);
756     loopNestingLevel = 0;
757     controlFlowNestingLevel = 0;
758     postMainReturn = false;
759
760     return paramNodes;
761 }
762
763 void HlslParseContext::handleFunctionArgument(TFunction* function, TIntermTyped*& arguments, TIntermTyped* newArg)
764 {
765     TParameter param = { 0, new TType };
766     param.type->shallowCopy(newArg->getType());
767     function->addParameter(param);
768     if (arguments)
769         arguments = intermediate.growAggregate(arguments, newArg);
770     else
771         arguments = newArg;
772 }
773
774 //
775 // HLSL atomic operations have slightly different arguments than
776 // GLSL/AST/SPIRV.  The semantics are converted below in decomposeIntrinsic.
777 // This provides the post-decomposition equivalent opcode.
778 //
779 TOperator HlslParseContext::mapAtomicOp(const TSourceLoc& loc, TOperator op, bool isImage)
780 {
781     switch (op) {
782     case EOpInterlockedAdd:             return isImage ? EOpImageAtomicAdd : EOpAtomicAdd;
783     case EOpInterlockedAnd:             return isImage ? EOpImageAtomicAnd : EOpAtomicAnd;
784     case EOpInterlockedCompareExchange: return isImage ? EOpImageAtomicCompSwap : EOpAtomicCompSwap;
785     case EOpInterlockedMax:             return isImage ? EOpImageAtomicMax : EOpAtomicMax;
786     case EOpInterlockedMin:             return isImage ? EOpImageAtomicMin : EOpAtomicMin;
787     case EOpInterlockedOr:              return isImage ? EOpImageAtomicOr : EOpAtomicOr;
788     case EOpInterlockedXor:             return isImage ? EOpImageAtomicXor : EOpAtomicXor;
789     case EOpInterlockedExchange:        return isImage ? EOpImageAtomicExchange : EOpAtomicExchange;
790     case EOpInterlockedCompareStore:  // TODO: ... 
791     default:
792         error(loc, "unknown atomic operation", "unknown op", "");
793         return EOpNull;
794     }
795 }
796
797 // Optionally decompose intrinsics to AST opcodes.
798 //
799 void HlslParseContext::decomposeIntrinsic(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
800 {
801     // HLSL intrinsics can be pass through to native AST opcodes, or decomposed here to existing AST
802     // opcodes for compatibility with existing software stacks.
803     static const bool decomposeHlslIntrinsics = true;
804
805     if (!decomposeHlslIntrinsics || !node || !node->getAsOperator())
806         return;
807     
808     const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
809     TIntermUnary* fnUnary = node->getAsUnaryNode();
810     const TOperator op  = node->getAsOperator()->getOp();
811
812     switch (op) {
813     case EOpGenMul:
814         {
815             // mul(a,b) -> MatrixTimesMatrix, MatrixTimesVector, MatrixTimesScalar, VectorTimesScalar, Dot, Mul
816             TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
817             TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
818
819             if (arg0->isVector() && arg1->isVector()) {  // vec * vec
820                 node->getAsAggregate()->setOperator(EOpDot);
821             } else {
822                 node = handleBinaryMath(loc, "mul", EOpMul, arg0, arg1);
823             }
824
825             break;
826         }
827
828     case EOpRcp:
829         {
830             // rcp(a) -> 1 / a
831             TIntermTyped* arg0 = fnUnary->getOperand();
832             TBasicType   type0 = arg0->getBasicType();
833             TIntermTyped* one  = intermediate.addConstantUnion(1, type0, loc, true);
834             node  = handleBinaryMath(loc, "rcp", EOpDiv, one, arg0);
835
836             break;
837         }
838
839     case EOpSaturate:
840         {
841             // saturate(a) -> clamp(a,0,1)
842             TIntermTyped* arg0 = fnUnary->getOperand();
843             TBasicType   type0 = arg0->getBasicType();
844             TIntermAggregate* clamp = new TIntermAggregate(EOpClamp);
845
846             clamp->getSequence().push_back(arg0);
847             clamp->getSequence().push_back(intermediate.addConstantUnion(0, type0, loc, true));
848             clamp->getSequence().push_back(intermediate.addConstantUnion(1, type0, loc, true));
849             clamp->setLoc(loc);
850             clamp->setType(node->getType());
851             clamp->getWritableType().getQualifier().makeTemporary();
852             node = clamp;
853
854             break;
855         }
856
857     case EOpSinCos:
858         {
859             // sincos(a,b,c) -> b = sin(a), c = cos(a)
860             TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
861             TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
862             TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped();
863
864             TIntermTyped* sinStatement = handleUnaryMath(loc, "sin", EOpSin, arg0);
865             TIntermTyped* cosStatement = handleUnaryMath(loc, "cos", EOpCos, arg0);
866             TIntermTyped* sinAssign    = intermediate.addAssign(EOpAssign, arg1, sinStatement, loc);
867             TIntermTyped* cosAssign    = intermediate.addAssign(EOpAssign, arg2, cosStatement, loc);
868
869             TIntermAggregate* compoundStatement = intermediate.makeAggregate(sinAssign, loc);
870             compoundStatement = intermediate.growAggregate(compoundStatement, cosAssign);
871             compoundStatement->setOperator(EOpSequence);
872             compoundStatement->setLoc(loc);
873
874             node = compoundStatement;
875
876             break;
877         }
878
879     case EOpClip:
880         {
881             // clip(a) -> if (any(a<0)) discard;
882             TIntermTyped*  arg0 = fnUnary->getOperand();
883             TBasicType     type0 = arg0->getBasicType();
884             TIntermTyped*  compareNode = nullptr;
885
886             // For non-scalars: per experiment with FXC compiler, discard if any component < 0.
887             if (!arg0->isScalar()) {
888                 // component-wise compare: a < 0
889                 TIntermAggregate* less = new TIntermAggregate(EOpLessThan);
890                 less->getSequence().push_back(arg0);
891                 less->setLoc(loc);
892
893                 // make vec or mat of bool matching dimensions of input
894                 less->setType(TType(EbtBool, EvqTemporary,
895                                     arg0->getType().getVectorSize(),
896                                     arg0->getType().getMatrixCols(),
897                                     arg0->getType().getMatrixRows(),
898                                     arg0->getType().isVector()));
899
900                 // calculate # of components for comparison const
901                 const int constComponentCount = 
902                     std::max(arg0->getType().getVectorSize(), 1) *
903                     std::max(arg0->getType().getMatrixCols(), 1) *
904                     std::max(arg0->getType().getMatrixRows(), 1);
905
906                 TConstUnion zero;
907                 zero.setDConst(0.0);
908                 TConstUnionArray zeros(constComponentCount, zero);
909
910                 less->getSequence().push_back(intermediate.addConstantUnion(zeros, arg0->getType(), loc, true));
911
912                 compareNode = intermediate.addBuiltInFunctionCall(loc, EOpAny, true, less, TType(EbtBool));
913             } else {
914                 TIntermTyped* zero = intermediate.addConstantUnion(0, type0, loc, true);
915                 compareNode = handleBinaryMath(loc, "clip", EOpLessThan, arg0, zero);
916             }
917             
918             TIntermBranch* killNode = intermediate.addBranch(EOpKill, loc);
919
920             node = new TIntermSelection(compareNode, killNode, nullptr);
921             node->setLoc(loc);
922             
923             break;
924         }
925
926     case EOpLog10:
927         {
928             // log10(a) -> log2(a) * 0.301029995663981  (== 1/log2(10))
929             TIntermTyped* arg0 = fnUnary->getOperand();
930             TIntermTyped* log2 = handleUnaryMath(loc, "log2", EOpLog2, arg0);
931             TIntermTyped* base = intermediate.addConstantUnion(0.301029995663981f, EbtFloat, loc, true);
932
933             node  = handleBinaryMath(loc, "mul", EOpMul, log2, base);
934
935             break;
936         }
937
938     case EOpDst:
939         {
940             // dest.x = 1;
941             // dest.y = src0.y * src1.y;
942             // dest.z = src0.z;
943             // dest.w = src1.w;
944
945             TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
946             TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
947             TBasicType    type0 = arg0->getBasicType();
948
949             TIntermTyped* x = intermediate.addConstantUnion(0, loc, true);
950             TIntermTyped* y = intermediate.addConstantUnion(1, loc, true);
951             TIntermTyped* z = intermediate.addConstantUnion(2, loc, true);
952             TIntermTyped* w = intermediate.addConstantUnion(3, loc, true);
953
954             TIntermTyped* src0y = intermediate.addIndex(EOpIndexDirect, arg0, y, loc);
955             TIntermTyped* src1y = intermediate.addIndex(EOpIndexDirect, arg1, y, loc);
956             TIntermTyped* src0z = intermediate.addIndex(EOpIndexDirect, arg0, z, loc);
957             TIntermTyped* src1w = intermediate.addIndex(EOpIndexDirect, arg1, w, loc);
958
959             TIntermAggregate* dst = new TIntermAggregate(EOpConstructVec4);
960
961             dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
962             dst->getSequence().push_back(handleBinaryMath(loc, "mul", EOpMul, src0y, src1y));
963             dst->getSequence().push_back(src0z);
964             dst->getSequence().push_back(src1w);
965             dst->setLoc(loc);
966             node = dst;
967
968             break;
969         }
970
971     case EOpInterlockedAdd: // optional last argument (if present) is assigned from return value
972     case EOpInterlockedMin: // ...
973     case EOpInterlockedMax: // ...
974     case EOpInterlockedAnd: // ...
975     case EOpInterlockedOr:  // ...
976     case EOpInterlockedXor: // ...
977     case EOpInterlockedExchange: // always has output arg
978         {
979             TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
980             TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
981
982             const bool isImage = arg0->getType().isImage();
983             const TOperator atomicOp = mapAtomicOp(loc, op, isImage);
984
985             if (argAggregate->getSequence().size() > 2) {
986                 // optional output param is present.  return value goes to arg2.
987                 TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped();
988
989                 TIntermAggregate* atomic = new TIntermAggregate(atomicOp);
990                 atomic->getSequence().push_back(arg0);
991                 atomic->getSequence().push_back(arg1);
992                 atomic->setLoc(loc);
993                 atomic->setType(arg0->getType());
994                 atomic->getWritableType().getQualifier().makeTemporary();
995
996                 node = intermediate.addAssign(EOpAssign, arg2, atomic, loc);
997             } else {
998                 // Set the matching operator.  Since output is absent, this is all we need to do.
999                 node->getAsAggregate()->setOperator(atomicOp);
1000             }
1001
1002             break;
1003         }
1004
1005     case EOpInterlockedCompareExchange:
1006         {
1007             TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();  // dest
1008             TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();  // cmp
1009             TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped();  // value
1010             TIntermTyped* arg3 = argAggregate->getSequence()[3]->getAsTyped();  // orig
1011
1012             const bool isImage = arg0->getType().isImage();
1013             TIntermAggregate* atomic = new TIntermAggregate(mapAtomicOp(loc, op, isImage));
1014             atomic->getSequence().push_back(arg0);
1015             atomic->getSequence().push_back(arg1);
1016             atomic->getSequence().push_back(arg2);
1017             atomic->setLoc(loc);
1018             atomic->setType(arg2->getType());
1019             atomic->getWritableType().getQualifier().makeTemporary();
1020
1021             node = intermediate.addAssign(EOpAssign, arg3, atomic, loc);
1022             
1023             break;
1024         }
1025
1026     default:
1027         break; // most pass through unchanged
1028     }
1029 }
1030
1031 //
1032 // Handle seeing function call syntax in the grammar, which could be any of
1033 //  - .length() method
1034 //  - constructor
1035 //  - a call to a built-in function mapped to an operator
1036 //  - a call to a built-in function that will remain a function call (e.g., texturing)
1037 //  - user function
1038 //  - subroutine call (not implemented yet)
1039 //
1040 TIntermTyped* HlslParseContext::handleFunctionCall(const TSourceLoc& loc, TFunction* function, TIntermNode* arguments)
1041 {
1042     TIntermTyped* result = nullptr;
1043
1044     TOperator op = function->getBuiltInOp();
1045     if (op == EOpArrayLength)
1046         result = handleLengthMethod(loc, function, arguments);
1047     else if (op != EOpNull) {
1048         //
1049         // Then this should be a constructor.
1050         // Don't go through the symbol table for constructors.
1051         // Their parameters will be verified algorithmically.
1052         //
1053         TType type(EbtVoid);  // use this to get the type back
1054         if (! constructorError(loc, arguments, *function, op, type)) {
1055             //
1056             // It's a constructor, of type 'type'.
1057             //
1058             result = addConstructor(loc, arguments, type, op);
1059             if (result == nullptr)
1060                 error(loc, "cannot construct with these arguments", type.getCompleteString().c_str(), "");
1061         }
1062     } else {
1063         //
1064         // Find it in the symbol table.
1065         //
1066         const TFunction* fnCandidate;
1067         bool builtIn;
1068         fnCandidate = findFunction(loc, *function, builtIn);
1069         if (fnCandidate) {
1070             // This is a declared function that might map to
1071             //  - a built-in operator,
1072             //  - a built-in function not mapped to an operator, or
1073             //  - a user function.
1074
1075             // Error check for a function requiring specific extensions present.
1076             if (builtIn && fnCandidate->getNumExtensions())
1077                 requireExtensions(loc, fnCandidate->getNumExtensions(), fnCandidate->getExtensions(), fnCandidate->getName().c_str());
1078
1079             if (arguments) {
1080                 // Make sure qualifications work for these arguments.
1081                 TIntermAggregate* aggregate = arguments->getAsAggregate();
1082                 for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
1083                     // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
1084                     // is the single argument itself or its children are the arguments.  Only one argument
1085                     // means take 'arguments' itself as the one argument.
1086                     TIntermNode* arg = fnCandidate->getParamCount() == 1 ? arguments : (aggregate ? aggregate->getSequence()[i] : arguments);
1087                     TQualifier& formalQualifier = (*fnCandidate)[i].type->getQualifier();
1088                     TQualifier& argQualifier = arg->getAsTyped()->getQualifier();
1089                 }
1090
1091                 // Convert 'in' arguments
1092                 addInputArgumentConversions(*fnCandidate, arguments);  // arguments may be modified if it's just a single argument node
1093             }
1094
1095             op = fnCandidate->getBuiltInOp();
1096             if (builtIn && op != EOpNull) {
1097                 // A function call mapped to a built-in operation.
1098                 result = intermediate.addBuiltInFunctionCall(loc, op, fnCandidate->getParamCount() == 1, arguments, fnCandidate->getType());
1099                 if (result == nullptr)  {
1100                     error(arguments->getLoc(), " wrong operand type", "Internal Error",
1101                         "built in unary operator function.  Type: %s",
1102                         static_cast<TIntermTyped*>(arguments)->getCompleteString().c_str());
1103                 } else if (result->getAsOperator()) {
1104                     builtInOpCheck(loc, *fnCandidate, *result->getAsOperator());
1105                 }
1106             } else {
1107                 // This is a function call not mapped to built-in operator.
1108                 // It could still be a built-in function, but only if PureOperatorBuiltins == false.
1109                 result = intermediate.setAggregateOperator(arguments, EOpFunctionCall, fnCandidate->getType(), loc);
1110                 TIntermAggregate* call = result->getAsAggregate();
1111                 call->setName(fnCandidate->getMangledName());
1112
1113                 // this is how we know whether the given function is a built-in function or a user-defined function
1114                 // if builtIn == false, it's a userDefined -> could be an overloaded built-in function also
1115                 // if builtIn == true, it's definitely a built-in function with EOpNull
1116                 if (! builtIn) {
1117                     call->setUserDefined();
1118                     intermediate.addToCallGraph(infoSink, currentCaller, fnCandidate->getMangledName());
1119                 }
1120             }
1121
1122             // Convert 'out' arguments.  If it was a constant folded built-in, it won't be an aggregate anymore.
1123             // Built-ins with a single argument aren't called with an aggregate, but they also don't have an output.
1124             // Also, build the qualifier list for user function calls, which are always called with an aggregate.
1125             if (result->getAsAggregate()) {
1126                 TQualifierList& qualifierList = result->getAsAggregate()->getQualifierList();
1127                 for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
1128                     TStorageQualifier qual = (*fnCandidate)[i].type->getQualifier().storage;
1129                     qualifierList.push_back(qual);
1130                 }
1131                 result = addOutputArgumentConversions(*fnCandidate, *result->getAsAggregate());
1132             }
1133
1134             decomposeIntrinsic(loc, result, arguments);
1135         }
1136     }
1137
1138     // generic error recovery
1139     // TODO: simplification: localize all the error recoveries that look like this, and taking type into account to reduce cascades
1140     if (result == nullptr)
1141         result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
1142
1143     return result;
1144 }
1145
1146 // Finish processing object.length(). This started earlier in handleDotDereference(), where
1147 // the ".length" part was recognized and semantically checked, and finished here where the 
1148 // function syntax "()" is recognized.
1149 //
1150 // Return resulting tree node.
1151 TIntermTyped* HlslParseContext::handleLengthMethod(const TSourceLoc& loc, TFunction* function, TIntermNode* intermNode)
1152 {
1153     int length = 0;
1154
1155     if (function->getParamCount() > 0)
1156         error(loc, "method does not accept any arguments", function->getName().c_str(), "");
1157     else {
1158         const TType& type = intermNode->getAsTyped()->getType();
1159         if (type.isArray()) {
1160             if (type.isRuntimeSizedArray()) {
1161                 // Create a unary op and let the back end handle it
1162                 return intermediate.addBuiltInFunctionCall(loc, EOpArrayLength, true, intermNode, TType(EbtInt));
1163             } else if (type.isImplicitlySizedArray()) {
1164                 if (intermNode->getAsSymbolNode() && isIoResizeArray(type)) {
1165                     // We could be between a layout declaration that gives a built-in io array implicit size and 
1166                     // a user redeclaration of that array, meaning we have to substitute its implicit size here 
1167                     // without actually redeclaring the array.  (It is an error to use a member before the
1168                     // redeclaration, but not an error to use the array name itself.)
1169                     const TString& name = intermNode->getAsSymbolNode()->getName();
1170                     if (name == "gl_in" || name == "gl_out")
1171                         length = getIoArrayImplicitSize();
1172                 }
1173                 if (length == 0) {
1174                     if (intermNode->getAsSymbolNode() && isIoResizeArray(type))
1175                         error(loc, "", function->getName().c_str(), "array must first be sized by a redeclaration or layout qualifier");
1176                     else
1177                         error(loc, "", function->getName().c_str(), "array must be declared with a size before using this method");
1178                 }
1179             } else
1180                 length = type.getOuterArraySize();
1181         } else if (type.isMatrix())
1182             length = type.getMatrixCols();
1183         else if (type.isVector())
1184             length = type.getVectorSize();
1185         else {
1186             // we should not get here, because earlier semantic checking should have prevented this path
1187             error(loc, ".length()", "unexpected use of .length()", "");
1188         }
1189     }
1190
1191     if (length == 0)
1192         length = 1;
1193
1194     return intermediate.addConstantUnion(length, loc);
1195 }
1196
1197 //
1198 // Add any needed implicit conversions for function-call arguments to input parameters.
1199 //
1200 void HlslParseContext::addInputArgumentConversions(const TFunction& function, TIntermNode*& arguments) const
1201 {
1202     TIntermAggregate* aggregate = arguments->getAsAggregate();
1203
1204     // Process each argument's conversion
1205     for (int i = 0; i < function.getParamCount(); ++i) {
1206         // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
1207         // is the single argument itself or its children are the arguments.  Only one argument
1208         // means take 'arguments' itself as the one argument.
1209         TIntermTyped* arg = function.getParamCount() == 1 ? arguments->getAsTyped() : (aggregate ? aggregate->getSequence()[i]->getAsTyped() : arguments->getAsTyped());
1210         if (*function[i].type != arg->getType()) {
1211             if (function[i].type->getQualifier().isParamInput()) {
1212                 // In-qualified arguments just need an extra node added above the argument to
1213                 // convert to the correct type.
1214                 arg = intermediate.addConversion(EOpFunctionCall, *function[i].type, arg);
1215                 if (arg) {
1216                     if (function.getParamCount() == 1)
1217                         arguments = arg;
1218                     else {
1219                         if (aggregate)
1220                             aggregate->getSequence()[i] = arg;
1221                         else
1222                             arguments = arg;
1223                     }
1224                 }
1225             }
1226         }
1227     }
1228 }
1229
1230 //
1231 // Add any needed implicit output conversions for function-call arguments.  This
1232 // can require a new tree topology, complicated further by whether the function
1233 // has a return value.
1234 //
1235 // Returns a node of a subtree that evaluates to the return value of the function.
1236 //
1237 TIntermTyped* HlslParseContext::addOutputArgumentConversions(const TFunction& function, TIntermAggregate& intermNode) const
1238 {
1239     TIntermSequence& arguments = intermNode.getSequence();
1240
1241     // Will there be any output conversions?
1242     bool outputConversions = false;
1243     for (int i = 0; i < function.getParamCount(); ++i) {
1244         if (*function[i].type != arguments[i]->getAsTyped()->getType() && function[i].type->getQualifier().storage == EvqOut) {
1245             outputConversions = true;
1246             break;
1247         }
1248     }
1249
1250     if (! outputConversions)
1251         return &intermNode;
1252
1253     // Setup for the new tree, if needed:
1254     //
1255     // Output conversions need a different tree topology.
1256     // Out-qualified arguments need a temporary of the correct type, with the call
1257     // followed by an assignment of the temporary to the original argument:
1258     //     void: function(arg, ...)  ->        (          function(tempArg, ...), arg = tempArg, ...)
1259     //     ret = function(arg, ...)  ->  ret = (tempRet = function(tempArg, ...), arg = tempArg, ..., tempRet)
1260     // Where the "tempArg" type needs no conversion as an argument, but will convert on assignment.
1261     TIntermTyped* conversionTree = nullptr;
1262     TVariable* tempRet = nullptr;
1263     if (intermNode.getBasicType() != EbtVoid) {
1264         // do the "tempRet = function(...), " bit from above
1265         tempRet = makeInternalVariable("tempReturn", intermNode.getType());
1266         TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, intermNode.getLoc());
1267         conversionTree = intermediate.addAssign(EOpAssign, tempRetNode, &intermNode, intermNode.getLoc());
1268     } else
1269         conversionTree = &intermNode;
1270
1271     conversionTree = intermediate.makeAggregate(conversionTree);
1272
1273     // Process each argument's conversion
1274     for (int i = 0; i < function.getParamCount(); ++i) {
1275         if (*function[i].type != arguments[i]->getAsTyped()->getType()) {
1276             if (function[i].type->getQualifier().isParamOutput()) {
1277                 // Out-qualified arguments need to use the topology set up above.
1278                 // do the " ...(tempArg, ...), arg = tempArg" bit from above
1279                 TVariable* tempArg = makeInternalVariable("tempArg", *function[i].type);
1280                 tempArg->getWritableType().getQualifier().makeTemporary();
1281                 TIntermSymbol* tempArgNode = intermediate.addSymbol(*tempArg, intermNode.getLoc());
1282                 TIntermTyped* tempAssign = intermediate.addAssign(EOpAssign, arguments[i]->getAsTyped(), tempArgNode, arguments[i]->getLoc());
1283                 conversionTree = intermediate.growAggregate(conversionTree, tempAssign, arguments[i]->getLoc());
1284                 // replace the argument with another node for the same tempArg variable
1285                 arguments[i] = intermediate.addSymbol(*tempArg, intermNode.getLoc());
1286             }
1287         }
1288     }
1289
1290     // Finalize the tree topology (see bigger comment above).
1291     if (tempRet) {
1292         // do the "..., tempRet" bit from above
1293         TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, intermNode.getLoc());
1294         conversionTree = intermediate.growAggregate(conversionTree, tempRetNode, intermNode.getLoc());
1295     }
1296     conversionTree = intermediate.setAggregateOperator(conversionTree, EOpComma, intermNode.getType(), intermNode.getLoc());
1297
1298     return conversionTree;
1299 }
1300
1301 //
1302 // Do additional checking of built-in function calls that is not caught
1303 // by normal semantic checks on argument type, extension tagging, etc.
1304 //
1305 // Assumes there has been a semantically correct match to a built-in function prototype.
1306 //
1307 void HlslParseContext::builtInOpCheck(const TSourceLoc& loc, const TFunction& fnCandidate, TIntermOperator& callNode)
1308 {
1309     // Set up convenience accessors to the argument(s).  There is almost always
1310     // multiple arguments for the cases below, but when there might be one,
1311     // check the unaryArg first.
1312     const TIntermSequence* argp = nullptr;   // confusing to use [] syntax on a pointer, so this is to help get a reference
1313     const TIntermTyped* unaryArg = nullptr;
1314     const TIntermTyped* arg0 = nullptr;
1315     if (callNode.getAsAggregate()) {
1316         argp = &callNode.getAsAggregate()->getSequence();
1317         if (argp->size() > 0)
1318             arg0 = (*argp)[0]->getAsTyped();
1319     } else {
1320         assert(callNode.getAsUnaryNode());
1321         unaryArg = callNode.getAsUnaryNode()->getOperand();
1322         arg0 = unaryArg;
1323     }
1324     const TIntermSequence& aggArgs = *argp;  // only valid when unaryArg is nullptr
1325
1326     // built-in texturing functions get their return value precision from the precision of the sampler
1327     if (fnCandidate.getType().getQualifier().precision == EpqNone &&
1328         fnCandidate.getParamCount() > 0 && fnCandidate[0].type->getBasicType() == EbtSampler)
1329         callNode.getQualifier().precision = arg0->getQualifier().precision;
1330
1331     switch (callNode.getOp()) {
1332     case EOpTextureGather:
1333     case EOpTextureGatherOffset:
1334     case EOpTextureGatherOffsets:
1335     {
1336         // Figure out which variants are allowed by what extensions,
1337         // and what arguments must be constant for which situations.
1338
1339         TString featureString = fnCandidate.getName() + "(...)";
1340         const char* feature = featureString.c_str();
1341         int compArg = -1;  // track which argument, if any, is the constant component argument
1342         switch (callNode.getOp()) {
1343         case EOpTextureGather:
1344             // More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5,
1345             // otherwise, need GL_ARB_texture_gather.
1346             if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect || fnCandidate[0].type->getSampler().shadow) {
1347                 if (! fnCandidate[0].type->getSampler().shadow)
1348                     compArg = 2;
1349             }
1350             break;
1351         case EOpTextureGatherOffset:
1352             // GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument
1353             if (! fnCandidate[0].type->getSampler().shadow)
1354                 compArg = 3;
1355             break;
1356         case EOpTextureGatherOffsets:
1357             if (! fnCandidate[0].type->getSampler().shadow)
1358                 compArg = 3;
1359             break;
1360         default:
1361             break;
1362         }
1363
1364         if (compArg > 0 && compArg < fnCandidate.getParamCount()) {
1365             if (aggArgs[compArg]->getAsConstantUnion()) {
1366                 int value = aggArgs[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst();
1367                 if (value < 0 || value > 3)
1368                     error(loc, "must be 0, 1, 2, or 3:", feature, "component argument");
1369             } else
1370                 error(loc, "must be a compile-time constant:", feature, "component argument");
1371         }
1372
1373         break;
1374     }
1375
1376     case EOpTextureOffset:
1377     case EOpTextureFetchOffset:
1378     case EOpTextureProjOffset:
1379     case EOpTextureLodOffset:
1380     case EOpTextureProjLodOffset:
1381     case EOpTextureGradOffset:
1382     case EOpTextureProjGradOffset:
1383     {
1384         // Handle texture-offset limits checking
1385         // Pick which argument has to hold constant offsets
1386         int arg = -1;
1387         switch (callNode.getOp()) {
1388         case EOpTextureOffset:          arg = 2;  break;
1389         case EOpTextureFetchOffset:     arg = (arg0->getType().getSampler().dim != EsdRect) ? 3 : 2; break;
1390         case EOpTextureProjOffset:      arg = 2;  break;
1391         case EOpTextureLodOffset:       arg = 3;  break;
1392         case EOpTextureProjLodOffset:   arg = 3;  break;
1393         case EOpTextureGradOffset:      arg = 4;  break;
1394         case EOpTextureProjGradOffset:  arg = 4;  break;
1395         default:
1396             assert(0);
1397             break;
1398         }
1399
1400         if (arg > 0) {
1401             if (! aggArgs[arg]->getAsConstantUnion())
1402                 error(loc, "argument must be compile-time constant", "texel offset", "");
1403             else {
1404                 const TType& type = aggArgs[arg]->getAsTyped()->getType();
1405                 for (int c = 0; c < type.getVectorSize(); ++c) {
1406                     int offset = aggArgs[arg]->getAsConstantUnion()->getConstArray()[c].getIConst();
1407                     if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset)
1408                         error(loc, "value is out of range:", "texel offset", "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]");
1409                 }
1410             }
1411         }
1412
1413         break;
1414     }
1415
1416     case EOpTextureQuerySamples:
1417     case EOpImageQuerySamples:
1418         break;
1419
1420     case EOpImageAtomicAdd:
1421     case EOpImageAtomicMin:
1422     case EOpImageAtomicMax:
1423     case EOpImageAtomicAnd:
1424     case EOpImageAtomicOr:
1425     case EOpImageAtomicXor:
1426     case EOpImageAtomicExchange:
1427     case EOpImageAtomicCompSwap:
1428         break;
1429
1430     case EOpInterpolateAtCentroid:
1431     case EOpInterpolateAtSample:
1432     case EOpInterpolateAtOffset:
1433         // "For the interpolateAt* functions, the call will return a precision
1434         // qualification matching the precision of the 'interpolant' argument to
1435         // the function call."
1436         callNode.getQualifier().precision = arg0->getQualifier().precision;
1437
1438         // Make sure the first argument is an interpolant, or an array element of an interpolant
1439         if (arg0->getType().getQualifier().storage != EvqVaryingIn) {
1440             // It might still be an array element.
1441             //
1442             // We could check more, but the semantics of the first argument are already met; the
1443             // only way to turn an array into a float/vec* is array dereference and swizzle.
1444             //
1445             // ES and desktop 4.3 and earlier:  swizzles may not be used
1446             // desktop 4.4 and later: swizzles may be used
1447             const TIntermTyped* base = TIntermediate::findLValueBase(arg0, true);
1448             if (base == nullptr || base->getType().getQualifier().storage != EvqVaryingIn)
1449                 error(loc, "first argument must be an interpolant, or interpolant-array element", fnCandidate.getName().c_str(), "");
1450         }
1451         break;
1452
1453     default:
1454         break;
1455     }
1456 }
1457
1458 //
1459 // Handle seeing a built-in constructor in a grammar production.
1460 //
1461 TFunction* HlslParseContext::handleConstructorCall(const TSourceLoc& loc, const TType& type)
1462 {
1463     TOperator op = mapTypeToConstructorOp(type);
1464
1465     if (op == EOpNull) {
1466         error(loc, "cannot construct this type", type.getBasicString(), "");
1467         return nullptr;
1468     }
1469
1470     TString empty("");
1471
1472     return new TFunction(&empty, type, op);
1473 }
1474
1475 //
1476 // Handle seeing a "COLON semantic" at the end of a type declaration,
1477 // by updating the type according to the semantic.
1478 //
1479 void HlslParseContext::handleSemantic(TType& type, const TString& semantic)
1480 {
1481     // TODO: need to know if it's an input or an output
1482     // The following sketches what needs to be done, but can't be right
1483     // without taking into account stage and input/output.
1484     
1485     if (semantic == "PSIZE")
1486         type.getQualifier().builtIn = EbvPointSize;
1487     else if (semantic == "POSITION")
1488         type.getQualifier().builtIn = EbvPosition;
1489     else if (semantic == "FOG")
1490         type.getQualifier().builtIn = EbvFogFragCoord;
1491     else if (semantic == "DEPTH" || semantic == "SV_Depth")
1492         type.getQualifier().builtIn = EbvFragDepth;
1493     else if (semantic == "VFACE" || semantic == "SV_IsFrontFace")
1494         type.getQualifier().builtIn = EbvFace;
1495     else if (semantic == "VPOS" || semantic == "SV_Position")
1496         type.getQualifier().builtIn = EbvFragCoord;
1497     else if (semantic == "SV_ClipDistance")
1498         type.getQualifier().builtIn = EbvClipDistance;
1499     else if (semantic == "SV_CullDistance")
1500         type.getQualifier().builtIn = EbvCullDistance;
1501     else if (semantic == "SV_VertexID")
1502         type.getQualifier().builtIn = EbvVertexId;
1503     else if (semantic == "SV_ViewportArrayIndex")
1504         type.getQualifier().builtIn = EbvViewportIndex;
1505 }
1506
1507 //
1508 // Given a type, find what operation would fully construct it.
1509 //
1510 TOperator HlslParseContext::mapTypeToConstructorOp(const TType& type) const
1511 {
1512     TOperator op = EOpNull;
1513
1514     switch (type.getBasicType()) {
1515     case EbtStruct:
1516         op = EOpConstructStruct;
1517         break;
1518     case EbtSampler:
1519         if (type.getSampler().combined)
1520             op = EOpConstructTextureSampler;
1521         break;
1522     case EbtFloat:
1523         if (type.isMatrix()) {
1524             switch (type.getMatrixCols()) {
1525             case 2:
1526                 switch (type.getMatrixRows()) {
1527                 case 2: op = EOpConstructMat2x2; break;
1528                 case 3: op = EOpConstructMat2x3; break;
1529                 case 4: op = EOpConstructMat2x4; break;
1530                 default: break; // some compilers want this
1531                 }
1532                 break;
1533             case 3:
1534                 switch (type.getMatrixRows()) {
1535                 case 2: op = EOpConstructMat3x2; break;
1536                 case 3: op = EOpConstructMat3x3; break;
1537                 case 4: op = EOpConstructMat3x4; break;
1538                 default: break; // some compilers want this
1539                 }
1540                 break;
1541             case 4:
1542                 switch (type.getMatrixRows()) {
1543                 case 2: op = EOpConstructMat4x2; break;
1544                 case 3: op = EOpConstructMat4x3; break;
1545                 case 4: op = EOpConstructMat4x4; break;
1546                 default: break; // some compilers want this
1547                 }
1548                 break;
1549             default: break; // some compilers want this
1550             }
1551         } else {
1552             switch (type.getVectorSize()) {
1553             case 1: op = EOpConstructFloat; break;
1554             case 2: op = EOpConstructVec2;  break;
1555             case 3: op = EOpConstructVec3;  break;
1556             case 4: op = EOpConstructVec4;  break;
1557             default: break; // some compilers want this
1558             }
1559         }
1560         break;
1561     case EbtDouble:
1562         if (type.getMatrixCols()) {
1563             switch (type.getMatrixCols()) {
1564             case 2:
1565                 switch (type.getMatrixRows()) {
1566                 case 2: op = EOpConstructDMat2x2; break;
1567                 case 3: op = EOpConstructDMat2x3; break;
1568                 case 4: op = EOpConstructDMat2x4; break;
1569                 default: break; // some compilers want this
1570                 }
1571                 break;
1572             case 3:
1573                 switch (type.getMatrixRows()) {
1574                 case 2: op = EOpConstructDMat3x2; break;
1575                 case 3: op = EOpConstructDMat3x3; break;
1576                 case 4: op = EOpConstructDMat3x4; break;
1577                 default: break; // some compilers want this
1578                 }
1579                 break;
1580             case 4:
1581                 switch (type.getMatrixRows()) {
1582                 case 2: op = EOpConstructDMat4x2; break;
1583                 case 3: op = EOpConstructDMat4x3; break;
1584                 case 4: op = EOpConstructDMat4x4; break;
1585                 default: break; // some compilers want this
1586                 }
1587                 break;
1588             }
1589         } else {
1590             switch (type.getVectorSize()) {
1591             case 1: op = EOpConstructDouble; break;
1592             case 2: op = EOpConstructDVec2;  break;
1593             case 3: op = EOpConstructDVec3;  break;
1594             case 4: op = EOpConstructDVec4;  break;
1595             default: break; // some compilers want this
1596             }
1597         }
1598         break;
1599     case EbtInt:
1600         switch (type.getVectorSize()) {
1601         case 1: op = EOpConstructInt;   break;
1602         case 2: op = EOpConstructIVec2; break;
1603         case 3: op = EOpConstructIVec3; break;
1604         case 4: op = EOpConstructIVec4; break;
1605         default: break; // some compilers want this
1606         }
1607         break;
1608     case EbtUint:
1609         switch (type.getVectorSize()) {
1610         case 1: op = EOpConstructUint;  break;
1611         case 2: op = EOpConstructUVec2; break;
1612         case 3: op = EOpConstructUVec3; break;
1613         case 4: op = EOpConstructUVec4; break;
1614         default: break; // some compilers want this
1615         }
1616         break;
1617     case EbtBool:
1618         switch (type.getVectorSize()) {
1619         case 1:  op = EOpConstructBool;  break;
1620         case 2:  op = EOpConstructBVec2; break;
1621         case 3:  op = EOpConstructBVec3; break;
1622         case 4:  op = EOpConstructBVec4; break;
1623         default: break; // some compilers want this
1624         }
1625         break;
1626     default:
1627         break;
1628     }
1629
1630     return op;
1631 }
1632
1633 //
1634 // Same error message for all places assignments don't work.
1635 //
1636 void HlslParseContext::assignError(const TSourceLoc& loc, const char* op, TString left, TString right)
1637 {
1638     error(loc, "", op, "cannot convert from '%s' to '%s'",
1639         right.c_str(), left.c_str());
1640 }
1641
1642 //
1643 // Same error message for all places unary operations don't work.
1644 //
1645 void HlslParseContext::unaryOpError(const TSourceLoc& loc, const char* op, TString operand)
1646 {
1647     error(loc, " wrong operand type", op,
1648         "no operation '%s' exists that takes an operand of type %s (or there is no acceptable conversion)",
1649         op, operand.c_str());
1650 }
1651
1652 //
1653 // Same error message for all binary operations don't work.
1654 //
1655 void HlslParseContext::binaryOpError(const TSourceLoc& loc, const char* op, TString left, TString right)
1656 {
1657     error(loc, " wrong operand types:", op,
1658         "no operation '%s' exists that takes a left-hand operand of type '%s' and "
1659         "a right operand of type '%s' (or there is no acceptable conversion)",
1660         op, left.c_str(), right.c_str());
1661 }
1662
1663 //
1664 // A basic type of EbtVoid is a key that the name string was seen in the source, but
1665 // it was not found as a variable in the symbol table.  If so, give the error
1666 // message and insert a dummy variable in the symbol table to prevent future errors.
1667 //
1668 void HlslParseContext::variableCheck(TIntermTyped*& nodePtr)
1669 {
1670     TIntermSymbol* symbol = nodePtr->getAsSymbolNode();
1671     if (! symbol)
1672         return;
1673
1674     if (symbol->getType().getBasicType() == EbtVoid) {
1675         error(symbol->getLoc(), "undeclared identifier", symbol->getName().c_str(), "");
1676
1677         // Add to symbol table to prevent future error messages on the same name
1678         if (symbol->getName().size() > 0) {
1679             TVariable* fakeVariable = new TVariable(&symbol->getName(), TType(EbtFloat));
1680             symbolTable.insert(*fakeVariable);
1681
1682             // substitute a symbol node for this new variable
1683             nodePtr = intermediate.addSymbol(*fakeVariable, symbol->getLoc());
1684         }
1685     }
1686 }
1687
1688 //
1689 // Both test, and if necessary spit out an error, to see if the node is really
1690 // a constant.
1691 //
1692 void HlslParseContext::constantValueCheck(TIntermTyped* node, const char* token)
1693 {
1694     if (node->getQualifier().storage != EvqConst)
1695         error(node->getLoc(), "constant expression required", token, "");
1696 }
1697
1698 //
1699 // Both test, and if necessary spit out an error, to see if the node is really
1700 // an integer.
1701 //
1702 void HlslParseContext::integerCheck(const TIntermTyped* node, const char* token)
1703 {
1704     if ((node->getBasicType() == EbtInt || node->getBasicType() == EbtUint) && node->isScalar())
1705         return;
1706
1707     error(node->getLoc(), "scalar integer expression required", token, "");
1708 }
1709
1710 //
1711 // Both test, and if necessary spit out an error, to see if we are currently
1712 // globally scoped.
1713 //
1714 void HlslParseContext::globalCheck(const TSourceLoc& loc, const char* token)
1715 {
1716     if (! symbolTable.atGlobalLevel())
1717         error(loc, "not allowed in nested scope", token, "");
1718 }
1719
1720
1721 bool HlslParseContext::builtInName(const TString& identifier)
1722 {
1723     return false;
1724 }
1725
1726 //
1727 // Make sure there is enough data and not too many arguments provided to the
1728 // constructor to build something of the type of the constructor.  Also returns
1729 // the type of the constructor.
1730 //
1731 // Returns true if there was an error in construction.
1732 //
1733 bool HlslParseContext::constructorError(const TSourceLoc& loc, TIntermNode* node, TFunction& function, TOperator op, TType& type)
1734 {
1735     type.shallowCopy(function.getType());
1736
1737     bool constructingMatrix = false;
1738     switch (op) {
1739     case EOpConstructTextureSampler:
1740         return constructorTextureSamplerError(loc, function);
1741     case EOpConstructMat2x2:
1742     case EOpConstructMat2x3:
1743     case EOpConstructMat2x4:
1744     case EOpConstructMat3x2:
1745     case EOpConstructMat3x3:
1746     case EOpConstructMat3x4:
1747     case EOpConstructMat4x2:
1748     case EOpConstructMat4x3:
1749     case EOpConstructMat4x4:
1750     case EOpConstructDMat2x2:
1751     case EOpConstructDMat2x3:
1752     case EOpConstructDMat2x4:
1753     case EOpConstructDMat3x2:
1754     case EOpConstructDMat3x3:
1755     case EOpConstructDMat3x4:
1756     case EOpConstructDMat4x2:
1757     case EOpConstructDMat4x3:
1758     case EOpConstructDMat4x4:
1759         constructingMatrix = true;
1760         break;
1761     default:
1762         break;
1763     }
1764
1765     //
1766     // Walk the arguments for first-pass checks and collection of information.
1767     //
1768
1769     int size = 0;
1770     bool constType = true;
1771     bool full = false;
1772     bool overFull = false;
1773     bool matrixInMatrix = false;
1774     bool arrayArg = false;
1775     for (int arg = 0; arg < function.getParamCount(); ++arg) {
1776         if (function[arg].type->isArray()) {
1777             if (! function[arg].type->isExplicitlySizedArray()) {
1778                 // Can't construct from an unsized array.
1779                 error(loc, "array argument must be sized", "constructor", "");
1780                 return true;
1781             }
1782             arrayArg = true;
1783         }
1784         if (constructingMatrix && function[arg].type->isMatrix())
1785             matrixInMatrix = true;
1786
1787         // 'full' will go to true when enough args have been seen.  If we loop
1788         // again, there is an extra argument.
1789         if (full) {
1790             // For vectors and matrices, it's okay to have too many components
1791             // available, but not okay to have unused arguments.
1792             overFull = true;
1793         }
1794
1795         size += function[arg].type->computeNumComponents();
1796         if (op != EOpConstructStruct && ! type.isArray() && size >= type.computeNumComponents())
1797             full = true;
1798
1799         if (function[arg].type->getQualifier().storage != EvqConst)
1800             constType = false;
1801     }
1802
1803     if (constType)
1804         type.getQualifier().storage = EvqConst;
1805
1806     if (type.isArray()) {
1807         if (function.getParamCount() == 0) {
1808             error(loc, "array constructor must have at least one argument", "constructor", "");
1809             return true;
1810         }
1811
1812         if (type.isImplicitlySizedArray()) {
1813             // auto adapt the constructor type to the number of arguments
1814             type.changeOuterArraySize(function.getParamCount());
1815         } else if (type.getOuterArraySize() != function.getParamCount()) {
1816             error(loc, "array constructor needs one argument per array element", "constructor", "");
1817             return true;
1818         }
1819
1820         if (type.isArrayOfArrays()) {
1821             // Types have to match, but we're still making the type.
1822             // Finish making the type, and the comparison is done later
1823             // when checking for conversion.
1824             TArraySizes& arraySizes = type.getArraySizes();
1825
1826             // At least the dimensionalities have to match.
1827             if (! function[0].type->isArray() || arraySizes.getNumDims() != function[0].type->getArraySizes().getNumDims() + 1) {
1828                 error(loc, "array constructor argument not correct type to construct array element", "constructior", "");
1829                 return true;
1830             }
1831
1832             if (arraySizes.isInnerImplicit()) {
1833                 // "Arrays of arrays ..., and the size for any dimension is optional"
1834                 // That means we need to adopt (from the first argument) the other array sizes into the type.
1835                 for (int d = 1; d < arraySizes.getNumDims(); ++d) {
1836                     if (arraySizes.getDimSize(d) == UnsizedArraySize) {
1837                         arraySizes.setDimSize(d, function[0].type->getArraySizes().getDimSize(d - 1));
1838                     }
1839                 }
1840             }
1841         }
1842     }
1843
1844     if (arrayArg && op != EOpConstructStruct && ! type.isArrayOfArrays()) {
1845         error(loc, "constructing non-array constituent from array argument", "constructor", "");
1846         return true;
1847     }
1848
1849     if (matrixInMatrix && ! type.isArray()) {
1850         return false;
1851     }
1852
1853     if (overFull) {
1854         error(loc, "too many arguments", "constructor", "");
1855         return true;
1856     }
1857
1858     if (op == EOpConstructStruct && ! type.isArray() && (int)type.getStruct()->size() != function.getParamCount()) {
1859         error(loc, "Number of constructor parameters does not match the number of structure fields", "constructor", "");
1860         return true;
1861     }
1862
1863     if ((op != EOpConstructStruct && size != 1 && size < type.computeNumComponents()) ||
1864         (op == EOpConstructStruct && size < type.computeNumComponents())) {
1865         error(loc, "not enough data provided for construction", "constructor", "");
1866         return true;
1867     }
1868
1869     TIntermTyped* typed = node->getAsTyped();
1870
1871     return false;
1872 }
1873
1874 // Verify all the correct semantics for constructing a combined texture/sampler.
1875 // Return true if the semantics are incorrect.
1876 bool HlslParseContext::constructorTextureSamplerError(const TSourceLoc& loc, const TFunction& function)
1877 {
1878     TString constructorName = function.getType().getBasicTypeString();  // TODO: performance: should not be making copy; interface needs to change
1879     const char* token = constructorName.c_str();
1880
1881     // exactly two arguments needed
1882     if (function.getParamCount() != 2) {
1883         error(loc, "sampler-constructor requires two arguments", token, "");
1884         return true;
1885     }
1886
1887     // For now, not allowing arrayed constructors, the rest of this function
1888     // is set up to allow them, if this test is removed:
1889     if (function.getType().isArray()) {
1890         error(loc, "sampler-constructor cannot make an array of samplers", token, "");
1891         return true;
1892     }
1893
1894     // first argument
1895     //  * the constructor's first argument must be a texture type
1896     //  * the dimensionality (1D, 2D, 3D, Cube, Rect, Buffer, MS, and Array)
1897     //    of the texture type must match that of the constructed sampler type
1898     //    (that is, the suffixes of the type of the first argument and the
1899     //    type of the constructor will be spelled the same way)
1900     if (function[0].type->getBasicType() != EbtSampler ||
1901         ! function[0].type->getSampler().isTexture() ||
1902         function[0].type->isArray()) {
1903         error(loc, "sampler-constructor first argument must be a scalar textureXXX type", token, "");
1904         return true;
1905     }
1906     // simulate the first argument's impact on the result type, so it can be compared with the encapsulated operator!=()
1907     TSampler texture = function.getType().getSampler();
1908     texture.combined = false;
1909     texture.shadow = false;
1910     if (texture != function[0].type->getSampler()) {
1911         error(loc, "sampler-constructor first argument must match type and dimensionality of constructor type", token, "");
1912         return true;
1913     }
1914
1915     // second argument
1916     //   * the constructor's second argument must be a scalar of type
1917     //     *sampler* or *samplerShadow*
1918     //   * the presence or absence of depth comparison (Shadow) must match
1919     //     between the constructed sampler type and the type of the second argument
1920     if (function[1].type->getBasicType() != EbtSampler ||
1921         ! function[1].type->getSampler().isPureSampler() ||
1922         function[1].type->isArray()) {
1923         error(loc, "sampler-constructor second argument must be a scalar type 'sampler'", token, "");
1924         return true;
1925     }
1926     if (function.getType().getSampler().shadow != function[1].type->getSampler().shadow) {
1927         error(loc, "sampler-constructor second argument presence of shadow must match constructor presence of shadow", token, "");
1928         return true;
1929     }
1930
1931     return false;
1932 }
1933
1934 // Checks to see if a void variable has been declared and raise an error message for such a case
1935 //
1936 // returns true in case of an error
1937 //
1938 bool HlslParseContext::voidErrorCheck(const TSourceLoc& loc, const TString& identifier, const TBasicType basicType)
1939 {
1940     if (basicType == EbtVoid) {
1941         error(loc, "illegal use of type 'void'", identifier.c_str(), "");
1942         return true;
1943     }
1944
1945     return false;
1946 }
1947
1948 // Checks to see if the node (for the expression) contains a scalar boolean expression or not
1949 void HlslParseContext::boolCheck(const TSourceLoc& loc, const TIntermTyped* type)
1950 {
1951     if (type->getBasicType() != EbtBool || type->isArray() || type->isMatrix() || type->isVector())
1952         error(loc, "boolean expression expected", "", "");
1953 }
1954
1955 //
1956 // Fix just a full qualifier (no variables or types yet, but qualifier is complete) at global level.
1957 //
1958 void HlslParseContext::globalQualifierFix(const TSourceLoc& loc, TQualifier& qualifier)
1959 {
1960     // move from parameter/unknown qualifiers to pipeline in/out qualifiers
1961     switch (qualifier.storage) {
1962     case EvqIn:
1963         qualifier.storage = EvqVaryingIn;
1964         break;
1965     case EvqOut:
1966         qualifier.storage = EvqVaryingOut;
1967         break;
1968     default:
1969         break;
1970     }
1971 }
1972
1973 //
1974 // Merge characteristics of the 'src' qualifier into the 'dst'.
1975 // If there is duplication, issue error messages, unless 'force'
1976 // is specified, which means to just override default settings.
1977 //
1978 // Also, when force is false, it will be assumed that 'src' follows
1979 // 'dst', for the purpose of error checking order for versions
1980 // that require specific orderings of qualifiers.
1981 //
1982 void HlslParseContext::mergeQualifiers(const TSourceLoc& loc, TQualifier& dst, const TQualifier& src, bool force)
1983 {
1984     // Storage qualification
1985     if (dst.storage == EvqTemporary || dst.storage == EvqGlobal)
1986         dst.storage = src.storage;
1987     else if ((dst.storage == EvqIn  && src.storage == EvqOut) ||
1988         (dst.storage == EvqOut && src.storage == EvqIn))
1989         dst.storage = EvqInOut;
1990     else if ((dst.storage == EvqIn    && src.storage == EvqConst) ||
1991         (dst.storage == EvqConst && src.storage == EvqIn))
1992         dst.storage = EvqConstReadOnly;
1993     else if (src.storage != EvqTemporary && src.storage != EvqGlobal)
1994         error(loc, "too many storage qualifiers", GetStorageQualifierString(src.storage), "");
1995
1996     // Precision qualifiers
1997     if (dst.precision == EpqNone || (force && src.precision != EpqNone))
1998         dst.precision = src.precision;
1999
2000     // Layout qualifiers
2001     mergeObjectLayoutQualifiers(dst, src, false);
2002
2003     // individual qualifiers
2004     bool repeated = false;
2005 #define MERGE_SINGLETON(field) repeated |= dst.field && src.field; dst.field |= src.field;
2006     MERGE_SINGLETON(invariant);
2007     MERGE_SINGLETON(noContraction);
2008     MERGE_SINGLETON(centroid);
2009     MERGE_SINGLETON(smooth);
2010     MERGE_SINGLETON(flat);
2011     MERGE_SINGLETON(nopersp);
2012     MERGE_SINGLETON(patch);
2013     MERGE_SINGLETON(sample);
2014     MERGE_SINGLETON(coherent);
2015     MERGE_SINGLETON(volatil);
2016     MERGE_SINGLETON(restrict);
2017     MERGE_SINGLETON(readonly);
2018     MERGE_SINGLETON(writeonly);
2019     MERGE_SINGLETON(specConstant);
2020 }
2021
2022 // used to flatten the sampler type space into a single dimension
2023 // correlates with the declaration of defaultSamplerPrecision[]
2024 int HlslParseContext::computeSamplerTypeIndex(TSampler& sampler)
2025 {
2026     int arrayIndex = sampler.arrayed ? 1 : 0;
2027     int shadowIndex = sampler.shadow ? 1 : 0;
2028     int externalIndex = sampler.external ? 1 : 0;
2029
2030     return EsdNumDims * (EbtNumTypes * (2 * (2 * arrayIndex + shadowIndex) + externalIndex) + sampler.type) + sampler.dim;
2031 }
2032
2033 //
2034 // Do size checking for an array type's size.
2035 //
2036 void HlslParseContext::arraySizeCheck(const TSourceLoc& loc, TIntermTyped* expr, TArraySize& sizePair)
2037 {
2038     bool isConst = false;
2039     sizePair.size = 1;
2040     sizePair.node = nullptr;
2041
2042     TIntermConstantUnion* constant = expr->getAsConstantUnion();
2043     if (constant) {
2044         // handle true (non-specialization) constant
2045         sizePair.size = constant->getConstArray()[0].getIConst();
2046         isConst = true;
2047     } else {
2048         // see if it's a specialization constant instead
2049         if (expr->getQualifier().isSpecConstant()) {
2050             isConst = true;
2051             sizePair.node = expr;
2052             TIntermSymbol* symbol = expr->getAsSymbolNode();
2053             if (symbol && symbol->getConstArray().size() > 0)
2054                 sizePair.size = symbol->getConstArray()[0].getIConst();
2055         }
2056     }
2057
2058     if (! isConst || (expr->getBasicType() != EbtInt && expr->getBasicType() != EbtUint)) {
2059         error(loc, "array size must be a constant integer expression", "", "");
2060         return;
2061     }
2062
2063     if (sizePair.size <= 0) {
2064         error(loc, "array size must be a positive integer", "", "");
2065         return;
2066     }
2067 }
2068
2069 //
2070 // Require array to be completely sized
2071 //
2072 void HlslParseContext::arraySizeRequiredCheck(const TSourceLoc& loc, const TArraySizes& arraySizes)
2073 {
2074     if (arraySizes.isImplicit())
2075         error(loc, "array size required", "", "");
2076 }
2077
2078 void HlslParseContext::structArrayCheck(const TSourceLoc& /*loc*/, const TType& type)
2079 {
2080     const TTypeList& structure = *type.getStruct();
2081     for (int m = 0; m < (int)structure.size(); ++m) {
2082         const TType& member = *structure[m].type;
2083         if (member.isArray())
2084             arraySizeRequiredCheck(structure[m].loc, *member.getArraySizes());
2085     }
2086 }
2087
2088 // Merge array dimensions listed in 'sizes' onto the type's array dimensions.
2089 //
2090 // From the spec: "vec4[2] a[3]; // size-3 array of size-2 array of vec4"
2091 //
2092 // That means, the 'sizes' go in front of the 'type' as outermost sizes.
2093 // 'type' is the type part of the declaration (to the left)
2094 // 'sizes' is the arrayness tagged on the identifier (to the right)
2095 //
2096 void HlslParseContext::arrayDimMerge(TType& type, const TArraySizes* sizes)
2097 {
2098     if (sizes)
2099         type.addArrayOuterSizes(*sizes);
2100 }
2101
2102 //
2103 // Do all the semantic checking for declaring or redeclaring an array, with and
2104 // without a size, and make the right changes to the symbol table.
2105 //
2106 void HlslParseContext::declareArray(const TSourceLoc& loc, TString& identifier, const TType& type, TSymbol*& symbol, bool& newDeclaration)
2107 {
2108     if (! symbol) {
2109         bool currentScope;
2110         symbol = symbolTable.find(identifier, nullptr, &currentScope);
2111
2112         if (symbol && builtInName(identifier) && ! symbolTable.atBuiltInLevel()) {
2113             // bad shader (errors already reported) trying to redeclare a built-in name as an array
2114             return;
2115         }
2116         if (symbol == nullptr || ! currentScope) {
2117             //
2118             // Successfully process a new definition.
2119             // (Redeclarations have to take place at the same scope; otherwise they are hiding declarations)
2120             //
2121             symbol = new TVariable(&identifier, type);
2122             symbolTable.insert(*symbol);
2123             newDeclaration = true;
2124
2125             if (! symbolTable.atBuiltInLevel()) {
2126                 if (isIoResizeArray(type)) {
2127                     ioArraySymbolResizeList.push_back(symbol);
2128                     checkIoArraysConsistency(loc, true);
2129                 } else
2130                     fixIoArraySize(loc, symbol->getWritableType());
2131             }
2132
2133             return;
2134         }
2135         if (symbol->getAsAnonMember()) {
2136             error(loc, "cannot redeclare a user-block member array", identifier.c_str(), "");
2137             symbol = nullptr;
2138             return;
2139         }
2140     }
2141
2142     //
2143     // Process a redeclaration.
2144     //
2145
2146     if (! symbol) {
2147         error(loc, "array variable name expected", identifier.c_str(), "");
2148         return;
2149     }
2150
2151     // redeclareBuiltinVariable() should have already done the copyUp()
2152     TType& existingType = symbol->getWritableType();
2153
2154
2155     if (existingType.isExplicitlySizedArray()) {
2156         // be more lenient for input arrays to geometry shaders and tessellation control outputs, where the redeclaration is the same size
2157         if (! (isIoResizeArray(type) && existingType.getOuterArraySize() == type.getOuterArraySize()))
2158             error(loc, "redeclaration of array with size", identifier.c_str(), "");
2159         return;
2160     }
2161
2162     existingType.updateArraySizes(type);
2163
2164     if (isIoResizeArray(type))
2165         checkIoArraysConsistency(loc);
2166 }
2167
2168 void HlslParseContext::updateImplicitArraySize(const TSourceLoc& loc, TIntermNode *node, int index)
2169 {
2170     // maybe there is nothing to do...
2171     TIntermTyped* typedNode = node->getAsTyped();
2172     if (typedNode->getType().getImplicitArraySize() > index)
2173         return;
2174
2175     // something to do...
2176
2177     // Figure out what symbol to lookup, as we will use its type to edit for the size change,
2178     // as that type will be shared through shallow copies for future references.
2179     TSymbol* symbol = nullptr;
2180     int blockIndex = -1;
2181     const TString* lookupName = nullptr;
2182     if (node->getAsSymbolNode())
2183         lookupName = &node->getAsSymbolNode()->getName();
2184     else if (node->getAsBinaryNode()) {
2185         const TIntermBinary* deref = node->getAsBinaryNode();
2186         // This has to be the result of a block dereference, unless it's bad shader code
2187         // If it's a uniform block, then an error will be issued elsewhere, but
2188         // return early now to avoid crashing later in this function.
2189         if (! deref->getLeft()->getAsSymbolNode() || deref->getLeft()->getBasicType() != EbtBlock ||
2190             deref->getLeft()->getType().getQualifier().storage == EvqUniform ||
2191             deref->getRight()->getAsConstantUnion() == nullptr)
2192             return;
2193
2194         blockIndex = deref->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
2195
2196         lookupName = &deref->getLeft()->getAsSymbolNode()->getName();
2197         if (IsAnonymous(*lookupName))
2198             lookupName = &(*deref->getLeft()->getType().getStruct())[blockIndex].type->getFieldName();
2199     }
2200
2201     // Lookup the symbol, should only fail if shader code is incorrect
2202     symbol = symbolTable.find(*lookupName);
2203     if (symbol == nullptr)
2204         return;
2205
2206     if (symbol->getAsFunction()) {
2207         error(loc, "array variable name expected", symbol->getName().c_str(), "");
2208         return;
2209     }
2210
2211     symbol->getWritableType().setImplicitArraySize(index + 1);
2212 }
2213
2214 //
2215 // See if the identifier is a built-in symbol that can be redeclared, and if so,
2216 // copy the symbol table's read-only built-in variable to the current
2217 // global level, where it can be modified based on the passed in type.
2218 //
2219 // Returns nullptr if no redeclaration took place; meaning a normal declaration still
2220 // needs to occur for it, not necessarily an error.
2221 //
2222 // Returns a redeclared and type-modified variable if a redeclared occurred.
2223 //
2224 TSymbol* HlslParseContext::redeclareBuiltinVariable(const TSourceLoc& loc, const TString& identifier, const TQualifier& qualifier, const TShaderQualifiers& publicType, bool& newDeclaration)
2225 {
2226     if (! builtInName(identifier) || symbolTable.atBuiltInLevel() || ! symbolTable.atGlobalLevel())
2227         return nullptr;
2228
2229     return nullptr;
2230 }
2231
2232 //
2233 // Either redeclare the requested block, or give an error message why it can't be done.
2234 //
2235 // TODO: functionality: explicitly sizing members of redeclared blocks is not giving them an explicit size
2236 void HlslParseContext::redeclareBuiltinBlock(const TSourceLoc& loc, TTypeList& newTypeList, const TString& blockName, const TString* instanceName, TArraySizes* arraySizes)
2237 {
2238     // Redeclaring a built-in block...
2239
2240     // Blocks with instance names are easy to find, lookup the instance name,
2241     // Anonymous blocks need to be found via a member.
2242     bool builtIn;
2243     TSymbol* block;
2244     if (instanceName)
2245         block = symbolTable.find(*instanceName, &builtIn);
2246     else
2247         block = symbolTable.find(newTypeList.front().type->getFieldName(), &builtIn);
2248
2249     // If the block was not found, this must be a version/profile/stage
2250     // that doesn't have it, or the instance name is wrong.
2251     const char* errorName = instanceName ? instanceName->c_str() : newTypeList.front().type->getFieldName().c_str();
2252     if (! block) {
2253         error(loc, "no declaration found for redeclaration", errorName, "");
2254         return;
2255     }
2256     // Built-in blocks cannot be redeclared more than once, which if happened,
2257     // we'd be finding the already redeclared one here, rather than the built in.
2258     if (! builtIn) {
2259         error(loc, "can only redeclare a built-in block once, and before any use", blockName.c_str(), "");
2260         return;
2261     }
2262
2263     // Copy the block to make a writable version, to insert into the block table after editing.
2264     block = symbolTable.copyUpDeferredInsert(block);
2265
2266     if (block->getType().getBasicType() != EbtBlock) {
2267         error(loc, "cannot redeclare a non block as a block", errorName, "");
2268         return;
2269     }
2270
2271     // Edit and error check the container against the redeclaration
2272     //  - remove unused members
2273     //  - ensure remaining qualifiers/types match
2274     TType& type = block->getWritableType();
2275     TTypeList::iterator member = type.getWritableStruct()->begin();
2276     size_t numOriginalMembersFound = 0;
2277     while (member != type.getStruct()->end()) {
2278         // look for match
2279         bool found = false;
2280         TTypeList::const_iterator newMember;
2281         TSourceLoc memberLoc;
2282         memberLoc.init();
2283         for (newMember = newTypeList.begin(); newMember != newTypeList.end(); ++newMember) {
2284             if (member->type->getFieldName() == newMember->type->getFieldName()) {
2285                 found = true;
2286                 memberLoc = newMember->loc;
2287                 break;
2288             }
2289         }
2290
2291         if (found) {
2292             ++numOriginalMembersFound;
2293             // - ensure match between redeclared members' types
2294             // - check for things that can't be changed
2295             // - update things that can be changed
2296             TType& oldType = *member->type;
2297             const TType& newType = *newMember->type;
2298             if (! newType.sameElementType(oldType))
2299                 error(memberLoc, "cannot redeclare block member with a different type", member->type->getFieldName().c_str(), "");
2300             if (oldType.isArray() != newType.isArray())
2301                 error(memberLoc, "cannot change arrayness of redeclared block member", member->type->getFieldName().c_str(), "");
2302             else if (! oldType.sameArrayness(newType) && oldType.isExplicitlySizedArray())
2303                 error(memberLoc, "cannot change array size of redeclared block member", member->type->getFieldName().c_str(), "");
2304             if (newType.getQualifier().isMemory())
2305                 error(memberLoc, "cannot add memory qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
2306             if (newType.getQualifier().hasLayout())
2307                 error(memberLoc, "cannot add layout to redeclared block member", member->type->getFieldName().c_str(), "");
2308             if (newType.getQualifier().patch)
2309                 error(memberLoc, "cannot add patch to redeclared block member", member->type->getFieldName().c_str(), "");
2310             oldType.getQualifier().centroid = newType.getQualifier().centroid;
2311             oldType.getQualifier().sample = newType.getQualifier().sample;
2312             oldType.getQualifier().invariant = newType.getQualifier().invariant;
2313             oldType.getQualifier().noContraction = newType.getQualifier().noContraction;
2314             oldType.getQualifier().smooth = newType.getQualifier().smooth;
2315             oldType.getQualifier().flat = newType.getQualifier().flat;
2316             oldType.getQualifier().nopersp = newType.getQualifier().nopersp;
2317
2318             // go to next member
2319             ++member;
2320         } else {
2321             // For missing members of anonymous blocks that have been redeclared,
2322             // hide the original (shared) declaration.
2323             // Instance-named blocks can just have the member removed.
2324             if (instanceName)
2325                 member = type.getWritableStruct()->erase(member);
2326             else {
2327                 member->type->hideMember();
2328                 ++member;
2329             }
2330         }
2331     }
2332
2333     if (numOriginalMembersFound < newTypeList.size())
2334         error(loc, "block redeclaration has extra members", blockName.c_str(), "");
2335     if (type.isArray() != (arraySizes != nullptr))
2336         error(loc, "cannot change arrayness of redeclared block", blockName.c_str(), "");
2337     else if (type.isArray()) {
2338         if (type.isExplicitlySizedArray() && arraySizes->getOuterSize() == UnsizedArraySize)
2339             error(loc, "block already declared with size, can't redeclare as implicitly-sized", blockName.c_str(), "");
2340         else if (type.isExplicitlySizedArray() && type.getArraySizes() != *arraySizes)
2341             error(loc, "cannot change array size of redeclared block", blockName.c_str(), "");
2342         else if (type.isImplicitlySizedArray() && arraySizes->getOuterSize() != UnsizedArraySize)
2343             type.changeOuterArraySize(arraySizes->getOuterSize());
2344     }
2345
2346     symbolTable.insert(*block);
2347
2348     // Tracking for implicit sizing of array
2349     if (isIoResizeArray(block->getType())) {
2350         ioArraySymbolResizeList.push_back(block);
2351         checkIoArraysConsistency(loc, true);
2352     } else if (block->getType().isArray())
2353         fixIoArraySize(loc, block->getWritableType());
2354
2355     // Save it in the AST for linker use.
2356     intermediate.addSymbolLinkageNode(linkage, *block);
2357 }
2358
2359 void HlslParseContext::paramCheckFix(const TSourceLoc& loc, const TStorageQualifier& qualifier, TType& type)
2360 {
2361     switch (qualifier) {
2362     case EvqConst:
2363     case EvqConstReadOnly:
2364         type.getQualifier().storage = EvqConstReadOnly;
2365         break;
2366     case EvqIn:
2367     case EvqOut:
2368     case EvqInOut:
2369         type.getQualifier().storage = qualifier;
2370         break;
2371     case EvqGlobal:
2372     case EvqTemporary:
2373         type.getQualifier().storage = EvqIn;
2374         break;
2375     default:
2376         type.getQualifier().storage = EvqIn;
2377         error(loc, "storage qualifier not allowed on function parameter", GetStorageQualifierString(qualifier), "");
2378         break;
2379     }
2380 }
2381
2382 void HlslParseContext::paramCheckFix(const TSourceLoc& loc, const TQualifier& qualifier, TType& type)
2383 {
2384     if (qualifier.isMemory()) {
2385         type.getQualifier().volatil = qualifier.volatil;
2386         type.getQualifier().coherent = qualifier.coherent;
2387         type.getQualifier().readonly = qualifier.readonly;
2388         type.getQualifier().writeonly = qualifier.writeonly;
2389         type.getQualifier().restrict = qualifier.restrict;
2390     }
2391
2392     paramCheckFix(loc, qualifier.storage, type);
2393 }
2394
2395 void HlslParseContext::specializationCheck(const TSourceLoc& loc, const TType& type, const char* op)
2396 {
2397     if (type.containsSpecializationSize())
2398         error(loc, "can't use with types containing arrays sized with a specialization constant", op, "");
2399 }
2400
2401 //
2402 // Layout qualifier stuff.
2403 //
2404
2405 // Put the id's layout qualification into the public type, for qualifiers not having a number set.
2406 // This is before we know any type information for error checking.
2407 void HlslParseContext::setLayoutQualifier(const TSourceLoc& loc, TPublicType& publicType, TString& id)
2408 {
2409     std::transform(id.begin(), id.end(), id.begin(), ::tolower);
2410
2411     if (id == TQualifier::getLayoutMatrixString(ElmColumnMajor)) {
2412         publicType.qualifier.layoutMatrix = ElmColumnMajor;
2413         return;
2414     }
2415     if (id == TQualifier::getLayoutMatrixString(ElmRowMajor)) {
2416         publicType.qualifier.layoutMatrix = ElmRowMajor;
2417         return;
2418     }
2419     if (id == TQualifier::getLayoutPackingString(ElpPacked)) {
2420         if (vulkan > 0)
2421             vulkanRemoved(loc, "packed");
2422         publicType.qualifier.layoutPacking = ElpPacked;
2423         return;
2424     }
2425     if (id == TQualifier::getLayoutPackingString(ElpShared)) {
2426         if (vulkan > 0)
2427             vulkanRemoved(loc, "shared");
2428         publicType.qualifier.layoutPacking = ElpShared;
2429         return;
2430     }
2431     if (id == "push_constant") {
2432         requireVulkan(loc, "push_constant");
2433         publicType.qualifier.layoutPushConstant = true;
2434         return;
2435     }
2436     if (language == EShLangGeometry || language == EShLangTessEvaluation) {
2437         if (id == TQualifier::getGeometryString(ElgTriangles)) {
2438             publicType.shaderQualifiers.geometry = ElgTriangles;
2439             return;
2440         }
2441         if (language == EShLangGeometry) {
2442             if (id == TQualifier::getGeometryString(ElgPoints)) {
2443                 publicType.shaderQualifiers.geometry = ElgPoints;
2444                 return;
2445             }
2446             if (id == TQualifier::getGeometryString(ElgLineStrip)) {
2447                 publicType.shaderQualifiers.geometry = ElgLineStrip;
2448                 return;
2449             }
2450             if (id == TQualifier::getGeometryString(ElgLines)) {
2451                 publicType.shaderQualifiers.geometry = ElgLines;
2452                 return;
2453             }
2454             if (id == TQualifier::getGeometryString(ElgLinesAdjacency)) {
2455                 publicType.shaderQualifiers.geometry = ElgLinesAdjacency;
2456                 return;
2457             }
2458             if (id == TQualifier::getGeometryString(ElgTrianglesAdjacency)) {
2459                 publicType.shaderQualifiers.geometry = ElgTrianglesAdjacency;
2460                 return;
2461             }
2462             if (id == TQualifier::getGeometryString(ElgTriangleStrip)) {
2463                 publicType.shaderQualifiers.geometry = ElgTriangleStrip;
2464                 return;
2465             }
2466         } else {
2467             assert(language == EShLangTessEvaluation);
2468
2469             // input primitive
2470             if (id == TQualifier::getGeometryString(ElgTriangles)) {
2471                 publicType.shaderQualifiers.geometry = ElgTriangles;
2472                 return;
2473             }
2474             if (id == TQualifier::getGeometryString(ElgQuads)) {
2475                 publicType.shaderQualifiers.geometry = ElgQuads;
2476                 return;
2477             }
2478             if (id == TQualifier::getGeometryString(ElgIsolines)) {
2479                 publicType.shaderQualifiers.geometry = ElgIsolines;
2480                 return;
2481             }
2482
2483             // vertex spacing
2484             if (id == TQualifier::getVertexSpacingString(EvsEqual)) {
2485                 publicType.shaderQualifiers.spacing = EvsEqual;
2486                 return;
2487             }
2488             if (id == TQualifier::getVertexSpacingString(EvsFractionalEven)) {
2489                 publicType.shaderQualifiers.spacing = EvsFractionalEven;
2490                 return;
2491             }
2492             if (id == TQualifier::getVertexSpacingString(EvsFractionalOdd)) {
2493                 publicType.shaderQualifiers.spacing = EvsFractionalOdd;
2494                 return;
2495             }
2496
2497             // triangle order
2498             if (id == TQualifier::getVertexOrderString(EvoCw)) {
2499                 publicType.shaderQualifiers.order = EvoCw;
2500                 return;
2501             }
2502             if (id == TQualifier::getVertexOrderString(EvoCcw)) {
2503                 publicType.shaderQualifiers.order = EvoCcw;
2504                 return;
2505             }
2506
2507             // point mode
2508             if (id == "point_mode") {
2509                 publicType.shaderQualifiers.pointMode = true;
2510                 return;
2511             }
2512         }
2513     }
2514     if (language == EShLangFragment) {
2515         if (id == "origin_upper_left") {
2516             publicType.shaderQualifiers.originUpperLeft = true;
2517             return;
2518         }
2519         if (id == "pixel_center_integer") {
2520             publicType.shaderQualifiers.pixelCenterInteger = true;
2521             return;
2522         }
2523         if (id == "early_fragment_tests") {
2524             publicType.shaderQualifiers.earlyFragmentTests = true;
2525             return;
2526         }
2527         for (TLayoutDepth depth = (TLayoutDepth)(EldNone + 1); depth < EldCount; depth = (TLayoutDepth)(depth + 1)) {
2528             if (id == TQualifier::getLayoutDepthString(depth)) {
2529                 publicType.shaderQualifiers.layoutDepth = depth;
2530                 return;
2531             }
2532         }
2533         if (id.compare(0, 13, "blend_support") == 0) {
2534             bool found = false;
2535             for (TBlendEquationShift be = (TBlendEquationShift)0; be < EBlendCount; be = (TBlendEquationShift)(be + 1)) {
2536                 if (id == TQualifier::getBlendEquationString(be)) {
2537                     requireExtensions(loc, 1, &E_GL_KHR_blend_equation_advanced, "blend equation");
2538                     intermediate.addBlendEquation(be);
2539                     publicType.shaderQualifiers.blendEquation = true;
2540                     found = true;
2541                     break;
2542                 }
2543             }
2544             if (! found)
2545                 error(loc, "unknown blend equation", "blend_support", "");
2546             return;
2547         }
2548     }
2549     error(loc, "unrecognized layout identifier, or qualifier requires assignment (e.g., binding = 4)", id.c_str(), "");
2550 }
2551
2552 // Put the id's layout qualifier value into the public type, for qualifiers having a number set.
2553 // This is before we know any type information for error checking.
2554 void HlslParseContext::setLayoutQualifier(const TSourceLoc& loc, TPublicType& publicType, TString& id, const TIntermTyped* node)
2555 {
2556     const char* feature = "layout-id value";
2557     const char* nonLiteralFeature = "non-literal layout-id value";
2558
2559     integerCheck(node, feature);
2560     const TIntermConstantUnion* constUnion = node->getAsConstantUnion();
2561     int value = 0;
2562     if (constUnion) {
2563         value = constUnion->getConstArray()[0].getIConst();
2564     }
2565
2566     std::transform(id.begin(), id.end(), id.begin(), ::tolower);
2567
2568     if (id == "offset") {
2569         publicType.qualifier.layoutOffset = value;
2570         return;
2571     } else if (id == "align") {
2572         // "The specified alignment must be a power of 2, or a compile-time error results."
2573         if (! IsPow2(value))
2574             error(loc, "must be a power of 2", "align", "");
2575         else
2576             publicType.qualifier.layoutAlign = value;
2577         return;
2578     } else if (id == "location") {
2579         if ((unsigned int)value >= TQualifier::layoutLocationEnd)
2580             error(loc, "location is too large", id.c_str(), "");
2581         else
2582             publicType.qualifier.layoutLocation = value;
2583         return;
2584     } else if (id == "set") {
2585         if ((unsigned int)value >= TQualifier::layoutSetEnd)
2586             error(loc, "set is too large", id.c_str(), "");
2587         else
2588             publicType.qualifier.layoutSet = value;
2589         return;
2590     } else if (id == "binding") {
2591         if ((unsigned int)value >= TQualifier::layoutBindingEnd)
2592             error(loc, "binding is too large", id.c_str(), "");
2593         else
2594             publicType.qualifier.layoutBinding = value;
2595         return;
2596     } else if (id == "component") {
2597         if ((unsigned)value >= TQualifier::layoutComponentEnd)
2598             error(loc, "component is too large", id.c_str(), "");
2599         else
2600             publicType.qualifier.layoutComponent = value;
2601         return;
2602     } else if (id.compare(0, 4, "xfb_") == 0) {
2603         // "Any shader making any static use (after preprocessing) of any of these 
2604         // *xfb_* qualifiers will cause the shader to be in a transform feedback 
2605         // capturing mode and hence responsible for describing the transform feedback 
2606         // setup."
2607         intermediate.setXfbMode();
2608         if (id == "xfb_buffer") {
2609             // "It is a compile-time error to specify an *xfb_buffer* that is greater than
2610             // the implementation-dependent constant gl_MaxTransformFeedbackBuffers."
2611             if (value >= resources.maxTransformFeedbackBuffers)
2612                 error(loc, "buffer is too large:", id.c_str(), "gl_MaxTransformFeedbackBuffers is %d", resources.maxTransformFeedbackBuffers);
2613             if (value >= (int)TQualifier::layoutXfbBufferEnd)
2614                 error(loc, "buffer is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbBufferEnd - 1);
2615             else
2616                 publicType.qualifier.layoutXfbBuffer = value;
2617             return;
2618         } else if (id == "xfb_offset") {
2619             if (value >= (int)TQualifier::layoutXfbOffsetEnd)
2620                 error(loc, "offset is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbOffsetEnd - 1);
2621             else
2622                 publicType.qualifier.layoutXfbOffset = value;
2623             return;
2624         } else if (id == "xfb_stride") {
2625             // "The resulting stride (implicit or explicit), when divided by 4, must be less than or equal to the 
2626             // implementation-dependent constant gl_MaxTransformFeedbackInterleavedComponents."
2627             if (value > 4 * resources.maxTransformFeedbackInterleavedComponents)
2628                 error(loc, "1/4 stride is too large:", id.c_str(), "gl_MaxTransformFeedbackInterleavedComponents is %d", resources.maxTransformFeedbackInterleavedComponents);
2629             else if (value >= (int)TQualifier::layoutXfbStrideEnd)
2630                 error(loc, "stride is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbStrideEnd - 1);
2631             if (value < (int)TQualifier::layoutXfbStrideEnd)
2632                 publicType.qualifier.layoutXfbStride = value;
2633             return;
2634         }
2635     }
2636
2637     if (id == "input_attachment_index") {
2638         requireVulkan(loc, "input_attachment_index");
2639         if (value >= (int)TQualifier::layoutAttachmentEnd)
2640             error(loc, "attachment index is too large", id.c_str(), "");
2641         else
2642             publicType.qualifier.layoutAttachment = value;
2643         return;
2644     }
2645     if (id == "constant_id") {
2646         requireSpv(loc, "constant_id");
2647         if (value >= (int)TQualifier::layoutSpecConstantIdEnd) {
2648             error(loc, "specialization-constant id is too large", id.c_str(), "");
2649         } else {
2650             publicType.qualifier.layoutSpecConstantId = value;
2651             publicType.qualifier.specConstant = true;
2652             if (! intermediate.addUsedConstantId(value))
2653                 error(loc, "specialization-constant id already used", id.c_str(), "");
2654         }
2655         return;
2656     }
2657
2658     switch (language) {
2659     case EShLangVertex:
2660         break;
2661
2662     case EShLangTessControl:
2663         if (id == "vertices") {
2664             if (value == 0)
2665                 error(loc, "must be greater than 0", "vertices", "");
2666             else
2667                 publicType.shaderQualifiers.vertices = value;
2668             return;
2669         }
2670         break;
2671
2672     case EShLangTessEvaluation:
2673         break;
2674
2675     case EShLangGeometry:
2676         if (id == "invocations") {
2677             if (value == 0)
2678                 error(loc, "must be at least 1", "invocations", "");
2679             else
2680                 publicType.shaderQualifiers.invocations = value;
2681             return;
2682         }
2683         if (id == "max_vertices") {
2684             publicType.shaderQualifiers.vertices = value;
2685             if (value > resources.maxGeometryOutputVertices)
2686                 error(loc, "too large, must be less than gl_MaxGeometryOutputVertices", "max_vertices", "");
2687             return;
2688         }
2689         if (id == "stream") {
2690             publicType.qualifier.layoutStream = value;
2691             return;
2692         }
2693         break;
2694
2695     case EShLangFragment:
2696         if (id == "index") {
2697             const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location };
2698             publicType.qualifier.layoutIndex = value;
2699             return;
2700         }
2701         break;
2702
2703     case EShLangCompute:
2704         if (id.compare(0, 11, "local_size_") == 0) {
2705             if (id == "local_size_x") {
2706                 publicType.shaderQualifiers.localSize[0] = value;
2707                 return;
2708             }
2709             if (id == "local_size_y") {
2710                 publicType.shaderQualifiers.localSize[1] = value;
2711                 return;
2712             }
2713             if (id == "local_size_z") {
2714                 publicType.shaderQualifiers.localSize[2] = value;
2715                 return;
2716             }
2717             if (spv > 0) {
2718                 if (id == "local_size_x_id") {
2719                     publicType.shaderQualifiers.localSizeSpecId[0] = value;
2720                     return;
2721                 }
2722                 if (id == "local_size_y_id") {
2723                     publicType.shaderQualifiers.localSizeSpecId[1] = value;
2724                     return;
2725                 }
2726                 if (id == "local_size_z_id") {
2727                     publicType.shaderQualifiers.localSizeSpecId[2] = value;
2728                     return;
2729                 }
2730             }
2731         }
2732         break;
2733
2734     default:
2735         break;
2736     }
2737
2738     error(loc, "there is no such layout identifier for this stage taking an assigned value", id.c_str(), "");
2739 }
2740
2741 // Merge any layout qualifier information from src into dst, leaving everything else in dst alone
2742 //
2743 // "More than one layout qualifier may appear in a single declaration.
2744 // Additionally, the same layout-qualifier-name can occur multiple times 
2745 // within a layout qualifier or across multiple layout qualifiers in the 
2746 // same declaration. When the same layout-qualifier-name occurs 
2747 // multiple times, in a single declaration, the last occurrence overrides 
2748 // the former occurrence(s).  Further, if such a layout-qualifier-name 
2749 // will effect subsequent declarations or other observable behavior, it 
2750 // is only the last occurrence that will have any effect, behaving as if 
2751 // the earlier occurrence(s) within the declaration are not present.  
2752 // This is also true for overriding layout-qualifier-names, where one 
2753 // overrides the other (e.g., row_major vs. column_major); only the last 
2754 // occurrence has any effect."    
2755 //
2756 void HlslParseContext::mergeObjectLayoutQualifiers(TQualifier& dst, const TQualifier& src, bool inheritOnly)
2757 {
2758     if (src.hasMatrix())
2759         dst.layoutMatrix = src.layoutMatrix;
2760     if (src.hasPacking())
2761         dst.layoutPacking = src.layoutPacking;
2762
2763     if (src.hasStream())
2764         dst.layoutStream = src.layoutStream;
2765
2766     if (src.hasFormat())
2767         dst.layoutFormat = src.layoutFormat;
2768
2769     if (src.hasXfbBuffer())
2770         dst.layoutXfbBuffer = src.layoutXfbBuffer;
2771
2772     if (src.hasAlign())
2773         dst.layoutAlign = src.layoutAlign;
2774
2775     if (! inheritOnly) {
2776         if (src.hasLocation())
2777             dst.layoutLocation = src.layoutLocation;
2778         if (src.hasComponent())
2779             dst.layoutComponent = src.layoutComponent;
2780         if (src.hasIndex())
2781             dst.layoutIndex = src.layoutIndex;
2782
2783         if (src.hasOffset())
2784             dst.layoutOffset = src.layoutOffset;
2785
2786         if (src.hasSet())
2787             dst.layoutSet = src.layoutSet;
2788         if (src.layoutBinding != TQualifier::layoutBindingEnd)
2789             dst.layoutBinding = src.layoutBinding;
2790
2791         if (src.hasXfbStride())
2792             dst.layoutXfbStride = src.layoutXfbStride;
2793         if (src.hasXfbOffset())
2794             dst.layoutXfbOffset = src.layoutXfbOffset;
2795         if (src.hasAttachment())
2796             dst.layoutAttachment = src.layoutAttachment;
2797         if (src.hasSpecConstantId())
2798             dst.layoutSpecConstantId = src.layoutSpecConstantId;
2799
2800         if (src.layoutPushConstant)
2801             dst.layoutPushConstant = true;
2802     }
2803 }
2804
2805 //
2806 // Look up a function name in the symbol table, and make sure it is a function.
2807 //
2808 // Return the function symbol if found, otherwise nullptr.
2809 //
2810 const TFunction* HlslParseContext::findFunction(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
2811 {
2812     const TFunction* function = nullptr;
2813
2814     if (symbolTable.isFunctionNameVariable(call.getName())) {
2815         error(loc, "can't use function syntax on variable", call.getName().c_str(), "");
2816         return nullptr;
2817     }
2818
2819     // first, look for an exact match
2820     TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
2821     if (symbol)
2822         return symbol->getAsFunction();
2823
2824     // exact match not found, look through a list of overloaded functions of the same name
2825
2826     const TFunction* candidate = nullptr;
2827     TVector<TFunction*> candidateList;
2828     symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
2829
2830     for (TVector<TFunction*>::const_iterator it = candidateList.begin(); it != candidateList.end(); ++it) {
2831         const TFunction& function = *(*it);
2832
2833         // to even be a potential match, number of arguments has to match
2834         if (call.getParamCount() != function.getParamCount())
2835             continue;
2836
2837         bool possibleMatch = true;
2838         for (int i = 0; i < function.getParamCount(); ++i) {
2839             // same types is easy
2840             if (*function[i].type == *call[i].type)
2841                 continue;
2842
2843             // We have a mismatch in type, see if it is implicitly convertible
2844
2845             if (function[i].type->isArray() || call[i].type->isArray() ||
2846                 ! function[i].type->sameElementShape(*call[i].type))
2847                 possibleMatch = false;
2848             else {
2849                 // do direction-specific checks for conversion of basic type
2850                 if (function[i].type->getQualifier().isParamInput()) {
2851                     if (! intermediate.canImplicitlyPromote(call[i].type->getBasicType(), function[i].type->getBasicType()))
2852                         possibleMatch = false;
2853                 }
2854                 if (function[i].type->getQualifier().isParamOutput()) {
2855                     if (! intermediate.canImplicitlyPromote(function[i].type->getBasicType(), call[i].type->getBasicType()))
2856                         possibleMatch = false;
2857                 }
2858             }
2859             if (! possibleMatch)
2860                 break;
2861         }
2862         if (possibleMatch) {
2863             if (candidate) {
2864                 // our second match, meaning ambiguity
2865                 error(loc, "ambiguous function signature match: multiple signatures match under implicit type conversion", call.getName().c_str(), "");
2866             } else
2867                 candidate = &function;
2868         }
2869     }
2870
2871     if (candidate == nullptr)
2872         error(loc, "no matching overloaded function found", call.getName().c_str(), "");
2873
2874     return candidate;
2875 }
2876
2877 //
2878 // Do everything necessary to handle a variable (non-block) declaration.
2879 // Either redeclaring a variable, or making a new one, updating the symbol
2880 // table, and all error checking.
2881 //
2882 // Returns a subtree node that computes an initializer, if needed.
2883 // Returns nullptr if there is no code to execute for initialization.
2884 //
2885 // 'publicType' is the type part of the declaration (to the left)
2886 // 'arraySizes' is the arrayness tagged on the identifier (to the right)
2887 //
2888 TIntermNode* HlslParseContext::declareVariable(const TSourceLoc& loc, TString& identifier, const TType& parseType, TArraySizes* arraySizes, TIntermTyped* initializer)
2889 {
2890     TType type;
2891     type.shallowCopy(parseType);
2892     if (type.isImplicitlySizedArray()) {
2893         // Because "int[] a = int[2](...), b = int[3](...)" makes two arrays a and b
2894         // of different sizes, for this case sharing the shallow copy of arrayness
2895         // with the publicType oversubscribes it, so get a deep copy of the arrayness.
2896         type.newArraySizes(*parseType.getArraySizes());
2897     }
2898
2899     if (voidErrorCheck(loc, identifier, type.getBasicType()))
2900         return nullptr;
2901
2902     // Check for redeclaration of built-ins and/or attempting to declare a reserved name
2903     bool newDeclaration = false;    // true if a new entry gets added to the symbol table
2904     TSymbol* symbol = nullptr; // = redeclareBuiltinVariable(loc, identifier, type.getQualifier(), publicType.shaderQualifiers, newDeclaration);
2905
2906     inheritGlobalDefaults(type.getQualifier());
2907
2908     // Declare the variable
2909     if (arraySizes || type.isArray()) {
2910         // Arrayness is potentially coming both from the type and from the 
2911         // variable: "int[] a[];" or just one or the other.
2912         // Merge it all to the type, so all arrayness is part of the type.
2913         arrayDimMerge(type, arraySizes);
2914         declareArray(loc, identifier, type, symbol, newDeclaration);
2915     } else {
2916         // non-array case
2917         if (! symbol)
2918             symbol = declareNonArray(loc, identifier, type, newDeclaration);
2919         else if (type != symbol->getType())
2920             error(loc, "cannot change the type of", "redeclaration", symbol->getName().c_str());
2921     }
2922
2923     if (! symbol)
2924         return nullptr;
2925
2926     // Deal with initializer
2927     TIntermNode* initNode = nullptr;
2928     if (symbol && initializer) {
2929         TVariable* variable = symbol->getAsVariable();
2930         if (! variable) {
2931             error(loc, "initializer requires a variable, not a member", identifier.c_str(), "");
2932             return nullptr;
2933         }
2934         initNode = executeInitializer(loc, initializer, variable);
2935     }
2936
2937     // see if it's a linker-level object to track
2938     if (newDeclaration && symbolTable.atGlobalLevel())
2939         intermediate.addSymbolLinkageNode(linkage, *symbol);
2940
2941     return initNode;
2942 }
2943
2944 // Pick up global defaults from the provide global defaults into dst.
2945 void HlslParseContext::inheritGlobalDefaults(TQualifier& dst) const
2946 {
2947     if (dst.storage == EvqVaryingOut) {
2948         if (! dst.hasStream() && language == EShLangGeometry)
2949             dst.layoutStream = globalOutputDefaults.layoutStream;
2950         if (! dst.hasXfbBuffer())
2951             dst.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
2952     }
2953 }
2954
2955 //
2956 // Make an internal-only variable whose name is for debug purposes only
2957 // and won't be searched for.  Callers will only use the return value to use
2958 // the variable, not the name to look it up.  It is okay if the name
2959 // is the same as other names; there won't be any conflict.
2960 //
2961 TVariable* HlslParseContext::makeInternalVariable(const char* name, const TType& type) const
2962 {
2963     TString* nameString = new TString(name);
2964     TVariable* variable = new TVariable(nameString, type);
2965     symbolTable.makeInternalVariable(*variable);
2966
2967     return variable;
2968 }
2969
2970 //
2971 // Declare a non-array variable, the main point being there is no redeclaration
2972 // for resizing allowed.
2973 //
2974 // Return the successfully declared variable.
2975 //
2976 TVariable* HlslParseContext::declareNonArray(const TSourceLoc& loc, TString& identifier, TType& type, bool& newDeclaration)
2977 {
2978     // make a new variable
2979     TVariable* variable = new TVariable(&identifier, type);
2980
2981     // add variable to symbol table
2982     if (! symbolTable.insert(*variable)) {
2983         error(loc, "redefinition", variable->getName().c_str(), "");
2984         return nullptr;
2985     } else {
2986         newDeclaration = true;
2987         return variable;
2988     }
2989 }
2990
2991 //
2992 // Handle all types of initializers from the grammar.
2993 //
2994 // Returning nullptr just means there is no code to execute to handle the
2995 // initializer, which will, for example, be the case for constant initializers.
2996 //
2997 TIntermNode* HlslParseContext::executeInitializer(const TSourceLoc& loc, TIntermTyped* initializer, TVariable* variable)
2998 {
2999     //
3000     // Identifier must be of type constant, a global, or a temporary, and
3001     // starting at version 120, desktop allows uniforms to have initializers.
3002     //
3003     TStorageQualifier qualifier = variable->getType().getQualifier().storage;
3004
3005     //
3006     // If the initializer was from braces { ... }, we convert the whole subtree to a
3007     // constructor-style subtree, allowing the rest of the code to operate
3008     // identically for both kinds of initializers.
3009     //
3010     initializer = convertInitializerList(loc, variable->getType(), initializer);
3011     if (! initializer) {
3012         // error recovery; don't leave const without constant values
3013         if (qualifier == EvqConst)
3014             variable->getWritableType().getQualifier().storage = EvqTemporary;
3015         return nullptr;
3016     }
3017
3018     // Fix outer arrayness if variable is unsized, getting size from the initializer
3019     if (initializer->getType().isExplicitlySizedArray() &&
3020         variable->getType().isImplicitlySizedArray())
3021         variable->getWritableType().changeOuterArraySize(initializer->getType().getOuterArraySize());
3022
3023     // Inner arrayness can also get set by an initializer
3024     if (initializer->getType().isArrayOfArrays() && variable->getType().isArrayOfArrays() &&
3025         initializer->getType().getArraySizes()->getNumDims() ==
3026         variable->getType().getArraySizes()->getNumDims()) {
3027         // adopt unsized sizes from the initializer's sizes
3028         for (int d = 1; d < variable->getType().getArraySizes()->getNumDims(); ++d) {
3029             if (variable->getType().getArraySizes()->getDimSize(d) == UnsizedArraySize)
3030                 variable->getWritableType().getArraySizes().setDimSize(d, initializer->getType().getArraySizes()->getDimSize(d));
3031         }
3032     }
3033
3034     // Uniform and global consts require a constant initializer
3035     if (qualifier == EvqUniform && initializer->getType().getQualifier().storage != EvqConst) {
3036         error(loc, "uniform initializers must be constant", "=", "'%s'", variable->getType().getCompleteString().c_str());
3037         variable->getWritableType().getQualifier().storage = EvqTemporary;
3038         return nullptr;
3039     }
3040     if (qualifier == EvqConst && symbolTable.atGlobalLevel() && initializer->getType().getQualifier().storage != EvqConst) {
3041         error(loc, "global const initializers must be constant", "=", "'%s'", variable->getType().getCompleteString().c_str());
3042         variable->getWritableType().getQualifier().storage = EvqTemporary;
3043         return nullptr;
3044     }
3045
3046     // Const variables require a constant initializer, depending on version
3047     if (qualifier == EvqConst) {
3048         if (initializer->getType().getQualifier().storage != EvqConst) {
3049             variable->getWritableType().getQualifier().storage = EvqConstReadOnly;
3050             qualifier = EvqConstReadOnly;
3051         }
3052     }
3053
3054     if (qualifier == EvqConst || qualifier == EvqUniform) {
3055         // Compile-time tagging of the variable with its constant value...
3056
3057         initializer = intermediate.addConversion(EOpAssign, variable->getType(), initializer);
3058         if (! initializer || ! initializer->getAsConstantUnion() || variable->getType() != initializer->getType()) {
3059             error(loc, "non-matching or non-convertible constant type for const initializer",
3060                 variable->getType().getStorageQualifierString(), "");
3061             variable->getWritableType().getQualifier().storage = EvqTemporary;
3062             return nullptr;
3063         }
3064
3065         variable->setConstArray(initializer->getAsConstantUnion()->getConstArray());
3066     } else {
3067         // normal assigning of a value to a variable...
3068         specializationCheck(loc, initializer->getType(), "initializer");
3069         TIntermSymbol* intermSymbol = intermediate.addSymbol(*variable, loc);
3070         TIntermNode* initNode = intermediate.addAssign(EOpAssign, intermSymbol, initializer, loc);
3071         if (! initNode)
3072             assignError(loc, "=", intermSymbol->getCompleteString(), initializer->getCompleteString());
3073
3074         return initNode;
3075     }
3076
3077     return nullptr;
3078 }
3079
3080 //
3081 // Reprocess any initializer-list { ... } parts of the initializer.
3082 // Need to hierarchically assign correct types and implicit
3083 // conversions. Will do this mimicking the same process used for
3084 // creating a constructor-style initializer, ensuring we get the
3085 // same form.
3086 //
3087 TIntermTyped* HlslParseContext::convertInitializerList(const TSourceLoc& loc, const TType& type, TIntermTyped* initializer)
3088 {
3089     // Will operate recursively.  Once a subtree is found that is constructor style,
3090     // everything below it is already good: Only the "top part" of the initializer
3091     // can be an initializer list, where "top part" can extend for several (or all) levels.
3092
3093     // see if we have bottomed out in the tree within the initializer-list part
3094     TIntermAggregate* initList = initializer->getAsAggregate();
3095     if (! initList || initList->getOp() != EOpNull)
3096         return initializer;
3097
3098     // Of the initializer-list set of nodes, need to process bottom up,
3099     // so recurse deep, then process on the way up.
3100
3101     // Go down the tree here...
3102     if (type.isArray()) {
3103         // The type's array might be unsized, which could be okay, so base sizes on the size of the aggregate.
3104         // Later on, initializer execution code will deal with array size logic.
3105         TType arrayType;
3106         arrayType.shallowCopy(type);                     // sharing struct stuff is fine
3107         arrayType.newArraySizes(*type.getArraySizes());  // but get a fresh copy of the array information, to edit below
3108
3109         // edit array sizes to fill in unsized dimensions
3110         arrayType.changeOuterArraySize((int)initList->getSequence().size());
3111         TIntermTyped* firstInit = initList->getSequence()[0]->getAsTyped();
3112         if (arrayType.isArrayOfArrays() && firstInit->getType().isArray() &&
3113             arrayType.getArraySizes().getNumDims() == firstInit->getType().getArraySizes()->getNumDims() + 1) {
3114             for (int d = 1; d < arrayType.getArraySizes().getNumDims(); ++d) {
3115                 if (arrayType.getArraySizes().getDimSize(d) == UnsizedArraySize)
3116                     arrayType.getArraySizes().setDimSize(d, firstInit->getType().getArraySizes()->getDimSize(d - 1));
3117             }
3118         }
3119
3120         TType elementType(arrayType, 0); // dereferenced type
3121         for (size_t i = 0; i < initList->getSequence().size(); ++i) {
3122             initList->getSequence()[i] = convertInitializerList(loc, elementType, initList->getSequence()[i]->getAsTyped());
3123             if (initList->getSequence()[i] == nullptr)
3124                 return nullptr;
3125         }
3126
3127         return addConstructor(loc, initList, arrayType, mapTypeToConstructorOp(arrayType));
3128     } else if (type.isStruct()) {
3129         if (type.getStruct()->size() != initList->getSequence().size()) {
3130             error(loc, "wrong number of structure members", "initializer list", "");
3131             return nullptr;
3132         }
3133         for (size_t i = 0; i < type.getStruct()->size(); ++i) {
3134             initList->getSequence()[i] = convertInitializerList(loc, *(*type.getStruct())[i].type, initList->getSequence()[i]->getAsTyped());
3135             if (initList->getSequence()[i] == nullptr)
3136                 return nullptr;
3137         }
3138     } else if (type.isMatrix()) {
3139         if (type.getMatrixCols() != (int)initList->getSequence().size()) {
3140             error(loc, "wrong number of matrix columns:", "initializer list", type.getCompleteString().c_str());
3141             return nullptr;
3142         }
3143         TType vectorType(type, 0); // dereferenced type
3144         for (int i = 0; i < type.getMatrixCols(); ++i) {
3145             initList->getSequence()[i] = convertInitializerList(loc, vectorType, initList->getSequence()[i]->getAsTyped());
3146             if (initList->getSequence()[i] == nullptr)
3147                 return nullptr;
3148         }
3149     } else if (type.isVector()) {
3150         if (type.getVectorSize() != (int)initList->getSequence().size()) {
3151             error(loc, "wrong vector size (or rows in a matrix column):", "initializer list", type.getCompleteString().c_str());
3152             return nullptr;
3153         }
3154     } else {
3155         error(loc, "unexpected initializer-list type:", "initializer list", type.getCompleteString().c_str());
3156         return nullptr;
3157     }
3158
3159     // now that the subtree is processed, process this node
3160     return addConstructor(loc, initList, type, mapTypeToConstructorOp(type));
3161 }
3162
3163 //
3164 // Test for the correctness of the parameters passed to various constructor functions
3165 // and also convert them to the right data type, if allowed and required.
3166 //
3167 // Returns nullptr for an error or the constructed node (aggregate or typed) for no error.
3168 //
3169 TIntermTyped* HlslParseContext::addConstructor(const TSourceLoc& loc, TIntermNode* node, const TType& type, TOperator op)
3170 {
3171     if (node == nullptr || node->getAsTyped() == nullptr)
3172         return nullptr;
3173
3174     TIntermAggregate* aggrNode = node->getAsAggregate();
3175
3176     // Combined texture-sampler constructors are completely semantic checked
3177     // in constructorTextureSamplerError()
3178     if (op == EOpConstructTextureSampler)
3179         return intermediate.setAggregateOperator(aggrNode, op, type, loc);
3180
3181     TTypeList::const_iterator memberTypes;
3182     if (op == EOpConstructStruct)
3183         memberTypes = type.getStruct()->begin();
3184
3185     TType elementType;
3186     if (type.isArray()) {
3187         TType dereferenced(type, 0);
3188         elementType.shallowCopy(dereferenced);
3189     } else
3190         elementType.shallowCopy(type);
3191
3192     bool singleArg;
3193     if (aggrNode) {
3194         if (aggrNode->getOp() != EOpNull || aggrNode->getSequence().size() == 1)
3195             singleArg = true;
3196         else
3197             singleArg = false;
3198     } else
3199         singleArg = true;
3200
3201     TIntermTyped *newNode;
3202     if (singleArg) {
3203         // If structure constructor or array constructor is being called
3204         // for only one parameter inside the structure, we need to call constructAggregate function once.
3205         if (type.isArray())
3206             newNode = constructAggregate(node, elementType, 1, node->getLoc());
3207         else if (op == EOpConstructStruct)
3208             newNode = constructAggregate(node, *(*memberTypes).type, 1, node->getLoc());
3209         else
3210             newNode = constructBuiltIn(type, op, node->getAsTyped(), node->getLoc(), false);
3211
3212         if (newNode && (type.isArray() || op == EOpConstructStruct))
3213             newNode = intermediate.setAggregateOperator(newNode, EOpConstructStruct, type, loc);
3214
3215         return newNode;
3216     }
3217
3218     //
3219     // Handle list of arguments.
3220     //
3221     TIntermSequence &sequenceVector = aggrNode->getSequence();    // Stores the information about the parameter to the constructor
3222     // if the structure constructor contains more than one parameter, then construct
3223     // each parameter
3224
3225     int paramCount = 0;  // keeps a track of the constructor parameter number being checked
3226
3227     // for each parameter to the constructor call, check to see if the right type is passed or convert them
3228     // to the right type if possible (and allowed).
3229     // for structure constructors, just check if the right type is passed, no conversion is allowed.
3230
3231     for (TIntermSequence::iterator p = sequenceVector.begin();
3232         p != sequenceVector.end(); p++, paramCount++) {
3233         if (type.isArray())
3234             newNode = constructAggregate(*p, elementType, paramCount + 1, node->getLoc());
3235         else if (op == EOpConstructStruct)
3236             newNode = constructAggregate(*p, *(memberTypes[paramCount]).type, paramCount + 1, node->getLoc());
3237         else
3238             newNode = constructBuiltIn(type, op, (*p)->getAsTyped(), node->getLoc(), true);
3239
3240         if (newNode)
3241             *p = newNode;
3242         else
3243             return nullptr;
3244     }
3245
3246     TIntermTyped* constructor = intermediate.setAggregateOperator(aggrNode, op, type, loc);
3247
3248     return constructor;
3249 }
3250
3251 // Function for constructor implementation. Calls addUnaryMath with appropriate EOp value
3252 // for the parameter to the constructor (passed to this function). Essentially, it converts
3253 // the parameter types correctly. If a constructor expects an int (like ivec2) and is passed a
3254 // float, then float is converted to int.
3255 //
3256 // Returns nullptr for an error or the constructed node.
3257 //
3258 TIntermTyped* HlslParseContext::constructBuiltIn(const TType& type, TOperator op, TIntermTyped* node, const TSourceLoc& loc, bool subset)
3259 {
3260     TIntermTyped* newNode;
3261     TOperator basicOp;
3262
3263     //
3264     // First, convert types as needed.
3265     //
3266     switch (op) {
3267     case EOpConstructVec2:
3268     case EOpConstructVec3:
3269     case EOpConstructVec4:
3270     case EOpConstructMat2x2:
3271     case EOpConstructMat2x3:
3272     case EOpConstructMat2x4:
3273     case EOpConstructMat3x2:
3274     case EOpConstructMat3x3:
3275     case EOpConstructMat3x4:
3276     case EOpConstructMat4x2:
3277     case EOpConstructMat4x3:
3278     case EOpConstructMat4x4:
3279     case EOpConstructFloat:
3280         basicOp = EOpConstructFloat;
3281         break;
3282
3283     case EOpConstructDVec2:
3284     case EOpConstructDVec3:
3285     case EOpConstructDVec4:
3286     case EOpConstructDMat2x2:
3287     case EOpConstructDMat2x3:
3288     case EOpConstructDMat2x4:
3289     case EOpConstructDMat3x2:
3290     case EOpConstructDMat3x3:
3291     case EOpConstructDMat3x4:
3292     case EOpConstructDMat4x2:
3293     case EOpConstructDMat4x3:
3294     case EOpConstructDMat4x4:
3295     case EOpConstructDouble:
3296         basicOp = EOpConstructDouble;
3297         break;
3298
3299     case EOpConstructIVec2:
3300     case EOpConstructIVec3:
3301     case EOpConstructIVec4:
3302     case EOpConstructInt:
3303         basicOp = EOpConstructInt;
3304         break;
3305
3306     case EOpConstructUVec2:
3307     case EOpConstructUVec3:
3308     case EOpConstructUVec4:
3309     case EOpConstructUint:
3310         basicOp = EOpConstructUint;
3311         break;
3312
3313     case EOpConstructBVec2:
3314     case EOpConstructBVec3:
3315     case EOpConstructBVec4:
3316     case EOpConstructBool:
3317         basicOp = EOpConstructBool;
3318         break;
3319
3320     default:
3321         error(loc, "unsupported construction", "", "");
3322
3323         return nullptr;
3324     }
3325     newNode = intermediate.addUnaryMath(basicOp, node, node->getLoc());
3326     if (newNode == nullptr) {
3327         error(loc, "can't convert", "constructor", "");
3328         return nullptr;
3329     }
3330
3331     //
3332     // Now, if there still isn't an operation to do the construction, and we need one, add one.
3333     //
3334
3335     // Otherwise, skip out early.
3336     if (subset || (newNode != node && newNode->getType() == type))
3337         return newNode;
3338
3339     // setAggregateOperator will insert a new node for the constructor, as needed.
3340     return intermediate.setAggregateOperator(newNode, op, type, loc);
3341 }
3342
3343 // This function tests for the type of the parameters to the structure or array constructor. Raises
3344 // an error message if the expected type does not match the parameter passed to the constructor.
3345 //
3346 // Returns nullptr for an error or the input node itself if the expected and the given parameter types match.
3347 //
3348 TIntermTyped* HlslParseContext::constructAggregate(TIntermNode* node, const TType& type, int paramCount, const TSourceLoc& loc)
3349 {
3350     TIntermTyped* converted = intermediate.addConversion(EOpConstructStruct, type, node->getAsTyped());
3351     if (! converted || converted->getType() != type) {
3352         error(loc, "", "constructor", "cannot convert parameter %d from '%s' to '%s'", paramCount,
3353             node->getAsTyped()->getType().getCompleteString().c_str(), type.getCompleteString().c_str());
3354
3355         return nullptr;
3356     }
3357
3358     return converted;
3359 }
3360
3361 //
3362 // Do everything needed to add an interface block.
3363 //
3364 void HlslParseContext::declareBlock(const TSourceLoc& loc, TTypeList& typeList, const TString* instanceName, TArraySizes* arraySizes)
3365 {
3366     // fix and check for member storage qualifiers and types that don't belong within a block
3367     for (unsigned int member = 0; member < typeList.size(); ++member) {
3368         TType& memberType = *typeList[member].type;
3369         TQualifier& memberQualifier = memberType.getQualifier();
3370         const TSourceLoc& memberLoc = typeList[member].loc;
3371         globalQualifierFix(memberLoc, memberQualifier);
3372         memberQualifier.storage = currentBlockQualifier.storage;
3373     }
3374
3375     // This might be a redeclaration of a built-in block.  If so, redeclareBuiltinBlock() will
3376     // do all the rest.
3377     if (! symbolTable.atBuiltInLevel() && builtInName(*blockName)) {
3378         redeclareBuiltinBlock(loc, typeList, *blockName, instanceName, arraySizes);
3379         return;
3380     }
3381
3382     // Make default block qualification, and adjust the member qualifications
3383
3384     TQualifier defaultQualification;
3385     switch (currentBlockQualifier.storage) {
3386     case EvqUniform:    defaultQualification = globalUniformDefaults;    break;
3387     case EvqBuffer:     defaultQualification = globalBufferDefaults;     break;
3388     case EvqVaryingIn:  defaultQualification = globalInputDefaults;      break;
3389     case EvqVaryingOut: defaultQualification = globalOutputDefaults;     break;
3390     default:            defaultQualification.clear();                    break;
3391     }
3392
3393     // Special case for "push_constant uniform", which has a default of std430,
3394     // contrary to normal uniform defaults, and can't have a default tracked for it.
3395     if (currentBlockQualifier.layoutPushConstant && ! currentBlockQualifier.hasPacking())
3396         currentBlockQualifier.layoutPacking = ElpStd430;
3397
3398     // fix and check for member layout qualifiers
3399
3400     mergeObjectLayoutQualifiers(defaultQualification, currentBlockQualifier, true);
3401
3402     bool memberWithLocation = false;
3403     bool memberWithoutLocation = false;
3404     for (unsigned int member = 0; member < typeList.size(); ++member) {
3405         TQualifier& memberQualifier = typeList[member].type->getQualifier();
3406         const TSourceLoc& memberLoc = typeList[member].loc;
3407         if (memberQualifier.hasStream()) {
3408             if (defaultQualification.layoutStream != memberQualifier.layoutStream)
3409                 error(memberLoc, "member cannot contradict block", "stream", "");
3410         }
3411
3412         // "This includes a block's inheritance of the 
3413         // current global default buffer, a block member's inheritance of the block's 
3414         // buffer, and the requirement that any *xfb_buffer* declared on a block 
3415         // member must match the buffer inherited from the block."
3416         if (memberQualifier.hasXfbBuffer()) {
3417             if (defaultQualification.layoutXfbBuffer != memberQualifier.layoutXfbBuffer)
3418                 error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_buffer", "");
3419         }
3420
3421         if (memberQualifier.hasPacking())
3422             error(memberLoc, "member of block cannot have a packing layout qualifier", typeList[member].type->getFieldName().c_str(), "");
3423         if (memberQualifier.hasLocation()) {
3424             switch (currentBlockQualifier.storage) {
3425             case EvqVaryingIn:
3426             case EvqVaryingOut:
3427                 memberWithLocation = true;
3428                 break;
3429             default:
3430                 break;
3431             }
3432         } else
3433             memberWithoutLocation = true;
3434         if (memberQualifier.hasAlign()) {
3435             if (defaultQualification.layoutPacking != ElpStd140 && defaultQualification.layoutPacking != ElpStd430)
3436                 error(memberLoc, "can only be used with std140 or std430 layout packing", "align", "");
3437         }
3438
3439         TQualifier newMemberQualification = defaultQualification;
3440         mergeQualifiers(memberLoc, newMemberQualification, memberQualifier, false);
3441         memberQualifier = newMemberQualification;
3442     }
3443
3444     // Process the members
3445     fixBlockLocations(loc, currentBlockQualifier, typeList, memberWithLocation, memberWithoutLocation);
3446     fixBlockXfbOffsets(currentBlockQualifier, typeList);
3447     fixBlockUniformOffsets(currentBlockQualifier, typeList);
3448
3449     // reverse merge, so that currentBlockQualifier now has all layout information
3450     // (can't use defaultQualification directly, it's missing other non-layout-default-class qualifiers)
3451     mergeObjectLayoutQualifiers(currentBlockQualifier, defaultQualification, true);
3452
3453     //
3454     // Build and add the interface block as a new type named 'blockName'
3455     //
3456
3457     TType blockType(&typeList, *blockName, currentBlockQualifier);
3458     if (arraySizes)
3459         blockType.newArraySizes(*arraySizes);
3460
3461     //
3462     // Don't make a user-defined type out of block name; that will cause an error
3463     // if the same block name gets reused in a different interface.
3464     //
3465     // "Block names have no other use within a shader
3466     // beyond interface matching; it is a compile-time error to use a block name at global scope for anything
3467     // other than as a block name (e.g., use of a block name for a global variable name or function name is
3468     // currently reserved)."
3469     //
3470     // Use the symbol table to prevent normal reuse of the block's name, as a variable entry,
3471     // whose type is EbtBlock, but without all the structure; that will come from the type
3472     // the instances point to.
3473     //
3474     TType blockNameType(EbtBlock, blockType.getQualifier().storage);
3475     TVariable* blockNameVar = new TVariable(blockName, blockNameType);
3476     if (! symbolTable.insert(*blockNameVar)) {
3477         TSymbol* existingName = symbolTable.find(*blockName);
3478         if (existingName->getType().getBasicType() == EbtBlock) {
3479             if (existingName->getType().getQualifier().storage == blockType.getQualifier().storage) {
3480                 error(loc, "Cannot reuse block name within the same interface:", blockName->c_str(), blockType.getStorageQualifierString());
3481                 return;
3482             }
3483         } else {
3484             error(loc, "block name cannot redefine a non-block name", blockName->c_str(), "");
3485             return;
3486         }
3487     }
3488
3489     // Add the variable, as anonymous or named instanceName.
3490     // Make an anonymous variable if no name was provided.
3491     if (! instanceName)
3492         instanceName = NewPoolTString("");
3493
3494     TVariable& variable = *new TVariable(instanceName, blockType);
3495     if (! symbolTable.insert(variable)) {
3496         if (*instanceName == "")
3497             error(loc, "nameless block contains a member that already has a name at global scope", blockName->c_str(), "");
3498         else
3499             error(loc, "block instance name redefinition", variable.getName().c_str(), "");
3500
3501         return;
3502     }
3503
3504     if (isIoResizeArray(blockType)) {
3505         ioArraySymbolResizeList.push_back(&variable);
3506         checkIoArraysConsistency(loc, true);
3507     } else
3508         fixIoArraySize(loc, variable.getWritableType());
3509
3510     // Save it in the AST for linker use.
3511     intermediate.addSymbolLinkageNode(linkage, variable);
3512 }
3513
3514 //
3515 // "For a block, this process applies to the entire block, or until the first member 
3516 // is reached that has a location layout qualifier. When a block member is declared with a location 
3517 // qualifier, its location comes from that qualifier: The member's location qualifier overrides the block-level
3518 // declaration. Subsequent members are again assigned consecutive locations, based on the newest location, 
3519 // until the next member declared with a location qualifier. The values used for locations do not have to be 
3520 // declared in increasing order."
3521 void HlslParseContext::fixBlockLocations(const TSourceLoc& loc, TQualifier& qualifier, TTypeList& typeList, bool memberWithLocation, bool memberWithoutLocation)
3522 {
3523     // "If a block has no block-level location layout qualifier, it is required that either all or none of its members 
3524     // have a location layout qualifier, or a compile-time error results."
3525     if (! qualifier.hasLocation() && memberWithLocation && memberWithoutLocation)
3526         error(loc, "either the block needs a location, or all members need a location, or no members have a location", "location", "");
3527     else {
3528         if (memberWithLocation) {
3529             // remove any block-level location and make it per *every* member
3530             int nextLocation = 0;  // by the rule above, initial value is not relevant
3531             if (qualifier.hasAnyLocation()) {
3532                 nextLocation = qualifier.layoutLocation;
3533                 qualifier.layoutLocation = TQualifier::layoutLocationEnd;
3534                 if (qualifier.hasComponent()) {
3535                     // "It is a compile-time error to apply the *component* qualifier to a ... block"
3536                     error(loc, "cannot apply to a block", "component", "");
3537                 }
3538                 if (qualifier.hasIndex()) {
3539                     error(loc, "cannot apply to a block", "index", "");
3540                 }
3541             }
3542             for (unsigned int member = 0; member < typeList.size(); ++member) {
3543                 TQualifier& memberQualifier = typeList[member].type->getQualifier();
3544                 const TSourceLoc& memberLoc = typeList[member].loc;
3545                 if (! memberQualifier.hasLocation()) {
3546                     if (nextLocation >= (int)TQualifier::layoutLocationEnd)
3547                         error(memberLoc, "location is too large", "location", "");
3548                     memberQualifier.layoutLocation = nextLocation;
3549                     memberQualifier.layoutComponent = 0;
3550                 }
3551                 nextLocation = memberQualifier.layoutLocation + intermediate.computeTypeLocationSize(*typeList[member].type);
3552             }
3553         }
3554     }
3555 }
3556
3557 void HlslParseContext::fixBlockXfbOffsets(TQualifier& qualifier, TTypeList& typeList)
3558 {
3559     // "If a block is qualified with xfb_offset, all its 
3560     // members are assigned transform feedback buffer offsets. If a block is not qualified with xfb_offset, any 
3561     // members of that block not qualified with an xfb_offset will not be assigned transform feedback buffer 
3562     // offsets."
3563
3564     if (! qualifier.hasXfbBuffer() || ! qualifier.hasXfbOffset())
3565         return;
3566
3567     int nextOffset = qualifier.layoutXfbOffset;
3568     for (unsigned int member = 0; member < typeList.size(); ++member) {
3569         TQualifier& memberQualifier = typeList[member].type->getQualifier();
3570         bool containsDouble = false;
3571         int memberSize = intermediate.computeTypeXfbSize(*typeList[member].type, containsDouble);
3572         // see if we need to auto-assign an offset to this member
3573         if (! memberQualifier.hasXfbOffset()) {
3574             // "if applied to an aggregate containing a double, the offset must also be a multiple of 8"
3575             if (containsDouble)
3576                 RoundToPow2(nextOffset, 8);
3577             memberQualifier.layoutXfbOffset = nextOffset;
3578         } else
3579             nextOffset = memberQualifier.layoutXfbOffset;
3580         nextOffset += memberSize;
3581     }
3582
3583     // The above gave all block members an offset, so we can take it off the block now,
3584     // which will avoid double counting the offset usage.
3585     qualifier.layoutXfbOffset = TQualifier::layoutXfbOffsetEnd;
3586 }
3587
3588 // Calculate and save the offset of each block member, using the recursively 
3589 // defined block offset rules and the user-provided offset and align.
3590 //
3591 // Also, compute and save the total size of the block. For the block's size, arrayness 
3592 // is not taken into account, as each element is backed by a separate buffer.
3593 //
3594 void HlslParseContext::fixBlockUniformOffsets(TQualifier& qualifier, TTypeList& typeList)
3595 {
3596     if (! qualifier.isUniformOrBuffer())
3597         return;
3598     if (qualifier.layoutPacking != ElpStd140 && qualifier.layoutPacking != ElpStd430)
3599         return;
3600
3601     int offset = 0;
3602     int memberSize;
3603     for (unsigned int member = 0; member < typeList.size(); ++member) {
3604         TQualifier& memberQualifier = typeList[member].type->getQualifier();
3605         const TSourceLoc& memberLoc = typeList[member].loc;
3606
3607         // "When align is applied to an array, it effects only the start of the array, not the array's internal stride."
3608
3609         // modify just the children's view of matrix layout, if there is one for this member
3610         TLayoutMatrix subMatrixLayout = typeList[member].type->getQualifier().layoutMatrix;
3611         int dummyStride;
3612         int memberAlignment = intermediate.getBaseAlignment(*typeList[member].type, memberSize, dummyStride, qualifier.layoutPacking == ElpStd140,
3613             subMatrixLayout != ElmNone ? subMatrixLayout == ElmRowMajor : qualifier.layoutMatrix == ElmRowMajor);
3614         if (memberQualifier.hasOffset()) {
3615             // "The specified offset must be a multiple 
3616             // of the base alignment of the type of the block member it qualifies, or a compile-time error results."
3617             if (! IsMultipleOfPow2(memberQualifier.layoutOffset, memberAlignment))
3618                 error(memberLoc, "must be a multiple of the member's alignment", "offset", "");
3619
3620             // "It is a compile-time error to specify an offset that is smaller than the offset of the previous 
3621             // member in the block or that lies within the previous member of the block"
3622             if (memberQualifier.layoutOffset < offset)
3623                 error(memberLoc, "cannot lie in previous members", "offset", "");
3624
3625             // "The offset qualifier forces the qualified member to start at or after the specified 
3626             // integral-constant expression, which will be its byte offset from the beginning of the buffer. 
3627             // "The actual offset of a member is computed as 
3628             // follows: If offset was declared, start with that offset, otherwise start with the next available offset."
3629             offset = std::max(offset, memberQualifier.layoutOffset);
3630         }
3631
3632         // "The actual alignment of a member will be the greater of the specified align alignment and the standard 
3633         // (e.g., std140) base alignment for the member's type."
3634         if (memberQualifier.hasAlign())
3635             memberAlignment = std::max(memberAlignment, memberQualifier.layoutAlign);
3636
3637         // "If the resulting offset is not a multiple of the actual alignment,
3638         // increase it to the first offset that is a multiple of 
3639         // the actual alignment."
3640         RoundToPow2(offset, memberAlignment);
3641         typeList[member].type->getQualifier().layoutOffset = offset;
3642         offset += memberSize;
3643     }
3644 }
3645
3646 // For an identifier that is already declared, add more qualification to it.
3647 void HlslParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, const TString& identifier)
3648 {
3649     TSymbol* symbol = symbolTable.find(identifier);
3650     if (! symbol) {
3651         error(loc, "identifier not previously declared", identifier.c_str(), "");
3652         return;
3653     }
3654     if (symbol->getAsFunction()) {
3655         error(loc, "cannot re-qualify a function name", identifier.c_str(), "");
3656         return;
3657     }
3658
3659     if (qualifier.isAuxiliary() ||
3660         qualifier.isMemory() ||
3661         qualifier.isInterpolation() ||
3662         qualifier.hasLayout() ||
3663         qualifier.storage != EvqTemporary ||
3664         qualifier.precision != EpqNone) {
3665         error(loc, "cannot add storage, auxiliary, memory, interpolation, layout, or precision qualifier to an existing variable", identifier.c_str(), "");
3666         return;
3667     }
3668
3669     // For read-only built-ins, add a new symbol for holding the modified qualifier.
3670     // This will bring up an entire block, if a block type has to be modified (e.g., gl_Position inside a block)
3671     if (symbol->isReadOnly())
3672         symbol = symbolTable.copyUp(symbol);
3673
3674     if (qualifier.invariant) {
3675         if (intermediate.inIoAccessed(identifier))
3676             error(loc, "cannot change qualification after use", "invariant", "");
3677         symbol->getWritableType().getQualifier().invariant = true;
3678     } else if (qualifier.noContraction) {
3679         if (intermediate.inIoAccessed(identifier))
3680             error(loc, "cannot change qualification after use", "precise", "");
3681         symbol->getWritableType().getQualifier().noContraction = true;
3682     } else if (qualifier.specConstant) {
3683         symbol->getWritableType().getQualifier().makeSpecConstant();
3684         if (qualifier.hasSpecConstantId())
3685             symbol->getWritableType().getQualifier().layoutSpecConstantId = qualifier.layoutSpecConstantId;
3686     } else
3687         warn(loc, "unknown requalification", "", "");
3688 }
3689
3690 void HlslParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, TIdentifierList& identifiers)
3691 {
3692     for (unsigned int i = 0; i < identifiers.size(); ++i)
3693         addQualifierToExisting(loc, qualifier, *identifiers[i]);
3694 }
3695
3696 //
3697 // Updating default qualifier for the case of a declaration with just a qualifier,
3698 // no type, block, or identifier.
3699 //
3700 void HlslParseContext::updateStandaloneQualifierDefaults(const TSourceLoc& loc, const TPublicType& publicType)
3701 {
3702     if (publicType.shaderQualifiers.vertices != TQualifier::layoutNotSet) {
3703         assert(language == EShLangTessControl || language == EShLangGeometry);
3704         const char* id = (language == EShLangTessControl) ? "vertices" : "max_vertices";
3705
3706         if (language == EShLangTessControl)
3707             checkIoArraysConsistency(loc);
3708     }
3709     if (publicType.shaderQualifiers.invocations != TQualifier::layoutNotSet) {
3710         if (! intermediate.setInvocations(publicType.shaderQualifiers.invocations))
3711             error(loc, "cannot change previously set layout value", "invocations", "");
3712     }
3713     if (publicType.shaderQualifiers.geometry != ElgNone) {
3714         if (publicType.qualifier.storage == EvqVaryingIn) {
3715             switch (publicType.shaderQualifiers.geometry) {
3716             case ElgPoints:
3717             case ElgLines:
3718             case ElgLinesAdjacency:
3719             case ElgTriangles:
3720             case ElgTrianglesAdjacency:
3721             case ElgQuads:
3722             case ElgIsolines:
3723                 if (intermediate.setInputPrimitive(publicType.shaderQualifiers.geometry)) {
3724                     if (language == EShLangGeometry)
3725                         checkIoArraysConsistency(loc);
3726                 } else
3727                     error(loc, "cannot change previously set input primitive", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
3728                 break;
3729             default:
3730                 error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
3731             }
3732         } else if (publicType.qualifier.storage == EvqVaryingOut) {
3733             switch (publicType.shaderQualifiers.geometry) {
3734             case ElgPoints:
3735             case ElgLineStrip:
3736             case ElgTriangleStrip:
3737                 if (! intermediate.setOutputPrimitive(publicType.shaderQualifiers.geometry))
3738                     error(loc, "cannot change previously set output primitive", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
3739                 break;
3740             default:
3741                 error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
3742             }
3743         } else
3744             error(loc, "cannot apply to:", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), GetStorageQualifierString(publicType.qualifier.storage));
3745     }
3746     if (publicType.shaderQualifiers.spacing != EvsNone)
3747         intermediate.setVertexSpacing(publicType.shaderQualifiers.spacing);
3748     if (publicType.shaderQualifiers.order != EvoNone)
3749         intermediate.setVertexOrder(publicType.shaderQualifiers.order);
3750     if (publicType.shaderQualifiers.pointMode)
3751         intermediate.setPointMode();
3752     for (int i = 0; i < 3; ++i) {
3753         if (publicType.shaderQualifiers.localSize[i] > 1) {
3754             int max = 0;
3755             switch (i) {
3756             case 0: max = resources.maxComputeWorkGroupSizeX; break;
3757             case 1: max = resources.maxComputeWorkGroupSizeY; break;
3758             case 2: max = resources.maxComputeWorkGroupSizeZ; break;
3759             default: break;
3760             }
3761             if (intermediate.getLocalSize(i) > (unsigned int)max)
3762                 error(loc, "too large; see gl_MaxComputeWorkGroupSize", "local_size", "");
3763
3764             // Fix the existing constant gl_WorkGroupSize with this new information.
3765             TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
3766             workGroupSize->getWritableConstArray()[i].setUConst(intermediate.getLocalSize(i));
3767         }
3768         if (publicType.shaderQualifiers.localSizeSpecId[i] != TQualifier::layoutNotSet) {
3769             intermediate.setLocalSizeSpecId(i, publicType.shaderQualifiers.localSizeSpecId[i]);
3770             // Set the workgroup built-in variable as a specialization constant
3771             TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
3772             workGroupSize->getWritableType().getQualifier().specConstant = true;
3773         }
3774     }
3775     if (publicType.shaderQualifiers.earlyFragmentTests)
3776         intermediate.setEarlyFragmentTests();
3777
3778     const TQualifier& qualifier = publicType.qualifier;
3779
3780     switch (qualifier.storage) {
3781     case EvqUniform:
3782         if (qualifier.hasMatrix())
3783             globalUniformDefaults.layoutMatrix = qualifier.layoutMatrix;
3784         if (qualifier.hasPacking())
3785             globalUniformDefaults.layoutPacking = qualifier.layoutPacking;
3786         break;
3787     case EvqBuffer:
3788         if (qualifier.hasMatrix())
3789             globalBufferDefaults.layoutMatrix = qualifier.layoutMatrix;
3790         if (qualifier.hasPacking())
3791             globalBufferDefaults.layoutPacking = qualifier.layoutPacking;
3792         break;
3793     case EvqVaryingIn:
3794         break;
3795     case EvqVaryingOut:
3796         if (qualifier.hasStream())
3797             globalOutputDefaults.layoutStream = qualifier.layoutStream;
3798         if (qualifier.hasXfbBuffer())
3799             globalOutputDefaults.layoutXfbBuffer = qualifier.layoutXfbBuffer;
3800         if (globalOutputDefaults.hasXfbBuffer() && qualifier.hasXfbStride()) {
3801             if (! intermediate.setXfbBufferStride(globalOutputDefaults.layoutXfbBuffer, qualifier.layoutXfbStride))
3802                 error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d", qualifier.layoutXfbBuffer);
3803         }
3804         break;
3805     default:
3806         error(loc, "default qualifier requires 'uniform', 'buffer', 'in', or 'out' storage qualification", "", "");
3807         return;
3808     }
3809 }
3810
3811 //
3812 // Take the sequence of statements that has been built up since the last case/default,
3813 // put it on the list of top-level nodes for the current (inner-most) switch statement,
3814 // and follow that by the case/default we are on now.  (See switch topology comment on
3815 // TIntermSwitch.)
3816 //
3817 void HlslParseContext::wrapupSwitchSubsequence(TIntermAggregate* statements, TIntermNode* branchNode)
3818 {
3819     TIntermSequence* switchSequence = switchSequenceStack.back();
3820
3821     if (statements) {
3822         if (switchSequence->size() == 0)
3823             error(statements->getLoc(), "cannot have statements before first case/default label", "switch", "");
3824         statements->setOperator(EOpSequence);
3825         switchSequence->push_back(statements);
3826     }
3827     if (branchNode) {
3828         // check all previous cases for the same label (or both are 'default')
3829         for (unsigned int s = 0; s < switchSequence->size(); ++s) {
3830             TIntermBranch* prevBranch = (*switchSequence)[s]->getAsBranchNode();
3831             if (prevBranch) {
3832                 TIntermTyped* prevExpression = prevBranch->getExpression();
3833                 TIntermTyped* newExpression = branchNode->getAsBranchNode()->getExpression();
3834                 if (prevExpression == nullptr && newExpression == nullptr)
3835                     error(branchNode->getLoc(), "duplicate label", "default", "");
3836                 else if (prevExpression != nullptr &&
3837                     newExpression != nullptr &&
3838                     prevExpression->getAsConstantUnion() &&
3839                     newExpression->getAsConstantUnion() &&
3840                     prevExpression->getAsConstantUnion()->getConstArray()[0].getIConst() ==
3841                     newExpression->getAsConstantUnion()->getConstArray()[0].getIConst())
3842                     error(branchNode->getLoc(), "duplicated value", "case", "");
3843             }
3844         }
3845         switchSequence->push_back(branchNode);
3846     }
3847 }
3848
3849 //
3850 // Turn the top-level node sequence built up of wrapupSwitchSubsequence
3851 // into a switch node.
3852 //
3853 TIntermNode* HlslParseContext::addSwitch(const TSourceLoc& loc, TIntermTyped* expression, TIntermAggregate* lastStatements)
3854 {
3855     wrapupSwitchSubsequence(lastStatements, nullptr);
3856
3857     if (expression == nullptr ||
3858         (expression->getBasicType() != EbtInt && expression->getBasicType() != EbtUint) ||
3859         expression->getType().isArray() || expression->getType().isMatrix() || expression->getType().isVector())
3860         error(loc, "condition must be a scalar integer expression", "switch", "");
3861
3862     // If there is nothing to do, drop the switch but still execute the expression
3863     TIntermSequence* switchSequence = switchSequenceStack.back();
3864     if (switchSequence->size() == 0)
3865         return expression;
3866
3867     if (lastStatements == nullptr) {
3868         // emulate a break for error recovery
3869         lastStatements = intermediate.makeAggregate(intermediate.addBranch(EOpBreak, loc));
3870         lastStatements->setOperator(EOpSequence);
3871         switchSequence->push_back(lastStatements);
3872     }
3873
3874     TIntermAggregate* body = new TIntermAggregate(EOpSequence);
3875     body->getSequence() = *switchSequenceStack.back();
3876     body->setLoc(loc);
3877
3878     TIntermSwitch* switchNode = new TIntermSwitch(expression, body);
3879     switchNode->setLoc(loc);
3880
3881     return switchNode;
3882 }
3883
3884 } // end namespace glslang