HLSL: Fix #1432: Globally initialize local static variables.
[platform/upstream/glslang.git] / hlsl / hlslParseHelper.cpp
1 //
2 // Copyright (C) 2017 Google, Inc.
3 // Copyright (C) 2017 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 #include "hlslAttributes.h"
41
42 #include "../glslang/MachineIndependent/Scan.h"
43 #include "../glslang/MachineIndependent/preprocessor/PpContext.h"
44
45 #include "../glslang/OSDependent/osinclude.h"
46
47 #include <algorithm>
48 #include <functional>
49 #include <cctype>
50 #include <array>
51 #include <set>
52
53 namespace glslang {
54
55 HlslParseContext::HlslParseContext(TSymbolTable& symbolTable, TIntermediate& interm, bool parsingBuiltins,
56                                    int version, EProfile profile, const SpvVersion& spvVersion, EShLanguage language,
57                                    TInfoSink& infoSink,
58                                    const TString sourceEntryPointName,
59                                    bool forwardCompatible, EShMessages messages) :
60     TParseContextBase(symbolTable, interm, parsingBuiltins, version, profile, spvVersion, language, infoSink,
61                       forwardCompatible, messages, &sourceEntryPointName),
62     annotationNestingLevel(0),
63     inputPatch(nullptr),
64     nextInLocation(0), nextOutLocation(0),
65     entryPointFunction(nullptr),
66     entryPointFunctionBody(nullptr),
67     gsStreamOutput(nullptr),
68     clipDistanceOutput(nullptr),
69     cullDistanceOutput(nullptr),
70     clipDistanceInput(nullptr),
71     cullDistanceInput(nullptr)
72 {
73     globalUniformDefaults.clear();
74     globalUniformDefaults.layoutMatrix = ElmRowMajor;
75     globalUniformDefaults.layoutPacking = ElpStd140;
76
77     globalBufferDefaults.clear();
78     globalBufferDefaults.layoutMatrix = ElmRowMajor;
79     globalBufferDefaults.layoutPacking = ElpStd430;
80
81     globalInputDefaults.clear();
82     globalOutputDefaults.clear();
83
84     clipSemanticNSizeIn.fill(0);
85     cullSemanticNSizeIn.fill(0);
86     clipSemanticNSizeOut.fill(0);
87     cullSemanticNSizeOut.fill(0);
88
89     // "Shaders in the transform
90     // feedback capturing mode have an initial global default of
91     //     layout(xfb_buffer = 0) out;"
92     if (language == EShLangVertex ||
93         language == EShLangTessControl ||
94         language == EShLangTessEvaluation ||
95         language == EShLangGeometry)
96         globalOutputDefaults.layoutXfbBuffer = 0;
97
98     if (language == EShLangGeometry)
99         globalOutputDefaults.layoutStream = 0;
100
101     if (spvVersion.spv == 0 || spvVersion.vulkan == 0)
102         infoSink.info << "ERROR: HLSL currently only supported when requesting SPIR-V for Vulkan.\n";
103 }
104
105 HlslParseContext::~HlslParseContext()
106 {
107 }
108
109 void HlslParseContext::initializeExtensionBehavior()
110 {
111     TParseContextBase::initializeExtensionBehavior();
112
113     // HLSL allows #line by default.
114     extensionBehavior[E_GL_GOOGLE_cpp_style_line_directive] = EBhEnable;
115 }
116
117 void HlslParseContext::setLimits(const TBuiltInResource& r)
118 {
119     resources = r;
120     intermediate.setLimits(resources);
121 }
122
123 //
124 // Parse an array of strings using the parser in HlslRules.
125 //
126 // Returns true for successful acceptance of the shader, false if any errors.
127 //
128 bool HlslParseContext::parseShaderStrings(TPpContext& ppContext, TInputScanner& input, bool versionWillBeError)
129 {
130     currentScanner = &input;
131     ppContext.setInput(input, versionWillBeError);
132
133     HlslScanContext scanContext(*this, ppContext);
134     HlslGrammar grammar(scanContext, *this);
135     if (!grammar.parse()) {
136         // Print a message formated such that if you click on the message it will take you right to
137         // the line through most UIs.
138         const glslang::TSourceLoc& sourceLoc = input.getSourceLoc();
139         infoSink.info << sourceLoc.name << "(" << sourceLoc.line << "): error at column " << sourceLoc.column
140                       << ", HLSL parsing failed.\n";
141         ++numErrors;
142         return false;
143     }
144
145     finish();
146
147     return numErrors == 0;
148 }
149
150 //
151 // Return true if this l-value node should be converted in some manner.
152 // For instance: turning a load aggregate into a store in an l-value.
153 //
154 bool HlslParseContext::shouldConvertLValue(const TIntermNode* node) const
155 {
156     if (node == nullptr || node->getAsTyped() == nullptr)
157         return false;
158
159     const TIntermAggregate* lhsAsAggregate = node->getAsAggregate();
160     const TIntermBinary* lhsAsBinary = node->getAsBinaryNode();
161
162     // If it's a swizzled/indexed aggregate, look at the left node instead.
163     if (lhsAsBinary != nullptr &&
164         (lhsAsBinary->getOp() == EOpVectorSwizzle || lhsAsBinary->getOp() == EOpIndexDirect))
165         lhsAsAggregate = lhsAsBinary->getLeft()->getAsAggregate();
166     if (lhsAsAggregate != nullptr && lhsAsAggregate->getOp() == EOpImageLoad)
167         return true;
168
169     return false;
170 }
171
172 void HlslParseContext::growGlobalUniformBlock(const TSourceLoc& loc, TType& memberType, const TString& memberName,
173                                               TTypeList* newTypeList)
174 {
175     newTypeList = nullptr;
176     correctUniform(memberType.getQualifier());
177     if (memberType.isStruct()) {
178         auto it = ioTypeMap.find(memberType.getStruct());
179         if (it != ioTypeMap.end() && it->second.uniform)
180             newTypeList = it->second.uniform;
181     }
182     TParseContextBase::growGlobalUniformBlock(loc, memberType, memberName, newTypeList);
183 }
184
185 //
186 // Return a TLayoutFormat corresponding to the given texture type.
187 //
188 TLayoutFormat HlslParseContext::getLayoutFromTxType(const TSourceLoc& loc, const TType& txType)
189 {
190     if (txType.isStruct()) {
191         // TODO: implement.
192         error(loc, "unimplemented: structure type in image or buffer", "", "");
193         return ElfNone;
194     }
195
196     const int components = txType.getVectorSize();
197     const TBasicType txBasicType = txType.getBasicType();
198
199     const auto selectFormat = [this,&components](TLayoutFormat v1, TLayoutFormat v2, TLayoutFormat v4) -> TLayoutFormat {
200         if (intermediate.getNoStorageFormat())
201             return ElfNone;
202
203         return components == 1 ? v1 :
204                components == 2 ? v2 : v4;
205     };
206
207     switch (txBasicType) {
208     case EbtFloat: return selectFormat(ElfR32f,  ElfRg32f,  ElfRgba32f);
209     case EbtInt:   return selectFormat(ElfR32i,  ElfRg32i,  ElfRgba32i);
210     case EbtUint:  return selectFormat(ElfR32ui, ElfRg32ui, ElfRgba32ui);
211     default:
212         error(loc, "unknown basic type in image format", "", "");
213         return ElfNone;
214     }
215 }
216
217 //
218 // Both test and if necessary, spit out an error, to see if the node is really
219 // an l-value that can be operated on this way.
220 //
221 // Returns true if there was an error.
222 //
223 bool HlslParseContext::lValueErrorCheck(const TSourceLoc& loc, const char* op, TIntermTyped* node)
224 {
225     if (shouldConvertLValue(node)) {
226         // if we're writing to a texture, it must be an RW form.
227
228         TIntermAggregate* lhsAsAggregate = node->getAsAggregate();
229         TIntermTyped* object = lhsAsAggregate->getSequence()[0]->getAsTyped();
230
231         if (!object->getType().getSampler().isImage()) {
232             error(loc, "operator[] on a non-RW texture must be an r-value", "", "");
233             return true;
234         }
235     }
236
237     // We tolerate samplers as l-values, even though they are nominally
238     // illegal, because we expect a later optimization to eliminate them.
239     if (node->getType().getBasicType() == EbtSampler) {
240         intermediate.setNeedsLegalization();
241         return false;
242     }
243
244     // Let the base class check errors
245     return TParseContextBase::lValueErrorCheck(loc, op, node);
246 }
247
248 //
249 // This function handles l-value conversions and verifications.  It uses, but is not synonymous
250 // with lValueErrorCheck.  That function accepts an l-value directly, while this one must be
251 // given the surrounding tree - e.g, with an assignment, so we can convert the assign into a
252 // series of other image operations.
253 //
254 // Most things are passed through unmodified, except for error checking.
255 //
256 TIntermTyped* HlslParseContext::handleLvalue(const TSourceLoc& loc, const char* op, TIntermTyped*& node)
257 {
258     if (node == nullptr)
259         return nullptr;
260
261     TIntermBinary* nodeAsBinary = node->getAsBinaryNode();
262     TIntermUnary* nodeAsUnary = node->getAsUnaryNode();
263     TIntermAggregate* sequence = nullptr;
264
265     TIntermTyped* lhs = nodeAsUnary  ? nodeAsUnary->getOperand() :
266                         nodeAsBinary ? nodeAsBinary->getLeft() :
267                         nullptr;
268
269     // Early bail out if there is no conversion to apply
270     if (!shouldConvertLValue(lhs)) {
271         if (lhs != nullptr)
272             if (lValueErrorCheck(loc, op, lhs))
273                 return nullptr;
274         return node;
275     }
276
277     // *** If we get here, we're going to apply some conversion to an l-value.
278
279     // Helper to create a load.
280     const auto makeLoad = [&](TIntermSymbol* rhsTmp, TIntermTyped* object, TIntermTyped* coord, const TType& derefType) {
281         TIntermAggregate* loadOp = new TIntermAggregate(EOpImageLoad);
282         loadOp->setLoc(loc);
283         loadOp->getSequence().push_back(object);
284         loadOp->getSequence().push_back(intermediate.addSymbol(*coord->getAsSymbolNode()));
285         loadOp->setType(derefType);
286
287         sequence = intermediate.growAggregate(sequence,
288                                               intermediate.addAssign(EOpAssign, rhsTmp, loadOp, loc),
289                                               loc);
290     };
291
292     // Helper to create a store.
293     const auto makeStore = [&](TIntermTyped* object, TIntermTyped* coord, TIntermSymbol* rhsTmp) {
294         TIntermAggregate* storeOp = new TIntermAggregate(EOpImageStore);
295         storeOp->getSequence().push_back(object);
296         storeOp->getSequence().push_back(coord);
297         storeOp->getSequence().push_back(intermediate.addSymbol(*rhsTmp));
298         storeOp->setLoc(loc);
299         storeOp->setType(TType(EbtVoid));
300
301         sequence = intermediate.growAggregate(sequence, storeOp);
302     };
303
304     // Helper to create an assign.
305     const auto makeBinary = [&](TOperator op, TIntermTyped* lhs, TIntermTyped* rhs) {
306         sequence = intermediate.growAggregate(sequence,
307                                               intermediate.addBinaryNode(op, lhs, rhs, loc, lhs->getType()),
308                                               loc);
309     };
310
311     // Helper to complete sequence by adding trailing variable, so we evaluate to the right value.
312     const auto finishSequence = [&](TIntermSymbol* rhsTmp, const TType& derefType) -> TIntermAggregate* {
313         // Add a trailing use of the temp, so the sequence returns the proper value.
314         sequence = intermediate.growAggregate(sequence, intermediate.addSymbol(*rhsTmp));
315         sequence->setOperator(EOpSequence);
316         sequence->setLoc(loc);
317         sequence->setType(derefType);
318
319         return sequence;
320     };
321
322     // Helper to add unary op
323     const auto makeUnary = [&](TOperator op, TIntermSymbol* rhsTmp) {
324         sequence = intermediate.growAggregate(sequence,
325                                               intermediate.addUnaryNode(op, intermediate.addSymbol(*rhsTmp), loc,
326                                                                         rhsTmp->getType()),
327                                               loc);
328     };
329
330     // Return true if swizzle or index writes all components of the given variable.
331     const auto writesAllComponents = [&](TIntermSymbol* var, TIntermBinary* swizzle) -> bool {
332         if (swizzle == nullptr)  // not a swizzle or index
333             return true;
334
335         // Track which components are being set.
336         std::array<bool, 4> compIsSet;
337         compIsSet.fill(false);
338
339         const TIntermConstantUnion* asConst     = swizzle->getRight()->getAsConstantUnion();
340         const TIntermAggregate*     asAggregate = swizzle->getRight()->getAsAggregate();
341
342         // This could be either a direct index, or a swizzle.
343         if (asConst) {
344             compIsSet[asConst->getConstArray()[0].getIConst()] = true;
345         } else if (asAggregate) {
346             const TIntermSequence& seq = asAggregate->getSequence();
347             for (int comp=0; comp<int(seq.size()); ++comp)
348                 compIsSet[seq[comp]->getAsConstantUnion()->getConstArray()[0].getIConst()] = true;
349         } else {
350             assert(0);
351         }
352
353         // Return true if all components are being set by the index or swizzle
354         return std::all_of(compIsSet.begin(), compIsSet.begin() + var->getType().getVectorSize(),
355                            [](bool isSet) { return isSet; } );
356     };
357
358     // Create swizzle matching input swizzle
359     const auto addSwizzle = [&](TIntermSymbol* var, TIntermBinary* swizzle) -> TIntermTyped* {
360         if (swizzle)
361             return intermediate.addBinaryNode(swizzle->getOp(), var, swizzle->getRight(), loc, swizzle->getType());
362         else
363             return var;
364     };
365
366     TIntermBinary*    lhsAsBinary    = lhs->getAsBinaryNode();
367     TIntermAggregate* lhsAsAggregate = lhs->getAsAggregate();
368     bool lhsIsSwizzle = false;
369
370     // If it's a swizzled L-value, remember the swizzle, and use the LHS.
371     if (lhsAsBinary != nullptr && (lhsAsBinary->getOp() == EOpVectorSwizzle || lhsAsBinary->getOp() == EOpIndexDirect)) {
372         lhsAsAggregate = lhsAsBinary->getLeft()->getAsAggregate();
373         lhsIsSwizzle = true;
374     }
375
376     TIntermTyped* object = lhsAsAggregate->getSequence()[0]->getAsTyped();
377     TIntermTyped* coord  = lhsAsAggregate->getSequence()[1]->getAsTyped();
378
379     const TSampler& texSampler = object->getType().getSampler();
380
381     TType objDerefType;
382     getTextureReturnType(texSampler, objDerefType);
383
384     if (nodeAsBinary) {
385         TIntermTyped* rhs = nodeAsBinary->getRight();
386         const TOperator assignOp = nodeAsBinary->getOp();
387
388         bool isModifyOp = false;
389
390         switch (assignOp) {
391         case EOpAddAssign:
392         case EOpSubAssign:
393         case EOpMulAssign:
394         case EOpVectorTimesMatrixAssign:
395         case EOpVectorTimesScalarAssign:
396         case EOpMatrixTimesScalarAssign:
397         case EOpMatrixTimesMatrixAssign:
398         case EOpDivAssign:
399         case EOpModAssign:
400         case EOpAndAssign:
401         case EOpInclusiveOrAssign:
402         case EOpExclusiveOrAssign:
403         case EOpLeftShiftAssign:
404         case EOpRightShiftAssign:
405             isModifyOp = true;
406             // fall through...
407         case EOpAssign:
408             {
409                 // Since this is an lvalue, we'll convert an image load to a sequence like this
410                 // (to still provide the value):
411                 //   OpSequence
412                 //      OpImageStore(object, lhs, rhs)
413                 //      rhs
414                 // But if it's not a simple symbol RHS (say, a fn call), we don't want to duplicate the RHS,
415                 // so we'll convert instead to this:
416                 //   OpSequence
417                 //      rhsTmp = rhs
418                 //      OpImageStore(object, coord, rhsTmp)
419                 //      rhsTmp
420                 // If this is a read-modify-write op, like +=, we issue:
421                 //   OpSequence
422                 //      coordtmp = load's param1
423                 //      rhsTmp = OpImageLoad(object, coordTmp)
424                 //      rhsTmp op= rhs
425                 //      OpImageStore(object, coordTmp, rhsTmp)
426                 //      rhsTmp
427                 //
428                 // If the lvalue is swizzled, we apply that when writing the temp variable, like so:
429                 //    ...
430                 //    rhsTmp.some_swizzle = ...
431                 // For partial writes, an error is generated.
432
433                 TIntermSymbol* rhsTmp = rhs->getAsSymbolNode();
434                 TIntermTyped* coordTmp = coord;
435
436                 if (rhsTmp == nullptr || isModifyOp || lhsIsSwizzle) {
437                     rhsTmp = makeInternalVariableNode(loc, "storeTemp", objDerefType);
438
439                     // Partial updates not yet supported
440                     if (!writesAllComponents(rhsTmp, lhsAsBinary)) {
441                         error(loc, "unimplemented: partial image updates", "", "");
442                     }
443
444                     // Assign storeTemp = rhs
445                     if (isModifyOp) {
446                         // We have to make a temp var for the coordinate, to avoid evaluating it twice.
447                         coordTmp = makeInternalVariableNode(loc, "coordTemp", coord->getType());
448                         makeBinary(EOpAssign, coordTmp, coord); // coordtmp = load[param1]
449                         makeLoad(rhsTmp, object, coordTmp, objDerefType); // rhsTmp = OpImageLoad(object, coordTmp)
450                     }
451
452                     // rhsTmp op= rhs.
453                     makeBinary(assignOp, addSwizzle(intermediate.addSymbol(*rhsTmp), lhsAsBinary), rhs);
454                 }
455
456                 makeStore(object, coordTmp, rhsTmp);         // add a store
457                 return finishSequence(rhsTmp, objDerefType); // return rhsTmp from sequence
458             }
459
460         default:
461             break;
462         }
463     }
464
465     if (nodeAsUnary) {
466         const TOperator assignOp = nodeAsUnary->getOp();
467
468         switch (assignOp) {
469         case EOpPreIncrement:
470         case EOpPreDecrement:
471             {
472                 // We turn this into:
473                 //   OpSequence
474                 //      coordtmp = load's param1
475                 //      rhsTmp = OpImageLoad(object, coordTmp)
476                 //      rhsTmp op
477                 //      OpImageStore(object, coordTmp, rhsTmp)
478                 //      rhsTmp
479
480                 TIntermSymbol* rhsTmp = makeInternalVariableNode(loc, "storeTemp", objDerefType);
481                 TIntermTyped* coordTmp = makeInternalVariableNode(loc, "coordTemp", coord->getType());
482
483                 makeBinary(EOpAssign, coordTmp, coord);           // coordtmp = load[param1]
484                 makeLoad(rhsTmp, object, coordTmp, objDerefType); // rhsTmp = OpImageLoad(object, coordTmp)
485                 makeUnary(assignOp, rhsTmp);                      // op rhsTmp
486                 makeStore(object, coordTmp, rhsTmp);              // OpImageStore(object, coordTmp, rhsTmp)
487                 return finishSequence(rhsTmp, objDerefType);      // return rhsTmp from sequence
488             }
489
490         case EOpPostIncrement:
491         case EOpPostDecrement:
492             {
493                 // We turn this into:
494                 //   OpSequence
495                 //      coordtmp = load's param1
496                 //      rhsTmp1 = OpImageLoad(object, coordTmp)
497                 //      rhsTmp2 = rhsTmp1
498                 //      rhsTmp2 op
499                 //      OpImageStore(object, coordTmp, rhsTmp2)
500                 //      rhsTmp1 (pre-op value)
501                 TIntermSymbol* rhsTmp1 = makeInternalVariableNode(loc, "storeTempPre",  objDerefType);
502                 TIntermSymbol* rhsTmp2 = makeInternalVariableNode(loc, "storeTempPost", objDerefType);
503                 TIntermTyped* coordTmp = makeInternalVariableNode(loc, "coordTemp", coord->getType());
504
505                 makeBinary(EOpAssign, coordTmp, coord);            // coordtmp = load[param1]
506                 makeLoad(rhsTmp1, object, coordTmp, objDerefType); // rhsTmp1 = OpImageLoad(object, coordTmp)
507                 makeBinary(EOpAssign, rhsTmp2, rhsTmp1);           // rhsTmp2 = rhsTmp1
508                 makeUnary(assignOp, rhsTmp2);                      // rhsTmp op
509                 makeStore(object, coordTmp, rhsTmp2);              // OpImageStore(object, coordTmp, rhsTmp2)
510                 return finishSequence(rhsTmp1, objDerefType);      // return rhsTmp from sequence
511             }
512
513         default:
514             break;
515         }
516     }
517
518     if (lhs)
519         if (lValueErrorCheck(loc, op, lhs))
520             return nullptr;
521
522     return node;
523 }
524
525 void HlslParseContext::handlePragma(const TSourceLoc& loc, const TVector<TString>& tokens)
526 {
527     if (pragmaCallback)
528         pragmaCallback(loc.line, tokens);
529
530     if (tokens.size() == 0)
531         return;
532
533     // These pragmas are case insensitive in HLSL, so we'll compare in lower case.
534     TVector<TString> lowerTokens = tokens;
535
536     for (auto it = lowerTokens.begin(); it != lowerTokens.end(); ++it)
537         std::transform(it->begin(), it->end(), it->begin(), ::tolower);
538
539     // Handle pack_matrix
540     if (tokens.size() == 4 && lowerTokens[0] == "pack_matrix" && tokens[1] == "(" && tokens[3] == ")") {
541         // Note that HLSL semantic order is Mrc, not Mcr like SPIR-V, so we reverse the sense.
542         // Row major becomes column major and vice versa.
543
544         if (lowerTokens[2] == "row_major") {
545             globalUniformDefaults.layoutMatrix = globalBufferDefaults.layoutMatrix = ElmColumnMajor;
546         } else if (lowerTokens[2] == "column_major") {
547             globalUniformDefaults.layoutMatrix = globalBufferDefaults.layoutMatrix = ElmRowMajor;
548         } else {
549             // unknown majorness strings are treated as (HLSL column major)==(SPIR-V row major)
550             warn(loc, "unknown pack_matrix pragma value", tokens[2].c_str(), "");
551             globalUniformDefaults.layoutMatrix = globalBufferDefaults.layoutMatrix = ElmRowMajor;
552         }
553         return;
554     }
555
556     // Handle once
557     if (lowerTokens[0] == "once") {
558         warn(loc, "not implemented", "#pragma once", "");
559         return;
560     }
561 }
562
563 //
564 // Look at a '.' matrix selector string and change it into components
565 // for a matrix. There are two types:
566 //
567 //   _21    second row, first column (one based)
568 //   _m21   third row, second column (zero based)
569 //
570 // Returns true if there is no error.
571 //
572 bool HlslParseContext::parseMatrixSwizzleSelector(const TSourceLoc& loc, const TString& fields, int cols, int rows,
573                                                   TSwizzleSelectors<TMatrixSelector>& components)
574 {
575     int startPos[MaxSwizzleSelectors];
576     int numComps = 0;
577     TString compString = fields;
578
579     // Find where each component starts,
580     // recording the first character position after the '_'.
581     for (size_t c = 0; c < compString.size(); ++c) {
582         if (compString[c] == '_') {
583             if (numComps >= MaxSwizzleSelectors) {
584                 error(loc, "matrix component swizzle has too many components", compString.c_str(), "");
585                 return false;
586             }
587             if (c > compString.size() - 3 ||
588                     ((compString[c+1] == 'm' || compString[c+1] == 'M') && c > compString.size() - 4)) {
589                 error(loc, "matrix component swizzle missing", compString.c_str(), "");
590                 return false;
591             }
592             startPos[numComps++] = (int)c + 1;
593         }
594     }
595
596     // Process each component
597     for (int i = 0; i < numComps; ++i) {
598         int pos = startPos[i];
599         int bias = -1;
600         if (compString[pos] == 'm' || compString[pos] == 'M') {
601             bias = 0;
602             ++pos;
603         }
604         TMatrixSelector comp;
605         comp.coord1 = compString[pos+0] - '0' + bias;
606         comp.coord2 = compString[pos+1] - '0' + bias;
607         if (comp.coord1 < 0 || comp.coord1 >= cols) {
608             error(loc, "matrix row component out of range", compString.c_str(), "");
609             return false;
610         }
611         if (comp.coord2 < 0 || comp.coord2 >= rows) {
612             error(loc, "matrix column component out of range", compString.c_str(), "");
613             return false;
614         }
615         components.push_back(comp);
616     }
617
618     return true;
619 }
620
621 // If the 'comps' express a column of a matrix,
622 // return the column.  Column means the first coords all match.
623 //
624 // Otherwise, return -1.
625 //
626 int HlslParseContext::getMatrixComponentsColumn(int rows, const TSwizzleSelectors<TMatrixSelector>& selector)
627 {
628     int col = -1;
629
630     // right number of comps?
631     if (selector.size() != rows)
632         return -1;
633
634     // all comps in the same column?
635     // rows in order?
636     col = selector[0].coord1;
637     for (int i = 0; i < rows; ++i) {
638         if (col != selector[i].coord1)
639             return -1;
640         if (i != selector[i].coord2)
641             return -1;
642     }
643
644     return col;
645 }
646
647 //
648 // Handle seeing a variable identifier in the grammar.
649 //
650 TIntermTyped* HlslParseContext::handleVariable(const TSourceLoc& loc, const TString* string)
651 {
652     int thisDepth;
653     TSymbol* symbol = symbolTable.find(*string, thisDepth);
654     if (symbol && symbol->getAsVariable() && symbol->getAsVariable()->isUserType()) {
655         error(loc, "expected symbol, not user-defined type", string->c_str(), "");
656         return nullptr;
657     }
658
659     // Error check for requiring specific extensions present.
660     if (symbol && symbol->getNumExtensions())
661         requireExtensions(loc, symbol->getNumExtensions(), symbol->getExtensions(), symbol->getName().c_str());
662
663     const TVariable* variable = nullptr;
664     const TAnonMember* anon = symbol ? symbol->getAsAnonMember() : nullptr;
665     TIntermTyped* node = nullptr;
666     if (anon) {
667         // It was a member of an anonymous container, which could be a 'this' structure.
668
669         // Create a subtree for its dereference.
670         if (thisDepth > 0) {
671             variable = getImplicitThis(thisDepth);
672             if (variable == nullptr)
673                 error(loc, "cannot access member variables (static member function?)", "this", "");
674         }
675         if (variable == nullptr)
676             variable = anon->getAnonContainer().getAsVariable();
677
678         TIntermTyped* container = intermediate.addSymbol(*variable, loc);
679         TIntermTyped* constNode = intermediate.addConstantUnion(anon->getMemberNumber(), loc);
680         node = intermediate.addIndex(EOpIndexDirectStruct, container, constNode, loc);
681
682         node->setType(*(*variable->getType().getStruct())[anon->getMemberNumber()].type);
683         if (node->getType().hiddenMember())
684             error(loc, "member of nameless block was not redeclared", string->c_str(), "");
685     } else {
686         // Not a member of an anonymous container.
687
688         // The symbol table search was done in the lexical phase.
689         // See if it was a variable.
690         variable = symbol ? symbol->getAsVariable() : nullptr;
691         if (variable) {
692             if ((variable->getType().getBasicType() == EbtBlock ||
693                 variable->getType().getBasicType() == EbtStruct) && variable->getType().getStruct() == nullptr) {
694                 error(loc, "cannot be used (maybe an instance name is needed)", string->c_str(), "");
695                 variable = nullptr;
696             }
697         } else {
698             if (symbol)
699                 error(loc, "variable name expected", string->c_str(), "");
700         }
701
702         // Recovery, if it wasn't found or was not a variable.
703         if (variable == nullptr) {
704             error(loc, "unknown variable", string->c_str(), "");
705             variable = new TVariable(string, TType(EbtVoid));
706         }
707
708         if (variable->getType().getQualifier().isFrontEndConstant())
709             node = intermediate.addConstantUnion(variable->getConstArray(), variable->getType(), loc);
710         else
711             node = intermediate.addSymbol(*variable, loc);
712     }
713
714     if (variable->getType().getQualifier().isIo())
715         intermediate.addIoAccessed(*string);
716
717     return node;
718 }
719
720 //
721 // Handle operator[] on any objects it applies to.  Currently:
722 //    Textures
723 //    Buffers
724 //
725 TIntermTyped* HlslParseContext::handleBracketOperator(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
726 {
727     // handle r-value operator[] on textures and images.  l-values will be processed later.
728     if (base->getType().getBasicType() == EbtSampler && !base->isArray()) {
729         const TSampler& sampler = base->getType().getSampler();
730         if (sampler.isImage() || sampler.isTexture()) {
731             if (! mipsOperatorMipArg.empty() && mipsOperatorMipArg.back().mipLevel == nullptr) {
732                 // The first operator[] to a .mips[] sequence is the mip level.  We'll remember it.
733                 mipsOperatorMipArg.back().mipLevel = index;
734                 return base;  // next [] index is to the same base.
735             } else {
736                 TIntermAggregate* load = new TIntermAggregate(sampler.isImage() ? EOpImageLoad : EOpTextureFetch);
737
738                 TType sampReturnType;
739                 getTextureReturnType(sampler, sampReturnType);
740
741                 load->setType(sampReturnType);
742                 load->setLoc(loc);
743                 load->getSequence().push_back(base);
744                 load->getSequence().push_back(index);
745
746                 // Textures need a MIP.  If we saw one go by, use it.  Otherwise, use zero.
747                 if (sampler.isTexture()) {
748                     if (! mipsOperatorMipArg.empty()) {
749                         load->getSequence().push_back(mipsOperatorMipArg.back().mipLevel);
750                         mipsOperatorMipArg.pop_back();
751                     } else {
752                         load->getSequence().push_back(intermediate.addConstantUnion(0, loc, true));
753                     }
754                 }
755
756                 return load;
757             }
758         }
759     }
760
761     // Handle operator[] on structured buffers: this indexes into the array element of the buffer.
762     // indexStructBufferContent returns nullptr if it isn't a structuredbuffer (SSBO).
763     TIntermTyped* sbArray = indexStructBufferContent(loc, base);
764     if (sbArray != nullptr) {
765         if (sbArray == nullptr)
766             return nullptr;
767
768         // Now we'll apply the [] index to that array
769         const TOperator idxOp = (index->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
770
771         TIntermTyped* element = intermediate.addIndex(idxOp, sbArray, index, loc);
772         const TType derefType(sbArray->getType(), 0);
773         element->setType(derefType);
774         return element;
775     }
776
777     return nullptr;
778 }
779
780 //
781 // Cast index value to a uint if it isn't already (for operator[], load indexes, etc)
782 TIntermTyped* HlslParseContext::makeIntegerIndex(TIntermTyped* index)
783 {
784     const TBasicType indexBasicType = index->getType().getBasicType();
785     const int vecSize = index->getType().getVectorSize();
786
787     // We can use int types directly as the index
788     if (indexBasicType == EbtInt || indexBasicType == EbtUint ||
789         indexBasicType == EbtInt64 || indexBasicType == EbtUint64)
790         return index;
791
792     // Cast index to unsigned integer if it isn't one.
793     return intermediate.addConversion(EOpConstructUint, TType(EbtUint, EvqTemporary, vecSize), index);
794 }
795
796 //
797 // Handle seeing a base[index] dereference in the grammar.
798 //
799 TIntermTyped* HlslParseContext::handleBracketDereference(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
800 {
801     index = makeIntegerIndex(index);
802
803     if (index == nullptr) {
804         error(loc, " unknown index type ", "", "");
805         return nullptr;
806     }
807
808     TIntermTyped* result = handleBracketOperator(loc, base, index);
809
810     if (result != nullptr)
811         return result;  // it was handled as an operator[]
812
813     bool flattened = false;
814     int indexValue = 0;
815     if (index->getQualifier().isFrontEndConstant())
816         indexValue = index->getAsConstantUnion()->getConstArray()[0].getIConst();
817
818     variableCheck(base);
819     if (! base->isArray() && ! base->isMatrix() && ! base->isVector()) {
820         if (base->getAsSymbolNode())
821             error(loc, " left of '[' is not of type array, matrix, or vector ",
822                   base->getAsSymbolNode()->getName().c_str(), "");
823         else
824             error(loc, " left of '[' is not of type array, matrix, or vector ", "expression", "");
825     } else if (base->getType().getQualifier().storage == EvqConst && index->getQualifier().storage == EvqConst) {
826         // both base and index are front-end constants
827         checkIndex(loc, base->getType(), indexValue);
828         return intermediate.foldDereference(base, indexValue, loc);
829     } else {
830         // at least one of base and index is variable...
831
832         if (index->getQualifier().isFrontEndConstant())
833             checkIndex(loc, base->getType(), indexValue);
834
835         if (base->getType().isScalarOrVec1())
836             result = base;
837         else if (base->getAsSymbolNode() && wasFlattened(base)) {
838             if (index->getQualifier().storage != EvqConst)
839                 error(loc, "Invalid variable index to flattened array", base->getAsSymbolNode()->getName().c_str(), "");
840
841             result = flattenAccess(base, indexValue);
842             flattened = (result != base);
843         } else {
844             if (index->getQualifier().isFrontEndConstant()) {
845                 if (base->getType().isUnsizedArray())
846                     base->getWritableType().updateImplicitArraySize(indexValue + 1);
847                 else
848                     checkIndex(loc, base->getType(), indexValue);
849                 result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
850             } else
851                 result = intermediate.addIndex(EOpIndexIndirect, base, index, loc);
852         }
853     }
854
855     if (result == nullptr) {
856         // Insert dummy error-recovery result
857         result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
858     } else {
859         // If the array reference was flattened, it has the correct type.  E.g, if it was
860         // a uniform array, it was flattened INTO a set of scalar uniforms, not scalar temps.
861         // In that case, we preserve the qualifiers.
862         if (!flattened) {
863             // Insert valid dereferenced result
864             TType newType(base->getType(), 0);  // dereferenced type
865             if (base->getType().getQualifier().storage == EvqConst && index->getQualifier().storage == EvqConst)
866                 newType.getQualifier().storage = EvqConst;
867             else
868                 newType.getQualifier().storage = EvqTemporary;
869             result->setType(newType);
870         }
871     }
872
873     return result;
874 }
875
876 // Handle seeing a binary node with a math operation.
877 TIntermTyped* HlslParseContext::handleBinaryMath(const TSourceLoc& loc, const char* str, TOperator op,
878                                                  TIntermTyped* left, TIntermTyped* right)
879 {
880     TIntermTyped* result = intermediate.addBinaryMath(op, left, right, loc);
881     if (result == nullptr)
882         binaryOpError(loc, str, left->getCompleteString(), right->getCompleteString());
883
884     return result;
885 }
886
887 // Handle seeing a unary node with a math operation.
888 TIntermTyped* HlslParseContext::handleUnaryMath(const TSourceLoc& loc, const char* str, TOperator op,
889                                                 TIntermTyped* childNode)
890 {
891     TIntermTyped* result = intermediate.addUnaryMath(op, childNode, loc);
892
893     if (result)
894         return result;
895     else
896         unaryOpError(loc, str, childNode->getCompleteString());
897
898     return childNode;
899 }
900 //
901 // Return true if the name is a struct buffer method
902 //
903 bool HlslParseContext::isStructBufferMethod(const TString& name) const
904 {
905     return
906         name == "GetDimensions"              ||
907         name == "Load"                       ||
908         name == "Load2"                      ||
909         name == "Load3"                      ||
910         name == "Load4"                      ||
911         name == "Store"                      ||
912         name == "Store2"                     ||
913         name == "Store3"                     ||
914         name == "Store4"                     ||
915         name == "InterlockedAdd"             ||
916         name == "InterlockedAnd"             ||
917         name == "InterlockedCompareExchange" ||
918         name == "InterlockedCompareStore"    ||
919         name == "InterlockedExchange"        ||
920         name == "InterlockedMax"             ||
921         name == "InterlockedMin"             ||
922         name == "InterlockedOr"              ||
923         name == "InterlockedXor"             ||
924         name == "IncrementCounter"           ||
925         name == "DecrementCounter"           ||
926         name == "Append"                     ||
927         name == "Consume";
928 }
929
930 //
931 // Handle seeing a base.field dereference in the grammar, where 'field' is a
932 // swizzle or member variable.
933 //
934 TIntermTyped* HlslParseContext::handleDotDereference(const TSourceLoc& loc, TIntermTyped* base, const TString& field)
935 {
936     variableCheck(base);
937
938     if (base->isArray()) {
939         error(loc, "cannot apply to an array:", ".", field.c_str());
940         return base;
941     }
942
943     TIntermTyped* result = base;
944
945     if (base->getType().getBasicType() == EbtSampler) {
946         // Handle .mips[mipid][pos] operation on textures
947         const TSampler& sampler = base->getType().getSampler();
948         if (sampler.isTexture() && field == "mips") {
949             // Push a null to signify that we expect a mip level under operator[] next.
950             mipsOperatorMipArg.push_back(tMipsOperatorData(loc, nullptr));
951             // Keep 'result' pointing to 'base', since we expect an operator[] to go by next.
952         } else {
953             if (field == "mips")
954                 error(loc, "unexpected texture type for .mips[][] operator:",
955                       base->getType().getCompleteString().c_str(), "");
956             else
957                 error(loc, "unexpected operator on texture type:", field.c_str(),
958                       base->getType().getCompleteString().c_str());
959         }
960     } else if (base->isVector() || base->isScalar()) {
961         TSwizzleSelectors<TVectorSelector> selectors;
962         parseSwizzleSelector(loc, field, base->getVectorSize(), selectors);
963
964         if (base->isScalar()) {
965             if (selectors.size() == 1)
966                 return result;
967             else {
968                 TType type(base->getBasicType(), EvqTemporary, selectors.size());
969                 return addConstructor(loc, base, type);
970             }
971         }
972         if (base->getVectorSize() == 1) {
973             TType scalarType(base->getBasicType(), EvqTemporary, 1);
974             if (selectors.size() == 1)
975                 return addConstructor(loc, base, scalarType);
976             else {
977                 TType vectorType(base->getBasicType(), EvqTemporary, selectors.size());
978                 return addConstructor(loc, addConstructor(loc, base, scalarType), vectorType);
979             }
980         }
981
982         if (base->getType().getQualifier().isFrontEndConstant())
983             result = intermediate.foldSwizzle(base, selectors, loc);
984         else {
985             if (selectors.size() == 1) {
986                 TIntermTyped* index = intermediate.addConstantUnion(selectors[0], loc);
987                 result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
988                 result->setType(TType(base->getBasicType(), EvqTemporary));
989             } else {
990                 TIntermTyped* index = intermediate.addSwizzle(selectors, loc);
991                 result = intermediate.addIndex(EOpVectorSwizzle, base, index, loc);
992                 result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision,
993                                 selectors.size()));
994             }
995         }
996     } else if (base->isMatrix()) {
997         TSwizzleSelectors<TMatrixSelector> selectors;
998         if (! parseMatrixSwizzleSelector(loc, field, base->getMatrixCols(), base->getMatrixRows(), selectors))
999             return result;
1000
1001         if (selectors.size() == 1) {
1002             // Representable by m[c][r]
1003             if (base->getType().getQualifier().isFrontEndConstant()) {
1004                 result = intermediate.foldDereference(base, selectors[0].coord1, loc);
1005                 result = intermediate.foldDereference(result, selectors[0].coord2, loc);
1006             } else {
1007                 result = intermediate.addIndex(EOpIndexDirect, base,
1008                                                intermediate.addConstantUnion(selectors[0].coord1, loc),
1009                                                loc);
1010                 TType dereferencedCol(base->getType(), 0);
1011                 result->setType(dereferencedCol);
1012                 result = intermediate.addIndex(EOpIndexDirect, result,
1013                                                intermediate.addConstantUnion(selectors[0].coord2, loc),
1014                                                loc);
1015                 TType dereferenced(dereferencedCol, 0);
1016                 result->setType(dereferenced);
1017             }
1018         } else {
1019             int column = getMatrixComponentsColumn(base->getMatrixRows(), selectors);
1020             if (column >= 0) {
1021                 // Representable by m[c]
1022                 if (base->getType().getQualifier().isFrontEndConstant())
1023                     result = intermediate.foldDereference(base, column, loc);
1024                 else {
1025                     result = intermediate.addIndex(EOpIndexDirect, base, intermediate.addConstantUnion(column, loc),
1026                                                    loc);
1027                     TType dereferenced(base->getType(), 0);
1028                     result->setType(dereferenced);
1029                 }
1030             } else {
1031                 // general case, not a column, not a single component
1032                 TIntermTyped* index = intermediate.addSwizzle(selectors, loc);
1033                 result = intermediate.addIndex(EOpMatrixSwizzle, base, index, loc);
1034                 result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision,
1035                                       selectors.size()));
1036            }
1037         }
1038     } else if (base->getBasicType() == EbtStruct || base->getBasicType() == EbtBlock) {
1039         const TTypeList* fields = base->getType().getStruct();
1040         bool fieldFound = false;
1041         int member;
1042         for (member = 0; member < (int)fields->size(); ++member) {
1043             if ((*fields)[member].type->getFieldName() == field) {
1044                 fieldFound = true;
1045                 break;
1046             }
1047         }
1048         if (fieldFound) {
1049             if (base->getAsSymbolNode() && wasFlattened(base)) {
1050                 result = flattenAccess(base, member);
1051             } else {
1052                 if (base->getType().getQualifier().storage == EvqConst)
1053                     result = intermediate.foldDereference(base, member, loc);
1054                 else {
1055                     TIntermTyped* index = intermediate.addConstantUnion(member, loc);
1056                     result = intermediate.addIndex(EOpIndexDirectStruct, base, index, loc);
1057                     result->setType(*(*fields)[member].type);
1058                 }
1059             }
1060         } else
1061             error(loc, "no such field in structure", field.c_str(), "");
1062     } else
1063         error(loc, "does not apply to this type:", field.c_str(), base->getType().getCompleteString().c_str());
1064
1065     return result;
1066 }
1067
1068 //
1069 // Return true if the field should be treated as a built-in method.
1070 // Return false otherwise.
1071 //
1072 bool HlslParseContext::isBuiltInMethod(const TSourceLoc&, TIntermTyped* base, const TString& field)
1073 {
1074     if (base == nullptr)
1075         return false;
1076
1077     variableCheck(base);
1078
1079     if (base->getType().getBasicType() == EbtSampler) {
1080         return true;
1081     } else if (isStructBufferType(base->getType()) && isStructBufferMethod(field)) {
1082         return true;
1083     } else if (field == "Append" ||
1084                field == "RestartStrip") {
1085         // We cannot check the type here: it may be sanitized if we're not compiling a geometry shader, but
1086         // the code is around in the shader source.
1087         return true;
1088     } else
1089         return false;
1090 }
1091
1092 // Independently establish a built-in that is a member of a structure.
1093 // 'arraySizes' are what's desired for the independent built-in, whatever
1094 // the higher-level source/expression of them was.
1095 void HlslParseContext::splitBuiltIn(const TString& baseName, const TType& memberType, const TArraySizes* arraySizes,
1096                                     const TQualifier& outerQualifier)
1097 {
1098     // Because of arrays of structs, we might be asked more than once,
1099     // but the arraySizes passed in should have captured the whole thing
1100     // the first time.
1101     // However, clip/cull rely on multiple updates.
1102     if (!isClipOrCullDistance(memberType))
1103         if (splitBuiltIns.find(tInterstageIoData(memberType.getQualifier().builtIn, outerQualifier.storage)) !=
1104             splitBuiltIns.end())
1105             return;
1106
1107     TVariable* ioVar = makeInternalVariable(baseName + "." + memberType.getFieldName(), memberType);
1108
1109     if (arraySizes != nullptr && !memberType.isArray())
1110         ioVar->getWritableType().copyArraySizes(*arraySizes);
1111
1112     splitBuiltIns[tInterstageIoData(memberType.getQualifier().builtIn, outerQualifier.storage)] = ioVar;
1113     if (!isClipOrCullDistance(ioVar->getType()))
1114         trackLinkage(*ioVar);
1115
1116     // Merge qualifier from the user structure
1117     mergeQualifiers(ioVar->getWritableType().getQualifier(), outerQualifier);
1118
1119     // Fix the builtin type if needed (e.g, some types require fixed array sizes, no matter how the
1120     // shader declared them).  This is done after mergeQualifiers(), in case fixBuiltInIoType looks
1121     // at the qualifier to determine e.g, in or out qualifications.
1122     fixBuiltInIoType(ioVar->getWritableType());
1123
1124     // But, not location, we're losing that
1125     ioVar->getWritableType().getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
1126 }
1127
1128 // Split a type into
1129 //   1. a struct of non-I/O members
1130 //   2. a collection of independent I/O variables
1131 void HlslParseContext::split(const TVariable& variable)
1132 {
1133     // Create a new variable:
1134     const TType& clonedType = *variable.getType().clone();
1135     const TType& splitType = split(clonedType, variable.getName(), clonedType.getQualifier());
1136     splitNonIoVars[variable.getUniqueId()] = makeInternalVariable(variable.getName(), splitType);
1137 }
1138
1139 // Recursive implementation of split().
1140 // Returns reference to the modified type.
1141 const TType& HlslParseContext::split(const TType& type, const TString& name, const TQualifier& outerQualifier)
1142 {
1143     if (type.isStruct()) {
1144         TTypeList* userStructure = type.getWritableStruct();
1145         for (auto ioType = userStructure->begin(); ioType != userStructure->end(); ) {
1146             if (ioType->type->isBuiltIn()) {
1147                 // move out the built-in
1148                 splitBuiltIn(name, *ioType->type, type.getArraySizes(), outerQualifier);
1149                 ioType = userStructure->erase(ioType);
1150             } else {
1151                 split(*ioType->type, name + "." + ioType->type->getFieldName(), outerQualifier);
1152                 ++ioType;
1153             }
1154         }
1155     }
1156
1157     return type;
1158 }
1159
1160 // Is this an aggregate that should be flattened?
1161 // Can be applied to intermediate levels of type in a hierarchy.
1162 // Some things like flattening uniform arrays are only about the top level
1163 // of the aggregate, triggered on 'topLevel'.
1164 bool HlslParseContext::shouldFlatten(const TType& type, TStorageQualifier qualifier, bool topLevel) const
1165 {
1166     switch (qualifier) {
1167     case EvqVaryingIn:
1168     case EvqVaryingOut:
1169         return type.isStruct() || type.isArray();
1170     case EvqUniform:
1171         return (type.isArray() && intermediate.getFlattenUniformArrays() && topLevel) ||
1172                (type.isStruct() && type.containsOpaque());
1173     default:
1174         return false;
1175     };
1176 }
1177
1178 // Top level variable flattening: construct data
1179 void HlslParseContext::flatten(const TVariable& variable, bool linkage)
1180 {
1181     const TType& type = variable.getType();
1182
1183     // If it's a standalone built-in, there is nothing to flatten
1184     if (type.isBuiltIn() && !type.isStruct())
1185         return;
1186
1187     auto entry = flattenMap.insert(std::make_pair(variable.getUniqueId(),
1188                                                   TFlattenData(type.getQualifier().layoutBinding,
1189                                                                type.getQualifier().layoutLocation)));
1190
1191     // the item is a map pair, so first->second is the TFlattenData itself.
1192     flatten(variable, type, entry.first->second, variable.getName(), linkage, type.getQualifier(), nullptr);
1193 }
1194
1195 // Recursively flatten the given variable at the provided type, building the flattenData as we go.
1196 //
1197 // This is mutually recursive with flattenStruct and flattenArray.
1198 // We are going to flatten an arbitrarily nested composite structure into a linear sequence of
1199 // members, and later on, we want to turn a path through the tree structure into a final
1200 // location in this linear sequence.
1201 //
1202 // If the tree was N-ary, that can be directly calculated.  However, we are dealing with
1203 // arbitrary numbers - perhaps a struct of 7 members containing an array of 3.  Thus, we must
1204 // build a data structure to allow the sequence of bracket and dot operators on arrays and
1205 // structs to arrive at the proper member.
1206 //
1207 // To avoid storing a tree with pointers, we are going to flatten the tree into a vector of integers.
1208 // The leaves are the indexes into the flattened member array.
1209 // Each level will have the next location for the Nth item stored sequentially, so for instance:
1210 //
1211 // struct { float2 a[2]; int b; float4 c[3] };
1212 //
1213 // This will produce the following flattened tree:
1214 // Pos: 0  1   2    3  4    5  6   7     8   9  10   11  12 13
1215 //     (3, 7,  8,   5, 6,   0, 1,  2,   11, 12, 13,   3,  4, 5}
1216 //
1217 // Given a reference to mystruct.c[1], the access chain is (2,1), so we traverse:
1218 //   (0+2) = 8  -->  (8+1) = 12 -->   12 = 4
1219 //
1220 // so the 4th flattened member in traversal order is ours.
1221 //
1222 int HlslParseContext::flatten(const TVariable& variable, const TType& type,
1223                               TFlattenData& flattenData, TString name, bool linkage,
1224                               const TQualifier& outerQualifier,
1225                               const TArraySizes* builtInArraySizes)
1226 {
1227     // If something is an arrayed struct, the array flattener will recursively call flatten()
1228     // to then flatten the struct, so this is an "if else": we don't do both.
1229     if (type.isArray())
1230         return flattenArray(variable, type, flattenData, name, linkage, outerQualifier);
1231     else if (type.isStruct())
1232         return flattenStruct(variable, type, flattenData, name, linkage, outerQualifier, builtInArraySizes);
1233     else {
1234         assert(0); // should never happen
1235         return -1;
1236     }
1237 }
1238
1239 // Add a single flattened member to the flattened data being tracked for the composite
1240 // Returns true for the final flattening level.
1241 int HlslParseContext::addFlattenedMember(const TVariable& variable, const TType& type, TFlattenData& flattenData,
1242                                          const TString& memberName, bool linkage,
1243                                          const TQualifier& outerQualifier,
1244                                          const TArraySizes* builtInArraySizes)
1245 {
1246     if (!shouldFlatten(type, outerQualifier.storage, false)) {
1247         // This is as far as we flatten.  Insert the variable.
1248         TVariable* memberVariable = makeInternalVariable(memberName, type);
1249         mergeQualifiers(memberVariable->getWritableType().getQualifier(), variable.getType().getQualifier());
1250
1251         if (flattenData.nextBinding != TQualifier::layoutBindingEnd)
1252             memberVariable->getWritableType().getQualifier().layoutBinding = flattenData.nextBinding++;
1253
1254         if (memberVariable->getType().isBuiltIn()) {
1255             // inherited locations are nonsensical for built-ins (TODO: what if semantic had a number)
1256             memberVariable->getWritableType().getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
1257         } else {
1258             // inherited locations must be auto bumped, not replicated
1259             if (flattenData.nextLocation != TQualifier::layoutLocationEnd) {
1260                 memberVariable->getWritableType().getQualifier().layoutLocation = flattenData.nextLocation;
1261                 flattenData.nextLocation += intermediate.computeTypeLocationSize(memberVariable->getType(), language);
1262                 nextOutLocation = std::max(nextOutLocation, flattenData.nextLocation);
1263             }
1264         }
1265
1266         flattenData.offsets.push_back(static_cast<int>(flattenData.members.size()));
1267         flattenData.members.push_back(memberVariable);
1268
1269         if (linkage)
1270             trackLinkage(*memberVariable);
1271
1272         return static_cast<int>(flattenData.offsets.size()) - 1; // location of the member reference
1273     } else {
1274         // Further recursion required
1275         return flatten(variable, type, flattenData, memberName, linkage, outerQualifier, builtInArraySizes);
1276     }
1277 }
1278
1279 // Figure out the mapping between an aggregate's top members and an
1280 // equivalent set of individual variables.
1281 //
1282 // Assumes shouldFlatten() or equivalent was called first.
1283 int HlslParseContext::flattenStruct(const TVariable& variable, const TType& type,
1284                                     TFlattenData& flattenData, TString name, bool linkage,
1285                                     const TQualifier& outerQualifier,
1286                                     const TArraySizes* builtInArraySizes)
1287 {
1288     assert(type.isStruct());
1289
1290     auto members = *type.getStruct();
1291
1292     // Reserve space for this tree level.
1293     int start = static_cast<int>(flattenData.offsets.size());
1294     int pos = start;
1295     flattenData.offsets.resize(int(pos + members.size()), -1);
1296
1297     for (int member = 0; member < (int)members.size(); ++member) {
1298         TType& dereferencedType = *members[member].type;
1299         if (dereferencedType.isBuiltIn())
1300             splitBuiltIn(variable.getName(), dereferencedType, builtInArraySizes, outerQualifier);
1301         else {
1302             const int mpos = addFlattenedMember(variable, dereferencedType, flattenData,
1303                                                 name + "." + dereferencedType.getFieldName(),
1304                                                 linkage, outerQualifier,
1305                                                 builtInArraySizes == nullptr && dereferencedType.isArray()
1306                                                                        ? dereferencedType.getArraySizes()
1307                                                                        : builtInArraySizes);
1308             flattenData.offsets[pos++] = mpos;
1309         }
1310     }
1311
1312     return start;
1313 }
1314
1315 // Figure out mapping between an array's members and an
1316 // equivalent set of individual variables.
1317 //
1318 // Assumes shouldFlatten() or equivalent was called first.
1319 int HlslParseContext::flattenArray(const TVariable& variable, const TType& type,
1320                                    TFlattenData& flattenData, TString name, bool linkage,
1321                                    const TQualifier& outerQualifier)
1322 {
1323     assert(type.isSizedArray());
1324
1325     const int size = type.getOuterArraySize();
1326     const TType dereferencedType(type, 0);
1327
1328     if (name.empty())
1329         name = variable.getName();
1330
1331     // Reserve space for this tree level.
1332     int start = static_cast<int>(flattenData.offsets.size());
1333     int pos   = start;
1334     flattenData.offsets.resize(int(pos + size), -1);
1335
1336     for (int element=0; element < size; ++element) {
1337         char elementNumBuf[20];  // sufficient for MAXINT
1338         snprintf(elementNumBuf, sizeof(elementNumBuf)-1, "[%d]", element);
1339         const int mpos = addFlattenedMember(variable, dereferencedType, flattenData,
1340                                             name + elementNumBuf, linkage, outerQualifier,
1341                                             type.getArraySizes());
1342
1343         flattenData.offsets[pos++] = mpos;
1344     }
1345
1346     return start;
1347 }
1348
1349 // Return true if we have flattened this node.
1350 bool HlslParseContext::wasFlattened(const TIntermTyped* node) const
1351 {
1352     return node != nullptr && node->getAsSymbolNode() != nullptr &&
1353            wasFlattened(node->getAsSymbolNode()->getId());
1354 }
1355
1356 // Return true if we have split this structure
1357 bool HlslParseContext::wasSplit(const TIntermTyped* node) const
1358 {
1359     return node != nullptr && node->getAsSymbolNode() != nullptr &&
1360            wasSplit(node->getAsSymbolNode()->getId());
1361 }
1362
1363 // Turn an access into an aggregate that was flattened to instead be
1364 // an access to the individual variable the member was flattened to.
1365 // Assumes wasFlattened() or equivalent was called first.
1366 TIntermTyped* HlslParseContext::flattenAccess(TIntermTyped* base, int member)
1367 {
1368     const TType dereferencedType(base->getType(), member);  // dereferenced type
1369     const TIntermSymbol& symbolNode = *base->getAsSymbolNode();
1370     TIntermTyped* flattened = flattenAccess(symbolNode.getId(), member, base->getQualifier().storage,
1371                                             dereferencedType, symbolNode.getFlattenSubset());
1372
1373     return flattened ? flattened : base;
1374 }
1375 TIntermTyped* HlslParseContext::flattenAccess(int uniqueId, int member, TStorageQualifier outerStorage,
1376     const TType& dereferencedType, int subset)
1377 {
1378     const auto flattenData = flattenMap.find(uniqueId);
1379
1380     if (flattenData == flattenMap.end())
1381         return nullptr;
1382
1383     // Calculate new cumulative offset from the packed tree
1384     int newSubset = flattenData->second.offsets[subset >= 0 ? subset + member : member];
1385
1386     TIntermSymbol* subsetSymbol;
1387     if (!shouldFlatten(dereferencedType, outerStorage, false)) {
1388         // Finished flattening: create symbol for variable
1389         member = flattenData->second.offsets[newSubset];
1390         const TVariable* memberVariable = flattenData->second.members[member];
1391         subsetSymbol = intermediate.addSymbol(*memberVariable);
1392         subsetSymbol->setFlattenSubset(-1);
1393     } else {
1394
1395         // If this is not the final flattening, accumulate the position and return
1396         // an object of the partially dereferenced type.
1397         subsetSymbol = new TIntermSymbol(uniqueId, "flattenShadow", dereferencedType);
1398         subsetSymbol->setFlattenSubset(newSubset);
1399     }
1400
1401     return subsetSymbol;
1402 }
1403
1404 // For finding where the first leaf is in a subtree of a multi-level aggregate
1405 // that is just getting a subset assigned. Follows the same logic as flattenAccess,
1406 // but logically going down the "left-most" tree branch each step of the way.
1407 //
1408 // Returns the offset into the first leaf of the subset.
1409 int HlslParseContext::findSubtreeOffset(const TIntermNode& node) const
1410 {
1411     const TIntermSymbol* sym = node.getAsSymbolNode();
1412     if (sym == nullptr)
1413         return 0;
1414     if (!sym->isArray() && !sym->isStruct())
1415         return 0;
1416     int subset = sym->getFlattenSubset();
1417     if (subset == -1)
1418         return 0;
1419
1420     // Getting this far means a partial aggregate is identified by the flatten subset.
1421     // Find the first leaf of the subset.
1422
1423     const auto flattenData = flattenMap.find(sym->getId());
1424     if (flattenData == flattenMap.end())
1425         return 0;
1426
1427     return findSubtreeOffset(sym->getType(), subset, flattenData->second.offsets);
1428
1429     do {
1430         subset = flattenData->second.offsets[subset];
1431     } while (true);
1432 }
1433 // Recursively do the desent
1434 int HlslParseContext::findSubtreeOffset(const TType& type, int subset, const TVector<int>& offsets) const
1435 {
1436     if (!type.isArray() && !type.isStruct())
1437         return offsets[subset];
1438     TType derefType(type, 0);
1439     return findSubtreeOffset(derefType, offsets[subset], offsets);
1440 };
1441
1442 // Find and return the split IO TVariable for id, or nullptr if none.
1443 TVariable* HlslParseContext::getSplitNonIoVar(int id) const
1444 {
1445     const auto splitNonIoVar = splitNonIoVars.find(id);
1446     if (splitNonIoVar == splitNonIoVars.end())
1447         return nullptr;
1448
1449     return splitNonIoVar->second;
1450 }
1451
1452 // Pass through to base class after remembering built-in mappings.
1453 void HlslParseContext::trackLinkage(TSymbol& symbol)
1454 {
1455     TBuiltInVariable biType = symbol.getType().getQualifier().builtIn;
1456
1457     if (biType != EbvNone)
1458         builtInTessLinkageSymbols[biType] = symbol.clone();
1459
1460     TParseContextBase::trackLinkage(symbol);
1461 }
1462
1463
1464 // Returns true if the built-in is a clip or cull distance variable.
1465 bool HlslParseContext::isClipOrCullDistance(TBuiltInVariable builtIn)
1466 {
1467     return builtIn == EbvClipDistance || builtIn == EbvCullDistance;
1468 }
1469
1470 // Some types require fixed array sizes in SPIR-V, but can be scalars or
1471 // arrays of sizes SPIR-V doesn't allow.  For example, tessellation factors.
1472 // This creates the right size.  A conversion is performed when the internal
1473 // type is copied to or from the external type.  This corrects the externally
1474 // facing input or output type to abide downstream semantics.
1475 void HlslParseContext::fixBuiltInIoType(TType& type)
1476 {
1477     int requiredArraySize = 0;
1478     int requiredVectorSize = 0;
1479
1480     switch (type.getQualifier().builtIn) {
1481     case EbvTessLevelOuter: requiredArraySize = 4; break;
1482     case EbvTessLevelInner: requiredArraySize = 2; break;
1483
1484     case EbvSampleMask:
1485         {
1486             // Promote scalar to array of size 1.  Leave existing arrays alone.
1487             if (!type.isArray())
1488                 requiredArraySize = 1;
1489             break;
1490         }
1491
1492     case EbvWorkGroupId:        requiredVectorSize = 3; break;
1493     case EbvGlobalInvocationId: requiredVectorSize = 3; break;
1494     case EbvLocalInvocationId:  requiredVectorSize = 3; break;
1495     case EbvTessCoord:          requiredVectorSize = 3; break;
1496
1497     default:
1498         if (isClipOrCullDistance(type)) {
1499             const int loc = type.getQualifier().layoutLocation;
1500
1501             if (type.getQualifier().builtIn == EbvClipDistance) {
1502                 if (type.getQualifier().storage == EvqVaryingIn)
1503                     clipSemanticNSizeIn[loc] = type.getVectorSize();
1504                 else
1505                     clipSemanticNSizeOut[loc] = type.getVectorSize();
1506             } else {
1507                 if (type.getQualifier().storage == EvqVaryingIn)
1508                     cullSemanticNSizeIn[loc] = type.getVectorSize();
1509                 else
1510                     cullSemanticNSizeOut[loc] = type.getVectorSize();
1511             }
1512         }
1513
1514         return;
1515     }
1516
1517     // Alter or set vector size as needed.
1518     if (requiredVectorSize > 0) {
1519         TType newType(type.getBasicType(), type.getQualifier().storage, requiredVectorSize);
1520         newType.getQualifier() = type.getQualifier();
1521
1522         type.shallowCopy(newType);
1523     }
1524
1525     // Alter or set array size as needed.
1526     if (requiredArraySize > 0) {
1527         if (!type.isArray() || type.getOuterArraySize() != requiredArraySize) {
1528             TArraySizes* arraySizes = new TArraySizes;
1529             arraySizes->addInnerSize(requiredArraySize);
1530             type.transferArraySizes(arraySizes);
1531         }
1532     }
1533 }
1534
1535 // Variables that correspond to the user-interface in and out of a stage
1536 // (not the built-in interface) are
1537 //  - assigned locations
1538 //  - registered as a linkage node (part of the stage's external interface).
1539 // Assumes it is called in the order in which locations should be assigned.
1540 void HlslParseContext::assignToInterface(TVariable& variable)
1541 {
1542     const auto assignLocation = [&](TVariable& variable) {
1543         TType& type = variable.getWritableType();
1544         if (!type.isStruct() || type.getStruct()->size() > 0) {
1545             TQualifier& qualifier = type.getQualifier();
1546             if (qualifier.storage == EvqVaryingIn || qualifier.storage == EvqVaryingOut) {
1547                 if (qualifier.builtIn == EbvNone && !qualifier.hasLocation()) {
1548                     // Strip off the outer array dimension for those having an extra one.
1549                     int size;
1550                     if (type.isArray() && qualifier.isArrayedIo(language)) {
1551                         TType elementType(type, 0);
1552                         size = intermediate.computeTypeLocationSize(elementType, language);
1553                     } else
1554                         size = intermediate.computeTypeLocationSize(type, language);
1555
1556                     if (qualifier.storage == EvqVaryingIn) {
1557                         variable.getWritableType().getQualifier().layoutLocation = nextInLocation;
1558                         nextInLocation += size;
1559                     } else {
1560                         variable.getWritableType().getQualifier().layoutLocation = nextOutLocation;
1561                         nextOutLocation += size;
1562                     }
1563                 }
1564                 trackLinkage(variable);
1565             }
1566         }
1567     };
1568
1569     if (wasFlattened(variable.getUniqueId())) {
1570         auto& memberList = flattenMap[variable.getUniqueId()].members;
1571         for (auto member = memberList.begin(); member != memberList.end(); ++member)
1572             assignLocation(**member);
1573     } else if (wasSplit(variable.getUniqueId())) {
1574         TVariable* splitIoVar = getSplitNonIoVar(variable.getUniqueId());
1575         assignLocation(*splitIoVar);
1576     } else {
1577         assignLocation(variable);
1578     }
1579 }
1580
1581 //
1582 // Handle seeing a function declarator in the grammar.  This is the precursor
1583 // to recognizing a function prototype or function definition.
1584 //
1585 void HlslParseContext::handleFunctionDeclarator(const TSourceLoc& loc, TFunction& function, bool prototype)
1586 {
1587     //
1588     // Multiple declarations of the same function name are allowed.
1589     //
1590     // If this is a definition, the definition production code will check for redefinitions
1591     // (we don't know at this point if it's a definition or not).
1592     //
1593     bool builtIn;
1594     TSymbol* symbol = symbolTable.find(function.getMangledName(), &builtIn);
1595     const TFunction* prevDec = symbol ? symbol->getAsFunction() : 0;
1596
1597     if (prototype) {
1598         // All built-in functions are defined, even though they don't have a body.
1599         // Count their prototype as a definition instead.
1600         if (symbolTable.atBuiltInLevel())
1601             function.setDefined();
1602         else {
1603             if (prevDec && ! builtIn)
1604                 symbol->getAsFunction()->setPrototyped();  // need a writable one, but like having prevDec as a const
1605             function.setPrototyped();
1606         }
1607     }
1608
1609     // This insert won't actually insert it if it's a duplicate signature, but it will still check for
1610     // other forms of name collisions.
1611     if (! symbolTable.insert(function))
1612         error(loc, "function name is redeclaration of existing name", function.getName().c_str(), "");
1613 }
1614
1615 // For struct buffers with counters, we must pass the counter buffer as hidden parameter.
1616 // This adds the hidden parameter to the parameter list in 'paramNodes' if needed.
1617 // Otherwise, it's a no-op
1618 void HlslParseContext::addStructBufferHiddenCounterParam(const TSourceLoc& loc, TParameter& param,
1619                                                          TIntermAggregate*& paramNodes)
1620 {
1621     if (! hasStructBuffCounter(*param.type))
1622         return;
1623
1624     const TString counterBlockName(intermediate.addCounterBufferName(*param.name));
1625
1626     TType counterType;
1627     counterBufferType(loc, counterType);
1628     TVariable *variable = makeInternalVariable(counterBlockName, counterType);
1629
1630     if (! symbolTable.insert(*variable))
1631         error(loc, "redefinition", variable->getName().c_str(), "");
1632
1633     paramNodes = intermediate.growAggregate(paramNodes,
1634                                             intermediate.addSymbol(*variable, loc),
1635                                             loc);
1636 }
1637
1638 //
1639 // Handle seeing the function prototype in front of a function definition in the grammar.
1640 // The body is handled after this function returns.
1641 //
1642 // Returns an aggregate of parameter-symbol nodes.
1643 //
1644 TIntermAggregate* HlslParseContext::handleFunctionDefinition(const TSourceLoc& loc, TFunction& function,
1645                                                              const TAttributes& attributes,
1646                                                              TIntermNode*& entryPointTree)
1647 {
1648     currentCaller = function.getMangledName();
1649     TSymbol* symbol = symbolTable.find(function.getMangledName());
1650     TFunction* prevDec = symbol ? symbol->getAsFunction() : nullptr;
1651
1652     if (prevDec == nullptr)
1653         error(loc, "can't find function", function.getName().c_str(), "");
1654     // Note:  'prevDec' could be 'function' if this is the first time we've seen function
1655     // as it would have just been put in the symbol table.  Otherwise, we're looking up
1656     // an earlier occurrence.
1657
1658     if (prevDec && prevDec->isDefined()) {
1659         // Then this function already has a body.
1660         error(loc, "function already has a body", function.getName().c_str(), "");
1661     }
1662     if (prevDec && ! prevDec->isDefined()) {
1663         prevDec->setDefined();
1664
1665         // Remember the return type for later checking for RETURN statements.
1666         currentFunctionType = &(prevDec->getType());
1667     } else
1668         currentFunctionType = new TType(EbtVoid);
1669     functionReturnsValue = false;
1670
1671     // Entry points need different I/O and other handling, transform it so the
1672     // rest of this function doesn't care.
1673     entryPointTree = transformEntryPoint(loc, function, attributes);
1674
1675     //
1676     // New symbol table scope for body of function plus its arguments
1677     //
1678     pushScope();
1679
1680     //
1681     // Insert parameters into the symbol table.
1682     // If the parameter has no name, it's not an error, just don't insert it
1683     // (could be used for unused args).
1684     //
1685     // Also, accumulate the list of parameters into the AST, so lower level code
1686     // knows where to find parameters.
1687     //
1688     TIntermAggregate* paramNodes = new TIntermAggregate;
1689     for (int i = 0; i < function.getParamCount(); i++) {
1690         TParameter& param = function[i];
1691         if (param.name != nullptr) {
1692             TVariable *variable = new TVariable(param.name, *param.type);
1693
1694             if (i == 0 && function.hasImplicitThis()) {
1695                 // Anonymous 'this' members are already in a symbol-table level,
1696                 // and we need to know what function parameter to map them to.
1697                 symbolTable.makeInternalVariable(*variable);
1698                 pushImplicitThis(variable);
1699             }
1700
1701             // Insert the parameters with name in the symbol table.
1702             if (! symbolTable.insert(*variable))
1703                 error(loc, "redefinition", variable->getName().c_str(), "");
1704
1705             // Add parameters to the AST list.
1706             if (shouldFlatten(variable->getType(), variable->getType().getQualifier().storage, true)) {
1707                 // Expand the AST parameter nodes (but not the name mangling or symbol table view)
1708                 // for structures that need to be flattened.
1709                 flatten(*variable, false);
1710                 const TTypeList* structure = variable->getType().getStruct();
1711                 for (int mem = 0; mem < (int)structure->size(); ++mem) {
1712                     paramNodes = intermediate.growAggregate(paramNodes,
1713                                                             flattenAccess(variable->getUniqueId(), mem,
1714                                                                           variable->getType().getQualifier().storage,
1715                                                                           *(*structure)[mem].type),
1716                                                             loc);
1717                 }
1718             } else {
1719                 // Add the parameter to the AST
1720                 paramNodes = intermediate.growAggregate(paramNodes,
1721                                                         intermediate.addSymbol(*variable, loc),
1722                                                         loc);
1723             }
1724
1725             // Add hidden AST parameter for struct buffer counters, if needed.
1726             addStructBufferHiddenCounterParam(loc, param, paramNodes);
1727         } else
1728             paramNodes = intermediate.growAggregate(paramNodes, intermediate.addSymbol(*param.type, loc), loc);
1729     }
1730     if (function.hasIllegalImplicitThis())
1731         pushImplicitThis(nullptr);
1732
1733     intermediate.setAggregateOperator(paramNodes, EOpParameters, TType(EbtVoid), loc);
1734     loopNestingLevel = 0;
1735     controlFlowNestingLevel = 0;
1736     postEntryPointReturn = false;
1737
1738     return paramNodes;
1739 }
1740
1741 // Handle all [attrib] attribute for the shader entry point
1742 void HlslParseContext::handleEntryPointAttributes(const TSourceLoc& loc, const TAttributes& attributes)
1743 {
1744     for (auto it = attributes.begin(); it != attributes.end(); ++it) {
1745         switch (it->name) {
1746         case EatNumThreads:
1747         {
1748             const TIntermSequence& sequence = it->args->getSequence();
1749             for (int lid = 0; lid < int(sequence.size()); ++lid)
1750                 intermediate.setLocalSize(lid, sequence[lid]->getAsConstantUnion()->getConstArray()[0].getIConst());
1751             break;
1752         }
1753         case EatMaxVertexCount:
1754         {
1755             int maxVertexCount;
1756
1757             if (! it->getInt(maxVertexCount)) {
1758                 error(loc, "invalid maxvertexcount", "", "");
1759             } else {
1760                 if (! intermediate.setVertices(maxVertexCount))
1761                     error(loc, "cannot change previously set maxvertexcount attribute", "", "");
1762             }
1763             break;
1764         }
1765         case EatPatchConstantFunc:
1766         {
1767             TString pcfName;
1768             if (! it->getString(pcfName, 0, false)) {
1769                 error(loc, "invalid patch constant function", "", "");
1770             } else {
1771                 patchConstantFunctionName = pcfName;
1772             }
1773             break;
1774         }
1775         case EatDomain:
1776         {
1777             // Handle [domain("...")]
1778             TString domainStr;
1779             if (! it->getString(domainStr)) {
1780                 error(loc, "invalid domain", "", "");
1781             } else {
1782                 TLayoutGeometry domain = ElgNone;
1783
1784                 if (domainStr == "tri") {
1785                     domain = ElgTriangles;
1786                 } else if (domainStr == "quad") {
1787                     domain = ElgQuads;
1788                 } else if (domainStr == "isoline") {
1789                     domain = ElgIsolines;
1790                 } else {
1791                     error(loc, "unsupported domain type", domainStr.c_str(), "");
1792                 }
1793
1794                 if (language == EShLangTessEvaluation) {
1795                     if (! intermediate.setInputPrimitive(domain))
1796                         error(loc, "cannot change previously set domain", TQualifier::getGeometryString(domain), "");
1797                 } else {
1798                     if (! intermediate.setOutputPrimitive(domain))
1799                         error(loc, "cannot change previously set domain", TQualifier::getGeometryString(domain), "");
1800                 }
1801             }
1802             break;
1803         }
1804         case EatOutputTopology:
1805         {
1806             // Handle [outputtopology("...")]
1807             TString topologyStr;
1808             if (! it->getString(topologyStr)) {
1809                 error(loc, "invalid outputtopology", "", "");
1810             } else {
1811                 TVertexOrder vertexOrder = EvoNone;
1812                 TLayoutGeometry primitive = ElgNone;
1813
1814                 if (topologyStr == "point") {
1815                     intermediate.setPointMode();
1816                 } else if (topologyStr == "line") {
1817                     primitive = ElgIsolines;
1818                 } else if (topologyStr == "triangle_cw") {
1819                     vertexOrder = EvoCw;
1820                     primitive = ElgTriangles;
1821                 } else if (topologyStr == "triangle_ccw") {
1822                     vertexOrder = EvoCcw;
1823                     primitive = ElgTriangles;
1824                 } else {
1825                     error(loc, "unsupported outputtopology type", topologyStr.c_str(), "");
1826                 }
1827
1828                 if (vertexOrder != EvoNone) {
1829                     if (! intermediate.setVertexOrder(vertexOrder)) {
1830                         error(loc, "cannot change previously set outputtopology",
1831                               TQualifier::getVertexOrderString(vertexOrder), "");
1832                     }
1833                 }
1834                 if (primitive != ElgNone)
1835                     intermediate.setOutputPrimitive(primitive);
1836             }
1837             break;
1838         }
1839         case EatPartitioning:
1840         {
1841             // Handle [partitioning("...")]
1842             TString partitionStr;
1843             if (! it->getString(partitionStr)) {
1844                 error(loc, "invalid partitioning", "", "");
1845             } else {
1846                 TVertexSpacing partitioning = EvsNone;
1847                 
1848                 if (partitionStr == "integer") {
1849                     partitioning = EvsEqual;
1850                 } else if (partitionStr == "fractional_even") {
1851                     partitioning = EvsFractionalEven;
1852                 } else if (partitionStr == "fractional_odd") {
1853                     partitioning = EvsFractionalOdd;
1854                     //} else if (partition == "pow2") { // TODO: currently nothing to map this to.
1855                 } else {
1856                     error(loc, "unsupported partitioning type", partitionStr.c_str(), "");
1857                 }
1858
1859                 if (! intermediate.setVertexSpacing(partitioning))
1860                     error(loc, "cannot change previously set partitioning",
1861                           TQualifier::getVertexSpacingString(partitioning), "");
1862             }
1863             break;
1864         }
1865         case EatOutputControlPoints:
1866         {
1867             // Handle [outputcontrolpoints("...")]
1868             int ctrlPoints;
1869             if (! it->getInt(ctrlPoints)) {
1870                 error(loc, "invalid outputcontrolpoints", "", "");
1871             } else {
1872                 if (! intermediate.setVertices(ctrlPoints)) {
1873                     error(loc, "cannot change previously set outputcontrolpoints attribute", "", "");
1874                 }
1875             }
1876             break;
1877         }
1878         case EatBuiltIn:
1879         case EatLocation:
1880             // tolerate these because of dual use of entrypoint and type attributes
1881             break;
1882         default:
1883             warn(loc, "attribute does not apply to entry point", "", "");
1884             break;
1885         }
1886     }
1887 }
1888
1889 // Update the given type with any type-like attribute information in the
1890 // attributes.
1891 void HlslParseContext::transferTypeAttributes(const TSourceLoc& loc, const TAttributes& attributes, TType& type,
1892     bool allowEntry)
1893 {
1894     if (attributes.size() == 0)
1895         return;
1896
1897     int value;
1898     TString builtInString;
1899     for (auto it = attributes.begin(); it != attributes.end(); ++it) {
1900         switch (it->name) {
1901         case EatLocation:
1902             // location
1903             if (it->getInt(value))
1904                 type.getQualifier().layoutLocation = value;
1905             break;
1906         case EatBinding:
1907             // binding
1908             if (it->getInt(value)) {
1909                 type.getQualifier().layoutBinding = value;
1910                 type.getQualifier().layoutSet = 0;
1911             }
1912             // set
1913             if (it->getInt(value, 1))
1914                 type.getQualifier().layoutSet = value;
1915             break;
1916         case EatGlobalBinding:
1917             // global cbuffer binding
1918             if (it->getInt(value))
1919                 globalUniformBinding = value;
1920             // global cbuffer binding
1921             if (it->getInt(value, 1))
1922                 globalUniformSet = value;
1923             break;
1924         case EatInputAttachment:
1925             // input attachment
1926             if (it->getInt(value))
1927                 type.getQualifier().layoutAttachment = value;
1928             break;
1929         case EatBuiltIn:
1930             // PointSize built-in
1931             if (it->getString(builtInString, 0, false)) {
1932                 if (builtInString == "PointSize")
1933                     type.getQualifier().builtIn = EbvPointSize;
1934             }
1935             break;
1936         case EatPushConstant:
1937             // push_constant
1938             type.getQualifier().layoutPushConstant = true;
1939             break;
1940         case EatConstantId:
1941             // specialization constant
1942             if (it->getInt(value)) {
1943                 TSourceLoc loc;
1944                 loc.init();
1945                 setSpecConstantId(loc, type.getQualifier(), value);
1946             }
1947             break;
1948         default:
1949             if (! allowEntry)
1950                 warn(loc, "attribute does not apply to a type", "", "");
1951             break;
1952         }
1953     }
1954 }
1955
1956 //
1957 // Do all special handling for the entry point, including wrapping
1958 // the shader's entry point with the official entry point that will call it.
1959 //
1960 // The following:
1961 //
1962 //    retType shaderEntryPoint(args...) // shader declared entry point
1963 //    { body }
1964 //
1965 // Becomes
1966 //
1967 //    out retType ret;
1968 //    in iargs<that are input>...;
1969 //    out oargs<that are output> ...;
1970 //
1971 //    void shaderEntryPoint()    // synthesized, but official, entry point
1972 //    {
1973 //        args<that are input> = iargs...;
1974 //        ret = @shaderEntryPoint(args...);
1975 //        oargs = args<that are output>...;
1976 //    }
1977 //    retType @shaderEntryPoint(args...)
1978 //    { body }
1979 //
1980 // The symbol table will still map the original entry point name to the
1981 // the modified function and its new name:
1982 //
1983 //    symbol table:  shaderEntryPoint  ->   @shaderEntryPoint
1984 //
1985 // Returns nullptr if no entry-point tree was built, otherwise, returns
1986 // a subtree that creates the entry point.
1987 //
1988 TIntermNode* HlslParseContext::transformEntryPoint(const TSourceLoc& loc, TFunction& userFunction,
1989                                                    const TAttributes& attributes)
1990 {
1991     // Return true if this is a tessellation patch constant function input to a domain shader.
1992     const auto isDsPcfInput = [this](const TType& type) {
1993         return language == EShLangTessEvaluation &&
1994         type.contains([](const TType* t) {
1995                 return t->getQualifier().builtIn == EbvTessLevelOuter ||
1996                        t->getQualifier().builtIn == EbvTessLevelInner;
1997             });
1998     };
1999
2000     // if we aren't in the entry point, fix the IO as such and exit
2001     if (userFunction.getName().compare(intermediate.getEntryPointName().c_str()) != 0) {
2002         remapNonEntryPointIO(userFunction);
2003         return nullptr;
2004     }
2005
2006     entryPointFunction = &userFunction; // needed in finish()
2007
2008     // Handle entry point attributes
2009     handleEntryPointAttributes(loc, attributes);
2010
2011     // entry point logic...
2012
2013     // Move parameters and return value to shader in/out
2014     TVariable* entryPointOutput; // gets created in remapEntryPointIO
2015     TVector<TVariable*> inputs;
2016     TVector<TVariable*> outputs;
2017     remapEntryPointIO(userFunction, entryPointOutput, inputs, outputs);
2018
2019     // Further this return/in/out transform by flattening, splitting, and assigning locations
2020     const auto makeVariableInOut = [&](TVariable& variable) {
2021         if (variable.getType().isStruct()) {
2022             if (variable.getType().getQualifier().isArrayedIo(language)) {
2023                 if (variable.getType().containsBuiltIn())
2024                     split(variable);
2025             } else if (shouldFlatten(variable.getType(), EvqVaryingIn /* not assigned yet, but close enough */, true))
2026                 flatten(variable, false /* don't track linkage here, it will be tracked in assignToInterface() */);
2027         }
2028         // TODO: flatten arrays too
2029         // TODO: flatten everything in I/O
2030         // TODO: replace all split with flatten, make all paths can create flattened I/O, then split code can be removed
2031
2032         // For clip and cull distance, multiple output variables potentially get merged
2033         // into one in assignClipCullDistance.  That code in assignClipCullDistance
2034         // handles the interface logic, so we avoid it here in that case.
2035         if (!isClipOrCullDistance(variable.getType()))
2036             assignToInterface(variable);
2037     };
2038     if (entryPointOutput != nullptr)
2039         makeVariableInOut(*entryPointOutput);
2040     for (auto it = inputs.begin(); it != inputs.end(); ++it)
2041         if (!isDsPcfInput((*it)->getType()))  // wait until the end for PCF input (see comment below)
2042             makeVariableInOut(*(*it));
2043     for (auto it = outputs.begin(); it != outputs.end(); ++it)
2044         makeVariableInOut(*(*it));
2045
2046     // In the domain shader, PCF input must be at the end of the linkage.  That's because in the
2047     // hull shader there is no ordering: the output comes from the separate PCF, which does not
2048     // participate in the argument list.  That is always put at the end of the HS linkage, so the
2049     // input side of the DS must match.  The argument may be in any position in the DS argument list
2050     // however, so this ensures the linkage is built in the correct order regardless of argument order.
2051     if (language == EShLangTessEvaluation) {
2052         for (auto it = inputs.begin(); it != inputs.end(); ++it)
2053             if (isDsPcfInput((*it)->getType()))
2054                 makeVariableInOut(*(*it));
2055     }
2056
2057     // Synthesize the call
2058
2059     pushScope(); // matches the one in handleFunctionBody()
2060
2061     // new signature
2062     TType voidType(EbtVoid);
2063     TFunction synthEntryPoint(&userFunction.getName(), voidType);
2064     TIntermAggregate* synthParams = new TIntermAggregate();
2065     intermediate.setAggregateOperator(synthParams, EOpParameters, voidType, loc);
2066     intermediate.setEntryPointMangledName(synthEntryPoint.getMangledName().c_str());
2067     intermediate.incrementEntryPointCount();
2068     TFunction callee(&userFunction.getName(), voidType); // call based on old name, which is still in the symbol table
2069
2070     // change original name
2071     userFunction.addPrefix("@");                         // change the name in the function, but not in the symbol table
2072
2073     // Copy inputs (shader-in -> calling arg), while building up the call node
2074     TVector<TVariable*> argVars;
2075     TIntermAggregate* synthBody = new TIntermAggregate();
2076     auto inputIt = inputs.begin();
2077     TIntermTyped* callingArgs = nullptr;
2078
2079     for (int i = 0; i < userFunction.getParamCount(); i++) {
2080         TParameter& param = userFunction[i];
2081         argVars.push_back(makeInternalVariable(*param.name, *param.type));
2082         argVars.back()->getWritableType().getQualifier().makeTemporary();
2083
2084         // Track the input patch, which is the only non-builtin supported by hull shader PCF.
2085         if (param.getDeclaredBuiltIn() == EbvInputPatch)
2086             inputPatch = argVars.back();
2087
2088         TIntermSymbol* arg = intermediate.addSymbol(*argVars.back());
2089         handleFunctionArgument(&callee, callingArgs, arg);
2090         if (param.type->getQualifier().isParamInput()) {
2091             intermediate.growAggregate(synthBody, handleAssign(loc, EOpAssign, arg,
2092                                                                intermediate.addSymbol(**inputIt)));
2093             inputIt++;
2094         }
2095     }
2096
2097     // Call
2098     currentCaller = synthEntryPoint.getMangledName();
2099     TIntermTyped* callReturn = handleFunctionCall(loc, &callee, callingArgs);
2100     currentCaller = userFunction.getMangledName();
2101
2102     // Return value
2103     if (entryPointOutput) {
2104         TIntermTyped* returnAssign;
2105
2106         // For hull shaders, the wrapped entry point return value is written to
2107         // an array element as indexed by invocation ID, which we might have to make up.
2108         // This is required to match SPIR-V semantics.
2109         if (language == EShLangTessControl) {
2110             TIntermSymbol* invocationIdSym = findTessLinkageSymbol(EbvInvocationId);
2111
2112             // If there is no user declared invocation ID, we must make one.
2113             if (invocationIdSym == nullptr) {
2114                 TType invocationIdType(EbtUint, EvqIn, 1);
2115                 TString* invocationIdName = NewPoolTString("InvocationId");
2116                 invocationIdType.getQualifier().builtIn = EbvInvocationId;
2117
2118                 TVariable* variable = makeInternalVariable(*invocationIdName, invocationIdType);
2119
2120                 globalQualifierFix(loc, variable->getWritableType().getQualifier());
2121                 trackLinkage(*variable);
2122
2123                 invocationIdSym = intermediate.addSymbol(*variable);
2124             }
2125
2126             TIntermTyped* element = intermediate.addIndex(EOpIndexIndirect, intermediate.addSymbol(*entryPointOutput),
2127                                                           invocationIdSym, loc);
2128
2129             // Set the type of the array element being dereferenced
2130             const TType derefElementType(entryPointOutput->getType(), 0);
2131             element->setType(derefElementType);
2132
2133             returnAssign = handleAssign(loc, EOpAssign, element, callReturn);
2134         } else {
2135             returnAssign = handleAssign(loc, EOpAssign, intermediate.addSymbol(*entryPointOutput), callReturn);
2136         }
2137         intermediate.growAggregate(synthBody, returnAssign);
2138     } else
2139         intermediate.growAggregate(synthBody, callReturn);
2140
2141     // Output copies
2142     auto outputIt = outputs.begin();
2143     for (int i = 0; i < userFunction.getParamCount(); i++) {
2144         TParameter& param = userFunction[i];
2145
2146         // GS outputs are via emit, so we do not copy them here.
2147         if (param.type->getQualifier().isParamOutput()) {
2148             if (param.getDeclaredBuiltIn() == EbvGsOutputStream) {
2149                 // GS output stream does not assign outputs here: it's the Append() method
2150                 // which writes to the output, probably multiple times separated by Emit.
2151                 // We merely remember the output to use, here.
2152                 gsStreamOutput = *outputIt;
2153             } else {
2154                 intermediate.growAggregate(synthBody, handleAssign(loc, EOpAssign,
2155                                                                    intermediate.addSymbol(**outputIt),
2156                                                                    intermediate.addSymbol(*argVars[i])));
2157             }
2158
2159             outputIt++;
2160         }
2161     }
2162
2163     // Put the pieces together to form a full function subtree
2164     // for the synthesized entry point.
2165     synthBody->setOperator(EOpSequence);
2166     TIntermNode* synthFunctionDef = synthParams;
2167     handleFunctionBody(loc, synthEntryPoint, synthBody, synthFunctionDef);
2168
2169     entryPointFunctionBody = synthBody;
2170
2171     return synthFunctionDef;
2172 }
2173
2174 void HlslParseContext::handleFunctionBody(const TSourceLoc& loc, TFunction& function, TIntermNode* functionBody,
2175                                           TIntermNode*& node)
2176 {
2177     node = intermediate.growAggregate(node, functionBody);
2178     intermediate.setAggregateOperator(node, EOpFunction, function.getType(), loc);
2179     node->getAsAggregate()->setName(function.getMangledName().c_str());
2180
2181     popScope();
2182     if (function.hasImplicitThis())
2183         popImplicitThis();
2184
2185     if (function.getType().getBasicType() != EbtVoid && ! functionReturnsValue)
2186         error(loc, "function does not return a value:", "", function.getName().c_str());
2187 }
2188
2189 // AST I/O is done through shader globals declared in the 'in' or 'out'
2190 // storage class.  An HLSL entry point has a return value, input parameters
2191 // and output parameters.  These need to get remapped to the AST I/O.
2192 void HlslParseContext::remapEntryPointIO(TFunction& function, TVariable*& returnValue,
2193     TVector<TVariable*>& inputs, TVector<TVariable*>& outputs)
2194 {
2195     // We might have in input structure type with no decorations that caused it
2196     // to look like an input type, yet it has (e.g.) interpolation types that
2197     // must be modified that turn it into an input type.
2198     // Hence, a missing ioTypeMap for 'input' might need to be synthesized.
2199     const auto synthesizeEditedInput = [this](TType& type) {
2200         // True if a type needs to be 'flat'
2201         const auto needsFlat = [](const TType& type) {
2202             return type.containsBasicType(EbtInt) ||
2203                     type.containsBasicType(EbtUint) ||
2204                     type.containsBasicType(EbtInt64) ||
2205                     type.containsBasicType(EbtUint64) ||
2206                     type.containsBasicType(EbtBool) ||
2207                     type.containsBasicType(EbtDouble);
2208         };
2209
2210         if (language == EShLangFragment && needsFlat(type)) {
2211             if (type.isStruct()) {
2212                 TTypeList* finalList = nullptr;
2213                 auto it = ioTypeMap.find(type.getStruct());
2214                 if (it == ioTypeMap.end() || it->second.input == nullptr) {
2215                     // Getting here means we have no input struct, but we need one.
2216                     auto list = new TTypeList;
2217                     for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member) {
2218                         TType* newType = new TType;
2219                         newType->shallowCopy(*member->type);
2220                         TTypeLoc typeLoc = { newType, member->loc };
2221                         list->push_back(typeLoc);
2222                     }
2223                     // install the new input type
2224                     if (it == ioTypeMap.end()) {
2225                         tIoKinds newLists = { list, nullptr, nullptr };
2226                         ioTypeMap[type.getStruct()] = newLists;
2227                     } else
2228                         it->second.input = list;
2229                     finalList = list;
2230                 } else
2231                     finalList = it->second.input;
2232                 // edit for 'flat'
2233                 for (auto member = finalList->begin(); member != finalList->end(); ++member) {
2234                     if (needsFlat(*member->type)) {
2235                         member->type->getQualifier().clearInterpolation();
2236                         member->type->getQualifier().flat = true;
2237                     }
2238                 }
2239             } else {
2240                 type.getQualifier().clearInterpolation();
2241                 type.getQualifier().flat = true;
2242             }
2243         }
2244     };
2245
2246     // Do the actual work to make a type be a shader input or output variable,
2247     // and clear the original to be non-IO (for use as a normal function parameter/return).
2248     const auto makeIoVariable = [this](const char* name, TType& type, TStorageQualifier storage) -> TVariable* {
2249         TVariable* ioVariable = makeInternalVariable(name, type);
2250         clearUniformInputOutput(type.getQualifier());
2251         if (type.isStruct()) {
2252             auto newLists = ioTypeMap.find(ioVariable->getType().getStruct());
2253             if (newLists != ioTypeMap.end()) {
2254                 if (storage == EvqVaryingIn && newLists->second.input)
2255                     ioVariable->getWritableType().setStruct(newLists->second.input);
2256                 else if (storage == EvqVaryingOut && newLists->second.output)
2257                     ioVariable->getWritableType().setStruct(newLists->second.output);
2258             }
2259         }
2260         if (storage == EvqVaryingIn) {
2261             correctInput(ioVariable->getWritableType().getQualifier());
2262             if (language == EShLangTessEvaluation)
2263                 if (!ioVariable->getType().isArray())
2264                     ioVariable->getWritableType().getQualifier().patch = true;
2265         } else {
2266             correctOutput(ioVariable->getWritableType().getQualifier());
2267         }
2268         ioVariable->getWritableType().getQualifier().storage = storage;
2269
2270         fixBuiltInIoType(ioVariable->getWritableType());
2271
2272         return ioVariable;
2273     };
2274
2275     // return value is actually a shader-scoped output (out)
2276     if (function.getType().getBasicType() == EbtVoid) {
2277         returnValue = nullptr;
2278     } else {
2279         if (language == EShLangTessControl) {
2280             // tessellation evaluation in HLSL writes a per-ctrl-pt value, but it needs to be an
2281             // array in SPIR-V semantics.  We'll write to it indexed by invocation ID.
2282
2283             returnValue = makeIoVariable("@entryPointOutput", function.getWritableType(), EvqVaryingOut);
2284
2285             TType outputType;
2286             outputType.shallowCopy(function.getType());
2287
2288             // vertices has necessarily already been set when handling entry point attributes.
2289             TArraySizes* arraySizes = new TArraySizes;
2290             arraySizes->addInnerSize(intermediate.getVertices());
2291             outputType.transferArraySizes(arraySizes);
2292
2293             clearUniformInputOutput(function.getWritableType().getQualifier());
2294             returnValue = makeIoVariable("@entryPointOutput", outputType, EvqVaryingOut);
2295         } else {
2296             returnValue = makeIoVariable("@entryPointOutput", function.getWritableType(), EvqVaryingOut);
2297         }
2298     }
2299
2300     // parameters are actually shader-scoped inputs and outputs (in or out)
2301     for (int i = 0; i < function.getParamCount(); i++) {
2302         TType& paramType = *function[i].type;
2303         if (paramType.getQualifier().isParamInput()) {
2304             synthesizeEditedInput(paramType);
2305             TVariable* argAsGlobal = makeIoVariable(function[i].name->c_str(), paramType, EvqVaryingIn);
2306             inputs.push_back(argAsGlobal);
2307         }
2308         if (paramType.getQualifier().isParamOutput()) {
2309             TVariable* argAsGlobal = makeIoVariable(function[i].name->c_str(), paramType, EvqVaryingOut);
2310             outputs.push_back(argAsGlobal);
2311         }
2312     }
2313 }
2314
2315 // An HLSL function that looks like an entry point, but is not,
2316 // declares entry point IO built-ins, but these have to be undone.
2317 void HlslParseContext::remapNonEntryPointIO(TFunction& function)
2318 {
2319     // return value
2320     if (function.getType().getBasicType() != EbtVoid)
2321         clearUniformInputOutput(function.getWritableType().getQualifier());
2322
2323     // parameters.
2324     // References to structuredbuffer types are left unmodified
2325     for (int i = 0; i < function.getParamCount(); i++)
2326         if (!isReference(*function[i].type))
2327             clearUniformInputOutput(function[i].type->getQualifier());
2328 }
2329
2330 // Handle function returns, including type conversions to the function return type
2331 // if necessary.
2332 TIntermNode* HlslParseContext::handleReturnValue(const TSourceLoc& loc, TIntermTyped* value)
2333 {
2334     functionReturnsValue = true;
2335
2336     if (currentFunctionType->getBasicType() == EbtVoid) {
2337         error(loc, "void function cannot return a value", "return", "");
2338         return intermediate.addBranch(EOpReturn, loc);
2339     } else if (*currentFunctionType != value->getType()) {
2340         value = intermediate.addConversion(EOpReturn, *currentFunctionType, value);
2341         if (value && *currentFunctionType != value->getType())
2342             value = intermediate.addUniShapeConversion(EOpReturn, *currentFunctionType, value);
2343         if (value == nullptr || *currentFunctionType != value->getType()) {
2344             error(loc, "type does not match, or is not convertible to, the function's return type", "return", "");
2345             return value;
2346         }
2347     }
2348
2349     return intermediate.addBranch(EOpReturn, value, loc);
2350 }
2351
2352 void HlslParseContext::handleFunctionArgument(TFunction* function,
2353                                               TIntermTyped*& arguments, TIntermTyped* newArg)
2354 {
2355     TParameter param = { 0, new TType, nullptr };
2356     param.type->shallowCopy(newArg->getType());
2357
2358     function->addParameter(param);
2359     if (arguments)
2360         arguments = intermediate.growAggregate(arguments, newArg);
2361     else
2362         arguments = newArg;
2363 }
2364
2365 // Position may require special handling: we can optionally invert Y.
2366 // See: https://github.com/KhronosGroup/glslang/issues/1173
2367 //      https://github.com/KhronosGroup/glslang/issues/494
2368 TIntermTyped* HlslParseContext::assignPosition(const TSourceLoc& loc, TOperator op,
2369                                                TIntermTyped* left, TIntermTyped* right)
2370 {
2371     // If we are not asked for Y inversion, use a plain old assign.
2372     if (!intermediate.getInvertY())
2373         return intermediate.addAssign(op, left, right, loc);
2374
2375     // If we get here, we should invert Y.
2376     TIntermAggregate* assignList = nullptr;
2377
2378     // If this is a complex rvalue, we don't want to dereference it many times.  Create a temporary.
2379     TVariable* rhsTempVar = nullptr;
2380     rhsTempVar = makeInternalVariable("@position", right->getType());
2381     rhsTempVar->getWritableType().getQualifier().makeTemporary();
2382
2383     {
2384         TIntermTyped* rhsTempSym = intermediate.addSymbol(*rhsTempVar, loc);
2385         assignList = intermediate.growAggregate(assignList,
2386                                                 intermediate.addAssign(EOpAssign, rhsTempSym, right, loc), loc);
2387     }
2388
2389     // pos.y = -pos.y
2390     {
2391         const int Y = 1;
2392
2393         TIntermTyped* tempSymL = intermediate.addSymbol(*rhsTempVar, loc);
2394         TIntermTyped* tempSymR = intermediate.addSymbol(*rhsTempVar, loc);
2395         TIntermTyped* index = intermediate.addConstantUnion(Y, loc);
2396
2397         TIntermTyped* lhsElement = intermediate.addIndex(EOpIndexDirect, tempSymL, index, loc);
2398         TIntermTyped* rhsElement = intermediate.addIndex(EOpIndexDirect, tempSymR, index, loc);
2399
2400         const TType derefType(right->getType(), 0);
2401     
2402         lhsElement->setType(derefType);
2403         rhsElement->setType(derefType);
2404
2405         TIntermTyped* yNeg = intermediate.addUnaryMath(EOpNegative, rhsElement, loc);
2406
2407         assignList = intermediate.growAggregate(assignList, intermediate.addAssign(EOpAssign, lhsElement, yNeg, loc));
2408     }
2409
2410     // Assign the rhs temp (now with Y inversion) to the final output
2411     {
2412         TIntermTyped* rhsTempSym = intermediate.addSymbol(*rhsTempVar, loc);
2413         assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, left, rhsTempSym, loc));
2414     }
2415
2416     assert(assignList != nullptr);
2417     assignList->setOperator(EOpSequence);
2418
2419     return assignList;
2420 }
2421     
2422 // Clip and cull distance require special handling due to a semantic mismatch.  In HLSL,
2423 // these can be float scalar, float vector, or arrays of float scalar or float vector.
2424 // In SPIR-V, they are arrays of scalar floats in all cases.  We must copy individual components
2425 // (e.g, both x and y components of a float2) out into the destination float array.
2426 //
2427 // The values are assigned to sequential members of the output array.  The inner dimension
2428 // is vector components.  The outer dimension is array elements.
2429 TIntermAggregate* HlslParseContext::assignClipCullDistance(const TSourceLoc& loc, TOperator op, int semanticId,
2430                                                            TIntermTyped* left, TIntermTyped* right)
2431 {
2432     switch (language) {
2433     case EShLangFragment:
2434     case EShLangVertex:
2435     case EShLangGeometry:
2436         break;
2437     default:
2438         error(loc, "unimplemented: clip/cull not currently implemented for this stage", "", "");
2439         return nullptr;
2440     }
2441
2442     TVariable** clipCullVar = nullptr;
2443
2444     // Figure out if we are assigning to, or from, clip or cull distance.
2445     const bool isOutput = isClipOrCullDistance(left->getType());
2446
2447     // This is the rvalue or lvalue holding the clip or cull distance.
2448     TIntermTyped* clipCullNode = isOutput ? left : right;
2449     // This is the value going into or out of the clip or cull distance.
2450     TIntermTyped* internalNode = isOutput ? right : left;
2451
2452     const TBuiltInVariable builtInType = clipCullNode->getQualifier().builtIn;
2453
2454     decltype(clipSemanticNSizeIn)* semanticNSize = nullptr;
2455
2456     // Refer to either the clip or the cull distance, depending on semantic.
2457     switch (builtInType) {
2458     case EbvClipDistance:
2459         clipCullVar = isOutput ? &clipDistanceOutput : &clipDistanceInput;
2460         semanticNSize = isOutput ? &clipSemanticNSizeOut : &clipSemanticNSizeIn;
2461         break;
2462     case EbvCullDistance:
2463         clipCullVar = isOutput ? &cullDistanceOutput : &cullDistanceInput;
2464         semanticNSize = isOutput ? &cullSemanticNSizeOut : &cullSemanticNSizeIn;
2465         break;
2466
2467     // called invalidly: we expected a clip or a cull distance.
2468     // static compile time problem: should not happen.
2469     default: assert(0); return nullptr;
2470     }
2471
2472     // This is the offset in the destination array of a given semantic's data
2473     std::array<int, maxClipCullRegs> semanticOffset;
2474
2475     // Calculate offset of variable of semantic N in destination array
2476     int arrayLoc = 0;
2477     int vecItems = 0;
2478
2479     for (int x = 0; x < maxClipCullRegs; ++x) {
2480         // See if we overflowed the vec4 packing
2481         if ((vecItems + (*semanticNSize)[x]) > 4) {
2482             arrayLoc = (arrayLoc + 3) & (~0x3); // round up to next multiple of 4
2483             vecItems = 0;
2484         }
2485
2486         semanticOffset[x] = arrayLoc;
2487         vecItems += (*semanticNSize)[x];
2488         arrayLoc += (*semanticNSize)[x];
2489     }
2490  
2491
2492     // It can have up to 2 array dimensions (in the case of geometry shader inputs)
2493     const TArraySizes* const internalArraySizes = internalNode->getType().getArraySizes();
2494     const int internalArrayDims = internalNode->getType().isArray() ? internalArraySizes->getNumDims() : 0;
2495     // vector sizes:
2496     const int internalVectorSize = internalNode->getType().getVectorSize();
2497     // array sizes, or 1 if it's not an array:
2498     const int internalInnerArraySize = (internalArrayDims > 0 ? internalArraySizes->getDimSize(internalArrayDims-1) : 1);
2499     const int internalOuterArraySize = (internalArrayDims > 1 ? internalArraySizes->getDimSize(0) : 1);
2500
2501     // The created type may be an array of arrays, e.g, for geometry shader inputs.
2502     const bool isImplicitlyArrayed = (language == EShLangGeometry && !isOutput);
2503
2504     // If we haven't created the output already, create it now.
2505     if (*clipCullVar == nullptr) {
2506         // ClipDistance and CullDistance are handled specially in the entry point input/output copy
2507         // algorithm, because they may need to be unpacked from components of vectors (or a scalar)
2508         // into a float array, or vice versa.  Here, we make the array the right size and type,
2509         // which depends on the incoming data, which has several potential dimensions:
2510         //    * Semantic ID
2511         //    * vector size 
2512         //    * array size
2513         // Of those, semantic ID and array size cannot appear simultaneously.
2514         //
2515         // Also to note: for implicitly arrayed forms (e.g, geometry shader inputs), we need to create two
2516         // array dimensions.  The shader's declaration may have one or two array dimensions.  One is always
2517         // the geometry's dimension.
2518
2519         const bool useInnerSize = internalArrayDims > 1 || !isImplicitlyArrayed;
2520
2521         const int requiredInnerArraySize = arrayLoc * (useInnerSize ? internalInnerArraySize : 1);
2522         const int requiredOuterArraySize = (internalArrayDims > 0) ? internalArraySizes->getDimSize(0) : 1;
2523
2524         TType clipCullType(EbtFloat, clipCullNode->getType().getQualifier().storage, 1);
2525         clipCullType.getQualifier() = clipCullNode->getType().getQualifier();
2526
2527         // Create required array dimension
2528         TArraySizes* arraySizes = new TArraySizes;
2529         if (isImplicitlyArrayed)
2530             arraySizes->addInnerSize(requiredOuterArraySize);
2531         arraySizes->addInnerSize(requiredInnerArraySize);
2532         clipCullType.transferArraySizes(arraySizes);
2533
2534         // Obtain symbol name: we'll use that for the symbol we introduce.
2535         TIntermSymbol* sym = clipCullNode->getAsSymbolNode();
2536         assert(sym != nullptr);
2537
2538         // We are moving the semantic ID from the layout location, so it is no longer needed or
2539         // desired there.
2540         clipCullType.getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
2541
2542         // Create variable and track its linkage
2543         *clipCullVar = makeInternalVariable(sym->getName().c_str(), clipCullType);
2544
2545         trackLinkage(**clipCullVar);
2546     }
2547
2548     // Create symbol for the clip or cull variable.
2549     TIntermSymbol* clipCullSym = intermediate.addSymbol(**clipCullVar);
2550
2551     // vector sizes:
2552     const int clipCullVectorSize = clipCullSym->getType().getVectorSize();
2553
2554     // array sizes, or 1 if it's not an array:
2555     const TArraySizes* const clipCullArraySizes = clipCullSym->getType().getArraySizes();
2556     const int clipCullOuterArraySize = isImplicitlyArrayed ? clipCullArraySizes->getDimSize(0) : 1;
2557     const int clipCullInnerArraySize = clipCullArraySizes->getDimSize(isImplicitlyArrayed ? 1 : 0);
2558
2559     // clipCullSym has got to be an array of scalar floats, per SPIR-V semantics.
2560     // fixBuiltInIoType() should have handled that upstream.
2561     assert(clipCullSym->getType().isArray());
2562     assert(clipCullSym->getType().getVectorSize() == 1);
2563     assert(clipCullSym->getType().getBasicType() == EbtFloat);
2564
2565     // We may be creating multiple sub-assignments.  This is an aggregate to hold them.
2566     // TODO: it would be possible to be clever sometimes and avoid the sequence node if not needed.
2567     TIntermAggregate* assignList = nullptr;
2568
2569     // Holds individual component assignments as we make them.
2570     TIntermTyped* clipCullAssign = nullptr;
2571
2572     // If the types are homomorphic, use a simple assign.  No need to mess about with 
2573     // individual components.
2574     if (clipCullSym->getType().isArray() == internalNode->getType().isArray() &&
2575         clipCullInnerArraySize == internalInnerArraySize &&
2576         clipCullOuterArraySize == internalOuterArraySize &&
2577         clipCullVectorSize == internalVectorSize) {
2578
2579         if (isOutput)
2580             clipCullAssign = intermediate.addAssign(op, clipCullSym, internalNode, loc);
2581         else
2582             clipCullAssign = intermediate.addAssign(op, internalNode, clipCullSym, loc);
2583
2584         assignList = intermediate.growAggregate(assignList, clipCullAssign);
2585         assignList->setOperator(EOpSequence);
2586
2587         return assignList;
2588     }
2589
2590     // We are going to copy each component of the internal (per array element if indicated) to sequential
2591     // array elements of the clipCullSym.  This tracks the lhs element we're writing to as we go along.
2592     // We may be starting in the middle - e.g, for a non-zero semantic ID calculated above.
2593     int clipCullInnerArrayPos = semanticOffset[semanticId];
2594     int clipCullOuterArrayPos = 0;
2595
2596     // Lambda to add an index to a node, set the type of the result, and return the new node.
2597     const auto addIndex = [this, &loc](TIntermTyped* node, int pos) -> TIntermTyped* {
2598         const TType derefType(node->getType(), 0);
2599         node = intermediate.addIndex(EOpIndexDirect, node, intermediate.addConstantUnion(pos, loc), loc);
2600         node->setType(derefType);
2601         return node;
2602     };
2603
2604     // Loop through every component of every element of the internal, and copy to or from the matching external.
2605     for (int internalOuterArrayPos = 0; internalOuterArrayPos < internalOuterArraySize; ++internalOuterArrayPos) {
2606         for (int internalInnerArrayPos = 0; internalInnerArrayPos < internalInnerArraySize; ++internalInnerArrayPos) {
2607             for (int internalComponent = 0; internalComponent < internalVectorSize; ++internalComponent) {
2608                 // clip/cull array member to read from / write to:
2609                 TIntermTyped* clipCullMember = clipCullSym;
2610
2611                 // If implicitly arrayed, there is an outer array dimension involved
2612                 if (isImplicitlyArrayed)
2613                     clipCullMember = addIndex(clipCullMember, clipCullOuterArrayPos);
2614
2615                 // Index into proper array position for clip cull member
2616                 clipCullMember = addIndex(clipCullMember, clipCullInnerArrayPos++);
2617
2618                 // if needed, start over with next outer array slice.
2619                 if (isImplicitlyArrayed && clipCullInnerArrayPos >= clipCullInnerArraySize) {
2620                     clipCullInnerArrayPos = semanticOffset[semanticId];
2621                     ++clipCullOuterArrayPos;
2622                 }
2623
2624                 // internal member to read from / write to:
2625                 TIntermTyped* internalMember = internalNode;
2626
2627                 // If internal node has outer array dimension, index appropriately.
2628                 if (internalArrayDims > 1)
2629                     internalMember = addIndex(internalMember, internalOuterArrayPos);
2630
2631                 // If internal node has inner array dimension, index appropriately.
2632                 if (internalArrayDims > 0)
2633                     internalMember = addIndex(internalMember, internalInnerArrayPos);
2634
2635                 // If internal node is a vector, extract the component of interest.
2636                 if (internalNode->getType().isVector())
2637                     internalMember = addIndex(internalMember, internalComponent);
2638
2639                 // Create an assignment: output from internal to clip cull, or input from clip cull to internal.
2640                 if (isOutput)
2641                     clipCullAssign = intermediate.addAssign(op, clipCullMember, internalMember, loc);
2642                 else
2643                     clipCullAssign = intermediate.addAssign(op, internalMember, clipCullMember, loc);
2644
2645                 // Track assignment in the sequence.
2646                 assignList = intermediate.growAggregate(assignList, clipCullAssign);
2647             }
2648         }
2649     }
2650
2651     assert(assignList != nullptr);
2652     assignList->setOperator(EOpSequence);
2653
2654     return assignList;
2655 }
2656
2657 // Some simple source assignments need to be flattened to a sequence
2658 // of AST assignments. Catch these and flatten, otherwise, pass through
2659 // to intermediate.addAssign().
2660 //
2661 // Also, assignment to matrix swizzles requires multiple component assignments,
2662 // intercept those as well.
2663 TIntermTyped* HlslParseContext::handleAssign(const TSourceLoc& loc, TOperator op, TIntermTyped* left,
2664                                              TIntermTyped* right)
2665 {
2666     if (left == nullptr || right == nullptr)
2667         return nullptr;
2668
2669     // writing to opaques will require fixing transforms
2670     if (left->getType().containsOpaque())
2671         intermediate.setNeedsLegalization();
2672
2673     if (left->getAsOperator() && left->getAsOperator()->getOp() == EOpMatrixSwizzle)
2674         return handleAssignToMatrixSwizzle(loc, op, left, right);
2675
2676     // Return true if the given node is an index operation into a split variable.
2677     const auto indexesSplit = [this](const TIntermTyped* node) -> bool {
2678         const TIntermBinary* binaryNode = node->getAsBinaryNode();
2679
2680         if (binaryNode == nullptr)
2681             return false;
2682
2683         return (binaryNode->getOp() == EOpIndexDirect || binaryNode->getOp() == EOpIndexIndirect) && 
2684                wasSplit(binaryNode->getLeft());
2685     };
2686
2687     // Return true if this stage assigns clip position with potentially inverted Y
2688     const auto assignsClipPos = [this](const TIntermTyped* node) -> bool {
2689         return node->getType().getQualifier().builtIn == EbvPosition &&
2690                (language == EShLangVertex || language == EShLangGeometry || language == EShLangTessEvaluation);
2691     };
2692
2693     const bool isSplitLeft    = wasSplit(left) || indexesSplit(left);
2694     const bool isSplitRight   = wasSplit(right) || indexesSplit(right);
2695
2696     const bool isFlattenLeft  = wasFlattened(left);
2697     const bool isFlattenRight = wasFlattened(right);
2698
2699     // OK to do a single assign if neither side is split or flattened.  Otherwise, 
2700     // fall through to a member-wise copy.
2701     if (!isFlattenLeft && !isFlattenRight && !isSplitLeft && !isSplitRight) {
2702         // Clip and cull distance requires more processing.  See comment above assignClipCullDistance.
2703         if (isClipOrCullDistance(left->getType()) || isClipOrCullDistance(right->getType())) {
2704             const bool isOutput = isClipOrCullDistance(left->getType());
2705
2706             const int semanticId = (isOutput ? left : right)->getType().getQualifier().layoutLocation;
2707             return assignClipCullDistance(loc, op, semanticId, left, right);
2708         } else if (assignsClipPos(left)) {
2709             // Position can require special handling: see comment above assignPosition
2710             return assignPosition(loc, op, left, right);
2711         } else if (left->getQualifier().builtIn == EbvSampleMask) {
2712             // Certain builtins are required to be arrayed outputs in SPIR-V, but may internally be scalars
2713             // in the shader.  Copy the scalar RHS into the LHS array element zero, if that happens.
2714             if (left->isArray() && !right->isArray()) {
2715                 const TType derefType(left->getType(), 0);
2716                 left = intermediate.addIndex(EOpIndexDirect, left, intermediate.addConstantUnion(0, loc), loc);
2717                 left->setType(derefType);
2718                 // Fall through to add assign.
2719             }
2720         }
2721
2722         return intermediate.addAssign(op, left, right, loc);
2723     }
2724
2725     TIntermAggregate* assignList = nullptr;
2726     const TVector<TVariable*>* leftVariables = nullptr;
2727     const TVector<TVariable*>* rightVariables = nullptr;
2728
2729     // A temporary to store the right node's value, so we don't keep indirecting into it
2730     // if it's not a simple symbol.
2731     TVariable* rhsTempVar = nullptr;
2732
2733     // If the RHS is a simple symbol node, we'll copy it for each member.
2734     TIntermSymbol* cloneSymNode = nullptr;
2735
2736     int memberCount = 0;
2737
2738     // Track how many items there are to copy.
2739     if (left->getType().isStruct())
2740         memberCount = (int)left->getType().getStruct()->size();
2741     if (left->getType().isArray())
2742         memberCount = left->getType().getCumulativeArraySize();
2743
2744     if (isFlattenLeft)
2745         leftVariables = &flattenMap.find(left->getAsSymbolNode()->getId())->second.members;
2746
2747     if (isFlattenRight) {
2748         rightVariables = &flattenMap.find(right->getAsSymbolNode()->getId())->second.members;
2749     } else {
2750         // The RHS is not flattened.  There are several cases:
2751         // 1. 1 item to copy:  Use the RHS directly.
2752         // 2. >1 item, simple symbol RHS: we'll create a new TIntermSymbol node for each, but no assign to temp.
2753         // 3. >1 item, complex RHS: assign it to a new temp variable, and create a TIntermSymbol for each member.
2754
2755         if (memberCount <= 1) {
2756             // case 1: we'll use the symbol directly below.  Nothing to do.
2757         } else {
2758             if (right->getAsSymbolNode() != nullptr) {
2759                 // case 2: we'll copy the symbol per iteration below.
2760                 cloneSymNode = right->getAsSymbolNode();
2761             } else {
2762                 // case 3: assign to a temp, and indirect into that.
2763                 rhsTempVar = makeInternalVariable("flattenTemp", right->getType());
2764                 rhsTempVar->getWritableType().getQualifier().makeTemporary();
2765                 TIntermTyped* noFlattenRHS = intermediate.addSymbol(*rhsTempVar, loc);
2766
2767                 // Add this to the aggregate being built.
2768                 assignList = intermediate.growAggregate(assignList,
2769                                                         intermediate.addAssign(op, noFlattenRHS, right, loc), loc);
2770             }
2771         }
2772     }
2773
2774     // When dealing with split arrayed structures of built-ins, the arrayness is moved to the extracted built-in
2775     // variables, which is awkward when copying between split and unsplit structures.  This variable tracks
2776     // array indirections so they can be percolated from outer structs to inner variables.
2777     std::vector <int> arrayElement;
2778
2779     TStorageQualifier leftStorage = left->getType().getQualifier().storage;
2780     TStorageQualifier rightStorage = right->getType().getQualifier().storage;
2781
2782     int leftOffset = findSubtreeOffset(*left);
2783     int rightOffset = findSubtreeOffset(*right);
2784
2785     const auto getMember = [&](bool isLeft, const TType& type, int member, TIntermTyped* splitNode, int splitMember,
2786                                bool flattened)
2787                            -> TIntermTyped * {
2788         const bool split     = isLeft ? isSplitLeft   : isSplitRight;
2789
2790         TIntermTyped* subTree;
2791         const TType derefType(type, member);
2792         const TVariable* builtInVar = nullptr;
2793         if ((flattened || split) && derefType.isBuiltIn()) {
2794             auto splitPair = splitBuiltIns.find(HlslParseContext::tInterstageIoData(
2795                                                    derefType.getQualifier().builtIn,
2796                                                    isLeft ? leftStorage : rightStorage));
2797             if (splitPair != splitBuiltIns.end())
2798                 builtInVar = splitPair->second;
2799         }
2800         if (builtInVar != nullptr) {
2801             // copy from interstage IO built-in if needed
2802             subTree = intermediate.addSymbol(*builtInVar);
2803
2804             if (subTree->getType().isArray()) {
2805                 // Arrayness of builtIn symbols isn't handled by the normal recursion:
2806                 // it's been extracted and moved to the built-in.
2807                 if (!arrayElement.empty()) {
2808                     const TType splitDerefType(subTree->getType(), arrayElement.back());
2809                     subTree = intermediate.addIndex(EOpIndexDirect, subTree,
2810                                                     intermediate.addConstantUnion(arrayElement.back(), loc), loc);
2811                     subTree->setType(splitDerefType);
2812                 } else if (splitNode->getAsOperator() != nullptr && (splitNode->getAsOperator()->getOp() == EOpIndexIndirect)) {
2813                     // This might also be a stage with arrayed outputs, in which case there's an index
2814                     // operation we should transfer to the output builtin.
2815
2816                     const TType splitDerefType(subTree->getType(), 0);
2817                     subTree = intermediate.addIndex(splitNode->getAsOperator()->getOp(), subTree,
2818                                                     splitNode->getAsBinaryNode()->getRight(), loc);
2819                     subTree->setType(splitDerefType);
2820                 }
2821             }
2822         } else if (flattened && !shouldFlatten(derefType, isLeft ? leftStorage : rightStorage, false)) {
2823             if (isLeft)
2824                 subTree = intermediate.addSymbol(*(*leftVariables)[leftOffset++]);
2825             else
2826                 subTree = intermediate.addSymbol(*(*rightVariables)[rightOffset++]);
2827         } else {
2828             // Index operator if it's an aggregate, else EOpNull
2829             const TOperator accessOp = type.isArray()  ? EOpIndexDirect
2830                                      : type.isStruct() ? EOpIndexDirectStruct
2831                                      : EOpNull;
2832             if (accessOp == EOpNull) {
2833                 subTree = splitNode;
2834             } else {
2835                 subTree = intermediate.addIndex(accessOp, splitNode, intermediate.addConstantUnion(splitMember, loc),
2836                                                 loc);
2837                 const TType splitDerefType(splitNode->getType(), splitMember);
2838                 subTree->setType(splitDerefType);
2839             }
2840         }
2841
2842         return subTree;
2843     };
2844
2845     // Use the proper RHS node: a new symbol from a TVariable, copy
2846     // of an TIntermSymbol node, or sometimes the right node directly.
2847     right = rhsTempVar != nullptr   ? intermediate.addSymbol(*rhsTempVar, loc) :
2848             cloneSymNode != nullptr ? intermediate.addSymbol(*cloneSymNode) :
2849             right;
2850
2851     // Cannot use auto here, because this is recursive, and auto can't work out the type without seeing the
2852     // whole thing.  So, we'll resort to an explicit type via std::function.
2853     const std::function<void(TIntermTyped* left, TIntermTyped* right, TIntermTyped* splitLeft, TIntermTyped* splitRight,
2854                              bool topLevel)>
2855     traverse = [&](TIntermTyped* left, TIntermTyped* right, TIntermTyped* splitLeft, TIntermTyped* splitRight,
2856                    bool topLevel) -> void {
2857         // If we get here, we are assigning to or from a whole array or struct that must be
2858         // flattened, so have to do member-by-member assignment:
2859
2860         bool shouldFlattenSubsetLeft = isFlattenLeft && shouldFlatten(left->getType(), leftStorage, topLevel);
2861         bool shouldFlattenSubsetRight = isFlattenRight && shouldFlatten(right->getType(), rightStorage, topLevel);
2862
2863         if ((left->getType().isArray() || right->getType().isArray()) &&
2864               (shouldFlattenSubsetLeft  || isSplitLeft ||
2865                shouldFlattenSubsetRight || isSplitRight)) {
2866             const int elementsL = left->getType().isArray()  ? left->getType().getOuterArraySize()  : 1;
2867             const int elementsR = right->getType().isArray() ? right->getType().getOuterArraySize() : 1;
2868
2869             // The arrays might not be the same size,
2870             // e.g., if the size has been forced for EbvTessLevelInner/Outer.
2871             const int elementsToCopy = std::min(elementsL, elementsR);
2872
2873             // array case
2874             for (int element = 0; element < elementsToCopy; ++element) {
2875                 arrayElement.push_back(element);
2876
2877                 // Add a new AST symbol node if we have a temp variable holding a complex RHS.
2878                 TIntermTyped* subLeft  = getMember(true,  left->getType(),  element, left, element,
2879                                                    shouldFlattenSubsetLeft);
2880                 TIntermTyped* subRight = getMember(false, right->getType(), element, right, element,
2881                                                    shouldFlattenSubsetRight);
2882
2883                 TIntermTyped* subSplitLeft =  isSplitLeft  ? getMember(true,  left->getType(),  element, splitLeft,
2884                                                                        element, shouldFlattenSubsetLeft)
2885                                                            : subLeft;
2886                 TIntermTyped* subSplitRight = isSplitRight ? getMember(false, right->getType(), element, splitRight,
2887                                                                        element, shouldFlattenSubsetRight)
2888                                                            : subRight;
2889
2890                 traverse(subLeft, subRight, subSplitLeft, subSplitRight, false);
2891
2892                 arrayElement.pop_back();
2893             }
2894         } else if (left->getType().isStruct() && (shouldFlattenSubsetLeft  || isSplitLeft ||
2895                                                   shouldFlattenSubsetRight || isSplitRight)) {
2896             // struct case
2897             const auto& membersL = *left->getType().getStruct();
2898             const auto& membersR = *right->getType().getStruct();
2899
2900             // These track the members in the split structures corresponding to the same in the unsplit structures,
2901             // which we traverse in parallel.
2902             int memberL = 0;
2903             int memberR = 0;
2904
2905             // Handle empty structure assignment
2906             if (int(membersL.size()) == 0 && int(membersR.size()) == 0)
2907                 assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, left, right, loc), loc);
2908
2909             for (int member = 0; member < int(membersL.size()); ++member) {
2910                 const TType& typeL = *membersL[member].type;
2911                 const TType& typeR = *membersR[member].type;
2912
2913                 TIntermTyped* subLeft  = getMember(true,  left->getType(), member, left, member,
2914                                                    shouldFlattenSubsetLeft);
2915                 TIntermTyped* subRight = getMember(false, right->getType(), member, right, member,
2916                                                    shouldFlattenSubsetRight);
2917
2918                 // If there is no splitting, use the same values to avoid inefficiency.
2919                 TIntermTyped* subSplitLeft =  isSplitLeft  ? getMember(true,  left->getType(),  member, splitLeft,
2920                                                                        memberL, shouldFlattenSubsetLeft)
2921                                                            : subLeft;
2922                 TIntermTyped* subSplitRight = isSplitRight ? getMember(false, right->getType(), member, splitRight,
2923                                                                        memberR, shouldFlattenSubsetRight)
2924                                                            : subRight;
2925
2926                 if (isClipOrCullDistance(subSplitLeft->getType()) || isClipOrCullDistance(subSplitRight->getType())) {
2927                     // Clip and cull distance built-in assignment is complex in its own right, and is handled in
2928                     // a separate function dedicated to that task.  See comment above assignClipCullDistance;
2929
2930                     const bool isOutput = isClipOrCullDistance(subSplitLeft->getType());
2931
2932                     // Since all clip/cull semantics boil down to the same built-in type, we need to get the
2933                     // semantic ID from the dereferenced type's layout location, to avoid an N-1 mapping.
2934                     const TType derefType((isOutput ? left : right)->getType(), member);
2935                     const int semanticId = derefType.getQualifier().layoutLocation;
2936
2937                     TIntermAggregate* clipCullAssign = assignClipCullDistance(loc, op, semanticId,
2938                                                                               subSplitLeft, subSplitRight);
2939
2940                     assignList = intermediate.growAggregate(assignList, clipCullAssign, loc);
2941                 } else if (assignsClipPos(subSplitLeft)) {
2942                     // Position can require special handling: see comment above assignPosition
2943                     TIntermTyped* positionAssign = assignPosition(loc, op, subSplitLeft, subSplitRight);
2944                     assignList = intermediate.growAggregate(assignList, positionAssign, loc);
2945                 } else if (!shouldFlattenSubsetLeft && !shouldFlattenSubsetRight &&
2946                            !typeL.containsBuiltIn() && !typeR.containsBuiltIn()) {
2947                     // If this is the final flattening (no nested types below to flatten)
2948                     // we'll copy the member, else recurse into the type hierarchy.
2949                     // However, if splitting the struct, that means we can copy a whole
2950                     // subtree here IFF it does not itself contain any interstage built-in
2951                     // IO variables, so we only have to recurse into it if there's something
2952                     // for splitting to do.  That can save a lot of AST verbosity for
2953                     // a bunch of memberwise copies.
2954
2955                     assignList = intermediate.growAggregate(assignList,
2956                                                             intermediate.addAssign(op, subSplitLeft, subSplitRight, loc),
2957                                                             loc);
2958                 } else {
2959                     traverse(subLeft, subRight, subSplitLeft, subSplitRight, false);
2960                 }
2961
2962                 memberL += (typeL.isBuiltIn() ? 0 : 1);
2963                 memberR += (typeR.isBuiltIn() ? 0 : 1);
2964             }
2965         } else {
2966             // Member copy
2967             assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, left, right, loc), loc);
2968         }
2969
2970     };
2971
2972     TIntermTyped* splitLeft  = left;
2973     TIntermTyped* splitRight = right;
2974
2975     // If either left or right was a split structure, we must read or write it, but still have to
2976     // parallel-recurse through the unsplit structure to identify the built-in IO vars.
2977     // The left can be either a symbol, or an index into a symbol (e.g, array reference)
2978     if (isSplitLeft) {
2979         if (indexesSplit(left)) {
2980             // Index case: Refer to the indexed symbol, if the left is an index operator.
2981             const TIntermSymbol* symNode = left->getAsBinaryNode()->getLeft()->getAsSymbolNode();
2982
2983             TIntermTyped* splitLeftNonIo = intermediate.addSymbol(*getSplitNonIoVar(symNode->getId()), loc);
2984
2985             splitLeft = intermediate.addIndex(left->getAsBinaryNode()->getOp(), splitLeftNonIo,
2986                                               left->getAsBinaryNode()->getRight(), loc);
2987
2988             const TType derefType(splitLeftNonIo->getType(), 0);
2989             splitLeft->setType(derefType);
2990         } else {
2991             // Symbol case: otherwise, if not indexed, we have the symbol directly.
2992             const TIntermSymbol* symNode = left->getAsSymbolNode();
2993             splitLeft = intermediate.addSymbol(*getSplitNonIoVar(symNode->getId()), loc);
2994         }
2995     }
2996
2997     if (isSplitRight)
2998         splitRight = intermediate.addSymbol(*getSplitNonIoVar(right->getAsSymbolNode()->getId()), loc);
2999
3000     // This makes the whole assignment, recursing through subtypes as needed.
3001     traverse(left, right, splitLeft, splitRight, true);
3002
3003     assert(assignList != nullptr);
3004     assignList->setOperator(EOpSequence);
3005
3006     return assignList;
3007 }
3008
3009 // An assignment to matrix swizzle must be decomposed into individual assignments.
3010 // These must be selected component-wise from the RHS and stored component-wise
3011 // into the LHS.
3012 TIntermTyped* HlslParseContext::handleAssignToMatrixSwizzle(const TSourceLoc& loc, TOperator op, TIntermTyped* left,
3013                                                             TIntermTyped* right)
3014 {
3015     assert(left->getAsOperator() && left->getAsOperator()->getOp() == EOpMatrixSwizzle);
3016
3017     if (op != EOpAssign)
3018         error(loc, "only simple assignment to non-simple matrix swizzle is supported", "assign", "");
3019
3020     // isolate the matrix and swizzle nodes
3021     TIntermTyped* matrix = left->getAsBinaryNode()->getLeft()->getAsTyped();
3022     const TIntermSequence& swizzle = left->getAsBinaryNode()->getRight()->getAsAggregate()->getSequence();
3023
3024     // if the RHS isn't already a simple vector, let's store into one
3025     TIntermSymbol* vector = right->getAsSymbolNode();
3026     TIntermTyped* vectorAssign = nullptr;
3027     if (vector == nullptr) {
3028         // create a new intermediate vector variable to assign to
3029         TType vectorType(matrix->getBasicType(), EvqTemporary, matrix->getQualifier().precision, (int)swizzle.size()/2);
3030         vector = intermediate.addSymbol(*makeInternalVariable("intermVec", vectorType), loc);
3031
3032         // assign the right to the new vector
3033         vectorAssign = handleAssign(loc, op, vector, right);
3034     }
3035
3036     // Assign the vector components to the matrix components.
3037     // Store this as a sequence, so a single aggregate node represents this
3038     // entire operation.
3039     TIntermAggregate* result = intermediate.makeAggregate(vectorAssign);
3040     TType columnType(matrix->getType(), 0);
3041     TType componentType(columnType, 0);
3042     TType indexType(EbtInt);
3043     for (int i = 0; i < (int)swizzle.size(); i += 2) {
3044         // the right component, single index into the RHS vector
3045         TIntermTyped* rightComp = intermediate.addIndex(EOpIndexDirect, vector,
3046                                     intermediate.addConstantUnion(i/2, loc), loc);
3047
3048         // the left component, double index into the LHS matrix
3049         TIntermTyped* leftComp = intermediate.addIndex(EOpIndexDirect, matrix,
3050                                     intermediate.addConstantUnion(swizzle[i]->getAsConstantUnion()->getConstArray(),
3051                                                                   indexType, loc),
3052                                     loc);
3053         leftComp->setType(columnType);
3054         leftComp = intermediate.addIndex(EOpIndexDirect, leftComp,
3055                                     intermediate.addConstantUnion(swizzle[i+1]->getAsConstantUnion()->getConstArray(),
3056                                                                   indexType, loc),
3057                                     loc);
3058         leftComp->setType(componentType);
3059
3060         // Add the assignment to the aggregate
3061         result = intermediate.growAggregate(result, intermediate.addAssign(op, leftComp, rightComp, loc));
3062     }
3063
3064     result->setOp(EOpSequence);
3065
3066     return result;
3067 }
3068
3069 //
3070 // HLSL atomic operations have slightly different arguments than
3071 // GLSL/AST/SPIRV.  The semantics are converted below in decomposeIntrinsic.
3072 // This provides the post-decomposition equivalent opcode.
3073 //
3074 TOperator HlslParseContext::mapAtomicOp(const TSourceLoc& loc, TOperator op, bool isImage)
3075 {
3076     switch (op) {
3077     case EOpInterlockedAdd:             return isImage ? EOpImageAtomicAdd      : EOpAtomicAdd;
3078     case EOpInterlockedAnd:             return isImage ? EOpImageAtomicAnd      : EOpAtomicAnd;
3079     case EOpInterlockedCompareExchange: return isImage ? EOpImageAtomicCompSwap : EOpAtomicCompSwap;
3080     case EOpInterlockedMax:             return isImage ? EOpImageAtomicMax      : EOpAtomicMax;
3081     case EOpInterlockedMin:             return isImage ? EOpImageAtomicMin      : EOpAtomicMin;
3082     case EOpInterlockedOr:              return isImage ? EOpImageAtomicOr       : EOpAtomicOr;
3083     case EOpInterlockedXor:             return isImage ? EOpImageAtomicXor      : EOpAtomicXor;
3084     case EOpInterlockedExchange:        return isImage ? EOpImageAtomicExchange : EOpAtomicExchange;
3085     case EOpInterlockedCompareStore:  // TODO: ...
3086     default:
3087         error(loc, "unknown atomic operation", "unknown op", "");
3088         return EOpNull;
3089     }
3090 }
3091
3092 //
3093 // Create a combined sampler/texture from separate sampler and texture.
3094 //
3095 TIntermAggregate* HlslParseContext::handleSamplerTextureCombine(const TSourceLoc& loc, TIntermTyped* argTex,
3096                                                                 TIntermTyped* argSampler)
3097 {
3098     TIntermAggregate* txcombine = new TIntermAggregate(EOpConstructTextureSampler);
3099
3100     txcombine->getSequence().push_back(argTex);
3101     txcombine->getSequence().push_back(argSampler);
3102
3103     TSampler samplerType = argTex->getType().getSampler();
3104     samplerType.combined = true;
3105
3106     // TODO:
3107     // This block exists until the spec no longer requires shadow modes on texture objects.
3108     // It can be deleted after that, along with the shadowTextureVariant member.
3109     {
3110         const bool shadowMode = argSampler->getType().getSampler().shadow;
3111
3112         TIntermSymbol* texSymbol = argTex->getAsSymbolNode();
3113
3114         if (texSymbol == nullptr)
3115             texSymbol = argTex->getAsBinaryNode()->getLeft()->getAsSymbolNode();
3116
3117         if (texSymbol == nullptr) {
3118             error(loc, "unable to find texture symbol", "", "");
3119             return nullptr;
3120         }
3121
3122         // This forces the texture's shadow state to be the sampler's
3123         // shadow state.  This depends on downstream optimization to
3124         // DCE one variant in [shadow, nonshadow] if both are present,
3125         // or the SPIR-V module would be invalid.
3126         int newId = texSymbol->getId();
3127
3128         // Check to see if this texture has been given a shadow mode already.
3129         // If so, look up the one we already have.
3130         const auto textureShadowEntry = textureShadowVariant.find(texSymbol->getId());
3131
3132         if (textureShadowEntry != textureShadowVariant.end())
3133             newId = textureShadowEntry->second->get(shadowMode);
3134         else
3135             textureShadowVariant[texSymbol->getId()] = new tShadowTextureSymbols;
3136
3137         // Sometimes we have to create another symbol (if this texture has been seen before,
3138         // and we haven't created the form for this shadow mode).
3139         if (newId == -1) {
3140             TType texType;
3141             texType.shallowCopy(argTex->getType());
3142             texType.getSampler().shadow = shadowMode;  // set appropriate shadow mode.
3143             globalQualifierFix(loc, texType.getQualifier());
3144
3145             TVariable* newTexture = makeInternalVariable(texSymbol->getName(), texType);
3146
3147             trackLinkage(*newTexture);
3148
3149             newId = newTexture->getUniqueId();
3150         }
3151
3152         assert(newId != -1);
3153
3154         if (textureShadowVariant.find(newId) == textureShadowVariant.end())
3155             textureShadowVariant[newId] = textureShadowVariant[texSymbol->getId()];
3156
3157         textureShadowVariant[newId]->set(shadowMode, newId);
3158
3159         // Remember this shadow mode in the texture and the merged type.
3160         argTex->getWritableType().getSampler().shadow = shadowMode;
3161         samplerType.shadow = shadowMode;
3162
3163         texSymbol->switchId(newId);
3164     }
3165
3166     txcombine->setType(TType(samplerType, EvqTemporary));
3167     txcombine->setLoc(loc);
3168
3169     return txcombine;
3170 }
3171
3172 // Return true if this a buffer type that has an associated counter buffer.
3173 bool HlslParseContext::hasStructBuffCounter(const TType& type) const
3174 {
3175     switch (type.getQualifier().declaredBuiltIn) {
3176     case EbvAppendConsume:       // fall through...
3177     case EbvRWStructuredBuffer:  // ...
3178         return true;
3179     default:
3180         return false; // the other structuredbuffer types do not have a counter.
3181     }
3182 }
3183
3184 void HlslParseContext::counterBufferType(const TSourceLoc& loc, TType& type)
3185 {
3186     // Counter type
3187     TType* counterType = new TType(EbtUint, EvqBuffer);
3188     counterType->setFieldName(intermediate.implicitCounterName);
3189
3190     TTypeList* blockStruct = new TTypeList;
3191     TTypeLoc  member = { counterType, loc };
3192     blockStruct->push_back(member);
3193
3194     TType blockType(blockStruct, "", counterType->getQualifier());
3195     blockType.getQualifier().storage = EvqBuffer;
3196
3197     type.shallowCopy(blockType);
3198     shareStructBufferType(type);
3199 }
3200
3201 // declare counter for a structured buffer type
3202 void HlslParseContext::declareStructBufferCounter(const TSourceLoc& loc, const TType& bufferType, const TString& name)
3203 {
3204     // Bail out if not a struct buffer
3205     if (! isStructBufferType(bufferType))
3206         return;
3207
3208     if (! hasStructBuffCounter(bufferType))
3209         return;
3210
3211     TType blockType;
3212     counterBufferType(loc, blockType);
3213
3214     TString* blockName = new TString(intermediate.addCounterBufferName(name));
3215
3216     // Counter buffer is not yet in use
3217     structBufferCounter[*blockName] = false;
3218
3219     shareStructBufferType(blockType);
3220     declareBlock(loc, blockType, blockName);
3221 }
3222
3223 // return the counter that goes with a given structuredbuffer
3224 TIntermTyped* HlslParseContext::getStructBufferCounter(const TSourceLoc& loc, TIntermTyped* buffer)
3225 {
3226     // Bail out if not a struct buffer
3227     if (buffer == nullptr || ! isStructBufferType(buffer->getType()))
3228         return nullptr;
3229
3230     const TString counterBlockName(intermediate.addCounterBufferName(buffer->getAsSymbolNode()->getName()));
3231
3232     // Mark the counter as being used
3233     structBufferCounter[counterBlockName] = true;
3234
3235     TIntermTyped* counterVar = handleVariable(loc, &counterBlockName);  // find the block structure
3236     TIntermTyped* index = intermediate.addConstantUnion(0, loc); // index to counter inside block struct
3237
3238     TIntermTyped* counterMember = intermediate.addIndex(EOpIndexDirectStruct, counterVar, index, loc);
3239     counterMember->setType(TType(EbtUint));
3240     return counterMember;
3241 }
3242
3243 //
3244 // Decompose structure buffer methods into AST
3245 //
3246 void HlslParseContext::decomposeStructBufferMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
3247 {
3248     if (node == nullptr || node->getAsOperator() == nullptr || arguments == nullptr)
3249         return;
3250
3251     const TOperator op  = node->getAsOperator()->getOp();
3252     TIntermAggregate* argAggregate = arguments->getAsAggregate();
3253
3254     // Buffer is the object upon which method is called, so always arg 0
3255     TIntermTyped* bufferObj = nullptr;
3256
3257     // The parameters can be an aggregate, or just a the object as a symbol if there are no fn params.
3258     if (argAggregate) {
3259         if (argAggregate->getSequence().empty())
3260             return;
3261         bufferObj = argAggregate->getSequence()[0]->getAsTyped();
3262     } else {
3263         bufferObj = arguments->getAsSymbolNode();
3264     }
3265
3266     if (bufferObj == nullptr || bufferObj->getAsSymbolNode() == nullptr)
3267         return;
3268
3269     // Some methods require a hidden internal counter, obtained via getStructBufferCounter().
3270     // This lambda adds something to it and returns the old value.
3271     const auto incDecCounter = [&](int incval) -> TIntermTyped* {
3272         TIntermTyped* incrementValue = intermediate.addConstantUnion(static_cast<unsigned int>(incval), loc, true);
3273         TIntermTyped* counter = getStructBufferCounter(loc, bufferObj); // obtain the counter member
3274
3275         if (counter == nullptr)
3276             return nullptr;
3277
3278         TIntermAggregate* counterIncrement = new TIntermAggregate(EOpAtomicAdd);
3279         counterIncrement->setType(TType(EbtUint, EvqTemporary));
3280         counterIncrement->setLoc(loc);
3281         counterIncrement->getSequence().push_back(counter);
3282         counterIncrement->getSequence().push_back(incrementValue);
3283
3284         return counterIncrement;
3285     };
3286
3287     // Index to obtain the runtime sized array out of the buffer.
3288     TIntermTyped* argArray = indexStructBufferContent(loc, bufferObj);
3289     if (argArray == nullptr)
3290         return;  // It might not be a struct buffer method.
3291
3292     switch (op) {
3293     case EOpMethodLoad:
3294         {
3295             TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped());  // index
3296
3297             const TType& bufferType = bufferObj->getType();
3298
3299             const TBuiltInVariable builtInType = bufferType.getQualifier().declaredBuiltIn;
3300
3301             // Byte address buffers index in bytes (only multiples of 4 permitted... not so much a byte address
3302             // buffer then, but that's what it calls itself.
3303             const bool isByteAddressBuffer = (builtInType == EbvByteAddressBuffer   || 
3304                                               builtInType == EbvRWByteAddressBuffer);
3305                 
3306
3307             if (isByteAddressBuffer)
3308                 argIndex = intermediate.addBinaryNode(EOpRightShift, argIndex,
3309                                                       intermediate.addConstantUnion(2, loc, true),
3310                                                       loc, TType(EbtInt));
3311
3312             // Index into the array to find the item being loaded.
3313             const TOperator idxOp = (argIndex->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
3314
3315             node = intermediate.addIndex(idxOp, argArray, argIndex, loc);
3316
3317             const TType derefType(argArray->getType(), 0);
3318             node->setType(derefType);
3319         }
3320         
3321         break;
3322
3323     case EOpMethodLoad2:
3324     case EOpMethodLoad3:
3325     case EOpMethodLoad4:
3326         {
3327             TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped());  // index
3328
3329             TOperator constructOp = EOpNull;
3330             int size = 0;
3331
3332             switch (op) {
3333             case EOpMethodLoad2: size = 2; constructOp = EOpConstructVec2; break;
3334             case EOpMethodLoad3: size = 3; constructOp = EOpConstructVec3; break;
3335             case EOpMethodLoad4: size = 4; constructOp = EOpConstructVec4; break;
3336             default: assert(0);
3337             }
3338
3339             TIntermTyped* body = nullptr;
3340
3341             // First, we'll store the address in a variable to avoid multiple shifts
3342             // (we must convert the byte address to an item address)
3343             TIntermTyped* byteAddrIdx = intermediate.addBinaryNode(EOpRightShift, argIndex,
3344                                                                    intermediate.addConstantUnion(2, loc, true),
3345                                                                    loc, TType(EbtInt));
3346
3347             TVariable* byteAddrSym = makeInternalVariable("byteAddrTemp", TType(EbtInt, EvqTemporary));
3348             TIntermTyped* byteAddrIdxVar = intermediate.addSymbol(*byteAddrSym, loc);
3349
3350             body = intermediate.growAggregate(body, intermediate.addAssign(EOpAssign, byteAddrIdxVar, byteAddrIdx, loc));
3351
3352             TIntermTyped* vec = nullptr;
3353
3354             // These are only valid on (rw)byteaddressbuffers, so we can always perform the >>2
3355             // address conversion.
3356             for (int idx=0; idx<size; ++idx) {
3357                 TIntermTyped* offsetIdx = byteAddrIdxVar;
3358
3359                 // add index offset
3360                 if (idx != 0)
3361                     offsetIdx = intermediate.addBinaryNode(EOpAdd, offsetIdx,
3362                                                            intermediate.addConstantUnion(idx, loc, true),
3363                                                            loc, TType(EbtInt));
3364
3365                 const TOperator idxOp = (offsetIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect
3366                                                                                         : EOpIndexIndirect;
3367
3368                 TIntermTyped* indexVal = intermediate.addIndex(idxOp, argArray, offsetIdx, loc);
3369
3370                 TType derefType(argArray->getType(), 0);
3371                 derefType.getQualifier().makeTemporary();
3372                 indexVal->setType(derefType);
3373
3374                 vec = intermediate.growAggregate(vec, indexVal);
3375             }
3376
3377             vec->setType(TType(argArray->getBasicType(), EvqTemporary, size));
3378             vec->getAsAggregate()->setOperator(constructOp);
3379
3380             body = intermediate.growAggregate(body, vec);
3381             body->setType(vec->getType());
3382             body->getAsAggregate()->setOperator(EOpSequence);
3383
3384             node = body;
3385         }
3386
3387         break;
3388
3389     case EOpMethodStore:
3390     case EOpMethodStore2:
3391     case EOpMethodStore3:
3392     case EOpMethodStore4:
3393         {
3394             TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped());  // index
3395             TIntermTyped* argValue = argAggregate->getSequence()[2]->getAsTyped();  // value
3396
3397             // Index into the array to find the item being loaded.
3398             // Byte address buffers index in bytes (only multiples of 4 permitted... not so much a byte address
3399             // buffer then, but that's what it calls itself).
3400
3401             int size = 0;
3402
3403             switch (op) {
3404             case EOpMethodStore:  size = 1; break;
3405             case EOpMethodStore2: size = 2; break;
3406             case EOpMethodStore3: size = 3; break;
3407             case EOpMethodStore4: size = 4; break;
3408             default: assert(0);
3409             }
3410
3411             TIntermAggregate* body = nullptr;
3412
3413             // First, we'll store the address in a variable to avoid multiple shifts
3414             // (we must convert the byte address to an item address)
3415             TIntermTyped* byteAddrIdx = intermediate.addBinaryNode(EOpRightShift, argIndex,
3416                                                                    intermediate.addConstantUnion(2, loc, true), loc, TType(EbtInt));
3417
3418             TVariable* byteAddrSym = makeInternalVariable("byteAddrTemp", TType(EbtInt, EvqTemporary));
3419             TIntermTyped* byteAddrIdxVar = intermediate.addSymbol(*byteAddrSym, loc);
3420
3421             body = intermediate.growAggregate(body, intermediate.addAssign(EOpAssign, byteAddrIdxVar, byteAddrIdx, loc));
3422
3423             for (int idx=0; idx<size; ++idx) {
3424                 TIntermTyped* offsetIdx = byteAddrIdxVar;
3425                 TIntermTyped* idxConst = intermediate.addConstantUnion(idx, loc, true);
3426
3427                 // add index offset
3428                 if (idx != 0)
3429                     offsetIdx = intermediate.addBinaryNode(EOpAdd, offsetIdx, idxConst, loc, TType(EbtInt));
3430
3431                 const TOperator idxOp = (offsetIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect
3432                                                                                         : EOpIndexIndirect;
3433
3434                 TIntermTyped* lValue = intermediate.addIndex(idxOp, argArray, offsetIdx, loc);
3435                 const TType derefType(argArray->getType(), 0);
3436                 lValue->setType(derefType);
3437
3438                 TIntermTyped* rValue;
3439                 if (size == 1) {
3440                     rValue = argValue;
3441                 } else {
3442                     rValue = intermediate.addIndex(EOpIndexDirect, argValue, idxConst, loc);
3443                     const TType indexType(argValue->getType(), 0);
3444                     rValue->setType(indexType);
3445                 }
3446                     
3447                 TIntermTyped* assign = intermediate.addAssign(EOpAssign, lValue, rValue, loc); 
3448
3449                 body = intermediate.growAggregate(body, assign);
3450             }
3451
3452             body->setOperator(EOpSequence);
3453             node = body;
3454         }
3455
3456         break;
3457
3458     case EOpMethodGetDimensions:
3459         {
3460             const int numArgs = (int)argAggregate->getSequence().size();
3461             TIntermTyped* argNumItems = argAggregate->getSequence()[1]->getAsTyped();  // out num items
3462             TIntermTyped* argStride   = numArgs > 2 ? argAggregate->getSequence()[2]->getAsTyped() : nullptr;  // out stride
3463
3464             TIntermAggregate* body = nullptr;
3465
3466             // Length output:
3467             if (argArray->getType().isSizedArray()) {
3468                 const int length = argArray->getType().getOuterArraySize();
3469                 TIntermTyped* assign = intermediate.addAssign(EOpAssign, argNumItems,
3470                                                               intermediate.addConstantUnion(length, loc, true), loc);
3471                 body = intermediate.growAggregate(body, assign, loc);
3472             } else {
3473                 TIntermTyped* lengthCall = intermediate.addBuiltInFunctionCall(loc, EOpArrayLength, true, argArray,
3474                                                                                argNumItems->getType());
3475                 TIntermTyped* assign = intermediate.addAssign(EOpAssign, argNumItems, lengthCall, loc);
3476                 body = intermediate.growAggregate(body, assign, loc);
3477             }
3478
3479             // Stride output:
3480             if (argStride != nullptr) {
3481                 int size;
3482                 int stride;
3483                 intermediate.getBaseAlignment(argArray->getType(), size, stride, false,
3484                                               argArray->getType().getQualifier().layoutMatrix == ElmRowMajor);
3485
3486                 TIntermTyped* assign = intermediate.addAssign(EOpAssign, argStride,
3487                                                               intermediate.addConstantUnion(stride, loc, true), loc);
3488
3489                 body = intermediate.growAggregate(body, assign);
3490             }
3491
3492             body->setOperator(EOpSequence);
3493             node = body;
3494         }
3495
3496         break;
3497
3498     case EOpInterlockedAdd:
3499     case EOpInterlockedAnd:
3500     case EOpInterlockedExchange:
3501     case EOpInterlockedMax:
3502     case EOpInterlockedMin:
3503     case EOpInterlockedOr:
3504     case EOpInterlockedXor:
3505     case EOpInterlockedCompareExchange:
3506     case EOpInterlockedCompareStore:
3507         {
3508             // We'll replace the first argument with the block dereference, and let
3509             // downstream decomposition handle the rest.
3510
3511             TIntermSequence& sequence = argAggregate->getSequence();
3512
3513             TIntermTyped* argIndex     = makeIntegerIndex(sequence[1]->getAsTyped());  // index
3514             argIndex = intermediate.addBinaryNode(EOpRightShift, argIndex, intermediate.addConstantUnion(2, loc, true),
3515                                                   loc, TType(EbtInt));
3516
3517             const TOperator idxOp = (argIndex->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
3518             TIntermTyped* element = intermediate.addIndex(idxOp, argArray, argIndex, loc);
3519
3520             const TType derefType(argArray->getType(), 0);
3521             element->setType(derefType);
3522
3523             // Replace the numeric byte offset parameter with array reference.
3524             sequence[1] = element;
3525             sequence.erase(sequence.begin(), sequence.begin()+1);
3526         }
3527         break;
3528
3529     case EOpMethodIncrementCounter:
3530         {
3531             node = incDecCounter(1);
3532             break;
3533         }
3534
3535     case EOpMethodDecrementCounter:
3536         {
3537             TIntermTyped* preIncValue = incDecCounter(-1); // result is original value
3538             node = intermediate.addBinaryNode(EOpAdd, preIncValue, intermediate.addConstantUnion(-1, loc, true), loc,
3539                                               preIncValue->getType());
3540             break;
3541         }
3542
3543     case EOpMethodAppend:
3544         {
3545             TIntermTyped* oldCounter = incDecCounter(1);
3546
3547             TIntermTyped* lValue = intermediate.addIndex(EOpIndexIndirect, argArray, oldCounter, loc);
3548             TIntermTyped* rValue = argAggregate->getSequence()[1]->getAsTyped();
3549
3550             const TType derefType(argArray->getType(), 0);
3551             lValue->setType(derefType);
3552
3553             node = intermediate.addAssign(EOpAssign, lValue, rValue, loc);
3554
3555             break;
3556         }
3557
3558     case EOpMethodConsume:
3559         {
3560             TIntermTyped* oldCounter = incDecCounter(-1);
3561
3562             TIntermTyped* newCounter = intermediate.addBinaryNode(EOpAdd, oldCounter,
3563                                                                   intermediate.addConstantUnion(-1, loc, true), loc,
3564                                                                   oldCounter->getType());
3565
3566             node = intermediate.addIndex(EOpIndexIndirect, argArray, newCounter, loc);
3567
3568             const TType derefType(argArray->getType(), 0);
3569             node->setType(derefType);
3570
3571             break;
3572         }
3573
3574     default:
3575         break; // most pass through unchanged
3576     }
3577 }
3578
3579 // Create array of standard sample positions for given sample count.
3580 // TODO: remove when a real method to query sample pos exists in SPIR-V.
3581 TIntermConstantUnion* HlslParseContext::getSamplePosArray(int count)
3582 {
3583     struct tSamplePos { float x, y; };
3584
3585     static const tSamplePos pos1[] = {
3586         { 0.0/16.0,  0.0/16.0 },
3587     };
3588
3589     // standard sample positions for 2, 4, 8, and 16 samples.
3590     static const tSamplePos pos2[] = {
3591         { 4.0/16.0,  4.0/16.0 }, {-4.0/16.0, -4.0/16.0 },
3592     };
3593
3594     static const tSamplePos pos4[] = {
3595         {-2.0/16.0, -6.0/16.0 }, { 6.0/16.0, -2.0/16.0 }, {-6.0/16.0,  2.0/16.0 }, { 2.0/16.0,  6.0/16.0 },
3596     };
3597
3598     static const tSamplePos pos8[] = {
3599         { 1.0/16.0, -3.0/16.0 }, {-1.0/16.0,  3.0/16.0 }, { 5.0/16.0,  1.0/16.0 }, {-3.0/16.0, -5.0/16.0 },
3600         {-5.0/16.0,  5.0/16.0 }, {-7.0/16.0, -1.0/16.0 }, { 3.0/16.0,  7.0/16.0 }, { 7.0/16.0, -7.0/16.0 },
3601     };
3602
3603     static const tSamplePos pos16[] = {
3604         { 1.0/16.0,  1.0/16.0 }, {-1.0/16.0, -3.0/16.0 }, {-3.0/16.0,  2.0/16.0 }, { 4.0/16.0, -1.0/16.0 },
3605         {-5.0/16.0, -2.0/16.0 }, { 2.0/16.0,  5.0/16.0 }, { 5.0/16.0,  3.0/16.0 }, { 3.0/16.0, -5.0/16.0 },
3606         {-2.0/16.0,  6.0/16.0 }, { 0.0/16.0, -7.0/16.0 }, {-4.0/16.0, -6.0/16.0 }, {-6.0/16.0,  4.0/16.0 },
3607         {-8.0/16.0,  0.0/16.0 }, { 7.0/16.0, -4.0/16.0 }, { 6.0/16.0,  7.0/16.0 }, {-7.0/16.0, -8.0/16.0 },
3608     };
3609
3610     const tSamplePos* sampleLoc = nullptr;
3611     int numSamples = count;
3612
3613     switch (count) {
3614     case 2:  sampleLoc = pos2;  break;
3615     case 4:  sampleLoc = pos4;  break;
3616     case 8:  sampleLoc = pos8;  break;
3617     case 16: sampleLoc = pos16; break;
3618     default:
3619         sampleLoc = pos1;
3620         numSamples = 1;
3621     }
3622
3623     TConstUnionArray* values = new TConstUnionArray(numSamples*2);
3624     
3625     for (int pos=0; pos<count; ++pos) {
3626         TConstUnion x, y;
3627         x.setDConst(sampleLoc[pos].x);
3628         y.setDConst(sampleLoc[pos].y);
3629
3630         (*values)[pos*2+0] = x;
3631         (*values)[pos*2+1] = y;
3632     }
3633
3634     TType retType(EbtFloat, EvqConst, 2);
3635
3636     if (numSamples != 1) {
3637         TArraySizes* arraySizes = new TArraySizes;
3638         arraySizes->addInnerSize(numSamples);
3639         retType.transferArraySizes(arraySizes);
3640     }
3641
3642     return new TIntermConstantUnion(*values, retType);
3643 }
3644
3645 //
3646 // Decompose DX9 and DX10 sample intrinsics & object methods into AST
3647 //
3648 void HlslParseContext::decomposeSampleMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
3649 {
3650     if (node == nullptr || !node->getAsOperator())
3651         return;
3652
3653     // Sampler return must always be a vec4, but we can construct a shorter vector or a structure from it.
3654     const auto convertReturn = [&loc, &node, this](TIntermTyped* result, const TSampler& sampler) -> TIntermTyped* {
3655         result->setType(TType(node->getType().getBasicType(), EvqTemporary, node->getVectorSize()));
3656
3657         TIntermTyped* convertedResult = nullptr;
3658         
3659         TType retType;
3660         getTextureReturnType(sampler, retType);
3661
3662         if (retType.isStruct()) {
3663             // For type convenience, conversionAggregate points to the convertedResult (we know it's an aggregate here)
3664             TIntermAggregate* conversionAggregate = new TIntermAggregate;
3665             convertedResult = conversionAggregate;
3666
3667             // Convert vector output to return structure.  We will need a temp symbol to copy the results to.
3668             TVariable* structVar = makeInternalVariable("@sampleStructTemp", retType);
3669
3670             // We also need a temp symbol to hold the result of the texture.  We don't want to re-fetch the
3671             // sample each time we'll index into the result, so we'll copy to this, and index into the copy.
3672             TVariable* sampleShadow = makeInternalVariable("@sampleResultShadow", result->getType());
3673
3674             // Initial copy from texture to our sample result shadow.
3675             TIntermTyped* shadowCopy = intermediate.addAssign(EOpAssign, intermediate.addSymbol(*sampleShadow, loc),
3676                                                               result, loc);
3677
3678             conversionAggregate->getSequence().push_back(shadowCopy);
3679
3680             unsigned vec4Pos = 0;
3681
3682             for (unsigned m = 0; m < unsigned(retType.getStruct()->size()); ++m) {
3683                 const TType memberType(retType, m); // dereferenced type of the member we're about to assign.
3684                 
3685                 // Check for bad struct members.  This should have been caught upstream.  Complain, because
3686                 // wwe don't know what to do with it.  This algorithm could be generalized to handle
3687                 // other things, e.g, sub-structures, but HLSL doesn't allow them.
3688                 if (!memberType.isVector() && !memberType.isScalar()) {
3689                     error(loc, "expected: scalar or vector type in texture structure", "", "");
3690                     return nullptr;
3691                 }
3692                     
3693                 // Index into the struct variable to find the member to assign.
3694                 TIntermTyped* structMember = intermediate.addIndex(EOpIndexDirectStruct,
3695                                                                    intermediate.addSymbol(*structVar, loc),
3696                                                                    intermediate.addConstantUnion(m, loc), loc);
3697
3698                 structMember->setType(memberType);
3699
3700                 // Assign each component of (possible) vector in struct member.
3701                 for (int component = 0; component < memberType.getVectorSize(); ++component) {
3702                     TIntermTyped* vec4Member = intermediate.addIndex(EOpIndexDirect,
3703                                                                      intermediate.addSymbol(*sampleShadow, loc),
3704                                                                      intermediate.addConstantUnion(vec4Pos++, loc), loc);
3705                     vec4Member->setType(TType(memberType.getBasicType(), EvqTemporary, 1));
3706
3707                     TIntermTyped* memberAssign = nullptr;
3708
3709                     if (memberType.isVector()) {
3710                         // Vector member: we need to create an access chain to the vector component.
3711
3712                         TIntermTyped* structVecComponent = intermediate.addIndex(EOpIndexDirect, structMember,
3713                                                                                  intermediate.addConstantUnion(component, loc), loc);
3714                         
3715                         memberAssign = intermediate.addAssign(EOpAssign, structVecComponent, vec4Member, loc);
3716                     } else {
3717                         // Scalar member: we can assign to it directly.
3718                         memberAssign = intermediate.addAssign(EOpAssign, structMember, vec4Member, loc);
3719                     }
3720
3721                     
3722                     conversionAggregate->getSequence().push_back(memberAssign);
3723                 }
3724             }
3725
3726             // Add completed variable so the expression results in the whole struct value we just built.
3727             conversionAggregate->getSequence().push_back(intermediate.addSymbol(*structVar, loc));
3728
3729             // Make it a sequence.
3730             intermediate.setAggregateOperator(conversionAggregate, EOpSequence, retType, loc);
3731         } else {
3732             // vector clamp the output if template vector type is smaller than sample result.
3733             if (retType.getVectorSize() < node->getVectorSize()) {
3734                 // Too many components.  Construct shorter vector from it.
3735                 const TOperator op = intermediate.mapTypeToConstructorOp(retType);
3736
3737                 convertedResult = constructBuiltIn(retType, op, result, loc, false);
3738             } else {
3739                 // Enough components.  Use directly.
3740                 convertedResult = result;
3741             }
3742         }
3743
3744         convertedResult->setLoc(loc);
3745         return convertedResult;
3746     };
3747
3748     const TOperator op  = node->getAsOperator()->getOp();
3749     const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
3750
3751     // Bail out if not a sampler method.
3752     // Note though this is odd to do before checking the op, because the op
3753     // could be something that takes the arguments, and the function in question
3754     // takes the result of the op.  So, this is not the final word.
3755     if (arguments != nullptr) {
3756         if (argAggregate == nullptr) {
3757             if (arguments->getAsTyped()->getBasicType() != EbtSampler)
3758                 return;
3759         } else {
3760             if (argAggregate->getSequence().size() == 0 ||
3761                 argAggregate->getSequence()[0]->getAsTyped()->getBasicType() != EbtSampler)
3762                 return;
3763         }
3764     }
3765
3766     switch (op) {
3767     // **** DX9 intrinsics: ****
3768     case EOpTexture:
3769         {
3770             // Texture with ddx & ddy is really gradient form in HLSL
3771             if (argAggregate->getSequence().size() == 4)
3772                 node->getAsAggregate()->setOperator(EOpTextureGrad);
3773
3774             break;
3775         }
3776
3777     case EOpTextureBias:
3778         {
3779             TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();  // sampler
3780             TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();  // coord
3781
3782             // HLSL puts bias in W component of coordinate.  We extract it and add it to
3783             // the argument list, instead
3784             TIntermTyped* w = intermediate.addConstantUnion(3, loc, true);
3785             TIntermTyped* bias = intermediate.addIndex(EOpIndexDirect, arg1, w, loc);
3786
3787             TOperator constructOp = EOpNull;
3788             const TSampler& sampler = arg0->getType().getSampler();
3789
3790             switch (sampler.dim) {
3791             case Esd1D:   constructOp = EOpConstructFloat; break; // 1D
3792             case Esd2D:   constructOp = EOpConstructVec2;  break; // 2D
3793             case Esd3D:   constructOp = EOpConstructVec3;  break; // 3D
3794             case EsdCube: constructOp = EOpConstructVec3;  break; // also 3D
3795             default: break;
3796             }
3797
3798             TIntermAggregate* constructCoord = new TIntermAggregate(constructOp);
3799             constructCoord->getSequence().push_back(arg1);
3800             constructCoord->setLoc(loc);
3801
3802             // The input vector should never be less than 2, since there's always a bias.
3803             // The max is for safety, and should be a no-op.
3804             constructCoord->setType(TType(arg1->getBasicType(), EvqTemporary, std::max(arg1->getVectorSize() - 1, 0)));
3805
3806             TIntermAggregate* tex = new TIntermAggregate(EOpTexture);
3807             tex->getSequence().push_back(arg0);           // sampler
3808             tex->getSequence().push_back(constructCoord); // coordinate
3809             tex->getSequence().push_back(bias);           // bias
3810
3811             node = convertReturn(tex, sampler);
3812
3813             break;
3814         }
3815
3816     // **** DX10 methods: ****
3817     case EOpMethodSample:     // fall through
3818     case EOpMethodSampleBias: // ...
3819         {
3820             TIntermTyped* argTex    = argAggregate->getSequence()[0]->getAsTyped();
3821             TIntermTyped* argSamp   = argAggregate->getSequence()[1]->getAsTyped();
3822             TIntermTyped* argCoord  = argAggregate->getSequence()[2]->getAsTyped();
3823             TIntermTyped* argBias   = nullptr;
3824             TIntermTyped* argOffset = nullptr;
3825             const TSampler& sampler = argTex->getType().getSampler();
3826
3827             int nextArg = 3;
3828
3829             if (op == EOpMethodSampleBias)  // SampleBias has a bias arg
3830                 argBias = argAggregate->getSequence()[nextArg++]->getAsTyped();
3831
3832             TOperator textureOp = EOpTexture;
3833
3834             if ((int)argAggregate->getSequence().size() == (nextArg+1)) { // last parameter is offset form
3835                 textureOp = EOpTextureOffset;
3836                 argOffset = argAggregate->getSequence()[nextArg++]->getAsTyped();
3837             }
3838
3839             TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
3840
3841             TIntermAggregate* txsample = new TIntermAggregate(textureOp);
3842             txsample->getSequence().push_back(txcombine);
3843             txsample->getSequence().push_back(argCoord);
3844
3845             if (argBias != nullptr)
3846                 txsample->getSequence().push_back(argBias);
3847
3848             if (argOffset != nullptr)
3849                 txsample->getSequence().push_back(argOffset);
3850
3851             node = convertReturn(txsample, sampler);
3852
3853             break;
3854         }
3855
3856     case EOpMethodSampleGrad: // ...
3857         {
3858             TIntermTyped* argTex    = argAggregate->getSequence()[0]->getAsTyped();
3859             TIntermTyped* argSamp   = argAggregate->getSequence()[1]->getAsTyped();
3860             TIntermTyped* argCoord  = argAggregate->getSequence()[2]->getAsTyped();
3861             TIntermTyped* argDDX    = argAggregate->getSequence()[3]->getAsTyped();
3862             TIntermTyped* argDDY    = argAggregate->getSequence()[4]->getAsTyped();
3863             TIntermTyped* argOffset = nullptr;
3864             const TSampler& sampler = argTex->getType().getSampler();
3865
3866             TOperator textureOp = EOpTextureGrad;
3867
3868             if (argAggregate->getSequence().size() == 6) { // last parameter is offset form
3869                 textureOp = EOpTextureGradOffset;
3870                 argOffset = argAggregate->getSequence()[5]->getAsTyped();
3871             }
3872
3873             TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
3874
3875             TIntermAggregate* txsample = new TIntermAggregate(textureOp);
3876             txsample->getSequence().push_back(txcombine);
3877             txsample->getSequence().push_back(argCoord);
3878             txsample->getSequence().push_back(argDDX);
3879             txsample->getSequence().push_back(argDDY);
3880
3881             if (argOffset != nullptr)
3882                 txsample->getSequence().push_back(argOffset);
3883
3884             node = convertReturn(txsample, sampler);
3885
3886             break;
3887         }
3888
3889     case EOpMethodGetDimensions:
3890         {
3891             // AST returns a vector of results, which we break apart component-wise into
3892             // separate values to assign to the HLSL method's outputs, ala:
3893             //  tx . GetDimensions(width, height);
3894             //      float2 sizeQueryTemp = EOpTextureQuerySize
3895             //      width = sizeQueryTemp.X;
3896             //      height = sizeQueryTemp.Y;
3897
3898             TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
3899             const TType& texType = argTex->getType();
3900
3901             assert(texType.getBasicType() == EbtSampler);
3902
3903             const TSampler& sampler = texType.getSampler();
3904             const TSamplerDim dim = sampler.dim;
3905             const bool isImage = sampler.isImage();
3906             const bool isMs = sampler.isMultiSample();
3907             const int numArgs = (int)argAggregate->getSequence().size();
3908
3909             int numDims = 0;
3910
3911             switch (dim) {
3912             case Esd1D:     numDims = 1; break; // W
3913             case Esd2D:     numDims = 2; break; // W, H
3914             case Esd3D:     numDims = 3; break; // W, H, D
3915             case EsdCube:   numDims = 2; break; // W, H (cube)
3916             case EsdBuffer: numDims = 1; break; // W (buffers)
3917             case EsdRect:   numDims = 2; break; // W, H (rect)
3918             default:
3919                 assert(0 && "unhandled texture dimension");
3920             }
3921
3922             // Arrayed adds another dimension for the number of array elements
3923             if (sampler.isArrayed())
3924                 ++numDims;
3925
3926             // Establish whether the method itself is querying mip levels.  This can be false even
3927             // if the underlying query requires a MIP level, due to the available HLSL method overloads.
3928             const bool mipQuery = (numArgs > (numDims + 1 + (isMs ? 1 : 0)));
3929
3930             // Establish whether we must use the LOD form of query (even if the method did not supply a mip level to query).
3931             // True if:
3932             //   1. 1D/2D/3D/Cube AND multisample==0 AND NOT image (those can be sent to the non-LOD query)
3933             // or,
3934             //   2. There is a LOD (because the non-LOD query cannot be used in that case, per spec)
3935             const bool mipRequired =
3936                 ((dim == Esd1D || dim == Esd2D || dim == Esd3D || dim == EsdCube) && !isMs && !isImage) || // 1...
3937                 mipQuery; // 2...
3938
3939             // AST assumes integer return.  Will be converted to float if required.
3940             TIntermAggregate* sizeQuery = new TIntermAggregate(isImage ? EOpImageQuerySize : EOpTextureQuerySize);
3941             sizeQuery->getSequence().push_back(argTex);
3942
3943             // If we're building an LOD query, add the LOD.
3944             if (mipRequired) {
3945                 // If the base HLSL query had no MIP level given, use level 0.
3946                 TIntermTyped* queryLod = mipQuery ? argAggregate->getSequence()[1]->getAsTyped() :
3947                     intermediate.addConstantUnion(0, loc, true);
3948                 sizeQuery->getSequence().push_back(queryLod);
3949             }
3950
3951             sizeQuery->setType(TType(EbtUint, EvqTemporary, numDims));
3952             sizeQuery->setLoc(loc);
3953
3954             // Return value from size query
3955             TVariable* tempArg = makeInternalVariable("sizeQueryTemp", sizeQuery->getType());
3956             tempArg->getWritableType().getQualifier().makeTemporary();
3957             TIntermTyped* sizeQueryAssign = intermediate.addAssign(EOpAssign,
3958                                                                    intermediate.addSymbol(*tempArg, loc),
3959                                                                    sizeQuery, loc);
3960
3961             // Compound statement for assigning outputs
3962             TIntermAggregate* compoundStatement = intermediate.makeAggregate(sizeQueryAssign, loc);
3963             // Index of first output parameter
3964             const int outParamBase = mipQuery ? 2 : 1;
3965
3966             for (int compNum = 0; compNum < numDims; ++compNum) {
3967                 TIntermTyped* indexedOut = nullptr;
3968                 TIntermSymbol* sizeQueryReturn = intermediate.addSymbol(*tempArg, loc);
3969
3970                 if (numDims > 1) {
3971                     TIntermTyped* component = intermediate.addConstantUnion(compNum, loc, true);
3972                     indexedOut = intermediate.addIndex(EOpIndexDirect, sizeQueryReturn, component, loc);
3973                     indexedOut->setType(TType(EbtUint, EvqTemporary, 1));
3974                     indexedOut->setLoc(loc);
3975                 } else {
3976                     indexedOut = sizeQueryReturn;
3977                 }
3978
3979                 TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + compNum]->getAsTyped();
3980                 TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, indexedOut, loc);
3981
3982                 compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
3983             }
3984
3985             // handle mip level parameter
3986             if (mipQuery) {
3987                 TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + numDims]->getAsTyped();
3988
3989                 TIntermAggregate* levelsQuery = new TIntermAggregate(EOpTextureQueryLevels);
3990                 levelsQuery->getSequence().push_back(argTex);
3991                 levelsQuery->setType(TType(EbtUint, EvqTemporary, 1));
3992                 levelsQuery->setLoc(loc);
3993
3994                 TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, levelsQuery, loc);
3995                 compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
3996             }
3997
3998             // 2DMS formats query # samples, which needs a different query op
3999             if (sampler.isMultiSample()) {
4000                 TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + numDims]->getAsTyped();
4001
4002                 TIntermAggregate* samplesQuery = new TIntermAggregate(EOpImageQuerySamples);
4003                 samplesQuery->getSequence().push_back(argTex);
4004                 samplesQuery->setType(TType(EbtUint, EvqTemporary, 1));
4005                 samplesQuery->setLoc(loc);
4006
4007                 TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, samplesQuery, loc);
4008                 compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
4009             }
4010
4011             compoundStatement->setOperator(EOpSequence);
4012             compoundStatement->setLoc(loc);
4013             compoundStatement->setType(TType(EbtVoid));
4014
4015             node = compoundStatement;
4016
4017             break;
4018         }
4019
4020     case EOpMethodSampleCmp:  // fall through...
4021     case EOpMethodSampleCmpLevelZero:
4022         {
4023             TIntermTyped* argTex    = argAggregate->getSequence()[0]->getAsTyped();
4024             TIntermTyped* argSamp   = argAggregate->getSequence()[1]->getAsTyped();
4025             TIntermTyped* argCoord  = argAggregate->getSequence()[2]->getAsTyped();
4026             TIntermTyped* argCmpVal = argAggregate->getSequence()[3]->getAsTyped();
4027             TIntermTyped* argOffset = nullptr;
4028
4029             // Sampler argument should be a sampler.
4030             if (argSamp->getType().getBasicType() != EbtSampler) {
4031                 error(loc, "expected: sampler type", "", "");
4032                 return;
4033             }
4034
4035             // Sampler should be a SamplerComparisonState
4036             if (! argSamp->getType().getSampler().isShadow()) {
4037                 error(loc, "expected: SamplerComparisonState", "", "");
4038                 return;
4039             }
4040
4041             // optional offset value
4042             if (argAggregate->getSequence().size() > 4)
4043                 argOffset = argAggregate->getSequence()[4]->getAsTyped();
4044
4045             const int coordDimWithCmpVal = argCoord->getType().getVectorSize() + 1; // +1 for cmp
4046
4047             // AST wants comparison value as one of the texture coordinates
4048             TOperator constructOp = EOpNull;
4049             switch (coordDimWithCmpVal) {
4050             // 1D can't happen: there's always at least 1 coordinate dimension + 1 cmp val
4051             case 2: constructOp = EOpConstructVec2;  break;
4052             case 3: constructOp = EOpConstructVec3;  break;
4053             case 4: constructOp = EOpConstructVec4;  break;
4054             case 5: constructOp = EOpConstructVec4;  break; // cubeArrayShadow, cmp value is separate arg.
4055             default: assert(0); break;
4056             }
4057
4058             TIntermAggregate* coordWithCmp = new TIntermAggregate(constructOp);
4059             coordWithCmp->getSequence().push_back(argCoord);
4060             if (coordDimWithCmpVal != 5) // cube array shadow is special.
4061                 coordWithCmp->getSequence().push_back(argCmpVal);
4062             coordWithCmp->setLoc(loc);
4063             coordWithCmp->setType(TType(argCoord->getBasicType(), EvqTemporary, std::min(coordDimWithCmpVal, 4)));
4064
4065             TOperator textureOp = (op == EOpMethodSampleCmpLevelZero ? EOpTextureLod : EOpTexture);
4066             if (argOffset != nullptr)
4067                 textureOp = (op == EOpMethodSampleCmpLevelZero ? EOpTextureLodOffset : EOpTextureOffset);
4068
4069             // Create combined sampler & texture op
4070             TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
4071             TIntermAggregate* txsample = new TIntermAggregate(textureOp);
4072             txsample->getSequence().push_back(txcombine);
4073             txsample->getSequence().push_back(coordWithCmp);
4074
4075             if (coordDimWithCmpVal == 5) // cube array shadow is special: cmp val follows coord.
4076                 txsample->getSequence().push_back(argCmpVal);
4077
4078             // the LevelZero form uses 0 as an explicit LOD
4079             if (op == EOpMethodSampleCmpLevelZero)
4080                 txsample->getSequence().push_back(intermediate.addConstantUnion(0.0, EbtFloat, loc, true));
4081
4082             // Add offset if present
4083             if (argOffset != nullptr)
4084                 txsample->getSequence().push_back(argOffset);
4085
4086             txsample->setType(node->getType());
4087             txsample->setLoc(loc);
4088             node = txsample;
4089
4090             break;
4091         }
4092
4093     case EOpMethodLoad:
4094         {
4095             TIntermTyped* argTex    = argAggregate->getSequence()[0]->getAsTyped();
4096             TIntermTyped* argCoord  = argAggregate->getSequence()[1]->getAsTyped();
4097             TIntermTyped* argOffset = nullptr;
4098             TIntermTyped* lodComponent = nullptr;
4099             TIntermTyped* coordSwizzle = nullptr;
4100
4101             const TSampler& sampler = argTex->getType().getSampler();
4102             const bool isMS = sampler.isMultiSample();
4103             const bool isBuffer = sampler.dim == EsdBuffer;
4104             const bool isImage = sampler.isImage();
4105             const TBasicType coordBaseType = argCoord->getType().getBasicType();
4106
4107             // Last component of coordinate is the mip level, for non-MS.  we separate them here:
4108             if (isMS || isBuffer || isImage) {
4109                 // MS, Buffer, and Image have no LOD
4110                 coordSwizzle = argCoord;
4111             } else {
4112                 // Extract coordinate
4113                 int swizzleSize = argCoord->getType().getVectorSize() - (isMS ? 0 : 1);
4114                 TSwizzleSelectors<TVectorSelector> coordFields;
4115                 for (int i = 0; i < swizzleSize; ++i)
4116                     coordFields.push_back(i);
4117                 TIntermTyped* coordIdx = intermediate.addSwizzle(coordFields, loc);
4118                 coordSwizzle = intermediate.addIndex(EOpVectorSwizzle, argCoord, coordIdx, loc);
4119                 coordSwizzle->setType(TType(coordBaseType, EvqTemporary, coordFields.size()));
4120
4121                 // Extract LOD
4122                 TIntermTyped* lodIdx = intermediate.addConstantUnion(coordFields.size(), loc, true);
4123                 lodComponent = intermediate.addIndex(EOpIndexDirect, argCoord, lodIdx, loc);
4124                 lodComponent->setType(TType(coordBaseType, EvqTemporary, 1));
4125             }
4126
4127             const int numArgs    = (int)argAggregate->getSequence().size();
4128             const bool hasOffset = ((!isMS && numArgs == 3) || (isMS && numArgs == 4));
4129
4130             // Create texel fetch
4131             const TOperator fetchOp = (isImage   ? EOpImageLoad :
4132                                        hasOffset ? EOpTextureFetchOffset :
4133                                        EOpTextureFetch);
4134             TIntermAggregate* txfetch = new TIntermAggregate(fetchOp);
4135
4136             // Build up the fetch
4137             txfetch->getSequence().push_back(argTex);
4138             txfetch->getSequence().push_back(coordSwizzle);
4139
4140             if (isMS) {
4141                 // add 2DMS sample index
4142                 TIntermTyped* argSampleIdx  = argAggregate->getSequence()[2]->getAsTyped();
4143                 txfetch->getSequence().push_back(argSampleIdx);
4144             } else if (isBuffer) {
4145                 // Nothing else to do for buffers.
4146             } else if (isImage) {
4147                 // Nothing else to do for images.
4148             } else {
4149                 // 2DMS and buffer have no LOD, but everything else does.
4150                 txfetch->getSequence().push_back(lodComponent);
4151             }
4152
4153             // Obtain offset arg, if there is one.
4154             if (hasOffset) {
4155                 const int offsetPos  = (isMS ? 3 : 2);
4156                 argOffset = argAggregate->getSequence()[offsetPos]->getAsTyped();
4157                 txfetch->getSequence().push_back(argOffset);
4158             }
4159
4160             node = convertReturn(txfetch, sampler);
4161
4162             break;
4163         }
4164
4165     case EOpMethodSampleLevel:
4166         {
4167             TIntermTyped* argTex    = argAggregate->getSequence()[0]->getAsTyped();
4168             TIntermTyped* argSamp   = argAggregate->getSequence()[1]->getAsTyped();
4169             TIntermTyped* argCoord  = argAggregate->getSequence()[2]->getAsTyped();
4170             TIntermTyped* argLod    = argAggregate->getSequence()[3]->getAsTyped();
4171             TIntermTyped* argOffset = nullptr;
4172             const TSampler& sampler = argTex->getType().getSampler();
4173
4174             const int  numArgs = (int)argAggregate->getSequence().size();
4175
4176             if (numArgs == 5) // offset, if present
4177                 argOffset = argAggregate->getSequence()[4]->getAsTyped();
4178
4179             const TOperator textureOp = (argOffset == nullptr ? EOpTextureLod : EOpTextureLodOffset);
4180             TIntermAggregate* txsample = new TIntermAggregate(textureOp);
4181
4182             TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
4183
4184             txsample->getSequence().push_back(txcombine);
4185             txsample->getSequence().push_back(argCoord);
4186             txsample->getSequence().push_back(argLod);
4187
4188             if (argOffset != nullptr)
4189                 txsample->getSequence().push_back(argOffset);
4190
4191             node = convertReturn(txsample, sampler);
4192
4193             break;
4194         }
4195
4196     case EOpMethodGather:
4197         {
4198             TIntermTyped* argTex    = argAggregate->getSequence()[0]->getAsTyped();
4199             TIntermTyped* argSamp   = argAggregate->getSequence()[1]->getAsTyped();
4200             TIntermTyped* argCoord  = argAggregate->getSequence()[2]->getAsTyped();
4201             TIntermTyped* argOffset = nullptr;
4202
4203             // Offset is optional
4204             if (argAggregate->getSequence().size() > 3)
4205                 argOffset = argAggregate->getSequence()[3]->getAsTyped();
4206
4207             const TOperator textureOp = (argOffset == nullptr ? EOpTextureGather : EOpTextureGatherOffset);
4208             TIntermAggregate* txgather = new TIntermAggregate(textureOp);
4209
4210             TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
4211
4212             txgather->getSequence().push_back(txcombine);
4213             txgather->getSequence().push_back(argCoord);
4214             // Offset if not given is implicitly channel 0 (red)
4215
4216             if (argOffset != nullptr)
4217                 txgather->getSequence().push_back(argOffset);
4218
4219             txgather->setType(node->getType());
4220             txgather->setLoc(loc);
4221             node = txgather;
4222
4223             break;
4224         }
4225
4226     case EOpMethodGatherRed:      // fall through...
4227     case EOpMethodGatherGreen:    // ...
4228     case EOpMethodGatherBlue:     // ...
4229     case EOpMethodGatherAlpha:    // ...
4230     case EOpMethodGatherCmpRed:   // ...
4231     case EOpMethodGatherCmpGreen: // ...
4232     case EOpMethodGatherCmpBlue:  // ...
4233     case EOpMethodGatherCmpAlpha: // ...
4234         {
4235             int channel = 0;    // the channel we are gathering
4236             int cmpValues = 0;  // 1 if there is a compare value (handier than a bool below)
4237
4238             switch (op) {
4239             case EOpMethodGatherCmpRed:   cmpValues = 1;  // fall through
4240             case EOpMethodGatherRed:      channel = 0; break;
4241             case EOpMethodGatherCmpGreen: cmpValues = 1;  // fall through
4242             case EOpMethodGatherGreen:    channel = 1; break;
4243             case EOpMethodGatherCmpBlue:  cmpValues = 1;  // fall through
4244             case EOpMethodGatherBlue:     channel = 2; break;
4245             case EOpMethodGatherCmpAlpha: cmpValues = 1;  // fall through
4246             case EOpMethodGatherAlpha:    channel = 3; break;
4247             default:                      assert(0);   break;
4248             }
4249
4250             // For now, we have nothing to map the component-wise comparison forms
4251             // to, because neither GLSL nor SPIR-V has such an opcode.  Issue an
4252             // unimplemented error instead.  Most of the machinery is here if that
4253             // should ever become available.  However, red can be passed through
4254             // to OpImageDrefGather.  G/B/A cannot, because that opcode does not
4255             // accept a component.
4256             if (cmpValues != 0 && op != EOpMethodGatherCmpRed) {
4257                 error(loc, "unimplemented: component-level gather compare", "", "");
4258                 return;
4259             }
4260
4261             int arg = 0;
4262
4263             TIntermTyped* argTex        = argAggregate->getSequence()[arg++]->getAsTyped();
4264             TIntermTyped* argSamp       = argAggregate->getSequence()[arg++]->getAsTyped();
4265             TIntermTyped* argCoord      = argAggregate->getSequence()[arg++]->getAsTyped();
4266             TIntermTyped* argOffset     = nullptr;
4267             TIntermTyped* argOffsets[4] = { nullptr, nullptr, nullptr, nullptr };
4268             // TIntermTyped* argStatus     = nullptr; // TODO: residency
4269             TIntermTyped* argCmp        = nullptr;
4270
4271             const TSamplerDim dim = argTex->getType().getSampler().dim;
4272
4273             const int  argSize = (int)argAggregate->getSequence().size();
4274             bool hasStatus     = (argSize == (5+cmpValues) || argSize == (8+cmpValues));
4275             bool hasOffset1    = false;
4276             bool hasOffset4    = false;
4277
4278             // Sampler argument should be a sampler.
4279             if (argSamp->getType().getBasicType() != EbtSampler) {
4280                 error(loc, "expected: sampler type", "", "");
4281                 return;
4282             }
4283
4284             // Cmp forms require SamplerComparisonState
4285             if (cmpValues > 0 && ! argSamp->getType().getSampler().isShadow()) {
4286                 error(loc, "expected: SamplerComparisonState", "", "");
4287                 return;
4288             }
4289
4290             // Only 2D forms can have offsets.  Discover if we have 0, 1 or 4 offsets.
4291             if (dim == Esd2D) {
4292                 hasOffset1 = (argSize == (4+cmpValues) || argSize == (5+cmpValues));
4293                 hasOffset4 = (argSize == (7+cmpValues) || argSize == (8+cmpValues));
4294             }
4295
4296             assert(!(hasOffset1 && hasOffset4));
4297
4298             TOperator textureOp = EOpTextureGather;
4299
4300             // Compare forms have compare value
4301             if (cmpValues != 0)
4302                 argCmp = argOffset = argAggregate->getSequence()[arg++]->getAsTyped();
4303
4304             // Some forms have single offset
4305             if (hasOffset1) {
4306                 textureOp = EOpTextureGatherOffset;   // single offset form
4307                 argOffset = argAggregate->getSequence()[arg++]->getAsTyped();
4308             }
4309
4310             // Some forms have 4 gather offsets
4311             if (hasOffset4) {
4312                 textureOp = EOpTextureGatherOffsets;  // note plural, for 4 offset form
4313                 for (int offsetNum = 0; offsetNum < 4; ++offsetNum)
4314                     argOffsets[offsetNum] = argAggregate->getSequence()[arg++]->getAsTyped();
4315             }
4316
4317             // Residency status
4318             if (hasStatus) {
4319                 // argStatus = argAggregate->getSequence()[arg++]->getAsTyped();
4320                 error(loc, "unimplemented: residency status", "", "");
4321                 return;
4322             }
4323
4324             TIntermAggregate* txgather = new TIntermAggregate(textureOp);
4325             TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
4326
4327             TIntermTyped* argChannel = intermediate.addConstantUnion(channel, loc, true);
4328
4329             txgather->getSequence().push_back(txcombine);
4330             txgather->getSequence().push_back(argCoord);
4331
4332             // AST wants an array of 4 offsets, where HLSL has separate args.  Here
4333             // we construct an array from the separate args.
4334             if (hasOffset4) {
4335                 TType arrayType(EbtInt, EvqTemporary, 2);
4336                 TArraySizes* arraySizes = new TArraySizes;
4337                 arraySizes->addInnerSize(4);
4338                 arrayType.transferArraySizes(arraySizes);
4339
4340                 TIntermAggregate* initList = new TIntermAggregate(EOpNull);
4341
4342                 for (int offsetNum = 0; offsetNum < 4; ++offsetNum)
4343                     initList->getSequence().push_back(argOffsets[offsetNum]);
4344
4345                 argOffset = addConstructor(loc, initList, arrayType);
4346             }
4347
4348             // Add comparison value if we have one
4349             if (argCmp != nullptr)
4350                 txgather->getSequence().push_back(argCmp);
4351
4352             // Add offset (either 1, or an array of 4) if we have one
4353             if (argOffset != nullptr)
4354                 txgather->getSequence().push_back(argOffset);
4355
4356             // Add channel value if the sampler is not shadow
4357             if (! argSamp->getType().getSampler().isShadow())
4358                 txgather->getSequence().push_back(argChannel);
4359
4360             txgather->setType(node->getType());
4361             txgather->setLoc(loc);
4362             node = txgather;
4363
4364             break;
4365         }
4366
4367     case EOpMethodCalculateLevelOfDetail:
4368     case EOpMethodCalculateLevelOfDetailUnclamped:
4369         {
4370             TIntermTyped* argTex    = argAggregate->getSequence()[0]->getAsTyped();
4371             TIntermTyped* argSamp   = argAggregate->getSequence()[1]->getAsTyped();
4372             TIntermTyped* argCoord  = argAggregate->getSequence()[2]->getAsTyped();
4373
4374             TIntermAggregate* txquerylod = new TIntermAggregate(EOpTextureQueryLod);
4375
4376             TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
4377             txquerylod->getSequence().push_back(txcombine);
4378             txquerylod->getSequence().push_back(argCoord);
4379
4380             TIntermTyped* lodComponent = intermediate.addConstantUnion(
4381                 op == EOpMethodCalculateLevelOfDetail ? 0 : 1,
4382                 loc, true);
4383             TIntermTyped* lodComponentIdx = intermediate.addIndex(EOpIndexDirect, txquerylod, lodComponent, loc);
4384             lodComponentIdx->setType(TType(EbtFloat, EvqTemporary, 1));
4385             node = lodComponentIdx;
4386
4387             break;
4388         }
4389
4390     case EOpMethodGetSamplePosition:
4391         {
4392             // TODO: this entire decomposition exists because there is not yet a way to query
4393             // the sample position directly through SPIR-V.  Instead, we return fixed sample
4394             // positions for common cases.  *** If the sample positions are set differently,
4395             // this will be wrong. ***
4396
4397             TIntermTyped* argTex     = argAggregate->getSequence()[0]->getAsTyped();
4398             TIntermTyped* argSampIdx = argAggregate->getSequence()[1]->getAsTyped();
4399
4400             TIntermAggregate* samplesQuery = new TIntermAggregate(EOpImageQuerySamples);
4401             samplesQuery->getSequence().push_back(argTex);
4402             samplesQuery->setType(TType(EbtUint, EvqTemporary, 1));
4403             samplesQuery->setLoc(loc);
4404
4405             TIntermAggregate* compoundStatement = nullptr;
4406
4407             TVariable* outSampleCount = makeInternalVariable("@sampleCount", TType(EbtUint));
4408             outSampleCount->getWritableType().getQualifier().makeTemporary();
4409             TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, intermediate.addSymbol(*outSampleCount, loc),
4410                                                               samplesQuery, loc);
4411             compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
4412
4413             TIntermTyped* idxtest[4];
4414
4415             // Create tests against 2, 4, 8, and 16 sample values
4416             int count = 0;
4417             for (int val = 2; val <= 16; val *= 2)
4418                 idxtest[count++] =
4419                     intermediate.addBinaryNode(EOpEqual, 
4420                                                intermediate.addSymbol(*outSampleCount, loc),
4421                                                intermediate.addConstantUnion(val, loc),
4422                                                loc, TType(EbtBool));
4423
4424             const TOperator idxOp = (argSampIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
4425             
4426             // Create index ops into position arrays given sample index.
4427             // TODO: should it be clamped?
4428             TIntermTyped* index[4];
4429             count = 0;
4430             for (int val = 2; val <= 16; val *= 2) {
4431                 index[count] = intermediate.addIndex(idxOp, getSamplePosArray(val), argSampIdx, loc);
4432                 index[count++]->setType(TType(EbtFloat, EvqTemporary, 2));
4433             }
4434
4435             // Create expression as:
4436             // (sampleCount == 2)  ? pos2[idx] :
4437             // (sampleCount == 4)  ? pos4[idx] :
4438             // (sampleCount == 8)  ? pos8[idx] :
4439             // (sampleCount == 16) ? pos16[idx] : float2(0,0);
4440             TIntermTyped* test = 
4441                 intermediate.addSelection(idxtest[0], index[0], 
4442                     intermediate.addSelection(idxtest[1], index[1], 
4443                         intermediate.addSelection(idxtest[2], index[2],
4444                             intermediate.addSelection(idxtest[3], index[3], 
4445                                                       getSamplePosArray(1), loc), loc), loc), loc);
4446                                          
4447             compoundStatement = intermediate.growAggregate(compoundStatement, test);
4448             compoundStatement->setOperator(EOpSequence);
4449             compoundStatement->setLoc(loc);
4450             compoundStatement->setType(TType(EbtFloat, EvqTemporary, 2));
4451
4452             node = compoundStatement;
4453
4454             break;
4455         }
4456
4457     case EOpSubpassLoad:
4458         {
4459             const TIntermTyped* argSubpass = 
4460                 argAggregate ? argAggregate->getSequence()[0]->getAsTyped() :
4461                 arguments->getAsTyped();
4462
4463             const TSampler& sampler = argSubpass->getType().getSampler();
4464
4465             // subpass load: the multisample form is overloaded.  Here, we convert that to
4466             // the EOpSubpassLoadMS opcode.
4467             if (argAggregate != nullptr && argAggregate->getSequence().size() > 1)
4468                 node->getAsOperator()->setOp(EOpSubpassLoadMS);
4469
4470             node = convertReturn(node, sampler);
4471
4472             break;
4473         }
4474         
4475
4476     default:
4477         break; // most pass through unchanged
4478     }
4479 }
4480
4481 //
4482 // Decompose geometry shader methods
4483 //
4484 void HlslParseContext::decomposeGeometryMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
4485 {
4486     if (node == nullptr || !node->getAsOperator())
4487         return;
4488
4489     const TOperator op  = node->getAsOperator()->getOp();
4490     const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
4491
4492     switch (op) {
4493     case EOpMethodAppend:
4494         if (argAggregate) {
4495             // Don't emit these for non-GS stage, since we won't have the gsStreamOutput symbol.
4496             if (language != EShLangGeometry) {
4497                 node = nullptr;
4498                 return;
4499             }
4500
4501             TIntermAggregate* sequence = nullptr;
4502             TIntermAggregate* emit = new TIntermAggregate(EOpEmitVertex);
4503
4504             emit->setLoc(loc);
4505             emit->setType(TType(EbtVoid));
4506
4507             TIntermTyped* data = argAggregate->getSequence()[1]->getAsTyped();
4508
4509             // This will be patched in finalization during finalizeAppendMethods()
4510             sequence = intermediate.growAggregate(sequence, data, loc);
4511             sequence = intermediate.growAggregate(sequence, emit);
4512
4513             sequence->setOperator(EOpSequence);
4514             sequence->setLoc(loc);
4515             sequence->setType(TType(EbtVoid));
4516
4517             gsAppends.push_back({sequence, loc});
4518
4519             node = sequence;
4520         }
4521         break;
4522
4523     case EOpMethodRestartStrip:
4524         {
4525             // Don't emit these for non-GS stage, since we won't have the gsStreamOutput symbol.
4526             if (language != EShLangGeometry) {
4527                 node = nullptr;
4528                 return;
4529             }
4530
4531             TIntermAggregate* cut = new TIntermAggregate(EOpEndPrimitive);
4532             cut->setLoc(loc);
4533             cut->setType(TType(EbtVoid));
4534             node = cut;
4535         }
4536         break;
4537
4538     default:
4539         break; // most pass through unchanged
4540     }
4541 }
4542
4543 //
4544 // Optionally decompose intrinsics to AST opcodes.
4545 //
4546 void HlslParseContext::decomposeIntrinsic(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
4547 {
4548     // Helper to find image data for image atomics:
4549     // OpImageLoad(image[idx])
4550     // We take the image load apart and add its params to the atomic op aggregate node
4551     const auto imageAtomicParams = [this, &loc, &node](TIntermAggregate* atomic, TIntermTyped* load) {
4552         TIntermAggregate* loadOp = load->getAsAggregate();
4553         if (loadOp == nullptr) {
4554             error(loc, "unknown image type in atomic operation", "", "");
4555             node = nullptr;
4556             return;
4557         }
4558
4559         atomic->getSequence().push_back(loadOp->getSequence()[0]);
4560         atomic->getSequence().push_back(loadOp->getSequence()[1]);
4561     };
4562
4563     // Return true if this is an imageLoad, which we will change to an image atomic.
4564     const auto isImageParam = [](TIntermTyped* image) -> bool {
4565         TIntermAggregate* imageAggregate = image->getAsAggregate();
4566         return imageAggregate != nullptr && imageAggregate->getOp() == EOpImageLoad;
4567     };
4568
4569     const auto lookupBuiltinVariable = [&](const char* name, TBuiltInVariable builtin, TType& type) -> TIntermTyped* {
4570         TSymbol* symbol = symbolTable.find(name);
4571         if (nullptr == symbol) {
4572             type.getQualifier().builtIn = builtin;
4573
4574             TVariable* variable = new TVariable(new TString(name), type);
4575
4576             symbolTable.insert(*variable);
4577
4578             symbol = symbolTable.find(name);
4579             assert(symbol && "Inserted symbol could not be found!");
4580         }
4581
4582         return intermediate.addSymbol(*(symbol->getAsVariable()), loc);
4583     };
4584
4585     // HLSL intrinsics can be pass through to native AST opcodes, or decomposed here to existing AST
4586     // opcodes for compatibility with existing software stacks.
4587     static const bool decomposeHlslIntrinsics = true;
4588
4589     if (!decomposeHlslIntrinsics || !node || !node->getAsOperator())
4590         return;
4591
4592     const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
4593     TIntermUnary* fnUnary = node->getAsUnaryNode();
4594     const TOperator op  = node->getAsOperator()->getOp();
4595
4596     switch (op) {
4597     case EOpGenMul:
4598         {
4599             // mul(a,b) -> MatrixTimesMatrix, MatrixTimesVector, MatrixTimesScalar, VectorTimesScalar, Dot, Mul
4600             // Since we are treating HLSL rows like GLSL columns (the first matrix indirection),
4601             // we must reverse the operand order here.  Hence, arg0 gets sequence[1], etc.
4602             TIntermTyped* arg0 = argAggregate->getSequence()[1]->getAsTyped();
4603             TIntermTyped* arg1 = argAggregate->getSequence()[0]->getAsTyped();
4604
4605             if (arg0->isVector() && arg1->isVector()) {  // vec * vec
4606                 node->getAsAggregate()->setOperator(EOpDot);
4607             } else {
4608                 node = handleBinaryMath(loc, "mul", EOpMul, arg0, arg1);
4609             }
4610
4611             break;
4612         }
4613
4614     case EOpRcp:
4615         {
4616             // rcp(a) -> 1 / a
4617             TIntermTyped* arg0 = fnUnary->getOperand();
4618             TBasicType   type0 = arg0->getBasicType();
4619             TIntermTyped* one  = intermediate.addConstantUnion(1, type0, loc, true);
4620             node  = handleBinaryMath(loc, "rcp", EOpDiv, one, arg0);
4621
4622             break;
4623         }
4624
4625     case EOpAny: // fall through
4626     case EOpAll:
4627         {
4628             TIntermTyped* typedArg = arguments->getAsTyped();
4629
4630             // HLSL allows float/etc types here, and the SPIR-V opcode requires a bool.
4631             // We'll convert here.  Note that for efficiency, we could add a smarter
4632             // decomposition for some type cases, e.g, maybe by decomposing a dot product.
4633             if (typedArg->getType().getBasicType() != EbtBool) {
4634                 const TType boolType(EbtBool, EvqTemporary,
4635                                      typedArg->getVectorSize(),
4636                                      typedArg->getMatrixCols(),
4637                                      typedArg->getMatrixRows(),
4638                                      typedArg->isVector());
4639
4640                 typedArg = intermediate.addConversion(EOpConstructBool, boolType, typedArg);
4641                 node->getAsUnaryNode()->setOperand(typedArg);
4642             }
4643
4644             break;
4645         }
4646
4647     case EOpSaturate:
4648         {
4649             // saturate(a) -> clamp(a,0,1)
4650             TIntermTyped* arg0 = fnUnary->getOperand();
4651             TBasicType   type0 = arg0->getBasicType();
4652             TIntermAggregate* clamp = new TIntermAggregate(EOpClamp);
4653
4654             clamp->getSequence().push_back(arg0);
4655             clamp->getSequence().push_back(intermediate.addConstantUnion(0, type0, loc, true));
4656             clamp->getSequence().push_back(intermediate.addConstantUnion(1, type0, loc, true));
4657             clamp->setLoc(loc);
4658             clamp->setType(node->getType());
4659             clamp->getWritableType().getQualifier().makeTemporary();
4660             node = clamp;
4661
4662             break;
4663         }
4664
4665     case EOpSinCos:
4666         {
4667             // sincos(a,b,c) -> b = sin(a), c = cos(a)
4668             TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
4669             TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
4670             TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped();
4671
4672             TIntermTyped* sinStatement = handleUnaryMath(loc, "sin", EOpSin, arg0);
4673             TIntermTyped* cosStatement = handleUnaryMath(loc, "cos", EOpCos, arg0);
4674             TIntermTyped* sinAssign    = intermediate.addAssign(EOpAssign, arg1, sinStatement, loc);
4675             TIntermTyped* cosAssign    = intermediate.addAssign(EOpAssign, arg2, cosStatement, loc);
4676
4677             TIntermAggregate* compoundStatement = intermediate.makeAggregate(sinAssign, loc);
4678             compoundStatement = intermediate.growAggregate(compoundStatement, cosAssign);
4679             compoundStatement->setOperator(EOpSequence);
4680             compoundStatement->setLoc(loc);
4681             compoundStatement->setType(TType(EbtVoid));
4682
4683             node = compoundStatement;
4684
4685             break;
4686         }
4687
4688     case EOpClip:
4689         {
4690             // clip(a) -> if (any(a<0)) discard;
4691             TIntermTyped*  arg0 = fnUnary->getOperand();
4692             TBasicType     type0 = arg0->getBasicType();
4693             TIntermTyped*  compareNode = nullptr;
4694
4695             // For non-scalars: per experiment with FXC compiler, discard if any component < 0.
4696             if (!arg0->isScalar()) {
4697                 // component-wise compare: a < 0
4698                 TIntermAggregate* less = new TIntermAggregate(EOpLessThan);
4699                 less->getSequence().push_back(arg0);
4700                 less->setLoc(loc);
4701
4702                 // make vec or mat of bool matching dimensions of input
4703                 less->setType(TType(EbtBool, EvqTemporary,
4704                                     arg0->getType().getVectorSize(),
4705                                     arg0->getType().getMatrixCols(),
4706                                     arg0->getType().getMatrixRows(),
4707                                     arg0->getType().isVector()));
4708
4709                 // calculate # of components for comparison const
4710                 const int constComponentCount =
4711                     std::max(arg0->getType().getVectorSize(), 1) *
4712                     std::max(arg0->getType().getMatrixCols(), 1) *
4713                     std::max(arg0->getType().getMatrixRows(), 1);
4714
4715                 TConstUnion zero;
4716                 if (arg0->getType().isIntegerDomain())
4717                     zero.setDConst(0);
4718                 else
4719                     zero.setDConst(0.0);
4720                 TConstUnionArray zeros(constComponentCount, zero);
4721
4722                 less->getSequence().push_back(intermediate.addConstantUnion(zeros, arg0->getType(), loc, true));
4723
4724                 compareNode = intermediate.addBuiltInFunctionCall(loc, EOpAny, true, less, TType(EbtBool));
4725             } else {
4726                 TIntermTyped* zero;
4727                 if (arg0->getType().isIntegerDomain())
4728                     zero = intermediate.addConstantUnion(0, loc, true);
4729                 else
4730                     zero = intermediate.addConstantUnion(0.0, type0, loc, true);
4731                 compareNode = handleBinaryMath(loc, "clip", EOpLessThan, arg0, zero);
4732             }
4733
4734             TIntermBranch* killNode = intermediate.addBranch(EOpKill, loc);
4735
4736             node = new TIntermSelection(compareNode, killNode, nullptr);
4737             node->setLoc(loc);
4738
4739             break;
4740         }
4741
4742     case EOpLog10:
4743         {
4744             // log10(a) -> log2(a) * 0.301029995663981  (== 1/log2(10))
4745             TIntermTyped* arg0 = fnUnary->getOperand();
4746             TIntermTyped* log2 = handleUnaryMath(loc, "log2", EOpLog2, arg0);
4747             TIntermTyped* base = intermediate.addConstantUnion(0.301029995663981f, EbtFloat, loc, true);
4748
4749             node  = handleBinaryMath(loc, "mul", EOpMul, log2, base);
4750
4751             break;
4752         }
4753
4754     case EOpDst:
4755         {
4756             // dest.x = 1;
4757             // dest.y = src0.y * src1.y;
4758             // dest.z = src0.z;
4759             // dest.w = src1.w;
4760
4761             TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
4762             TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
4763
4764             TIntermTyped* y = intermediate.addConstantUnion(1, loc, true);
4765             TIntermTyped* z = intermediate.addConstantUnion(2, loc, true);
4766             TIntermTyped* w = intermediate.addConstantUnion(3, loc, true);
4767
4768             TIntermTyped* src0y = intermediate.addIndex(EOpIndexDirect, arg0, y, loc);
4769             TIntermTyped* src1y = intermediate.addIndex(EOpIndexDirect, arg1, y, loc);
4770             TIntermTyped* src0z = intermediate.addIndex(EOpIndexDirect, arg0, z, loc);
4771             TIntermTyped* src1w = intermediate.addIndex(EOpIndexDirect, arg1, w, loc);
4772
4773             TIntermAggregate* dst = new TIntermAggregate(EOpConstructVec4);
4774
4775             dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
4776             dst->getSequence().push_back(handleBinaryMath(loc, "mul", EOpMul, src0y, src1y));
4777             dst->getSequence().push_back(src0z);
4778             dst->getSequence().push_back(src1w);
4779             dst->setType(TType(EbtFloat, EvqTemporary, 4));
4780             dst->setLoc(loc);
4781             node = dst;
4782
4783             break;
4784         }
4785
4786     case EOpInterlockedAdd: // optional last argument (if present) is assigned from return value
4787     case EOpInterlockedMin: // ...
4788     case EOpInterlockedMax: // ...
4789     case EOpInterlockedAnd: // ...
4790     case EOpInterlockedOr:  // ...
4791     case EOpInterlockedXor: // ...
4792     case EOpInterlockedExchange: // always has output arg
4793         {
4794             TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();  // dest
4795             TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();  // value
4796             TIntermTyped* arg2 = nullptr;
4797
4798             if (argAggregate->getSequence().size() > 2)
4799                 arg2 = argAggregate->getSequence()[2]->getAsTyped();
4800
4801             const bool isImage = isImageParam(arg0);
4802             const TOperator atomicOp = mapAtomicOp(loc, op, isImage);
4803             TIntermAggregate* atomic = new TIntermAggregate(atomicOp);
4804             atomic->setType(arg0->getType());
4805             atomic->getWritableType().getQualifier().makeTemporary();
4806             atomic->setLoc(loc);
4807
4808             if (isImage) {
4809                 // orig_value = imageAtomicOp(image, loc, data)
4810                 imageAtomicParams(atomic, arg0);
4811                 atomic->getSequence().push_back(arg1);
4812
4813                 if (argAggregate->getSequence().size() > 2) {
4814                     node = intermediate.addAssign(EOpAssign, arg2, atomic, loc);
4815                 } else {
4816                     node = atomic; // no assignment needed, as there was no out var.
4817                 }
4818             } else {
4819                 // Normal memory variable:
4820                 // arg0 = mem, arg1 = data, arg2(optional,out) = orig_value
4821                 if (argAggregate->getSequence().size() > 2) {
4822                     // optional output param is present.  return value goes to arg2.
4823                     atomic->getSequence().push_back(arg0);
4824                     atomic->getSequence().push_back(arg1);
4825
4826                     node = intermediate.addAssign(EOpAssign, arg2, atomic, loc);
4827                 } else {
4828                     // Set the matching operator.  Since output is absent, this is all we need to do.
4829                     node->getAsAggregate()->setOperator(atomicOp);
4830                     node->setType(atomic->getType());
4831                 }
4832             }
4833
4834             break;
4835         }
4836
4837     case EOpInterlockedCompareExchange:
4838         {
4839             TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();  // dest
4840             TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();  // cmp
4841             TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped();  // value
4842             TIntermTyped* arg3 = argAggregate->getSequence()[3]->getAsTyped();  // orig
4843
4844             const bool isImage = isImageParam(arg0);
4845             TIntermAggregate* atomic = new TIntermAggregate(mapAtomicOp(loc, op, isImage));
4846             atomic->setLoc(loc);
4847             atomic->setType(arg2->getType());
4848             atomic->getWritableType().getQualifier().makeTemporary();
4849
4850             if (isImage) {
4851                 imageAtomicParams(atomic, arg0);
4852             } else {
4853                 atomic->getSequence().push_back(arg0);
4854             }
4855
4856             atomic->getSequence().push_back(arg1);
4857             atomic->getSequence().push_back(arg2);
4858             node = intermediate.addAssign(EOpAssign, arg3, atomic, loc);
4859
4860             break;
4861         }
4862
4863     case EOpEvaluateAttributeSnapped:
4864         {
4865             // SPIR-V InterpolateAtOffset uses float vec2 offset in pixels
4866             // HLSL uses int2 offset on a 16x16 grid in [-8..7] on x & y:
4867             //   iU = (iU<<28)>>28
4868             //   fU = ((float)iU)/16
4869             // Targets might handle this natively, in which case they can disable
4870             // decompositions.
4871
4872             TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();  // value
4873             TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();  // offset
4874
4875             TIntermTyped* i28 = intermediate.addConstantUnion(28, loc, true);
4876             TIntermTyped* iU = handleBinaryMath(loc, ">>", EOpRightShift,
4877                                                 handleBinaryMath(loc, "<<", EOpLeftShift, arg1, i28),
4878                                                 i28);
4879
4880             TIntermTyped* recip16 = intermediate.addConstantUnion((1.0/16.0), EbtFloat, loc, true);
4881             TIntermTyped* floatOffset = handleBinaryMath(loc, "mul", EOpMul,
4882                                                          intermediate.addConversion(EOpConstructFloat,
4883                                                                                     TType(EbtFloat, EvqTemporary, 2), iU),
4884                                                          recip16);
4885
4886             TIntermAggregate* interp = new TIntermAggregate(EOpInterpolateAtOffset);
4887             interp->getSequence().push_back(arg0);
4888             interp->getSequence().push_back(floatOffset);
4889             interp->setLoc(loc);
4890             interp->setType(arg0->getType());
4891             interp->getWritableType().getQualifier().makeTemporary();
4892
4893             node = interp;
4894
4895             break;
4896         }
4897
4898     case EOpLit:
4899         {
4900             TIntermTyped* n_dot_l = argAggregate->getSequence()[0]->getAsTyped();
4901             TIntermTyped* n_dot_h = argAggregate->getSequence()[1]->getAsTyped();
4902             TIntermTyped* m = argAggregate->getSequence()[2]->getAsTyped();
4903
4904             TIntermAggregate* dst = new TIntermAggregate(EOpConstructVec4);
4905
4906             // Ambient
4907             dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
4908
4909             // Diffuse:
4910             TIntermTyped* zero = intermediate.addConstantUnion(0.0, EbtFloat, loc, true);
4911             TIntermAggregate* diffuse = new TIntermAggregate(EOpMax);
4912             diffuse->getSequence().push_back(n_dot_l);
4913             diffuse->getSequence().push_back(zero);
4914             diffuse->setLoc(loc);
4915             diffuse->setType(TType(EbtFloat));
4916             dst->getSequence().push_back(diffuse);
4917
4918             // Specular:
4919             TIntermAggregate* min_ndot = new TIntermAggregate(EOpMin);
4920             min_ndot->getSequence().push_back(n_dot_l);
4921             min_ndot->getSequence().push_back(n_dot_h);
4922             min_ndot->setLoc(loc);
4923             min_ndot->setType(TType(EbtFloat));
4924
4925             TIntermTyped* compare = handleBinaryMath(loc, "<", EOpLessThan, min_ndot, zero);
4926             TIntermTyped* n_dot_h_m = handleBinaryMath(loc, "mul", EOpMul, n_dot_h, m);  // n_dot_h * m
4927
4928             dst->getSequence().push_back(intermediate.addSelection(compare, zero, n_dot_h_m, loc));
4929
4930             // One:
4931             dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
4932
4933             dst->setLoc(loc);
4934             dst->setType(TType(EbtFloat, EvqTemporary, 4));
4935             node = dst;
4936             break;
4937         }
4938
4939     case EOpAsDouble:
4940         {
4941             // asdouble accepts two 32 bit ints.  we can use EOpUint64BitsToDouble, but must
4942             // first construct a uint64.
4943             TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
4944             TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
4945
4946             if (arg0->getType().isVector()) { // TODO: ...
4947                 error(loc, "double2 conversion not implemented", "asdouble", "");
4948                 break;
4949             }
4950
4951             TIntermAggregate* uint64 = new TIntermAggregate(EOpConstructUVec2);
4952
4953             uint64->getSequence().push_back(arg0);
4954             uint64->getSequence().push_back(arg1);
4955             uint64->setType(TType(EbtUint, EvqTemporary, 2));  // convert 2 uints to a uint2
4956             uint64->setLoc(loc);
4957
4958             // bitcast uint2 to a double
4959             TIntermTyped* convert = new TIntermUnary(EOpUint64BitsToDouble);
4960             convert->getAsUnaryNode()->setOperand(uint64);
4961             convert->setLoc(loc);
4962             convert->setType(TType(EbtDouble, EvqTemporary));
4963             node = convert;
4964
4965             break;
4966         }
4967
4968     case EOpF16tof32:
4969         {
4970             // input uvecN with low 16 bits of each component holding a float16.  convert to float32.
4971             TIntermTyped* argValue = node->getAsUnaryNode()->getOperand();
4972             TIntermTyped* zero = intermediate.addConstantUnion(0, loc, true);
4973             const int vecSize = argValue->getType().getVectorSize();
4974
4975             TOperator constructOp = EOpNull;
4976             switch (vecSize) {
4977             case 1: constructOp = EOpNull;          break; // direct use, no construct needed
4978             case 2: constructOp = EOpConstructVec2; break;
4979             case 3: constructOp = EOpConstructVec3; break;
4980             case 4: constructOp = EOpConstructVec4; break;
4981             default: assert(0); break;
4982             }
4983
4984             // For scalar case, we don't need to construct another type.
4985             TIntermAggregate* result = (vecSize > 1) ? new TIntermAggregate(constructOp) : nullptr;
4986
4987             if (result) {
4988                 result->setType(TType(EbtFloat, EvqTemporary, vecSize));
4989                 result->setLoc(loc);
4990             }
4991
4992             for (int idx = 0; idx < vecSize; ++idx) {
4993                 TIntermTyped* idxConst = intermediate.addConstantUnion(idx, loc, true);
4994                 TIntermTyped* component = argValue->getType().isVector() ? 
4995                     intermediate.addIndex(EOpIndexDirect, argValue, idxConst, loc) : argValue;
4996
4997                 if (component != argValue)
4998                     component->setType(TType(argValue->getBasicType(), EvqTemporary));
4999
5000                 TIntermTyped* unpackOp  = new TIntermUnary(EOpUnpackHalf2x16);
5001                 unpackOp->setType(TType(EbtFloat, EvqTemporary, 2));
5002                 unpackOp->getAsUnaryNode()->setOperand(component);
5003                 unpackOp->setLoc(loc);
5004
5005                 TIntermTyped* lowOrder  = intermediate.addIndex(EOpIndexDirect, unpackOp, zero, loc);
5006                 
5007                 if (result != nullptr) {
5008                     result->getSequence().push_back(lowOrder);
5009                     node = result;
5010                 } else {
5011                     node = lowOrder;
5012                 }
5013             }
5014             
5015             break;
5016         }
5017
5018     case EOpF32tof16:
5019         {
5020             // input floatN converted to 16 bit float in low order bits of each component of uintN
5021             TIntermTyped* argValue = node->getAsUnaryNode()->getOperand();
5022
5023             TIntermTyped* zero = intermediate.addConstantUnion(0.0, EbtFloat, loc, true);
5024             const int vecSize = argValue->getType().getVectorSize();
5025
5026             TOperator constructOp = EOpNull;
5027             switch (vecSize) {
5028             case 1: constructOp = EOpNull;           break; // direct use, no construct needed
5029             case 2: constructOp = EOpConstructUVec2; break;
5030             case 3: constructOp = EOpConstructUVec3; break;
5031             case 4: constructOp = EOpConstructUVec4; break;
5032             default: assert(0); break;
5033             }
5034
5035             // For scalar case, we don't need to construct another type.
5036             TIntermAggregate* result = (vecSize > 1) ? new TIntermAggregate(constructOp) : nullptr;
5037
5038             if (result) {
5039                 result->setType(TType(EbtUint, EvqTemporary, vecSize));
5040                 result->setLoc(loc);
5041             }
5042
5043             for (int idx = 0; idx < vecSize; ++idx) {
5044                 TIntermTyped* idxConst = intermediate.addConstantUnion(idx, loc, true);
5045                 TIntermTyped* component = argValue->getType().isVector() ? 
5046                     intermediate.addIndex(EOpIndexDirect, argValue, idxConst, loc) : argValue;
5047
5048                 if (component != argValue)
5049                     component->setType(TType(argValue->getBasicType(), EvqTemporary));
5050
5051                 TIntermAggregate* vec2ComponentAndZero = new TIntermAggregate(EOpConstructVec2);
5052                 vec2ComponentAndZero->getSequence().push_back(component);
5053                 vec2ComponentAndZero->getSequence().push_back(zero);
5054                 vec2ComponentAndZero->setType(TType(EbtFloat, EvqTemporary, 2));
5055                 vec2ComponentAndZero->setLoc(loc);
5056                 
5057                 TIntermTyped* packOp = new TIntermUnary(EOpPackHalf2x16);
5058                 packOp->getAsUnaryNode()->setOperand(vec2ComponentAndZero);
5059                 packOp->setLoc(loc);
5060                 packOp->setType(TType(EbtUint, EvqTemporary));
5061
5062                 if (result != nullptr) {
5063                     result->getSequence().push_back(packOp);
5064                     node = result;
5065                 } else {
5066                     node = packOp;
5067                 }
5068             }
5069
5070             break;
5071         }
5072
5073     case EOpD3DCOLORtoUBYTE4:
5074         {
5075             // ivec4 ( x.zyxw * 255.001953 );
5076             TIntermTyped* arg0 = node->getAsUnaryNode()->getOperand();
5077             TSwizzleSelectors<TVectorSelector> selectors;
5078             selectors.push_back(2);
5079             selectors.push_back(1);
5080             selectors.push_back(0);
5081             selectors.push_back(3);
5082             TIntermTyped* swizzleIdx = intermediate.addSwizzle(selectors, loc);
5083             TIntermTyped* swizzled = intermediate.addIndex(EOpVectorSwizzle, arg0, swizzleIdx, loc);
5084             swizzled->setType(arg0->getType());
5085             swizzled->getWritableType().getQualifier().makeTemporary();
5086
5087             TIntermTyped* conversion = intermediate.addConstantUnion(255.001953f, EbtFloat, loc, true);
5088             TIntermTyped* rangeConverted = handleBinaryMath(loc, "mul", EOpMul, conversion, swizzled);
5089             rangeConverted->setType(arg0->getType());
5090             rangeConverted->getWritableType().getQualifier().makeTemporary();
5091
5092             node = intermediate.addConversion(EOpConstructInt, TType(EbtInt, EvqTemporary, 4), rangeConverted);
5093             node->setLoc(loc);
5094             node->setType(TType(EbtInt, EvqTemporary, 4));
5095             break;
5096         }
5097
5098     case EOpIsFinite:
5099         {
5100             // Since OPIsFinite in SPIR-V is only supported with the Kernel capability, we translate
5101             // it to !isnan && !isinf
5102
5103             TIntermTyped* arg0 = node->getAsUnaryNode()->getOperand();
5104
5105             // We'll make a temporary in case the RHS is cmoplex
5106             TVariable* tempArg = makeInternalVariable("@finitetmp", arg0->getType());
5107             tempArg->getWritableType().getQualifier().makeTemporary();
5108
5109             TIntermTyped* tmpArgAssign = intermediate.addAssign(EOpAssign,
5110                                                                 intermediate.addSymbol(*tempArg, loc),
5111                                                                 arg0, loc);
5112
5113             TIntermAggregate* compoundStatement = intermediate.makeAggregate(tmpArgAssign, loc);
5114
5115             const TType boolType(EbtBool, EvqTemporary, arg0->getVectorSize(), arg0->getMatrixCols(),
5116                                  arg0->getMatrixRows());
5117
5118             TIntermTyped* isnan = handleUnaryMath(loc, "isnan", EOpIsNan, intermediate.addSymbol(*tempArg, loc));
5119             isnan->setType(boolType);
5120
5121             TIntermTyped* notnan = handleUnaryMath(loc, "!", EOpLogicalNot, isnan);
5122             notnan->setType(boolType);
5123
5124             TIntermTyped* isinf = handleUnaryMath(loc, "isinf", EOpIsInf, intermediate.addSymbol(*tempArg, loc));
5125             isinf->setType(boolType);
5126
5127             TIntermTyped* notinf = handleUnaryMath(loc, "!", EOpLogicalNot, isinf);
5128             notinf->setType(boolType);
5129             
5130             TIntermTyped* andNode = handleBinaryMath(loc, "and", EOpLogicalAnd, notnan, notinf);
5131             andNode->setType(boolType);
5132
5133             compoundStatement = intermediate.growAggregate(compoundStatement, andNode);
5134             compoundStatement->setOperator(EOpSequence);
5135             compoundStatement->setLoc(loc);
5136             compoundStatement->setType(boolType);
5137
5138             node = compoundStatement;
5139
5140             break;
5141         }
5142     case EOpWaveGetLaneCount:
5143         {
5144             // Mapped to gl_SubgroupSize builtin (We preprend @ to the symbol
5145             // so that it inhabits the symbol table, but has a user-invalid name
5146             // in-case some source HLSL defined the symbol also).
5147             TType type(EbtUint, EvqVaryingIn);
5148             node = lookupBuiltinVariable("@gl_SubgroupSize", EbvSubgroupSize2, type);
5149             break;
5150         }
5151     case EOpWaveGetLaneIndex:
5152         {
5153             // Mapped to gl_SubgroupInvocationID builtin (We preprend @ to the
5154             // symbol so that it inhabits the symbol table, but has a
5155             // user-invalid name in-case some source HLSL defined the symbol
5156             // also).
5157             TType type(EbtUint, EvqVaryingIn);
5158             node = lookupBuiltinVariable("@gl_SubgroupInvocationID", EbvSubgroupInvocation2, type);
5159             break;
5160         }
5161     case EOpWaveActiveCountBits:
5162         {
5163             // Mapped to subgroupBallotBitCount(subgroupBallot()) builtin
5164
5165             // uvec4 type.
5166             TType uvec4Type(EbtUint, EvqTemporary, 4);
5167
5168             // Get the uvec4 return from subgroupBallot().
5169             TIntermTyped* res = intermediate.addBuiltInFunctionCall(loc,
5170                 EOpSubgroupBallot, true, arguments, uvec4Type);
5171
5172             // uint type.
5173             TType uintType(EbtUint, EvqTemporary);
5174
5175             node = intermediate.addBuiltInFunctionCall(loc,
5176                 EOpSubgroupBallotBitCount, true, res, uintType);
5177
5178             break;
5179         }
5180     case EOpWavePrefixCountBits:
5181         {
5182             // Mapped to subgroupBallotInclusiveBitCount(subgroupBallot())
5183             // builtin
5184
5185             // uvec4 type.
5186             TType uvec4Type(EbtUint, EvqTemporary, 4);
5187
5188             // Get the uvec4 return from subgroupBallot().
5189             TIntermTyped* res = intermediate.addBuiltInFunctionCall(loc,
5190                 EOpSubgroupBallot, true, arguments, uvec4Type);
5191
5192             // uint type.
5193             TType uintType(EbtUint, EvqTemporary);
5194
5195             node = intermediate.addBuiltInFunctionCall(loc,
5196                 EOpSubgroupBallotInclusiveBitCount, true, res, uintType);
5197
5198             break;
5199         }
5200
5201     default:
5202         break; // most pass through unchanged
5203     }
5204 }
5205
5206 //
5207 // Handle seeing function call syntax in the grammar, which could be any of
5208 //  - .length() method
5209 //  - constructor
5210 //  - a call to a built-in function mapped to an operator
5211 //  - a call to a built-in function that will remain a function call (e.g., texturing)
5212 //  - user function
5213 //  - subroutine call (not implemented yet)
5214 //
5215 TIntermTyped* HlslParseContext::handleFunctionCall(const TSourceLoc& loc, TFunction* function, TIntermTyped* arguments)
5216 {
5217     TIntermTyped* result = nullptr;
5218
5219     TOperator op = function->getBuiltInOp();
5220     if (op != EOpNull) {
5221         //
5222         // Then this should be a constructor.
5223         // Don't go through the symbol table for constructors.
5224         // Their parameters will be verified algorithmically.
5225         //
5226         TType type(EbtVoid);  // use this to get the type back
5227         if (! constructorError(loc, arguments, *function, op, type)) {
5228             //
5229             // It's a constructor, of type 'type'.
5230             //
5231             result = handleConstructor(loc, arguments, type);
5232             if (result == nullptr) {
5233                 error(loc, "cannot construct with these arguments", type.getCompleteString().c_str(), "");
5234                 return nullptr;
5235             }
5236         }
5237     } else {
5238         //
5239         // Find it in the symbol table.
5240         //
5241         const TFunction* fnCandidate = nullptr;
5242         bool builtIn = false;
5243         int thisDepth = 0;
5244
5245         // For mat mul, the situation is unusual: we have to compare vector sizes to mat row or col sizes,
5246         // and clamp the opposite arg.  Since that's complex, we farm it off to a separate method.
5247         // It doesn't naturally fall out of processing an argument at a time in isolation.
5248         if (function->getName() == "mul")
5249             addGenMulArgumentConversion(loc, *function, arguments);
5250
5251         TIntermAggregate* aggregate = arguments ? arguments->getAsAggregate() : nullptr;
5252
5253         // TODO: this needs improvement: there's no way at present to look up a signature in
5254         // the symbol table for an arbitrary type.  This is a temporary hack until that ability exists.
5255         // It will have false positives, since it doesn't check arg counts or types.
5256         if (arguments) {
5257             // Check if first argument is struct buffer type.  It may be an aggregate or a symbol, so we
5258             // look for either case.
5259
5260             TIntermTyped* arg0 = nullptr;
5261
5262             if (aggregate && aggregate->getSequence().size() > 0)
5263                 arg0 = aggregate->getSequence()[0]->getAsTyped();
5264             else if (arguments->getAsSymbolNode())
5265                 arg0 = arguments->getAsSymbolNode();
5266
5267             if (arg0 != nullptr && isStructBufferType(arg0->getType())) {
5268                 static const int methodPrefixSize = sizeof(BUILTIN_PREFIX)-1;
5269
5270                 if (function->getName().length() > methodPrefixSize &&
5271                     isStructBufferMethod(function->getName().substr(methodPrefixSize))) {
5272                     const TString mangle = function->getName() + "(";
5273                     TSymbol* symbol = symbolTable.find(mangle, &builtIn);
5274
5275                     if (symbol)
5276                         fnCandidate = symbol->getAsFunction();
5277                 }
5278             }
5279         }
5280
5281         if (fnCandidate == nullptr)
5282             fnCandidate = findFunction(loc, *function, builtIn, thisDepth, arguments);
5283
5284         if (fnCandidate) {
5285             // This is a declared function that might map to
5286             //  - a built-in operator,
5287             //  - a built-in function not mapped to an operator, or
5288             //  - a user function.
5289
5290             // Error check for a function requiring specific extensions present.
5291             if (builtIn && fnCandidate->getNumExtensions())
5292                 requireExtensions(loc, fnCandidate->getNumExtensions(), fnCandidate->getExtensions(),
5293                                   fnCandidate->getName().c_str());
5294
5295             // turn an implicit member-function resolution into an explicit call
5296             TString callerName;
5297             if (thisDepth == 0)
5298                 callerName = fnCandidate->getMangledName();
5299             else {
5300                 // get the explicit (full) name of the function
5301                 callerName = currentTypePrefix[currentTypePrefix.size() - thisDepth];
5302                 callerName += fnCandidate->getMangledName();
5303                 // insert the implicit calling argument
5304                 pushFrontArguments(intermediate.addSymbol(*getImplicitThis(thisDepth)), arguments);
5305             }
5306
5307             // Convert 'in' arguments, so that types match.
5308             // However, skip those that need expansion, that is covered next.
5309             if (arguments)
5310                 addInputArgumentConversions(*fnCandidate, arguments);
5311
5312             // Expand arguments.  Some arguments must physically expand to a different set
5313             // than what the shader declared and passes.
5314             if (arguments && !builtIn)
5315                 expandArguments(loc, *fnCandidate, arguments);
5316
5317             // Expansion may have changed the form of arguments
5318             aggregate = arguments ? arguments->getAsAggregate() : nullptr;
5319
5320             op = fnCandidate->getBuiltInOp();
5321             if (builtIn && op != EOpNull) {
5322                 // A function call mapped to a built-in operation.
5323                 result = intermediate.addBuiltInFunctionCall(loc, op, fnCandidate->getParamCount() == 1, arguments,
5324                                                              fnCandidate->getType());
5325                 if (result == nullptr)  {
5326                     error(arguments->getLoc(), " wrong operand type", "Internal Error",
5327                         "built in unary operator function.  Type: %s",
5328                         static_cast<TIntermTyped*>(arguments)->getCompleteString().c_str());
5329                 } else if (result->getAsOperator()) {
5330                     builtInOpCheck(loc, *fnCandidate, *result->getAsOperator());
5331                 }
5332             } else {
5333                 // This is a function call not mapped to built-in operator.
5334                 // It could still be a built-in function, but only if PureOperatorBuiltins == false.
5335                 result = intermediate.setAggregateOperator(arguments, EOpFunctionCall, fnCandidate->getType(), loc);
5336                 TIntermAggregate* call = result->getAsAggregate();
5337                 call->setName(callerName);
5338
5339                 // this is how we know whether the given function is a built-in function or a user-defined function
5340                 // if builtIn == false, it's a userDefined -> could be an overloaded built-in function also
5341                 // if builtIn == true, it's definitely a built-in function with EOpNull
5342                 if (! builtIn) {
5343                     call->setUserDefined();
5344                     intermediate.addToCallGraph(infoSink, currentCaller, callerName);
5345                 }
5346             }
5347
5348             // for decompositions, since we want to operate on the function node, not the aggregate holding
5349             // output conversions.
5350             const TIntermTyped* fnNode = result;
5351
5352             decomposeStructBufferMethods(loc, result, arguments); // HLSL->AST struct buffer method decompositions
5353             decomposeIntrinsic(loc, result, arguments);           // HLSL->AST intrinsic decompositions
5354             decomposeSampleMethods(loc, result, arguments);       // HLSL->AST sample method decompositions
5355             decomposeGeometryMethods(loc, result, arguments);     // HLSL->AST geometry method decompositions
5356
5357             // Create the qualifier list, carried in the AST for the call.
5358             // Because some arguments expand to multiple arguments, the qualifier list will
5359             // be longer than the formal parameter list.
5360             if (result == fnNode && result->getAsAggregate()) {
5361                 TQualifierList& qualifierList = result->getAsAggregate()->getQualifierList();
5362                 for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
5363                     TStorageQualifier qual = (*fnCandidate)[i].type->getQualifier().storage;
5364                     if (hasStructBuffCounter(*(*fnCandidate)[i].type)) {
5365                         // add buffer and counter buffer argument qualifier
5366                         qualifierList.push_back(qual);
5367                         qualifierList.push_back(qual);
5368                     } else if (shouldFlatten(*(*fnCandidate)[i].type, (*fnCandidate)[i].type->getQualifier().storage,
5369                                              true)) {
5370                         // add structure member expansion
5371                         for (int memb = 0; memb < (int)(*fnCandidate)[i].type->getStruct()->size(); ++memb)
5372                             qualifierList.push_back(qual);
5373                     } else {
5374                         // Normal 1:1 case
5375                         qualifierList.push_back(qual);
5376                     }
5377                 }
5378             }
5379
5380             // Convert 'out' arguments.  If it was a constant folded built-in, it won't be an aggregate anymore.
5381             // Built-ins with a single argument aren't called with an aggregate, but they also don't have an output.
5382             // Also, build the qualifier list for user function calls, which are always called with an aggregate.
5383             // We don't do this is if there has been a decomposition, which will have added its own conversions
5384             // for output parameters.
5385             if (result == fnNode && result->getAsAggregate())
5386                 result = addOutputArgumentConversions(*fnCandidate, *result->getAsOperator());
5387         }
5388     }
5389
5390     // generic error recovery
5391     // TODO: simplification: localize all the error recoveries that look like this, and taking type into account to
5392     //       reduce cascades
5393     if (result == nullptr)
5394         result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
5395
5396     return result;
5397 }
5398
5399 // An initial argument list is difficult: it can be null, or a single node,
5400 // or an aggregate if more than one argument.  Add one to the front, maintaining
5401 // this lack of uniformity.
5402 void HlslParseContext::pushFrontArguments(TIntermTyped* front, TIntermTyped*& arguments)
5403 {
5404     if (arguments == nullptr)
5405         arguments = front;
5406     else if (arguments->getAsAggregate() != nullptr)
5407         arguments->getAsAggregate()->getSequence().insert(arguments->getAsAggregate()->getSequence().begin(), front);
5408     else
5409         arguments = intermediate.growAggregate(front, arguments);
5410 }
5411
5412 //
5413 // HLSL allows mismatched dimensions on vec*mat, mat*vec, vec*vec, and mat*mat.  This is a
5414 // situation not well suited to resolution in intrinsic selection, but we can do so here, since we
5415 // can look at both arguments insert explicit shape changes if required.
5416 //
5417 void HlslParseContext::addGenMulArgumentConversion(const TSourceLoc& loc, TFunction& call, TIntermTyped*& args)
5418 {
5419     TIntermAggregate* argAggregate = args ? args->getAsAggregate() : nullptr;
5420
5421     if (argAggregate == nullptr || argAggregate->getSequence().size() != 2) {
5422         // It really ought to have two arguments.
5423         error(loc, "expected: mul arguments", "", "");
5424         return;
5425     }
5426
5427     TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
5428     TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
5429
5430     if (arg0->isVector() && arg1->isVector()) {
5431         // For:
5432         //    vec * vec: it's handled during intrinsic selection, so while we could do it here,
5433         //               we can also ignore it, which is easier.
5434     } else if (arg0->isVector() && arg1->isMatrix()) {
5435         // vec * mat: we clamp the vec if the mat col is smaller, else clamp the mat col.
5436         if (arg0->getVectorSize() < arg1->getMatrixCols()) {
5437             // vec is smaller, so truncate larger mat dimension
5438             const TType truncType(arg1->getBasicType(), arg1->getQualifier().storage, arg1->getQualifier().precision,
5439                                   0, arg0->getVectorSize(), arg1->getMatrixRows());
5440             arg1 = addConstructor(loc, arg1, truncType);
5441         } else if (arg0->getVectorSize() > arg1->getMatrixCols()) {
5442             // vec is larger, so truncate vec to mat size
5443             const TType truncType(arg0->getBasicType(), arg0->getQualifier().storage, arg0->getQualifier().precision,
5444                                   arg1->getMatrixCols());
5445             arg0 = addConstructor(loc, arg0, truncType);
5446         }
5447     } else if (arg0->isMatrix() && arg1->isVector()) {
5448         // mat * vec: we clamp the vec if the mat col is smaller, else clamp the mat col.
5449         if (arg1->getVectorSize() < arg0->getMatrixRows()) {
5450             // vec is smaller, so truncate larger mat dimension
5451             const TType truncType(arg0->getBasicType(), arg0->getQualifier().storage, arg0->getQualifier().precision,
5452                                   0, arg0->getMatrixCols(), arg1->getVectorSize());
5453             arg0 = addConstructor(loc, arg0, truncType);
5454         } else if (arg1->getVectorSize() > arg0->getMatrixRows()) {
5455             // vec is larger, so truncate vec to mat size
5456             const TType truncType(arg1->getBasicType(), arg1->getQualifier().storage, arg1->getQualifier().precision,
5457                                   arg0->getMatrixRows());
5458             arg1 = addConstructor(loc, arg1, truncType);
5459         }
5460     } else if (arg0->isMatrix() && arg1->isMatrix()) {
5461         // mat * mat: we clamp the smaller inner dimension to match the other matrix size.
5462         // Remember, HLSL Mrc = GLSL/SPIRV Mcr.
5463         if (arg0->getMatrixRows() > arg1->getMatrixCols()) {
5464             const TType truncType(arg0->getBasicType(), arg0->getQualifier().storage, arg0->getQualifier().precision,
5465                                   0, arg0->getMatrixCols(), arg1->getMatrixCols());
5466             arg0 = addConstructor(loc, arg0, truncType);
5467         } else if (arg0->getMatrixRows() < arg1->getMatrixCols()) {
5468             const TType truncType(arg1->getBasicType(), arg1->getQualifier().storage, arg1->getQualifier().precision,
5469                                   0, arg0->getMatrixRows(), arg1->getMatrixRows());
5470             arg1 = addConstructor(loc, arg1, truncType);
5471         }
5472     } else {
5473         // It's something with scalars: we'll just leave it alone.  Function selection will handle it
5474         // downstream.
5475     }
5476
5477     // Warn if we altered one of the arguments
5478     if (arg0 != argAggregate->getSequence()[0] || arg1 != argAggregate->getSequence()[1])
5479         warn(loc, "mul() matrix size mismatch", "", "");
5480
5481     // Put arguments back.  (They might be unchanged, in which case this is harmless).
5482     argAggregate->getSequence()[0] = arg0;
5483     argAggregate->getSequence()[1] = arg1;
5484
5485     call[0].type = &arg0->getWritableType();
5486     call[1].type = &arg1->getWritableType();
5487 }
5488
5489 //
5490 // Add any needed implicit conversions for function-call arguments to input parameters.
5491 //
5492 void HlslParseContext::addInputArgumentConversions(const TFunction& function, TIntermTyped*& arguments)
5493 {
5494     TIntermAggregate* aggregate = arguments->getAsAggregate();
5495
5496     // Replace a single argument with a single argument.
5497     const auto setArg = [&](int paramNum, TIntermTyped* arg) {
5498         if (function.getParamCount() == 1)
5499             arguments = arg;
5500         else {
5501             if (aggregate == nullptr)
5502                 arguments = arg;
5503             else
5504                 aggregate->getSequence()[paramNum] = arg;
5505         }
5506     };
5507
5508     // Process each argument's conversion
5509     for (int param = 0; param < function.getParamCount(); ++param) {
5510         if (! function[param].type->getQualifier().isParamInput())
5511             continue;
5512
5513         // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
5514         // is the single argument itself or its children are the arguments.  Only one argument
5515         // means take 'arguments' itself as the one argument.
5516         TIntermTyped* arg = function.getParamCount() == 1
5517                                    ? arguments->getAsTyped()
5518                                    : (aggregate ? 
5519                                         aggregate->getSequence()[param]->getAsTyped() :
5520                                         arguments->getAsTyped());
5521         if (*function[param].type != arg->getType()) {
5522             // In-qualified arguments just need an extra node added above the argument to
5523             // convert to the correct type.
5524             TIntermTyped* convArg = intermediate.addConversion(EOpFunctionCall, *function[param].type, arg);
5525             if (convArg != nullptr)
5526                 convArg = intermediate.addUniShapeConversion(EOpFunctionCall, *function[param].type, convArg);
5527             if (convArg != nullptr)
5528                 setArg(param, convArg);
5529             else
5530                 error(arg->getLoc(), "cannot convert input argument, argument", "", "%d", param);
5531         } else {
5532             if (wasFlattened(arg)) {
5533                 // If both formal and calling arg are to be flattened, leave that to argument
5534                 // expansion, not conversion.
5535                 if (!shouldFlatten(*function[param].type, function[param].type->getQualifier().storage, true)) {
5536                     // Will make a two-level subtree.
5537                     // The deepest will copy member-by-member to build the structure to pass.
5538                     // The level above that will be a two-operand EOpComma sequence that follows the copy by the
5539                     // object itself.
5540                     TVariable* internalAggregate = makeInternalVariable("aggShadow", *function[param].type);
5541                     internalAggregate->getWritableType().getQualifier().makeTemporary();
5542                     TIntermSymbol* internalSymbolNode = new TIntermSymbol(internalAggregate->getUniqueId(),
5543                                                                           internalAggregate->getName(),
5544                                                                           internalAggregate->getType());
5545                     internalSymbolNode->setLoc(arg->getLoc());
5546                     // This makes the deepest level, the member-wise copy
5547                     TIntermAggregate* assignAgg = handleAssign(arg->getLoc(), EOpAssign,
5548                                                                internalSymbolNode, arg)->getAsAggregate();
5549
5550                     // Now, pair that with the resulting aggregate.
5551                     assignAgg = intermediate.growAggregate(assignAgg, internalSymbolNode, arg->getLoc());
5552                     assignAgg->setOperator(EOpComma);
5553                     assignAgg->setType(internalAggregate->getType());
5554                     setArg(param, assignAgg);
5555                 }
5556             }
5557         }
5558     }
5559 }
5560
5561 //
5562 // Add any needed implicit expansion of calling arguments from what the shader listed to what's
5563 // internally needed for the AST (given the constraints downstream).
5564 //
5565 void HlslParseContext::expandArguments(const TSourceLoc& loc, const TFunction& function, TIntermTyped*& arguments)
5566 {
5567     TIntermAggregate* aggregate = arguments->getAsAggregate();
5568     int functionParamNumberOffset = 0;
5569
5570     // Replace a single argument with a single argument.
5571     const auto setArg = [&](int paramNum, TIntermTyped* arg) {
5572         if (function.getParamCount() + functionParamNumberOffset == 1)
5573             arguments = arg;
5574         else {
5575             if (aggregate == nullptr)
5576                 arguments = arg;
5577             else
5578                 aggregate->getSequence()[paramNum] = arg;
5579         }
5580     };
5581
5582     // Replace a single argument with a list of arguments
5583     const auto setArgList = [&](int paramNum, const TVector<TIntermTyped*>& args) {
5584         if (args.size() == 1)
5585             setArg(paramNum, args.front());
5586         else if (args.size() > 1) {
5587             if (function.getParamCount() + functionParamNumberOffset == 1) {
5588                 arguments = intermediate.makeAggregate(args.front());
5589                 std::for_each(args.begin() + 1, args.end(), 
5590                     [&](TIntermTyped* arg) {
5591                         arguments = intermediate.growAggregate(arguments, arg);
5592                     });
5593             } else {
5594                 auto it = aggregate->getSequence().erase(aggregate->getSequence().begin() + paramNum);
5595                 aggregate->getSequence().insert(it, args.begin(), args.end());
5596             }
5597             functionParamNumberOffset += (int)(args.size() - 1);
5598         }
5599     };
5600
5601     // Process each argument's conversion
5602     for (int param = 0; param < function.getParamCount(); ++param) {
5603         // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
5604         // is the single argument itself or its children are the arguments.  Only one argument
5605         // means take 'arguments' itself as the one argument.
5606         TIntermTyped* arg = function.getParamCount() == 1
5607                                    ? arguments->getAsTyped()
5608                                    : (aggregate ? 
5609                                         aggregate->getSequence()[param + functionParamNumberOffset]->getAsTyped() :
5610                                         arguments->getAsTyped());
5611
5612         if (wasFlattened(arg) && shouldFlatten(*function[param].type, function[param].type->getQualifier().storage, true)) {
5613             // Need to pass the structure members instead of the structure.
5614             TVector<TIntermTyped*> memberArgs;
5615             for (int memb = 0; memb < (int)arg->getType().getStruct()->size(); ++memb)
5616                 memberArgs.push_back(flattenAccess(arg, memb));
5617             setArgList(param + functionParamNumberOffset, memberArgs);
5618         }
5619     }
5620
5621     // TODO: if we need both hidden counter args (below) and struct expansion (above)
5622     // the two algorithms need to be merged: Each assumes the list starts out 1:1 between
5623     // parameters and arguments.
5624
5625     // If any argument is a pass-by-reference struct buffer with an associated counter
5626     // buffer, we have to add another hidden parameter for that counter.
5627     if (aggregate)
5628         addStructBuffArguments(loc, aggregate);
5629 }
5630
5631 //
5632 // Add any needed implicit output conversions for function-call arguments.  This
5633 // can require a new tree topology, complicated further by whether the function
5634 // has a return value.
5635 //
5636 // Returns a node of a subtree that evaluates to the return value of the function.
5637 //
5638 TIntermTyped* HlslParseContext::addOutputArgumentConversions(const TFunction& function, TIntermOperator& intermNode)
5639 {
5640     assert (intermNode.getAsAggregate() != nullptr || intermNode.getAsUnaryNode() != nullptr);
5641
5642     const TSourceLoc& loc = intermNode.getLoc();
5643
5644     TIntermSequence argSequence; // temp sequence for unary node args
5645
5646     if (intermNode.getAsUnaryNode())
5647         argSequence.push_back(intermNode.getAsUnaryNode()->getOperand());
5648
5649     TIntermSequence& arguments = argSequence.empty() ? intermNode.getAsAggregate()->getSequence() : argSequence;
5650
5651     const auto needsConversion = [&](int argNum) {
5652         return function[argNum].type->getQualifier().isParamOutput() &&
5653                (*function[argNum].type != arguments[argNum]->getAsTyped()->getType() ||
5654                 shouldConvertLValue(arguments[argNum]) ||
5655                 wasFlattened(arguments[argNum]->getAsTyped()));
5656     };
5657
5658     // Will there be any output conversions?
5659     bool outputConversions = false;
5660     for (int i = 0; i < function.getParamCount(); ++i) {
5661         if (needsConversion(i)) {
5662             outputConversions = true;
5663             break;
5664         }
5665     }
5666
5667     if (! outputConversions)
5668         return &intermNode;
5669
5670     // Setup for the new tree, if needed:
5671     //
5672     // Output conversions need a different tree topology.
5673     // Out-qualified arguments need a temporary of the correct type, with the call
5674     // followed by an assignment of the temporary to the original argument:
5675     //     void: function(arg, ...)  ->        (          function(tempArg, ...), arg = tempArg, ...)
5676     //     ret = function(arg, ...)  ->  ret = (tempRet = function(tempArg, ...), arg = tempArg, ..., tempRet)
5677     // Where the "tempArg" type needs no conversion as an argument, but will convert on assignment.
5678     TIntermTyped* conversionTree = nullptr;
5679     TVariable* tempRet = nullptr;
5680     if (intermNode.getBasicType() != EbtVoid) {
5681         // do the "tempRet = function(...), " bit from above
5682         tempRet = makeInternalVariable("tempReturn", intermNode.getType());
5683         TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, loc);
5684         conversionTree = intermediate.addAssign(EOpAssign, tempRetNode, &intermNode, loc);
5685     } else
5686         conversionTree = &intermNode;
5687
5688     conversionTree = intermediate.makeAggregate(conversionTree);
5689
5690     // Process each argument's conversion
5691     for (int i = 0; i < function.getParamCount(); ++i) {
5692         if (needsConversion(i)) {
5693             // Out-qualified arguments needing conversion need to use the topology setup above.
5694             // Do the " ...(tempArg, ...), arg = tempArg" bit from above.
5695
5696             // Make a temporary for what the function expects the argument to look like.
5697             TVariable* tempArg = makeInternalVariable("tempArg", *function[i].type);
5698             tempArg->getWritableType().getQualifier().makeTemporary();
5699             TIntermSymbol* tempArgNode = intermediate.addSymbol(*tempArg, loc);
5700
5701             // This makes the deepest level, the member-wise copy
5702             TIntermTyped* tempAssign = handleAssign(arguments[i]->getLoc(), EOpAssign, arguments[i]->getAsTyped(),
5703                                                     tempArgNode);
5704             tempAssign = handleLvalue(arguments[i]->getLoc(), "assign", tempAssign);
5705             conversionTree = intermediate.growAggregate(conversionTree, tempAssign, arguments[i]->getLoc());
5706
5707             // replace the argument with another node for the same tempArg variable
5708             arguments[i] = intermediate.addSymbol(*tempArg, loc);
5709         }
5710     }
5711
5712     // Finalize the tree topology (see bigger comment above).
5713     if (tempRet) {
5714         // do the "..., tempRet" bit from above
5715         TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, loc);
5716         conversionTree = intermediate.growAggregate(conversionTree, tempRetNode, loc);
5717     }
5718
5719     conversionTree = intermediate.setAggregateOperator(conversionTree, EOpComma, intermNode.getType(), loc);
5720
5721     return conversionTree;
5722 }
5723
5724 //
5725 // Add any needed "hidden" counter buffer arguments for function calls.
5726 //
5727 // Modifies the 'aggregate' argument if needed.  Otherwise, is no-op.
5728 //
5729 void HlslParseContext::addStructBuffArguments(const TSourceLoc& loc, TIntermAggregate*& aggregate)
5730 {
5731     // See if there are any SB types with counters.
5732     const bool hasStructBuffArg =
5733         std::any_of(aggregate->getSequence().begin(),
5734                     aggregate->getSequence().end(),
5735                     [this](const TIntermNode* node) {
5736                         return (node->getAsTyped() != nullptr) && hasStructBuffCounter(node->getAsTyped()->getType());
5737                     });
5738
5739     // Nothing to do, if we didn't find one.
5740     if (! hasStructBuffArg)
5741         return;
5742
5743     TIntermSequence argsWithCounterBuffers;
5744
5745     for (int param = 0; param < int(aggregate->getSequence().size()); ++param) {
5746         argsWithCounterBuffers.push_back(aggregate->getSequence()[param]);
5747
5748         if (hasStructBuffCounter(aggregate->getSequence()[param]->getAsTyped()->getType())) {
5749             const TIntermSymbol* blockSym = aggregate->getSequence()[param]->getAsSymbolNode();
5750             if (blockSym != nullptr) {
5751                 TType counterType;
5752                 counterBufferType(loc, counterType);
5753
5754                 const TString counterBlockName(intermediate.addCounterBufferName(blockSym->getName()));
5755
5756                 TVariable* variable = makeInternalVariable(counterBlockName, counterType);
5757
5758                 // Mark this buffer's counter block as being in use
5759                 structBufferCounter[counterBlockName] = true;
5760
5761                 TIntermSymbol* sym = intermediate.addSymbol(*variable, loc);
5762                 argsWithCounterBuffers.push_back(sym);
5763             }
5764         }
5765     }
5766
5767     // Swap with the temp list we've built up.
5768     aggregate->getSequence().swap(argsWithCounterBuffers);
5769 }
5770
5771
5772 //
5773 // Do additional checking of built-in function calls that is not caught
5774 // by normal semantic checks on argument type, extension tagging, etc.
5775 //
5776 // Assumes there has been a semantically correct match to a built-in function prototype.
5777 //
5778 void HlslParseContext::builtInOpCheck(const TSourceLoc& loc, const TFunction& fnCandidate, TIntermOperator& callNode)
5779 {
5780     // Set up convenience accessors to the argument(s).  There is almost always
5781     // multiple arguments for the cases below, but when there might be one,
5782     // check the unaryArg first.
5783     const TIntermSequence* argp = nullptr;   // confusing to use [] syntax on a pointer, so this is to help get a reference
5784     const TIntermTyped* unaryArg = nullptr;
5785     const TIntermTyped* arg0 = nullptr;
5786     if (callNode.getAsAggregate()) {
5787         argp = &callNode.getAsAggregate()->getSequence();
5788         if (argp->size() > 0)
5789             arg0 = (*argp)[0]->getAsTyped();
5790     } else {
5791         assert(callNode.getAsUnaryNode());
5792         unaryArg = callNode.getAsUnaryNode()->getOperand();
5793         arg0 = unaryArg;
5794     }
5795     const TIntermSequence& aggArgs = *argp;  // only valid when unaryArg is nullptr
5796
5797     switch (callNode.getOp()) {
5798     case EOpTextureGather:
5799     case EOpTextureGatherOffset:
5800     case EOpTextureGatherOffsets:
5801     {
5802         // Figure out which variants are allowed by what extensions,
5803         // and what arguments must be constant for which situations.
5804
5805         TString featureString = fnCandidate.getName() + "(...)";
5806         const char* feature = featureString.c_str();
5807         int compArg = -1;  // track which argument, if any, is the constant component argument
5808         switch (callNode.getOp()) {
5809         case EOpTextureGather:
5810             // More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5,
5811             // otherwise, need GL_ARB_texture_gather.
5812             if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect ||
5813                 fnCandidate[0].type->getSampler().shadow) {
5814                 if (! fnCandidate[0].type->getSampler().shadow)
5815                     compArg = 2;
5816             }
5817             break;
5818         case EOpTextureGatherOffset:
5819             // GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument
5820             if (! fnCandidate[0].type->getSampler().shadow)
5821                 compArg = 3;
5822             break;
5823         case EOpTextureGatherOffsets:
5824             if (! fnCandidate[0].type->getSampler().shadow)
5825                 compArg = 3;
5826             break;
5827         default:
5828             break;
5829         }
5830
5831         if (compArg > 0 && compArg < fnCandidate.getParamCount()) {
5832             if (aggArgs[compArg]->getAsConstantUnion()) {
5833                 int value = aggArgs[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst();
5834                 if (value < 0 || value > 3)
5835                     error(loc, "must be 0, 1, 2, or 3:", feature, "component argument");
5836             } else
5837                 error(loc, "must be a compile-time constant:", feature, "component argument");
5838         }
5839
5840         break;
5841     }
5842
5843     case EOpTextureOffset:
5844     case EOpTextureFetchOffset:
5845     case EOpTextureProjOffset:
5846     case EOpTextureLodOffset:
5847     case EOpTextureProjLodOffset:
5848     case EOpTextureGradOffset:
5849     case EOpTextureProjGradOffset:
5850     {
5851         // Handle texture-offset limits checking
5852         // Pick which argument has to hold constant offsets
5853         int arg = -1;
5854         switch (callNode.getOp()) {
5855         case EOpTextureOffset:          arg = 2;  break;
5856         case EOpTextureFetchOffset:     arg = (arg0->getType().getSampler().dim != EsdRect) ? 3 : 2; break;
5857         case EOpTextureProjOffset:      arg = 2;  break;
5858         case EOpTextureLodOffset:       arg = 3;  break;
5859         case EOpTextureProjLodOffset:   arg = 3;  break;
5860         case EOpTextureGradOffset:      arg = 4;  break;
5861         case EOpTextureProjGradOffset:  arg = 4;  break;
5862         default:
5863             assert(0);
5864             break;
5865         }
5866
5867         if (arg > 0) {
5868             if (aggArgs[arg]->getAsConstantUnion() == nullptr)
5869                 error(loc, "argument must be compile-time constant", "texel offset", "");
5870             else {
5871                 const TType& type = aggArgs[arg]->getAsTyped()->getType();
5872                 for (int c = 0; c < type.getVectorSize(); ++c) {
5873                     int offset = aggArgs[arg]->getAsConstantUnion()->getConstArray()[c].getIConst();
5874                     if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset)
5875                         error(loc, "value is out of range:", "texel offset",
5876                               "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]");
5877                 }
5878             }
5879         }
5880
5881         break;
5882     }
5883
5884     case EOpTextureQuerySamples:
5885     case EOpImageQuerySamples:
5886         break;
5887
5888     case EOpImageAtomicAdd:
5889     case EOpImageAtomicMin:
5890     case EOpImageAtomicMax:
5891     case EOpImageAtomicAnd:
5892     case EOpImageAtomicOr:
5893     case EOpImageAtomicXor:
5894     case EOpImageAtomicExchange:
5895     case EOpImageAtomicCompSwap:
5896         break;
5897
5898     case EOpInterpolateAtCentroid:
5899     case EOpInterpolateAtSample:
5900     case EOpInterpolateAtOffset:
5901         // Make sure the first argument is an interpolant, or an array element of an interpolant
5902         if (arg0->getType().getQualifier().storage != EvqVaryingIn) {
5903             // It might still be an array element.
5904             //
5905             // We could check more, but the semantics of the first argument are already met; the
5906             // only way to turn an array into a float/vec* is array dereference and swizzle.
5907             //
5908             // ES and desktop 4.3 and earlier:  swizzles may not be used
5909             // desktop 4.4 and later: swizzles may be used
5910             const TIntermTyped* base = TIntermediate::findLValueBase(arg0, true);
5911             if (base == nullptr || base->getType().getQualifier().storage != EvqVaryingIn)
5912                 error(loc, "first argument must be an interpolant, or interpolant-array element",
5913                       fnCandidate.getName().c_str(), "");
5914         }
5915         break;
5916
5917     default:
5918         break;
5919     }
5920 }
5921
5922 //
5923 // Handle seeing something in a grammar production that can be done by calling
5924 // a constructor.
5925 //
5926 // The constructor still must be "handled" by handleFunctionCall(), which will
5927 // then call handleConstructor().
5928 //
5929 TFunction* HlslParseContext::makeConstructorCall(const TSourceLoc& loc, const TType& type)
5930 {
5931     TOperator op = intermediate.mapTypeToConstructorOp(type);
5932
5933     if (op == EOpNull) {
5934         error(loc, "cannot construct this type", type.getBasicString(), "");
5935         return nullptr;
5936     }
5937
5938     TString empty("");
5939
5940     return new TFunction(&empty, type, op);
5941 }
5942
5943 //
5944 // Handle seeing a "COLON semantic" at the end of a type declaration,
5945 // by updating the type according to the semantic.
5946 //
5947 void HlslParseContext::handleSemantic(TSourceLoc loc, TQualifier& qualifier, TBuiltInVariable builtIn,
5948                                       const TString& upperCase)
5949 {
5950     // Parse and return semantic number.  If limit is 0, it will be ignored.  Otherwise, if the parsed
5951     // semantic number is >= limit, errorMsg is issued and 0 is returned.
5952     // TODO: it would be nicer if limit and errorMsg had default parameters, but some compilers don't yet
5953     // accept those in lambda functions.
5954     const auto getSemanticNumber = [this, loc](const TString& semantic, unsigned int limit, const char* errorMsg) -> unsigned int {
5955         size_t pos = semantic.find_last_not_of("0123456789");
5956         if (pos == std::string::npos)
5957             return 0u;
5958
5959         unsigned int semanticNum = (unsigned int)atoi(semantic.c_str() + pos + 1);
5960
5961         if (limit != 0 && semanticNum >= limit) {
5962             error(loc, errorMsg, semantic.c_str(), "");
5963             return 0u;
5964         }
5965
5966         return semanticNum;
5967     };
5968
5969     switch(builtIn) {
5970     case EbvNone:
5971         // Get location numbers from fragment outputs, instead of
5972         // auto-assigning them.
5973         if (language == EShLangFragment && upperCase.compare(0, 9, "SV_TARGET") == 0) {
5974             qualifier.layoutLocation = getSemanticNumber(upperCase, 0, nullptr);
5975             nextOutLocation = std::max(nextOutLocation, qualifier.layoutLocation + 1u);
5976         } else if (upperCase.compare(0, 15, "SV_CLIPDISTANCE") == 0) {
5977             builtIn = EbvClipDistance;
5978             qualifier.layoutLocation = getSemanticNumber(upperCase, maxClipCullRegs, "invalid clip semantic");
5979         } else if (upperCase.compare(0, 15, "SV_CULLDISTANCE") == 0) {
5980             builtIn = EbvCullDistance;
5981             qualifier.layoutLocation = getSemanticNumber(upperCase, maxClipCullRegs, "invalid cull semantic");
5982         }
5983         break;
5984     case EbvPosition:
5985         // adjust for stage in/out
5986         if (language == EShLangFragment)
5987             builtIn = EbvFragCoord;
5988         break;
5989     case EbvFragStencilRef:
5990         error(loc, "unimplemented; need ARB_shader_stencil_export", "SV_STENCILREF", "");
5991         break;
5992     case EbvTessLevelInner:
5993     case EbvTessLevelOuter:
5994         qualifier.patch = true;
5995         break;
5996     default:
5997         break;
5998     }
5999
6000     if (qualifier.builtIn == EbvNone)
6001         qualifier.builtIn = builtIn;
6002     qualifier.semanticName = intermediate.addSemanticName(upperCase);
6003 }
6004
6005 //
6006 // Handle seeing something like "PACKOFFSET LEFT_PAREN c[Subcomponent][.component] RIGHT_PAREN"
6007 //
6008 // 'location' has the "c[Subcomponent]" part.
6009 // 'component' points to the "component" part, or nullptr if not present.
6010 //
6011 void HlslParseContext::handlePackOffset(const TSourceLoc& loc, TQualifier& qualifier, const glslang::TString& location,
6012                                         const glslang::TString* component)
6013 {
6014     if (location.size() == 0 || location[0] != 'c') {
6015         error(loc, "expected 'c'", "packoffset", "");
6016         return;
6017     }
6018     if (location.size() == 1)
6019         return;
6020     if (! isdigit(location[1])) {
6021         error(loc, "expected number after 'c'", "packoffset", "");
6022         return;
6023     }
6024
6025     qualifier.layoutOffset = 16 * atoi(location.substr(1, location.size()).c_str());
6026     if (component != nullptr) {
6027         int componentOffset = 0;
6028         switch ((*component)[0]) {
6029         case 'x': componentOffset =  0; break;
6030         case 'y': componentOffset =  4; break;
6031         case 'z': componentOffset =  8; break;
6032         case 'w': componentOffset = 12; break;
6033         default:
6034             componentOffset = -1;
6035             break;
6036         }
6037         if (componentOffset < 0 || component->size() > 1) {
6038             error(loc, "expected {x, y, z, w} for component", "packoffset", "");
6039             return;
6040         }
6041         qualifier.layoutOffset += componentOffset;
6042     }
6043 }
6044
6045 //
6046 // Handle seeing something like "REGISTER LEFT_PAREN [shader_profile,] Type# RIGHT_PAREN"
6047 //
6048 // 'profile' points to the shader_profile part, or nullptr if not present.
6049 // 'desc' is the type# part.
6050 //
6051 void HlslParseContext::handleRegister(const TSourceLoc& loc, TQualifier& qualifier, const glslang::TString* profile,
6052                                       const glslang::TString& desc, int subComponent, const glslang::TString* spaceDesc)
6053 {
6054     if (profile != nullptr)
6055         warn(loc, "ignoring shader_profile", "register", "");
6056
6057     if (desc.size() < 1) {
6058         error(loc, "expected register type", "register", "");
6059         return;
6060     }
6061
6062     int regNumber = 0;
6063     if (desc.size() > 1) {
6064         if (isdigit(desc[1]))
6065             regNumber = atoi(desc.substr(1, desc.size()).c_str());
6066         else {
6067             error(loc, "expected register number after register type", "register", "");
6068             return;
6069         }
6070     }
6071
6072     // TODO: learn what all these really mean and how they interact with regNumber and subComponent
6073     const std::vector<std::string>& resourceInfo = intermediate.getResourceSetBinding();
6074     switch (std::tolower(desc[0])) {
6075     case 'b':
6076     case 't':
6077     case 'c':
6078     case 's':
6079     case 'u':
6080         // if nothing else has set the binding, do so now
6081         // (other mechanisms override this one)
6082         if (!qualifier.hasBinding())
6083             qualifier.layoutBinding = regNumber + subComponent;
6084
6085         // This handles per-register layout sets numbers.  For the global mode which sets
6086         // every symbol to the same value, see setLinkageLayoutSets().
6087         if ((resourceInfo.size() % 3) == 0) {
6088             // Apply per-symbol resource set and binding.
6089             for (auto it = resourceInfo.cbegin(); it != resourceInfo.cend(); it = it + 3) {
6090                 if (strcmp(desc.c_str(), it[0].c_str()) == 0) {
6091                     qualifier.layoutSet = atoi(it[1].c_str());
6092                     qualifier.layoutBinding = atoi(it[2].c_str()) + subComponent;
6093                     break;
6094                 }
6095             }
6096         }
6097         break;
6098     default:
6099         warn(loc, "ignoring unrecognized register type", "register", "%c", desc[0]);
6100         break;
6101     }
6102
6103     // space
6104     unsigned int setNumber;
6105     const auto crackSpace = [&]() -> bool {
6106         const int spaceLen = 5;
6107         if (spaceDesc->size() < spaceLen + 1)
6108             return false;
6109         if (spaceDesc->compare(0, spaceLen, "space") != 0)
6110             return false;
6111         if (! isdigit((*spaceDesc)[spaceLen]))
6112             return false;
6113         setNumber = atoi(spaceDesc->substr(spaceLen, spaceDesc->size()).c_str());
6114         return true;
6115     };
6116
6117     // if nothing else has set the set, do so now
6118     // (other mechanisms override this one)
6119     if (spaceDesc && !qualifier.hasSet()) {
6120         if (! crackSpace()) {
6121             error(loc, "expected spaceN", "register", "");
6122             return;
6123         }
6124         qualifier.layoutSet = setNumber;
6125     }
6126 }
6127
6128 // Convert to a scalar boolean, or if not allowed by HLSL semantics,
6129 // report an error and return nullptr.
6130 TIntermTyped* HlslParseContext::convertConditionalExpression(const TSourceLoc& loc, TIntermTyped* condition,
6131                                                              bool mustBeScalar)
6132 {
6133     if (mustBeScalar && !condition->getType().isScalarOrVec1()) {
6134         error(loc, "requires a scalar", "conditional expression", "");
6135         return nullptr;
6136     }
6137
6138     return intermediate.addConversion(EOpConstructBool, TType(EbtBool, EvqTemporary, condition->getVectorSize()),
6139                                       condition);
6140 }
6141
6142 //
6143 // Same error message for all places assignments don't work.
6144 //
6145 void HlslParseContext::assignError(const TSourceLoc& loc, const char* op, TString left, TString right)
6146 {
6147     error(loc, "", op, "cannot convert from '%s' to '%s'",
6148         right.c_str(), left.c_str());
6149 }
6150
6151 //
6152 // Same error message for all places unary operations don't work.
6153 //
6154 void HlslParseContext::unaryOpError(const TSourceLoc& loc, const char* op, TString operand)
6155 {
6156     error(loc, " wrong operand type", op,
6157         "no operation '%s' exists that takes an operand of type %s (or there is no acceptable conversion)",
6158         op, operand.c_str());
6159 }
6160
6161 //
6162 // Same error message for all binary operations don't work.
6163 //
6164 void HlslParseContext::binaryOpError(const TSourceLoc& loc, const char* op, TString left, TString right)
6165 {
6166     error(loc, " wrong operand types:", op,
6167         "no operation '%s' exists that takes a left-hand operand of type '%s' and "
6168         "a right operand of type '%s' (or there is no acceptable conversion)",
6169         op, left.c_str(), right.c_str());
6170 }
6171
6172 //
6173 // A basic type of EbtVoid is a key that the name string was seen in the source, but
6174 // it was not found as a variable in the symbol table.  If so, give the error
6175 // message and insert a dummy variable in the symbol table to prevent future errors.
6176 //
6177 void HlslParseContext::variableCheck(TIntermTyped*& nodePtr)
6178 {
6179     TIntermSymbol* symbol = nodePtr->getAsSymbolNode();
6180     if (! symbol)
6181         return;
6182
6183     if (symbol->getType().getBasicType() == EbtVoid) {
6184         error(symbol->getLoc(), "undeclared identifier", symbol->getName().c_str(), "");
6185
6186         // Add to symbol table to prevent future error messages on the same name
6187         if (symbol->getName().size() > 0) {
6188             TVariable* fakeVariable = new TVariable(&symbol->getName(), TType(EbtFloat));
6189             symbolTable.insert(*fakeVariable);
6190
6191             // substitute a symbol node for this new variable
6192             nodePtr = intermediate.addSymbol(*fakeVariable, symbol->getLoc());
6193         }
6194     }
6195 }
6196
6197 //
6198 // Both test, and if necessary spit out an error, to see if the node is really
6199 // a constant.
6200 //
6201 void HlslParseContext::constantValueCheck(TIntermTyped* node, const char* token)
6202 {
6203     if (node->getQualifier().storage != EvqConst)
6204         error(node->getLoc(), "constant expression required", token, "");
6205 }
6206
6207 //
6208 // Both test, and if necessary spit out an error, to see if the node is really
6209 // an integer.
6210 //
6211 void HlslParseContext::integerCheck(const TIntermTyped* node, const char* token)
6212 {
6213     if ((node->getBasicType() == EbtInt || node->getBasicType() == EbtUint) && node->isScalar())
6214         return;
6215
6216     error(node->getLoc(), "scalar integer expression required", token, "");
6217 }
6218
6219 //
6220 // Both test, and if necessary spit out an error, to see if we are currently
6221 // globally scoped.
6222 //
6223 void HlslParseContext::globalCheck(const TSourceLoc& loc, const char* token)
6224 {
6225     if (! symbolTable.atGlobalLevel())
6226         error(loc, "not allowed in nested scope", token, "");
6227 }
6228
6229 bool HlslParseContext::builtInName(const TString& /*identifier*/)
6230 {
6231     return false;
6232 }
6233
6234 //
6235 // Make sure there is enough data and not too many arguments provided to the
6236 // constructor to build something of the type of the constructor.  Also returns
6237 // the type of the constructor.
6238 //
6239 // Returns true if there was an error in construction.
6240 //
6241 bool HlslParseContext::constructorError(const TSourceLoc& loc, TIntermNode* node, TFunction& function,
6242                                         TOperator op, TType& type)
6243 {
6244     type.shallowCopy(function.getType());
6245
6246     bool constructingMatrix = false;
6247     switch (op) {
6248     case EOpConstructTextureSampler:
6249         return constructorTextureSamplerError(loc, function);
6250     case EOpConstructMat2x2:
6251     case EOpConstructMat2x3:
6252     case EOpConstructMat2x4:
6253     case EOpConstructMat3x2:
6254     case EOpConstructMat3x3:
6255     case EOpConstructMat3x4:
6256     case EOpConstructMat4x2:
6257     case EOpConstructMat4x3:
6258     case EOpConstructMat4x4:
6259     case EOpConstructDMat2x2:
6260     case EOpConstructDMat2x3:
6261     case EOpConstructDMat2x4:
6262     case EOpConstructDMat3x2:
6263     case EOpConstructDMat3x3:
6264     case EOpConstructDMat3x4:
6265     case EOpConstructDMat4x2:
6266     case EOpConstructDMat4x3:
6267     case EOpConstructDMat4x4:
6268     case EOpConstructIMat2x2:
6269     case EOpConstructIMat2x3:
6270     case EOpConstructIMat2x4:
6271     case EOpConstructIMat3x2:
6272     case EOpConstructIMat3x3:
6273     case EOpConstructIMat3x4:
6274     case EOpConstructIMat4x2:
6275     case EOpConstructIMat4x3:
6276     case EOpConstructIMat4x4:
6277     case EOpConstructUMat2x2:
6278     case EOpConstructUMat2x3:
6279     case EOpConstructUMat2x4:
6280     case EOpConstructUMat3x2:
6281     case EOpConstructUMat3x3:
6282     case EOpConstructUMat3x4:
6283     case EOpConstructUMat4x2:
6284     case EOpConstructUMat4x3:
6285     case EOpConstructUMat4x4:
6286     case EOpConstructBMat2x2:
6287     case EOpConstructBMat2x3:
6288     case EOpConstructBMat2x4:
6289     case EOpConstructBMat3x2:
6290     case EOpConstructBMat3x3:
6291     case EOpConstructBMat3x4:
6292     case EOpConstructBMat4x2:
6293     case EOpConstructBMat4x3:
6294     case EOpConstructBMat4x4:
6295         constructingMatrix = true;
6296         break;
6297     default:
6298         break;
6299     }
6300
6301     //
6302     // Walk the arguments for first-pass checks and collection of information.
6303     //
6304
6305     int size = 0;
6306     bool constType = true;
6307     bool full = false;
6308     bool overFull = false;
6309     bool matrixInMatrix = false;
6310     bool arrayArg = false;
6311     for (int arg = 0; arg < function.getParamCount(); ++arg) {
6312         if (function[arg].type->isArray()) {
6313             if (function[arg].type->isUnsizedArray()) {
6314                 // Can't construct from an unsized array.
6315                 error(loc, "array argument must be sized", "constructor", "");
6316                 return true;
6317             }
6318             arrayArg = true;
6319         }
6320         if (constructingMatrix && function[arg].type->isMatrix())
6321             matrixInMatrix = true;
6322
6323         // 'full' will go to true when enough args have been seen.  If we loop
6324         // again, there is an extra argument.
6325         if (full) {
6326             // For vectors and matrices, it's okay to have too many components
6327             // available, but not okay to have unused arguments.
6328             overFull = true;
6329         }
6330
6331         size += function[arg].type->computeNumComponents();
6332         if (op != EOpConstructStruct && ! type.isArray() && size >= type.computeNumComponents())
6333             full = true;
6334
6335         if (function[arg].type->getQualifier().storage != EvqConst)
6336             constType = false;
6337     }
6338
6339     if (constType)
6340         type.getQualifier().storage = EvqConst;
6341
6342     if (type.isArray()) {
6343         if (function.getParamCount() == 0) {
6344             error(loc, "array constructor must have at least one argument", "constructor", "");
6345             return true;
6346         }
6347
6348         if (type.isUnsizedArray()) {
6349             // auto adapt the constructor type to the number of arguments
6350             type.changeOuterArraySize(function.getParamCount());
6351         } else if (type.getOuterArraySize() != function.getParamCount() && type.computeNumComponents() > size) {
6352             error(loc, "array constructor needs one argument per array element", "constructor", "");
6353             return true;
6354         }
6355
6356         if (type.isArrayOfArrays()) {
6357             // Types have to match, but we're still making the type.
6358             // Finish making the type, and the comparison is done later
6359             // when checking for conversion.
6360             TArraySizes& arraySizes = *type.getArraySizes();
6361
6362             // At least the dimensionalities have to match.
6363             if (! function[0].type->isArray() ||
6364                 arraySizes.getNumDims() != function[0].type->getArraySizes()->getNumDims() + 1) {
6365                 error(loc, "array constructor argument not correct type to construct array element", "constructor", "");
6366                 return true;
6367             }
6368
6369             if (arraySizes.isInnerUnsized()) {
6370                 // "Arrays of arrays ..., and the size for any dimension is optional"
6371                 // That means we need to adopt (from the first argument) the other array sizes into the type.
6372                 for (int d = 1; d < arraySizes.getNumDims(); ++d) {
6373                     if (arraySizes.getDimSize(d) == UnsizedArraySize) {
6374                         arraySizes.setDimSize(d, function[0].type->getArraySizes()->getDimSize(d - 1));
6375                     }
6376                 }
6377             }
6378         }
6379     }
6380
6381     // Some array -> array type casts are okay
6382     if (arrayArg && function.getParamCount() == 1 && op != EOpConstructStruct && type.isArray() &&
6383         !type.isArrayOfArrays() && !function[0].type->isArrayOfArrays() &&
6384         type.getVectorSize() >= 1 && function[0].type->getVectorSize() >= 1)
6385         return false;
6386
6387     if (arrayArg && op != EOpConstructStruct && ! type.isArrayOfArrays()) {
6388         error(loc, "constructing non-array constituent from array argument", "constructor", "");
6389         return true;
6390     }
6391
6392     if (matrixInMatrix && ! type.isArray()) {
6393         return false;
6394     }
6395
6396     if (overFull) {
6397         error(loc, "too many arguments", "constructor", "");
6398         return true;
6399     }
6400
6401     if (op == EOpConstructStruct && ! type.isArray()) {
6402         if (isScalarConstructor(node))
6403             return false;
6404
6405         // Self-type construction: e.g, we can construct a struct from a single identically typed object.
6406         if (function.getParamCount() == 1 && type == *function[0].type)
6407             return false;
6408
6409         if ((int)type.getStruct()->size() != function.getParamCount()) {
6410             error(loc, "Number of constructor parameters does not match the number of structure fields", "constructor", "");
6411             return true;
6412         }
6413     }
6414
6415     if ((op != EOpConstructStruct && size != 1 && size < type.computeNumComponents()) ||
6416         (op == EOpConstructStruct && size < type.computeNumComponents())) {
6417         error(loc, "not enough data provided for construction", "constructor", "");
6418         return true;
6419     }
6420
6421     return false;
6422 }
6423
6424 // See if 'node', in the context of constructing aggregates, is a scalar argument
6425 // to a constructor.
6426 //
6427 bool HlslParseContext::isScalarConstructor(const TIntermNode* node)
6428 {
6429     // Obviously, it must be a scalar, but an aggregate node might not be fully
6430     // completed yet: holding a sequence of initializers under an aggregate
6431     // would not yet be typed, so don't check it's type.  This corresponds to
6432     // the aggregate operator also not being set yet. (An aggregate operation
6433     // that legitimately yields a scalar will have a getOp() of that operator,
6434     // not EOpNull.)
6435
6436     return node->getAsTyped() != nullptr &&
6437            node->getAsTyped()->isScalar() &&
6438            (node->getAsAggregate() == nullptr || node->getAsAggregate()->getOp() != EOpNull);
6439 }
6440
6441 // Verify all the correct semantics for constructing a combined texture/sampler.
6442 // Return true if the semantics are incorrect.
6443 bool HlslParseContext::constructorTextureSamplerError(const TSourceLoc& loc, const TFunction& function)
6444 {
6445     TString constructorName = function.getType().getBasicTypeString();  // TODO: performance: should not be making copy; interface needs to change
6446     const char* token = constructorName.c_str();
6447
6448     // exactly two arguments needed
6449     if (function.getParamCount() != 2) {
6450         error(loc, "sampler-constructor requires two arguments", token, "");
6451         return true;
6452     }
6453
6454     // For now, not allowing arrayed constructors, the rest of this function
6455     // is set up to allow them, if this test is removed:
6456     if (function.getType().isArray()) {
6457         error(loc, "sampler-constructor cannot make an array of samplers", token, "");
6458         return true;
6459     }
6460
6461     // first argument
6462     //  * the constructor's first argument must be a texture type
6463     //  * the dimensionality (1D, 2D, 3D, Cube, Rect, Buffer, MS, and Array)
6464     //    of the texture type must match that of the constructed sampler type
6465     //    (that is, the suffixes of the type of the first argument and the
6466     //    type of the constructor will be spelled the same way)
6467     if (function[0].type->getBasicType() != EbtSampler ||
6468         ! function[0].type->getSampler().isTexture() ||
6469         function[0].type->isArray()) {
6470         error(loc, "sampler-constructor first argument must be a scalar textureXXX type", token, "");
6471         return true;
6472     }
6473     // simulate the first argument's impact on the result type, so it can be compared with the encapsulated operator!=()
6474     TSampler texture = function.getType().getSampler();
6475     texture.combined = false;
6476     texture.shadow = false;
6477     if (texture != function[0].type->getSampler()) {
6478         error(loc, "sampler-constructor first argument must match type and dimensionality of constructor type", token, "");
6479         return true;
6480     }
6481
6482     // second argument
6483     //   * the constructor's second argument must be a scalar of type
6484     //     *sampler* or *samplerShadow*
6485     //   * the presence or absence of depth comparison (Shadow) must match
6486     //     between the constructed sampler type and the type of the second argument
6487     if (function[1].type->getBasicType() != EbtSampler ||
6488         ! function[1].type->getSampler().isPureSampler() ||
6489         function[1].type->isArray()) {
6490         error(loc, "sampler-constructor second argument must be a scalar type 'sampler'", token, "");
6491         return true;
6492     }
6493     if (function.getType().getSampler().shadow != function[1].type->getSampler().shadow) {
6494         error(loc, "sampler-constructor second argument presence of shadow must match constructor presence of shadow",
6495               token, "");
6496         return true;
6497     }
6498
6499     return false;
6500 }
6501
6502 // Checks to see if a void variable has been declared and raise an error message for such a case
6503 //
6504 // returns true in case of an error
6505 //
6506 bool HlslParseContext::voidErrorCheck(const TSourceLoc& loc, const TString& identifier, const TBasicType basicType)
6507 {
6508     if (basicType == EbtVoid) {
6509         error(loc, "illegal use of type 'void'", identifier.c_str(), "");
6510         return true;
6511     }
6512
6513     return false;
6514 }
6515
6516 //
6517 // Fix just a full qualifier (no variables or types yet, but qualifier is complete) at global level.
6518 //
6519 void HlslParseContext::globalQualifierFix(const TSourceLoc&, TQualifier& qualifier)
6520 {
6521     // move from parameter/unknown qualifiers to pipeline in/out qualifiers
6522     switch (qualifier.storage) {
6523     case EvqIn:
6524         qualifier.storage = EvqVaryingIn;
6525         break;
6526     case EvqOut:
6527         qualifier.storage = EvqVaryingOut;
6528         break;
6529     default:
6530         break;
6531     }
6532 }
6533
6534 //
6535 // Merge characteristics of the 'src' qualifier into the 'dst'.
6536 // If there is duplication, issue error messages, unless 'force'
6537 // is specified, which means to just override default settings.
6538 //
6539 // Also, when force is false, it will be assumed that 'src' follows
6540 // 'dst', for the purpose of error checking order for versions
6541 // that require specific orderings of qualifiers.
6542 //
6543 void HlslParseContext::mergeQualifiers(TQualifier& dst, const TQualifier& src)
6544 {
6545     // Storage qualification
6546     if (dst.storage == EvqTemporary || dst.storage == EvqGlobal)
6547         dst.storage = src.storage;
6548     else if ((dst.storage == EvqIn  && src.storage == EvqOut) ||
6549              (dst.storage == EvqOut && src.storage == EvqIn))
6550         dst.storage = EvqInOut;
6551     else if ((dst.storage == EvqIn    && src.storage == EvqConst) ||
6552              (dst.storage == EvqConst && src.storage == EvqIn))
6553         dst.storage = EvqConstReadOnly;
6554
6555     // Layout qualifiers
6556     mergeObjectLayoutQualifiers(dst, src, false);
6557
6558     // individual qualifiers
6559     bool repeated = false;
6560 #define MERGE_SINGLETON(field) repeated |= dst.field && src.field; dst.field |= src.field;
6561     MERGE_SINGLETON(invariant);
6562     MERGE_SINGLETON(noContraction);
6563     MERGE_SINGLETON(centroid);
6564     MERGE_SINGLETON(smooth);
6565     MERGE_SINGLETON(flat);
6566     MERGE_SINGLETON(nopersp);
6567     MERGE_SINGLETON(patch);
6568     MERGE_SINGLETON(sample);
6569     MERGE_SINGLETON(coherent);
6570     MERGE_SINGLETON(volatil);
6571     MERGE_SINGLETON(restrict);
6572     MERGE_SINGLETON(readonly);
6573     MERGE_SINGLETON(writeonly);
6574     MERGE_SINGLETON(specConstant);
6575     MERGE_SINGLETON(nonUniform);
6576 }
6577
6578 // used to flatten the sampler type space into a single dimension
6579 // correlates with the declaration of defaultSamplerPrecision[]
6580 int HlslParseContext::computeSamplerTypeIndex(TSampler& sampler)
6581 {
6582     int arrayIndex = sampler.arrayed ? 1 : 0;
6583     int shadowIndex = sampler.shadow ? 1 : 0;
6584     int externalIndex = sampler.external ? 1 : 0;
6585
6586     return EsdNumDims *
6587            (EbtNumTypes * (2 * (2 * arrayIndex + shadowIndex) + externalIndex) + sampler.type) + sampler.dim;
6588 }
6589
6590 //
6591 // Do size checking for an array type's size.
6592 //
6593 void HlslParseContext::arraySizeCheck(const TSourceLoc& loc, TIntermTyped* expr, TArraySize& sizePair)
6594 {
6595     bool isConst = false;
6596     sizePair.size = 1;
6597     sizePair.node = nullptr;
6598
6599     TIntermConstantUnion* constant = expr->getAsConstantUnion();
6600     if (constant) {
6601         // handle true (non-specialization) constant
6602         sizePair.size = constant->getConstArray()[0].getIConst();
6603         isConst = true;
6604     } else {
6605         // see if it's a specialization constant instead
6606         if (expr->getQualifier().isSpecConstant()) {
6607             isConst = true;
6608             sizePair.node = expr;
6609             TIntermSymbol* symbol = expr->getAsSymbolNode();
6610             if (symbol && symbol->getConstArray().size() > 0)
6611                 sizePair.size = symbol->getConstArray()[0].getIConst();
6612         }
6613     }
6614
6615     if (! isConst || (expr->getBasicType() != EbtInt && expr->getBasicType() != EbtUint)) {
6616         error(loc, "array size must be a constant integer expression", "", "");
6617         return;
6618     }
6619
6620     if (sizePair.size <= 0) {
6621         error(loc, "array size must be a positive integer", "", "");
6622         return;
6623     }
6624 }
6625
6626 //
6627 // Require array to be completely sized
6628 //
6629 void HlslParseContext::arraySizeRequiredCheck(const TSourceLoc& loc, const TArraySizes& arraySizes)
6630 {
6631     if (arraySizes.hasUnsized())
6632         error(loc, "array size required", "", "");
6633 }
6634
6635 void HlslParseContext::structArrayCheck(const TSourceLoc& /*loc*/, const TType& type)
6636 {
6637     const TTypeList& structure = *type.getStruct();
6638     for (int m = 0; m < (int)structure.size(); ++m) {
6639         const TType& member = *structure[m].type;
6640         if (member.isArray())
6641             arraySizeRequiredCheck(structure[m].loc, *member.getArraySizes());
6642     }
6643 }
6644
6645 //
6646 // Do all the semantic checking for declaring or redeclaring an array, with and
6647 // without a size, and make the right changes to the symbol table.
6648 //
6649 void HlslParseContext::declareArray(const TSourceLoc& loc, const TString& identifier, const TType& type,
6650                                     TSymbol*& symbol, bool track)
6651 {
6652     if (symbol == nullptr) {
6653         bool currentScope;
6654         symbol = symbolTable.find(identifier, nullptr, &currentScope);
6655
6656         if (symbol && builtInName(identifier) && ! symbolTable.atBuiltInLevel()) {
6657             // bad shader (errors already reported) trying to redeclare a built-in name as an array
6658             return;
6659         }
6660         if (symbol == nullptr || ! currentScope) {
6661             //
6662             // Successfully process a new definition.
6663             // (Redeclarations have to take place at the same scope; otherwise they are hiding declarations)
6664             //
6665             symbol = new TVariable(&identifier, type);
6666             symbolTable.insert(*symbol);
6667             if (track && symbolTable.atGlobalLevel())
6668                 trackLinkage(*symbol);
6669
6670             return;
6671         }
6672         if (symbol->getAsAnonMember()) {
6673             error(loc, "cannot redeclare a user-block member array", identifier.c_str(), "");
6674             symbol = nullptr;
6675             return;
6676         }
6677     }
6678
6679     //
6680     // Process a redeclaration.
6681     //
6682
6683     if (symbol == nullptr) {
6684         error(loc, "array variable name expected", identifier.c_str(), "");
6685         return;
6686     }
6687
6688     // redeclareBuiltinVariable() should have already done the copyUp()
6689     TType& existingType = symbol->getWritableType();
6690
6691     if (existingType.isSizedArray()) {
6692         // be more lenient for input arrays to geometry shaders and tessellation control outputs,
6693         // where the redeclaration is the same size
6694         return;
6695     }
6696
6697     existingType.updateArraySizes(type);
6698 }
6699
6700 //
6701 // Enforce non-initializer type/qualifier rules.
6702 //
6703 void HlslParseContext::fixConstInit(const TSourceLoc& loc, const TString& identifier, TType& type,
6704                                     TIntermTyped*& initializer)
6705 {
6706     //
6707     // Make the qualifier make sense, given that there is an initializer.
6708     //
6709     if (initializer == nullptr) {
6710         if (type.getQualifier().storage == EvqConst ||
6711             type.getQualifier().storage == EvqConstReadOnly) {
6712             initializer = intermediate.makeAggregate(loc);
6713             warn(loc, "variable with qualifier 'const' not initialized; zero initializing", identifier.c_str(), "");
6714         }
6715     }
6716 }
6717
6718 //
6719 // See if the identifier is a built-in symbol that can be redeclared, and if so,
6720 // copy the symbol table's read-only built-in variable to the current
6721 // global level, where it can be modified based on the passed in type.
6722 //
6723 // Returns nullptr if no redeclaration took place; meaning a normal declaration still
6724 // needs to occur for it, not necessarily an error.
6725 //
6726 // Returns a redeclared and type-modified variable if a redeclared occurred.
6727 //
6728 TSymbol* HlslParseContext::redeclareBuiltinVariable(const TSourceLoc& /*loc*/, const TString& identifier,
6729                                                     const TQualifier& /*qualifier*/,
6730                                                     const TShaderQualifiers& /*publicType*/)
6731 {
6732     if (! builtInName(identifier) || symbolTable.atBuiltInLevel() || ! symbolTable.atGlobalLevel())
6733         return nullptr;
6734
6735     return nullptr;
6736 }
6737
6738 //
6739 // Generate index to the array element in a structure buffer (SSBO)
6740 //
6741 TIntermTyped* HlslParseContext::indexStructBufferContent(const TSourceLoc& loc, TIntermTyped* buffer) const
6742 {
6743     // Bail out if not a struct buffer
6744     if (buffer == nullptr || ! isStructBufferType(buffer->getType()))
6745         return nullptr;
6746
6747     // Runtime sized array is always the last element.
6748     const TTypeList* bufferStruct = buffer->getType().getStruct();
6749     TIntermTyped* arrayPosition = intermediate.addConstantUnion(unsigned(bufferStruct->size()-1), loc);
6750
6751     TIntermTyped* argArray = intermediate.addIndex(EOpIndexDirectStruct, buffer, arrayPosition, loc);
6752     argArray->setType(*(*bufferStruct)[bufferStruct->size()-1].type);
6753
6754     return argArray;
6755 }
6756
6757 //
6758 // IFF type is a structuredbuffer/byteaddressbuffer type, return the content
6759 // (template) type.   E.g, StructuredBuffer<MyType> -> MyType.  Else return nullptr.
6760 //
6761 TType* HlslParseContext::getStructBufferContentType(const TType& type) const
6762 {
6763     if (type.getBasicType() != EbtBlock || type.getQualifier().storage != EvqBuffer)
6764         return nullptr;
6765
6766     const int memberCount = (int)type.getStruct()->size();
6767     assert(memberCount > 0);
6768
6769     TType* contentType = (*type.getStruct())[memberCount-1].type;
6770
6771     return contentType->isUnsizedArray() ? contentType : nullptr;
6772 }
6773
6774 //
6775 // If an existing struct buffer has a sharable type, then share it.
6776 //
6777 void HlslParseContext::shareStructBufferType(TType& type)
6778 {
6779     // PackOffset must be equivalent to share types on a per-member basis.
6780     // Note: cannot use auto type due to recursion.  Thus, this is a std::function.
6781     const std::function<bool(TType& lhs, TType& rhs)>
6782     compareQualifiers = [&](TType& lhs, TType& rhs) -> bool {
6783         if (lhs.getQualifier().layoutOffset != rhs.getQualifier().layoutOffset)
6784             return false;
6785
6786         if (lhs.isStruct() != rhs.isStruct())
6787             return false;
6788
6789         if (lhs.isStruct() && rhs.isStruct()) {
6790             if (lhs.getStruct()->size() != rhs.getStruct()->size())
6791                 return false;
6792
6793             for (int i = 0; i < int(lhs.getStruct()->size()); ++i)
6794                 if (!compareQualifiers(*(*lhs.getStruct())[i].type, *(*rhs.getStruct())[i].type))
6795                     return false;
6796         }
6797
6798         return true;
6799     };
6800
6801     // We need to compare certain qualifiers in addition to the type.
6802     const auto typeEqual = [compareQualifiers](TType& lhs, TType& rhs) -> bool {
6803         if (lhs.getQualifier().readonly != rhs.getQualifier().readonly)
6804             return false;
6805
6806         // If both are structures, recursively look for packOffset equality
6807         // as well as type equality.
6808         return compareQualifiers(lhs, rhs) && lhs == rhs;
6809     };
6810
6811     // This is an exhaustive O(N) search, but real world shaders have
6812     // only a small number of these.
6813     for (int idx = 0; idx < int(structBufferTypes.size()); ++idx) {
6814         // If the deep structure matches, modulo qualifiers, use it
6815         if (typeEqual(*structBufferTypes[idx], type)) {
6816             type.shallowCopy(*structBufferTypes[idx]);
6817             return;
6818         }
6819     }
6820
6821     // Otherwise, remember it:
6822     TType* typeCopy = new TType;
6823     typeCopy->shallowCopy(type);
6824     structBufferTypes.push_back(typeCopy);
6825 }
6826
6827 void HlslParseContext::paramFix(TType& type)
6828 {
6829     switch (type.getQualifier().storage) {
6830     case EvqConst:
6831         type.getQualifier().storage = EvqConstReadOnly;
6832         break;
6833     case EvqGlobal:
6834     case EvqUniform:
6835     case EvqTemporary:
6836         type.getQualifier().storage = EvqIn;
6837         break;
6838     case EvqBuffer:
6839         {
6840             // SSBO parameter.  These do not go through the declareBlock path since they are fn parameters.
6841             correctUniform(type.getQualifier());
6842             TQualifier bufferQualifier = globalBufferDefaults;
6843             mergeObjectLayoutQualifiers(bufferQualifier, type.getQualifier(), true);
6844             bufferQualifier.storage = type.getQualifier().storage;
6845             bufferQualifier.readonly = type.getQualifier().readonly;
6846             bufferQualifier.coherent = type.getQualifier().coherent;
6847             bufferQualifier.declaredBuiltIn = type.getQualifier().declaredBuiltIn;
6848             type.getQualifier() = bufferQualifier;
6849             break;
6850         }
6851     default:
6852         break;
6853     }
6854 }
6855
6856 void HlslParseContext::specializationCheck(const TSourceLoc& loc, const TType& type, const char* op)
6857 {
6858     if (type.containsSpecializationSize())
6859         error(loc, "can't use with types containing arrays sized with a specialization constant", op, "");
6860 }
6861
6862 //
6863 // Layout qualifier stuff.
6864 //
6865
6866 // Put the id's layout qualification into the public type, for qualifiers not having a number set.
6867 // This is before we know any type information for error checking.
6868 void HlslParseContext::setLayoutQualifier(const TSourceLoc& loc, TQualifier& qualifier, TString& id)
6869 {
6870     std::transform(id.begin(), id.end(), id.begin(), ::tolower);
6871
6872     if (id == TQualifier::getLayoutMatrixString(ElmColumnMajor)) {
6873         qualifier.layoutMatrix = ElmRowMajor;
6874         return;
6875     }
6876     if (id == TQualifier::getLayoutMatrixString(ElmRowMajor)) {
6877         qualifier.layoutMatrix = ElmColumnMajor;
6878         return;
6879     }
6880     if (id == "push_constant") {
6881         requireVulkan(loc, "push_constant");
6882         qualifier.layoutPushConstant = true;
6883         return;
6884     }
6885     if (language == EShLangGeometry || language == EShLangTessEvaluation) {
6886         if (id == TQualifier::getGeometryString(ElgTriangles)) {
6887             // publicType.shaderQualifiers.geometry = ElgTriangles;
6888             warn(loc, "ignored", id.c_str(), "");
6889             return;
6890         }
6891         if (language == EShLangGeometry) {
6892             if (id == TQualifier::getGeometryString(ElgPoints)) {
6893                 // publicType.shaderQualifiers.geometry = ElgPoints;
6894                 warn(loc, "ignored", id.c_str(), "");
6895                 return;
6896             }
6897             if (id == TQualifier::getGeometryString(ElgLineStrip)) {
6898                 // publicType.shaderQualifiers.geometry = ElgLineStrip;
6899                 warn(loc, "ignored", id.c_str(), "");
6900                 return;
6901             }
6902             if (id == TQualifier::getGeometryString(ElgLines)) {
6903                 // publicType.shaderQualifiers.geometry = ElgLines;
6904                 warn(loc, "ignored", id.c_str(), "");
6905                 return;
6906             }
6907             if (id == TQualifier::getGeometryString(ElgLinesAdjacency)) {
6908                 // publicType.shaderQualifiers.geometry = ElgLinesAdjacency;
6909                 warn(loc, "ignored", id.c_str(), "");
6910                 return;
6911             }
6912             if (id == TQualifier::getGeometryString(ElgTrianglesAdjacency)) {
6913                 // publicType.shaderQualifiers.geometry = ElgTrianglesAdjacency;
6914                 warn(loc, "ignored", id.c_str(), "");
6915                 return;
6916             }
6917             if (id == TQualifier::getGeometryString(ElgTriangleStrip)) {
6918                 // publicType.shaderQualifiers.geometry = ElgTriangleStrip;
6919                 warn(loc, "ignored", id.c_str(), "");
6920                 return;
6921             }
6922         } else {
6923             assert(language == EShLangTessEvaluation);
6924
6925             // input primitive
6926             if (id == TQualifier::getGeometryString(ElgTriangles)) {
6927                 // publicType.shaderQualifiers.geometry = ElgTriangles;
6928                 warn(loc, "ignored", id.c_str(), "");
6929                 return;
6930             }
6931             if (id == TQualifier::getGeometryString(ElgQuads)) {
6932                 // publicType.shaderQualifiers.geometry = ElgQuads;
6933                 warn(loc, "ignored", id.c_str(), "");
6934                 return;
6935             }
6936             if (id == TQualifier::getGeometryString(ElgIsolines)) {
6937                 // publicType.shaderQualifiers.geometry = ElgIsolines;
6938                 warn(loc, "ignored", id.c_str(), "");
6939                 return;
6940             }
6941
6942             // vertex spacing
6943             if (id == TQualifier::getVertexSpacingString(EvsEqual)) {
6944                 // publicType.shaderQualifiers.spacing = EvsEqual;
6945                 warn(loc, "ignored", id.c_str(), "");
6946                 return;
6947             }
6948             if (id == TQualifier::getVertexSpacingString(EvsFractionalEven)) {
6949                 // publicType.shaderQualifiers.spacing = EvsFractionalEven;
6950                 warn(loc, "ignored", id.c_str(), "");
6951                 return;
6952             }
6953             if (id == TQualifier::getVertexSpacingString(EvsFractionalOdd)) {
6954                 // publicType.shaderQualifiers.spacing = EvsFractionalOdd;
6955                 warn(loc, "ignored", id.c_str(), "");
6956                 return;
6957             }
6958
6959             // triangle order
6960             if (id == TQualifier::getVertexOrderString(EvoCw)) {
6961                 // publicType.shaderQualifiers.order = EvoCw;
6962                 warn(loc, "ignored", id.c_str(), "");
6963                 return;
6964             }
6965             if (id == TQualifier::getVertexOrderString(EvoCcw)) {
6966                 // publicType.shaderQualifiers.order = EvoCcw;
6967                 warn(loc, "ignored", id.c_str(), "");
6968                 return;
6969             }
6970
6971             // point mode
6972             if (id == "point_mode") {
6973                 // publicType.shaderQualifiers.pointMode = true;
6974                 warn(loc, "ignored", id.c_str(), "");
6975                 return;
6976             }
6977         }
6978     }
6979     if (language == EShLangFragment) {
6980         if (id == "origin_upper_left") {
6981             // publicType.shaderQualifiers.originUpperLeft = true;
6982             warn(loc, "ignored", id.c_str(), "");
6983             return;
6984         }
6985         if (id == "pixel_center_integer") {
6986             // publicType.shaderQualifiers.pixelCenterInteger = true;
6987             warn(loc, "ignored", id.c_str(), "");
6988             return;
6989         }
6990         if (id == "early_fragment_tests") {
6991             // publicType.shaderQualifiers.earlyFragmentTests = true;
6992             warn(loc, "ignored", id.c_str(), "");
6993             return;
6994         }
6995         for (TLayoutDepth depth = (TLayoutDepth)(EldNone + 1); depth < EldCount; depth = (TLayoutDepth)(depth + 1)) {
6996             if (id == TQualifier::getLayoutDepthString(depth)) {
6997                 // publicType.shaderQualifiers.layoutDepth = depth;
6998                 warn(loc, "ignored", id.c_str(), "");
6999                 return;
7000             }
7001         }
7002         if (id.compare(0, 13, "blend_support") == 0) {
7003             bool found = false;
7004             for (TBlendEquationShift be = (TBlendEquationShift)0; be < EBlendCount; be = (TBlendEquationShift)(be + 1)) {
7005                 if (id == TQualifier::getBlendEquationString(be)) {
7006                     requireExtensions(loc, 1, &E_GL_KHR_blend_equation_advanced, "blend equation");
7007                     intermediate.addBlendEquation(be);
7008                     // publicType.shaderQualifiers.blendEquation = true;
7009                     warn(loc, "ignored", id.c_str(), "");
7010                     found = true;
7011                     break;
7012                 }
7013             }
7014             if (! found)
7015                 error(loc, "unknown blend equation", "blend_support", "");
7016             return;
7017         }
7018     }
7019     error(loc, "unrecognized layout identifier, or qualifier requires assignment (e.g., binding = 4)", id.c_str(), "");
7020 }
7021
7022 // Put the id's layout qualifier value into the public type, for qualifiers having a number set.
7023 // This is before we know any type information for error checking.
7024 void HlslParseContext::setLayoutQualifier(const TSourceLoc& loc, TQualifier& qualifier, TString& id,
7025                                           const TIntermTyped* node)
7026 {
7027     const char* feature = "layout-id value";
7028     // const char* nonLiteralFeature = "non-literal layout-id value";
7029
7030     integerCheck(node, feature);
7031     const TIntermConstantUnion* constUnion = node->getAsConstantUnion();
7032     int value = 0;
7033     if (constUnion) {
7034         value = constUnion->getConstArray()[0].getIConst();
7035     }
7036
7037     std::transform(id.begin(), id.end(), id.begin(), ::tolower);
7038
7039     if (id == "offset") {
7040         qualifier.layoutOffset = value;
7041         return;
7042     } else if (id == "align") {
7043         // "The specified alignment must be a power of 2, or a compile-time error results."
7044         if (! IsPow2(value))
7045             error(loc, "must be a power of 2", "align", "");
7046         else
7047             qualifier.layoutAlign = value;
7048         return;
7049     } else if (id == "location") {
7050         if ((unsigned int)value >= TQualifier::layoutLocationEnd)
7051             error(loc, "location is too large", id.c_str(), "");
7052         else
7053             qualifier.layoutLocation = value;
7054         return;
7055     } else if (id == "set") {
7056         if ((unsigned int)value >= TQualifier::layoutSetEnd)
7057             error(loc, "set is too large", id.c_str(), "");
7058         else
7059             qualifier.layoutSet = value;
7060         return;
7061     } else if (id == "binding") {
7062         if ((unsigned int)value >= TQualifier::layoutBindingEnd)
7063             error(loc, "binding is too large", id.c_str(), "");
7064         else
7065             qualifier.layoutBinding = value;
7066         return;
7067     } else if (id == "component") {
7068         if ((unsigned)value >= TQualifier::layoutComponentEnd)
7069             error(loc, "component is too large", id.c_str(), "");
7070         else
7071             qualifier.layoutComponent = value;
7072         return;
7073     } else if (id.compare(0, 4, "xfb_") == 0) {
7074         // "Any shader making any static use (after preprocessing) of any of these
7075         // *xfb_* qualifiers will cause the shader to be in a transform feedback
7076         // capturing mode and hence responsible for describing the transform feedback
7077         // setup."
7078         intermediate.setXfbMode();
7079         if (id == "xfb_buffer") {
7080             // "It is a compile-time error to specify an *xfb_buffer* that is greater than
7081             // the implementation-dependent constant gl_MaxTransformFeedbackBuffers."
7082             if (value >= resources.maxTransformFeedbackBuffers)
7083                 error(loc, "buffer is too large:", id.c_str(), "gl_MaxTransformFeedbackBuffers is %d",
7084                       resources.maxTransformFeedbackBuffers);
7085             if (value >= (int)TQualifier::layoutXfbBufferEnd)
7086                 error(loc, "buffer is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbBufferEnd - 1);
7087             else
7088                 qualifier.layoutXfbBuffer = value;
7089             return;
7090         } else if (id == "xfb_offset") {
7091             if (value >= (int)TQualifier::layoutXfbOffsetEnd)
7092                 error(loc, "offset is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbOffsetEnd - 1);
7093             else
7094                 qualifier.layoutXfbOffset = value;
7095             return;
7096         } else if (id == "xfb_stride") {
7097             // "The resulting stride (implicit or explicit), when divided by 4, must be less than or equal to the
7098             // implementation-dependent constant gl_MaxTransformFeedbackInterleavedComponents."
7099             if (value > 4 * resources.maxTransformFeedbackInterleavedComponents)
7100                 error(loc, "1/4 stride is too large:", id.c_str(), "gl_MaxTransformFeedbackInterleavedComponents is %d",
7101                       resources.maxTransformFeedbackInterleavedComponents);
7102             else if (value >= (int)TQualifier::layoutXfbStrideEnd)
7103                 error(loc, "stride is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbStrideEnd - 1);
7104             if (value < (int)TQualifier::layoutXfbStrideEnd)
7105                 qualifier.layoutXfbStride = value;
7106             return;
7107         }
7108     }
7109
7110     if (id == "input_attachment_index") {
7111         requireVulkan(loc, "input_attachment_index");
7112         if (value >= (int)TQualifier::layoutAttachmentEnd)
7113             error(loc, "attachment index is too large", id.c_str(), "");
7114         else
7115             qualifier.layoutAttachment = value;
7116         return;
7117     }
7118     if (id == "constant_id") {
7119         setSpecConstantId(loc, qualifier, value);
7120         return;
7121     }
7122
7123     switch (language) {
7124     case EShLangVertex:
7125         break;
7126
7127     case EShLangTessControl:
7128         if (id == "vertices") {
7129             if (value == 0)
7130                 error(loc, "must be greater than 0", "vertices", "");
7131             else
7132                 // publicType.shaderQualifiers.vertices = value;
7133                 warn(loc, "ignored", id.c_str(), "");
7134             return;
7135         }
7136         break;
7137
7138     case EShLangTessEvaluation:
7139         break;
7140
7141     case EShLangGeometry:
7142         if (id == "invocations") {
7143             if (value == 0)
7144                 error(loc, "must be at least 1", "invocations", "");
7145             else
7146                 // publicType.shaderQualifiers.invocations = value;
7147                 warn(loc, "ignored", id.c_str(), "");
7148             return;
7149         }
7150         if (id == "max_vertices") {
7151             // publicType.shaderQualifiers.vertices = value;
7152             warn(loc, "ignored", id.c_str(), "");
7153             if (value > resources.maxGeometryOutputVertices)
7154                 error(loc, "too large, must be less than gl_MaxGeometryOutputVertices", "max_vertices", "");
7155             return;
7156         }
7157         if (id == "stream") {
7158             qualifier.layoutStream = value;
7159             return;
7160         }
7161         break;
7162
7163     case EShLangFragment:
7164         if (id == "index") {
7165             qualifier.layoutIndex = value;
7166             return;
7167         }
7168         break;
7169
7170     case EShLangCompute:
7171         if (id.compare(0, 11, "local_size_") == 0) {
7172             if (id == "local_size_x") {
7173                 // publicType.shaderQualifiers.localSize[0] = value;
7174                 warn(loc, "ignored", id.c_str(), "");
7175                 return;
7176             }
7177             if (id == "local_size_y") {
7178                 // publicType.shaderQualifiers.localSize[1] = value;
7179                 warn(loc, "ignored", id.c_str(), "");
7180                 return;
7181             }
7182             if (id == "local_size_z") {
7183                 // publicType.shaderQualifiers.localSize[2] = value;
7184                 warn(loc, "ignored", id.c_str(), "");
7185                 return;
7186             }
7187             if (spvVersion.spv != 0) {
7188                 if (id == "local_size_x_id") {
7189                     // publicType.shaderQualifiers.localSizeSpecId[0] = value;
7190                     warn(loc, "ignored", id.c_str(), "");
7191                     return;
7192                 }
7193                 if (id == "local_size_y_id") {
7194                     // publicType.shaderQualifiers.localSizeSpecId[1] = value;
7195                     warn(loc, "ignored", id.c_str(), "");
7196                     return;
7197                 }
7198                 if (id == "local_size_z_id") {
7199                     // publicType.shaderQualifiers.localSizeSpecId[2] = value;
7200                     warn(loc, "ignored", id.c_str(), "");
7201                     return;
7202                 }
7203             }
7204         }
7205         break;
7206
7207     default:
7208         break;
7209     }
7210
7211     error(loc, "there is no such layout identifier for this stage taking an assigned value", id.c_str(), "");
7212 }
7213
7214 void HlslParseContext::setSpecConstantId(const TSourceLoc& loc, TQualifier& qualifier, int value)
7215 {
7216     if (value >= (int)TQualifier::layoutSpecConstantIdEnd) {
7217         error(loc, "specialization-constant id is too large", "constant_id", "");
7218     } else {
7219         qualifier.layoutSpecConstantId = value;
7220         qualifier.specConstant = true;
7221         if (! intermediate.addUsedConstantId(value))
7222             error(loc, "specialization-constant id already used", "constant_id", "");
7223     }
7224     return;
7225 }
7226
7227 // Merge any layout qualifier information from src into dst, leaving everything else in dst alone
7228 //
7229 // "More than one layout qualifier may appear in a single declaration.
7230 // Additionally, the same layout-qualifier-name can occur multiple times
7231 // within a layout qualifier or across multiple layout qualifiers in the
7232 // same declaration. When the same layout-qualifier-name occurs
7233 // multiple times, in a single declaration, the last occurrence overrides
7234 // the former occurrence(s).  Further, if such a layout-qualifier-name
7235 // will effect subsequent declarations or other observable behavior, it
7236 // is only the last occurrence that will have any effect, behaving as if
7237 // the earlier occurrence(s) within the declaration are not present.
7238 // This is also true for overriding layout-qualifier-names, where one
7239 // overrides the other (e.g., row_major vs. column_major); only the last
7240 // occurrence has any effect."
7241 //
7242 void HlslParseContext::mergeObjectLayoutQualifiers(TQualifier& dst, const TQualifier& src, bool inheritOnly)
7243 {
7244     if (src.hasMatrix())
7245         dst.layoutMatrix = src.layoutMatrix;
7246     if (src.hasPacking())
7247         dst.layoutPacking = src.layoutPacking;
7248
7249     if (src.hasStream())
7250         dst.layoutStream = src.layoutStream;
7251
7252     if (src.hasFormat())
7253         dst.layoutFormat = src.layoutFormat;
7254
7255     if (src.hasXfbBuffer())
7256         dst.layoutXfbBuffer = src.layoutXfbBuffer;
7257
7258     if (src.hasAlign())
7259         dst.layoutAlign = src.layoutAlign;
7260
7261     if (! inheritOnly) {
7262         if (src.hasLocation())
7263             dst.layoutLocation = src.layoutLocation;
7264         if (src.hasComponent())
7265             dst.layoutComponent = src.layoutComponent;
7266         if (src.hasIndex())
7267             dst.layoutIndex = src.layoutIndex;
7268
7269         if (src.hasOffset())
7270             dst.layoutOffset = src.layoutOffset;
7271
7272         if (src.hasSet())
7273             dst.layoutSet = src.layoutSet;
7274         if (src.layoutBinding != TQualifier::layoutBindingEnd)
7275             dst.layoutBinding = src.layoutBinding;
7276
7277         if (src.hasXfbStride())
7278             dst.layoutXfbStride = src.layoutXfbStride;
7279         if (src.hasXfbOffset())
7280             dst.layoutXfbOffset = src.layoutXfbOffset;
7281         if (src.hasAttachment())
7282             dst.layoutAttachment = src.layoutAttachment;
7283         if (src.hasSpecConstantId())
7284             dst.layoutSpecConstantId = src.layoutSpecConstantId;
7285
7286         if (src.layoutPushConstant)
7287             dst.layoutPushConstant = true;
7288     }
7289 }
7290
7291
7292 //
7293 // Look up a function name in the symbol table, and make sure it is a function.
7294 //
7295 // First, look for an exact match.  If there is none, use the generic selector
7296 // TParseContextBase::selectFunction() to find one, parameterized by the
7297 // convertible() and better() predicates defined below.
7298 //
7299 // Return the function symbol if found, otherwise nullptr.
7300 //
7301 const TFunction* HlslParseContext::findFunction(const TSourceLoc& loc, TFunction& call, bool& builtIn, int& thisDepth,
7302                                                 TIntermTyped*& args)
7303 {
7304     if (symbolTable.isFunctionNameVariable(call.getName())) {
7305         error(loc, "can't use function syntax on variable", call.getName().c_str(), "");
7306         return nullptr;
7307     }
7308
7309     // first, look for an exact match
7310     bool dummyScope;
7311     TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn, &dummyScope, &thisDepth);
7312     if (symbol)
7313         return symbol->getAsFunction();
7314
7315     // no exact match, use the generic selector, parameterized by the GLSL rules
7316
7317     // create list of candidates to send
7318     TVector<const TFunction*> candidateList;
7319     symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
7320
7321     // These built-in ops can accept any type, so we bypass the argument selection
7322     if (candidateList.size() == 1 && builtIn &&
7323         (candidateList[0]->getBuiltInOp() == EOpMethodAppend ||
7324          candidateList[0]->getBuiltInOp() == EOpMethodRestartStrip ||
7325          candidateList[0]->getBuiltInOp() == EOpMethodIncrementCounter ||
7326          candidateList[0]->getBuiltInOp() == EOpMethodDecrementCounter ||
7327          candidateList[0]->getBuiltInOp() == EOpMethodAppend ||
7328          candidateList[0]->getBuiltInOp() == EOpMethodConsume)) {
7329         return candidateList[0];
7330     }
7331
7332     bool allowOnlyUpConversions = true;
7333
7334     // can 'from' convert to 'to'?
7335     const auto convertible = [&](const TType& from, const TType& to, TOperator op, int arg) -> bool {
7336         if (from == to)
7337             return true;
7338
7339         // no aggregate conversions
7340         if (from.isArray()  || to.isArray() ||
7341             from.isStruct() || to.isStruct())
7342             return false;
7343
7344         switch (op) {
7345         case EOpInterlockedAdd:
7346         case EOpInterlockedAnd:
7347         case EOpInterlockedCompareExchange:
7348         case EOpInterlockedCompareStore:
7349         case EOpInterlockedExchange:
7350         case EOpInterlockedMax:
7351         case EOpInterlockedMin:
7352         case EOpInterlockedOr:
7353         case EOpInterlockedXor:
7354             // We do not promote the texture or image type for these ocodes.  Normally that would not
7355             // be an issue because it's a buffer, but we haven't decomposed the opcode yet, and at this
7356             // stage it's merely e.g, a basic integer type.
7357             //
7358             // Instead, we want to promote other arguments, but stay within the same family.  In other
7359             // words, InterlockedAdd(RWBuffer<int>, ...) will always use the int flavor, never the uint flavor,
7360             // but it is allowed to promote its other arguments.
7361             if (arg == 0)
7362                 return false;
7363             break;
7364         case EOpMethodSample:
7365         case EOpMethodSampleBias:
7366         case EOpMethodSampleCmp:
7367         case EOpMethodSampleCmpLevelZero:
7368         case EOpMethodSampleGrad:
7369         case EOpMethodSampleLevel:
7370         case EOpMethodLoad:
7371         case EOpMethodGetDimensions:
7372         case EOpMethodGetSamplePosition:
7373         case EOpMethodGather:
7374         case EOpMethodCalculateLevelOfDetail:
7375         case EOpMethodCalculateLevelOfDetailUnclamped:
7376         case EOpMethodGatherRed:
7377         case EOpMethodGatherGreen:
7378         case EOpMethodGatherBlue:
7379         case EOpMethodGatherAlpha:
7380         case EOpMethodGatherCmp:
7381         case EOpMethodGatherCmpRed:
7382         case EOpMethodGatherCmpGreen:
7383         case EOpMethodGatherCmpBlue:
7384         case EOpMethodGatherCmpAlpha:
7385         case EOpMethodAppend:
7386         case EOpMethodRestartStrip:
7387             // those are method calls, the object type can not be changed
7388             // they are equal if the dim and type match (is dim sufficient?)
7389             if (arg == 0)
7390                 return from.getSampler().type == to.getSampler().type &&
7391                        from.getSampler().arrayed == to.getSampler().arrayed &&
7392                        from.getSampler().shadow == to.getSampler().shadow &&
7393                        from.getSampler().ms == to.getSampler().ms &&
7394                        from.getSampler().dim == to.getSampler().dim;
7395             break;
7396         default:
7397             break;
7398         }
7399
7400         // basic types have to be convertible
7401         if (allowOnlyUpConversions)
7402             if (! intermediate.canImplicitlyPromote(from.getBasicType(), to.getBasicType(), EOpFunctionCall))
7403                 return false;
7404
7405         // shapes have to be convertible
7406         if ((from.isScalarOrVec1() && to.isScalarOrVec1()) ||
7407             (from.isScalarOrVec1() && to.isVector())    ||
7408             (from.isScalarOrVec1() && to.isMatrix())    ||
7409             (from.isVector() && to.isVector() && from.getVectorSize() >= to.getVectorSize()))
7410             return true;
7411
7412         // TODO: what are the matrix rules? they go here
7413
7414         return false;
7415     };
7416
7417     // Is 'to2' a better conversion than 'to1'?
7418     // Ties should not be considered as better.
7419     // Assumes 'convertible' already said true.
7420     const auto better = [](const TType& from, const TType& to1, const TType& to2) -> bool {
7421         // exact match is always better than mismatch
7422         if (from == to2)
7423             return from != to1;
7424         if (from == to1)
7425             return false;
7426
7427         // shape changes are always worse
7428         if (from.isScalar() || from.isVector()) {
7429             if (from.getVectorSize() == to2.getVectorSize() &&
7430                 from.getVectorSize() != to1.getVectorSize())
7431                 return true;
7432             if (from.getVectorSize() == to1.getVectorSize() &&
7433                 from.getVectorSize() != to2.getVectorSize())
7434                 return false;
7435         }
7436
7437         // Handle sampler betterness: An exact sampler match beats a non-exact match.
7438         // (If we just looked at basic type, all EbtSamplers would look the same).
7439         // If any type is not a sampler, just use the linearize function below.
7440         if (from.getBasicType() == EbtSampler && to1.getBasicType() == EbtSampler && to2.getBasicType() == EbtSampler) {
7441             // We can ignore the vector size in the comparison.
7442             TSampler to1Sampler = to1.getSampler();
7443             TSampler to2Sampler = to2.getSampler();
7444
7445             to1Sampler.vectorSize = to2Sampler.vectorSize = from.getSampler().vectorSize;
7446
7447             if (from.getSampler() == to2Sampler)
7448                 return from.getSampler() != to1Sampler;
7449             if (from.getSampler() == to1Sampler)
7450                 return false;
7451         }
7452
7453         // Might or might not be changing shape, which means basic type might
7454         // or might not match, so within that, the question is how big a
7455         // basic-type conversion is being done.
7456         //
7457         // Use a hierarchy of domains, translated to order of magnitude
7458         // in a linearized view:
7459         //   - floating-point vs. integer
7460         //     - 32 vs. 64 bit (or width in general)
7461         //       - bool vs. non bool
7462         //         - signed vs. not signed
7463         const auto linearize = [](const TBasicType& basicType) -> int {
7464             switch (basicType) {
7465             case EbtBool:     return 1;
7466             case EbtInt:      return 10;
7467             case EbtUint:     return 11;
7468             case EbtInt64:    return 20;
7469             case EbtUint64:   return 21;
7470             case EbtFloat:    return 100;
7471             case EbtDouble:   return 110;
7472             default:          return 0;
7473             }
7474         };
7475
7476         return abs(linearize(to2.getBasicType()) - linearize(from.getBasicType())) <
7477                abs(linearize(to1.getBasicType()) - linearize(from.getBasicType()));
7478     };
7479
7480     // for ambiguity reporting
7481     bool tie = false;
7482
7483     // send to the generic selector
7484     const TFunction* bestMatch = selectFunction(candidateList, call, convertible, better, tie);
7485
7486     if (bestMatch == nullptr) {
7487         // If there is nothing selected by allowing only up-conversions (to a larger linearize() value),
7488         // we instead try down-conversions, which are valid in HLSL, but not preferred if there are any
7489         // upconversions possible.
7490         allowOnlyUpConversions = false;
7491         bestMatch = selectFunction(candidateList, call, convertible, better, tie);
7492     }
7493
7494     if (bestMatch == nullptr) {
7495         error(loc, "no matching overloaded function found", call.getName().c_str(), "");
7496         return nullptr;
7497     }
7498
7499     // For built-ins, we can convert across the arguments.  This will happen in several steps:
7500     // Step 1:  If there's an exact match, use it.
7501     // Step 2a: Otherwise, get the operator from the best match and promote arguments:
7502     // Step 2b: reconstruct the TFunction based on the new arg types
7503     // Step 3:  Re-select after type promotion is applied, to find proper candidate.
7504     if (builtIn) {
7505         // Step 1: If there's an exact match, use it.
7506         if (call.getMangledName() == bestMatch->getMangledName())
7507             return bestMatch;
7508
7509         // Step 2a: Otherwise, get the operator from the best match and promote arguments as if we
7510         // are that kind of operator.
7511         if (args != nullptr) {
7512             // The arg list can be a unary node, or an aggregate.  We have to handle both.
7513             // We will use the normal promote() facilities, which require an interm node.
7514             TIntermOperator* promote = nullptr;
7515
7516             if (call.getParamCount() == 1) {
7517                 promote = new TIntermUnary(bestMatch->getBuiltInOp());
7518                 promote->getAsUnaryNode()->setOperand(args->getAsTyped());
7519             } else {
7520                 promote = new TIntermAggregate(bestMatch->getBuiltInOp());
7521                 promote->getAsAggregate()->getSequence().swap(args->getAsAggregate()->getSequence());
7522             }
7523
7524             if (! intermediate.promote(promote))
7525                 return nullptr;
7526
7527             // Obtain the promoted arg list.
7528             if (call.getParamCount() == 1) {
7529                 args = promote->getAsUnaryNode()->getOperand();
7530             } else {
7531                 promote->getAsAggregate()->getSequence().swap(args->getAsAggregate()->getSequence());
7532             }
7533         }
7534
7535         // Step 2b: reconstruct the TFunction based on the new arg types
7536         TFunction convertedCall(&call.getName(), call.getType(), call.getBuiltInOp());
7537
7538         if (args->getAsAggregate()) {
7539             // Handle aggregates: put all args into the new function call
7540             for (int arg=0; arg<int(args->getAsAggregate()->getSequence().size()); ++arg) {
7541                 // TODO: But for constness, we could avoid the new & shallowCopy, and use the pointer directly.
7542                 TParameter param = { 0, new TType, nullptr };
7543                 param.type->shallowCopy(args->getAsAggregate()->getSequence()[arg]->getAsTyped()->getType());
7544                 convertedCall.addParameter(param);
7545             }
7546         } else if (args->getAsUnaryNode()) {
7547             // Handle unaries: put all args into the new function call
7548             TParameter param = { 0, new TType, nullptr };
7549             param.type->shallowCopy(args->getAsUnaryNode()->getOperand()->getAsTyped()->getType());
7550             convertedCall.addParameter(param);
7551         } else if (args->getAsTyped()) {
7552             // Handle bare e.g, floats, not in an aggregate.
7553             TParameter param = { 0, new TType, nullptr };
7554             param.type->shallowCopy(args->getAsTyped()->getType());
7555             convertedCall.addParameter(param);
7556         } else {
7557             assert(0); // unknown argument list.
7558             return nullptr;
7559         }
7560
7561         // Step 3: Re-select after type promotion, to find proper candidate
7562         // send to the generic selector
7563         bestMatch = selectFunction(candidateList, convertedCall, convertible, better, tie);
7564
7565         // At this point, there should be no tie.
7566     }
7567
7568     if (tie)
7569         error(loc, "ambiguous best function under implicit type conversion", call.getName().c_str(), "");
7570
7571     // Append default parameter values if needed
7572     if (!tie && bestMatch != nullptr) {
7573         for (int defParam = call.getParamCount(); defParam < bestMatch->getParamCount(); ++defParam) {
7574             handleFunctionArgument(&call, args, (*bestMatch)[defParam].defaultValue);
7575         }
7576     }
7577
7578     return bestMatch;
7579 }
7580
7581 //
7582 // Do everything necessary to handle a typedef declaration, for a single symbol.
7583 //
7584 // 'parseType' is the type part of the declaration (to the left)
7585 // 'arraySizes' is the arrayness tagged on the identifier (to the right)
7586 //
7587 void HlslParseContext::declareTypedef(const TSourceLoc& loc, const TString& identifier, const TType& parseType)
7588 {
7589     TVariable* typeSymbol = new TVariable(&identifier, parseType, true);
7590     if (! symbolTable.insert(*typeSymbol))
7591         error(loc, "name already defined", "typedef", identifier.c_str());
7592 }
7593
7594 // Do everything necessary to handle a struct declaration, including
7595 // making IO aliases because HLSL allows mixed IO in a struct that specializes
7596 // based on the usage (input, output, uniform, none).
7597 void HlslParseContext::declareStruct(const TSourceLoc& loc, TString& structName, TType& type)
7598 {
7599     // If it was named, which means the type can be reused later, add
7600     // it to the symbol table.  (Unless it's a block, in which
7601     // case the name is not a type.)
7602     if (type.getBasicType() == EbtBlock || structName.size() == 0)
7603         return;
7604
7605     TVariable* userTypeDef = new TVariable(&structName, type, true);
7606     if (! symbolTable.insert(*userTypeDef)) {
7607         error(loc, "redefinition", structName.c_str(), "struct");
7608         return;
7609     }
7610
7611     // See if we need IO aliases for the structure typeList
7612
7613     const auto condAlloc = [](bool pred, TTypeList*& list) {
7614         if (pred && list == nullptr)
7615             list = new TTypeList;
7616     };
7617
7618     tIoKinds newLists = { nullptr, nullptr, nullptr }; // allocate for each kind found
7619     for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member) {
7620         condAlloc(hasUniform(member->type->getQualifier()), newLists.uniform);
7621         condAlloc(  hasInput(member->type->getQualifier()), newLists.input);
7622         condAlloc( hasOutput(member->type->getQualifier()), newLists.output);
7623
7624         if (member->type->isStruct()) {
7625             auto it = ioTypeMap.find(member->type->getStruct());
7626             if (it != ioTypeMap.end()) {
7627                 condAlloc(it->second.uniform != nullptr, newLists.uniform);
7628                 condAlloc(it->second.input   != nullptr, newLists.input);
7629                 condAlloc(it->second.output  != nullptr, newLists.output);
7630             }
7631         }
7632     }
7633     if (newLists.uniform == nullptr &&
7634         newLists.input   == nullptr &&
7635         newLists.output  == nullptr) {
7636         // Won't do any IO caching, clear up the type and get out now.
7637         for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member)
7638             clearUniformInputOutput(member->type->getQualifier());
7639         return;
7640     }
7641
7642     // We have IO involved.
7643
7644     // Make a pure typeList for the symbol table, and cache side copies of IO versions.
7645     for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member) {
7646         const auto inheritStruct = [&](TTypeList* s, TTypeLoc& ioMember) {
7647             if (s != nullptr) {
7648                 ioMember.type = new TType;
7649                 ioMember.type->shallowCopy(*member->type);
7650                 ioMember.type->setStruct(s);
7651             }
7652         };
7653         const auto newMember = [&](TTypeLoc& m) {
7654             if (m.type == nullptr) {
7655                 m.type = new TType;
7656                 m.type->shallowCopy(*member->type);
7657             }
7658         };
7659
7660         TTypeLoc newUniformMember = { nullptr, member->loc };
7661         TTypeLoc newInputMember   = { nullptr, member->loc };
7662         TTypeLoc newOutputMember  = { nullptr, member->loc };
7663         if (member->type->isStruct()) {
7664             // swap in an IO child if there is one
7665             auto it = ioTypeMap.find(member->type->getStruct());
7666             if (it != ioTypeMap.end()) {
7667                 inheritStruct(it->second.uniform, newUniformMember);
7668                 inheritStruct(it->second.input,   newInputMember);
7669                 inheritStruct(it->second.output,  newOutputMember);
7670             }
7671         }
7672         if (newLists.uniform) {
7673             newMember(newUniformMember);
7674
7675             // inherit default matrix layout (changeable via #pragma pack_matrix), if none given.
7676             if (member->type->isMatrix() && member->type->getQualifier().layoutMatrix == ElmNone)
7677                 newUniformMember.type->getQualifier().layoutMatrix = globalUniformDefaults.layoutMatrix;
7678
7679             correctUniform(newUniformMember.type->getQualifier());
7680             newLists.uniform->push_back(newUniformMember);
7681         }
7682         if (newLists.input) {
7683             newMember(newInputMember);
7684             correctInput(newInputMember.type->getQualifier());
7685             newLists.input->push_back(newInputMember);
7686         }
7687         if (newLists.output) {
7688             newMember(newOutputMember);
7689             correctOutput(newOutputMember.type->getQualifier());
7690             newLists.output->push_back(newOutputMember);
7691         }
7692
7693         // make original pure
7694         clearUniformInputOutput(member->type->getQualifier());
7695     }
7696     ioTypeMap[type.getStruct()] = newLists;
7697 }
7698
7699 // Lookup a user-type by name.
7700 // If found, fill in the type and return the defining symbol.
7701 // If not found, return nullptr.
7702 TSymbol* HlslParseContext::lookupUserType(const TString& typeName, TType& type)
7703 {
7704     TSymbol* symbol = symbolTable.find(typeName);
7705     if (symbol && symbol->getAsVariable() && symbol->getAsVariable()->isUserType()) {
7706         type.shallowCopy(symbol->getType());
7707         return symbol;
7708     } else
7709         return nullptr;
7710 }
7711
7712 //
7713 // Do everything necessary to handle a variable (non-block) declaration.
7714 // Either redeclaring a variable, or making a new one, updating the symbol
7715 // table, and all error checking.
7716 //
7717 // Returns a subtree node that computes an initializer, if needed.
7718 // Returns nullptr if there is no code to execute for initialization.
7719 //
7720 // 'parseType' is the type part of the declaration (to the left)
7721 // 'arraySizes' is the arrayness tagged on the identifier (to the right)
7722 //
7723 TIntermNode* HlslParseContext::declareVariable(const TSourceLoc& loc, const TString& identifier, TType& type,
7724                                                TIntermTyped* initializer)
7725 {
7726     if (voidErrorCheck(loc, identifier, type.getBasicType()))
7727         return nullptr;
7728
7729     // Global consts with initializers that are non-const act like EvqGlobal in HLSL.
7730     // This test is implicitly recursive, because initializers propagate constness
7731     // up the aggregate node tree during creation.  E.g, for:
7732     //    { { 1, 2 }, { 3, 4 } }
7733     // the initializer list is marked EvqConst at the top node, and remains so here.  However:
7734     //    { 1, { myvar, 2 }, 3 }
7735     // is not a const intializer, and still becomes EvqGlobal here.
7736
7737     const bool nonConstInitializer = (initializer != nullptr && initializer->getQualifier().storage != EvqConst);
7738
7739     if (type.getQualifier().storage == EvqConst && symbolTable.atGlobalLevel() && nonConstInitializer) {
7740         // Force to global
7741         type.getQualifier().storage = EvqGlobal;
7742     }
7743
7744     // make const and initialization consistent
7745     fixConstInit(loc, identifier, type, initializer);
7746
7747     // Check for redeclaration of built-ins and/or attempting to declare a reserved name
7748     TSymbol* symbol = nullptr;
7749
7750     inheritGlobalDefaults(type.getQualifier());
7751
7752     const bool flattenVar = shouldFlatten(type, type.getQualifier().storage, true);
7753
7754     // correct IO in the type
7755     switch (type.getQualifier().storage) {
7756     case EvqGlobal:
7757     case EvqTemporary:
7758         clearUniformInputOutput(type.getQualifier());
7759         break;
7760     case EvqUniform:
7761     case EvqBuffer:
7762         correctUniform(type.getQualifier());
7763         if (type.isStruct()) {
7764             auto it = ioTypeMap.find(type.getStruct());
7765             if (it != ioTypeMap.end())
7766                 type.setStruct(it->second.uniform);
7767         }
7768
7769         break;
7770     default:
7771         break;
7772     }
7773
7774     // Declare the variable
7775     if (type.isArray()) {
7776         // array case
7777         declareArray(loc, identifier, type, symbol, !flattenVar);
7778     } else {
7779         // non-array case
7780         if (symbol == nullptr)
7781             symbol = declareNonArray(loc, identifier, type, !flattenVar);
7782         else if (type != symbol->getType())
7783             error(loc, "cannot change the type of", "redeclaration", symbol->getName().c_str());
7784     }
7785
7786     if (symbol == nullptr)
7787         return nullptr;
7788
7789     if (flattenVar)
7790         flatten(*symbol->getAsVariable(), symbolTable.atGlobalLevel());
7791
7792     if (initializer == nullptr)
7793         return nullptr;
7794
7795     // Deal with initializer
7796     TVariable* variable = symbol->getAsVariable();
7797     if (variable == nullptr) {
7798         error(loc, "initializer requires a variable, not a member", identifier.c_str(), "");
7799         return nullptr;
7800     }
7801     return executeInitializer(loc, initializer, variable);
7802 }
7803
7804 // Pick up global defaults from the provide global defaults into dst.
7805 void HlslParseContext::inheritGlobalDefaults(TQualifier& dst) const
7806 {
7807     if (dst.storage == EvqVaryingOut) {
7808         if (! dst.hasStream() && language == EShLangGeometry)
7809             dst.layoutStream = globalOutputDefaults.layoutStream;
7810         if (! dst.hasXfbBuffer())
7811             dst.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
7812     }
7813 }
7814
7815 //
7816 // Make an internal-only variable whose name is for debug purposes only
7817 // and won't be searched for.  Callers will only use the return value to use
7818 // the variable, not the name to look it up.  It is okay if the name
7819 // is the same as other names; there won't be any conflict.
7820 //
7821 TVariable* HlslParseContext::makeInternalVariable(const char* name, const TType& type) const
7822 {
7823     TString* nameString = NewPoolTString(name);
7824     TVariable* variable = new TVariable(nameString, type);
7825     symbolTable.makeInternalVariable(*variable);
7826
7827     return variable;
7828 }
7829
7830 // Make a symbol node holding a new internal temporary variable.
7831 TIntermSymbol* HlslParseContext::makeInternalVariableNode(const TSourceLoc& loc, const char* name,
7832                                                           const TType& type) const
7833 {
7834     TVariable* tmpVar = makeInternalVariable(name, type);
7835     tmpVar->getWritableType().getQualifier().makeTemporary();
7836
7837     return intermediate.addSymbol(*tmpVar, loc);
7838 }
7839
7840 //
7841 // Declare a non-array variable, the main point being there is no redeclaration
7842 // for resizing allowed.
7843 //
7844 // Return the successfully declared variable.
7845 //
7846 TVariable* HlslParseContext::declareNonArray(const TSourceLoc& loc, const TString& identifier, const TType& type,
7847                                              bool track)
7848 {
7849     // make a new variable
7850     TVariable* variable = new TVariable(&identifier, type);
7851
7852     // add variable to symbol table
7853     if (symbolTable.insert(*variable)) {
7854         if (track && symbolTable.atGlobalLevel())
7855             trackLinkage(*variable);
7856         return variable;
7857     }
7858
7859     error(loc, "redefinition", variable->getName().c_str(), "");
7860     return nullptr;
7861 }
7862
7863 //
7864 // Handle all types of initializers from the grammar.
7865 //
7866 // Returning nullptr just means there is no code to execute to handle the
7867 // initializer, which will, for example, be the case for constant initializers.
7868 //
7869 // Returns a subtree that accomplished the initialization.
7870 //
7871 TIntermNode* HlslParseContext::executeInitializer(const TSourceLoc& loc, TIntermTyped* initializer, TVariable* variable)
7872 {
7873     //
7874     // Identifier must be of type constant, a global, or a temporary, and
7875     // starting at version 120, desktop allows uniforms to have initializers.
7876     //
7877     TStorageQualifier qualifier = variable->getType().getQualifier().storage;
7878
7879     //
7880     // If the initializer was from braces { ... }, we convert the whole subtree to a
7881     // constructor-style subtree, allowing the rest of the code to operate
7882     // identically for both kinds of initializers.
7883     //
7884     //
7885     // Type can't be deduced from the initializer list, so a skeletal type to
7886     // follow has to be passed in.  Constness and specialization-constness
7887     // should be deduced bottom up, not dictated by the skeletal type.
7888     //
7889     TType skeletalType;
7890     skeletalType.shallowCopy(variable->getType());
7891     skeletalType.getQualifier().makeTemporary();
7892     if (initializer->getAsAggregate() && initializer->getAsAggregate()->getOp() == EOpNull)
7893         initializer = convertInitializerList(loc, skeletalType, initializer, nullptr);
7894     if (initializer == nullptr) {
7895         // error recovery; don't leave const without constant values
7896         if (qualifier == EvqConst)
7897             variable->getWritableType().getQualifier().storage = EvqTemporary;
7898         return nullptr;
7899     }
7900
7901     // Fix outer arrayness if variable is unsized, getting size from the initializer
7902     if (initializer->getType().isSizedArray() && variable->getType().isUnsizedArray())
7903         variable->getWritableType().changeOuterArraySize(initializer->getType().getOuterArraySize());
7904
7905     // Inner arrayness can also get set by an initializer
7906     if (initializer->getType().isArrayOfArrays() && variable->getType().isArrayOfArrays() &&
7907         initializer->getType().getArraySizes()->getNumDims() ==
7908         variable->getType().getArraySizes()->getNumDims()) {
7909         // adopt unsized sizes from the initializer's sizes
7910         for (int d = 1; d < variable->getType().getArraySizes()->getNumDims(); ++d) {
7911             if (variable->getType().getArraySizes()->getDimSize(d) == UnsizedArraySize) {
7912                 variable->getWritableType().getArraySizes()->setDimSize(d,
7913                     initializer->getType().getArraySizes()->getDimSize(d));
7914             }
7915         }
7916     }
7917
7918     // Uniform and global consts require a constant initializer
7919     if (qualifier == EvqUniform && initializer->getType().getQualifier().storage != EvqConst) {
7920         error(loc, "uniform initializers must be constant", "=", "'%s'", variable->getType().getCompleteString().c_str());
7921         variable->getWritableType().getQualifier().storage = EvqTemporary;
7922         return nullptr;
7923     }
7924
7925     // Const variables require a constant initializer
7926     if (qualifier == EvqConst) {
7927         if (initializer->getType().getQualifier().storage != EvqConst) {
7928             variable->getWritableType().getQualifier().storage = EvqConstReadOnly;
7929             qualifier = EvqConstReadOnly;
7930         }
7931     }
7932
7933     if (qualifier == EvqConst || qualifier == EvqUniform) {
7934         // Compile-time tagging of the variable with its constant value...
7935
7936         initializer = intermediate.addConversion(EOpAssign, variable->getType(), initializer);
7937         if (initializer != nullptr && variable->getType() != initializer->getType())
7938             initializer = intermediate.addUniShapeConversion(EOpAssign, variable->getType(), initializer);
7939         if (initializer == nullptr || !initializer->getAsConstantUnion() ||
7940                                       variable->getType() != initializer->getType()) {
7941             error(loc, "non-matching or non-convertible constant type for const initializer",
7942                 variable->getType().getStorageQualifierString(), "");
7943             variable->getWritableType().getQualifier().storage = EvqTemporary;
7944             return nullptr;
7945         }
7946
7947         variable->setConstArray(initializer->getAsConstantUnion()->getConstArray());
7948     } else {
7949         // normal assigning of a value to a variable...
7950         specializationCheck(loc, initializer->getType(), "initializer");
7951         TIntermSymbol* intermSymbol = intermediate.addSymbol(*variable, loc);
7952         TIntermNode* initNode = handleAssign(loc, EOpAssign, intermSymbol, initializer);
7953         if (initNode == nullptr)
7954             assignError(loc, "=", intermSymbol->getCompleteString(), initializer->getCompleteString());
7955         return initNode;
7956     }
7957
7958     return nullptr;
7959 }
7960
7961 //
7962 // Reprocess any initializer-list { ... } parts of the initializer.
7963 // Need to hierarchically assign correct types and implicit
7964 // conversions. Will do this mimicking the same process used for
7965 // creating a constructor-style initializer, ensuring we get the
7966 // same form.
7967 //
7968 // Returns a node representing an expression for the initializer list expressed
7969 // as the correct type.
7970 //
7971 // Returns nullptr if there is an error.
7972 //
7973 TIntermTyped* HlslParseContext::convertInitializerList(const TSourceLoc& loc, const TType& type,
7974                                                        TIntermTyped* initializer, TIntermTyped* scalarInit)
7975 {
7976     // Will operate recursively.  Once a subtree is found that is constructor style,
7977     // everything below it is already good: Only the "top part" of the initializer
7978     // can be an initializer list, where "top part" can extend for several (or all) levels.
7979
7980     // see if we have bottomed out in the tree within the initializer-list part
7981     TIntermAggregate* initList = initializer->getAsAggregate();
7982     if (initList == nullptr || initList->getOp() != EOpNull) {
7983         // We don't have a list, but if it's a scalar and the 'type' is a
7984         // composite, we need to lengthen below to make it useful.
7985         // Otherwise, this is an already formed object to initialize with.
7986         if (type.isScalar() || !initializer->getType().isScalar())
7987             return initializer;
7988         else
7989             initList = intermediate.makeAggregate(initializer);
7990     }
7991
7992     // Of the initializer-list set of nodes, need to process bottom up,
7993     // so recurse deep, then process on the way up.
7994
7995     // Go down the tree here...
7996     if (type.isArray()) {
7997         // The type's array might be unsized, which could be okay, so base sizes on the size of the aggregate.
7998         // Later on, initializer execution code will deal with array size logic.
7999         TType arrayType;
8000         arrayType.shallowCopy(type);                     // sharing struct stuff is fine
8001         arrayType.copyArraySizes(*type.getArraySizes()); // but get a fresh copy of the array information, to edit below
8002
8003         // edit array sizes to fill in unsized dimensions
8004         if (type.isUnsizedArray())
8005             arrayType.changeOuterArraySize((int)initList->getSequence().size());
8006
8007         // set unsized array dimensions that can be derived from the initializer's first element
8008         if (arrayType.isArrayOfArrays() && initList->getSequence().size() > 0) {
8009             TIntermTyped* firstInit = initList->getSequence()[0]->getAsTyped();
8010             if (firstInit->getType().isArray() &&
8011                 arrayType.getArraySizes()->getNumDims() == firstInit->getType().getArraySizes()->getNumDims() + 1) {
8012                 for (int d = 1; d < arrayType.getArraySizes()->getNumDims(); ++d) {
8013                     if (arrayType.getArraySizes()->getDimSize(d) == UnsizedArraySize)
8014                         arrayType.getArraySizes()->setDimSize(d, firstInit->getType().getArraySizes()->getDimSize(d - 1));
8015                 }
8016             }
8017         }
8018
8019         // lengthen list to be long enough
8020         lengthenList(loc, initList->getSequence(), arrayType.getOuterArraySize(), scalarInit);
8021
8022         // recursively process each element
8023         TType elementType(arrayType, 0); // dereferenced type
8024         for (int i = 0; i < arrayType.getOuterArraySize(); ++i) {
8025             initList->getSequence()[i] = convertInitializerList(loc, elementType,
8026                                                                 initList->getSequence()[i]->getAsTyped(), scalarInit);
8027             if (initList->getSequence()[i] == nullptr)
8028                 return nullptr;
8029         }
8030
8031         return addConstructor(loc, initList, arrayType);
8032     } else if (type.isStruct()) {
8033         // do we have implicit assignments to opaques?
8034         for (size_t i = initList->getSequence().size(); i < type.getStruct()->size(); ++i) {
8035             if ((*type.getStruct())[i].type->containsOpaque()) {
8036                 error(loc, "cannot implicitly initialize opaque members", "initializer list", "");
8037                 return nullptr;
8038             }
8039         }
8040
8041         // lengthen list to be long enough
8042         lengthenList(loc, initList->getSequence(), static_cast<int>(type.getStruct()->size()), scalarInit);
8043
8044         if (type.getStruct()->size() != initList->getSequence().size()) {
8045             error(loc, "wrong number of structure members", "initializer list", "");
8046             return nullptr;
8047         }
8048         for (size_t i = 0; i < type.getStruct()->size(); ++i) {
8049             initList->getSequence()[i] = convertInitializerList(loc, *(*type.getStruct())[i].type,
8050                                                                 initList->getSequence()[i]->getAsTyped(), scalarInit);
8051             if (initList->getSequence()[i] == nullptr)
8052                 return nullptr;
8053         }
8054     } else if (type.isMatrix()) {
8055         if (type.computeNumComponents() == (int)initList->getSequence().size()) {
8056             // This means the matrix is initialized component-wise, rather than as
8057             // a series of rows and columns.  We can just use the list directly as
8058             // a constructor; no further processing needed.
8059         } else {
8060             // lengthen list to be long enough
8061             lengthenList(loc, initList->getSequence(), type.getMatrixCols(), scalarInit);
8062
8063             if (type.getMatrixCols() != (int)initList->getSequence().size()) {
8064                 error(loc, "wrong number of matrix columns:", "initializer list", type.getCompleteString().c_str());
8065                 return nullptr;
8066             }
8067             TType vectorType(type, 0); // dereferenced type
8068             for (int i = 0; i < type.getMatrixCols(); ++i) {
8069                 initList->getSequence()[i] = convertInitializerList(loc, vectorType,
8070                                                                     initList->getSequence()[i]->getAsTyped(), scalarInit);
8071                 if (initList->getSequence()[i] == nullptr)
8072                     return nullptr;
8073             }
8074         }
8075     } else if (type.isVector()) {
8076         // lengthen list to be long enough
8077         lengthenList(loc, initList->getSequence(), type.getVectorSize(), scalarInit);
8078
8079         // error check; we're at bottom, so work is finished below
8080         if (type.getVectorSize() != (int)initList->getSequence().size()) {
8081             error(loc, "wrong vector size (or rows in a matrix column):", "initializer list",
8082                   type.getCompleteString().c_str());
8083             return nullptr;
8084         }
8085     } else if (type.isScalar()) {
8086         // lengthen list to be long enough
8087         lengthenList(loc, initList->getSequence(), 1, scalarInit);
8088
8089         if ((int)initList->getSequence().size() != 1) {
8090             error(loc, "scalar expected one element:", "initializer list", type.getCompleteString().c_str());
8091             return nullptr;
8092         }
8093     } else {
8094         error(loc, "unexpected initializer-list type:", "initializer list", type.getCompleteString().c_str());
8095         return nullptr;
8096     }
8097
8098     // Now that the subtree is processed, process this node as if the
8099     // initializer list is a set of arguments to a constructor.
8100     TIntermTyped* emulatedConstructorArguments;
8101     if (initList->getSequence().size() == 1)
8102         emulatedConstructorArguments = initList->getSequence()[0]->getAsTyped();
8103     else
8104         emulatedConstructorArguments = initList;
8105
8106     return addConstructor(loc, emulatedConstructorArguments, type);
8107 }
8108
8109 // Lengthen list to be long enough to cover any gap from the current list size
8110 // to 'size'. If the list is longer, do nothing.
8111 // The value to lengthen with is the default for short lists.
8112 //
8113 // By default, lists that are too short due to lack of initializers initialize to zero.
8114 // Alternatively, it could be a scalar initializer for a structure. Both cases are handled,
8115 // based on whether something is passed in as 'scalarInit'.
8116 //
8117 // 'scalarInit' must be safe to use each time this is called (no side effects replication).
8118 //
8119 void HlslParseContext::lengthenList(const TSourceLoc& loc, TIntermSequence& list, int size, TIntermTyped* scalarInit)
8120 {
8121     for (int c = (int)list.size(); c < size; ++c) {
8122         if (scalarInit == nullptr)
8123             list.push_back(intermediate.addConstantUnion(0, loc));
8124         else
8125             list.push_back(scalarInit);
8126     }
8127 }
8128
8129 //
8130 // Test for the correctness of the parameters passed to various constructor functions
8131 // and also convert them to the right data type, if allowed and required.
8132 //
8133 // Returns nullptr for an error or the constructed node (aggregate or typed) for no error.
8134 //
8135 TIntermTyped* HlslParseContext::handleConstructor(const TSourceLoc& loc, TIntermTyped* node, const TType& type)
8136 {
8137     if (node == nullptr)
8138         return nullptr;
8139
8140     // Construct identical type
8141     if (type == node->getType())
8142         return node;
8143
8144     // Handle the idiom "(struct type)<scalar value>"
8145     if (type.isStruct() && isScalarConstructor(node)) {
8146         // 'node' will almost always get used multiple times, so should not be used directly,
8147         // it would create a DAG instead of a tree, which might be okay (would
8148         // like to formalize that for constants and symbols), but if it has
8149         // side effects, they would get executed multiple times, which is not okay.
8150         if (node->getAsConstantUnion() == nullptr && node->getAsSymbolNode() == nullptr) {
8151             TIntermAggregate* seq = intermediate.makeAggregate(loc);
8152             TIntermSymbol* copy = makeInternalVariableNode(loc, "scalarCopy", node->getType());
8153             seq = intermediate.growAggregate(seq, intermediate.addBinaryNode(EOpAssign, copy, node, loc));
8154             seq = intermediate.growAggregate(seq, convertInitializerList(loc, type, intermediate.makeAggregate(loc), copy));
8155             seq->setOp(EOpComma);
8156             seq->setType(type);
8157             return seq;
8158         } else
8159             return convertInitializerList(loc, type, intermediate.makeAggregate(loc), node);
8160     }
8161
8162     return addConstructor(loc, node, type);
8163 }
8164
8165 // Add a constructor, either from the grammar, or other programmatic reasons.
8166 //
8167 // 'node' is what to construct from.
8168 // 'type' is what type to construct.
8169 //
8170 // Returns the constructed object.
8171 // Return nullptr if it can't be done.
8172 //
8173 TIntermTyped* HlslParseContext::addConstructor(const TSourceLoc& loc, TIntermTyped* node, const TType& type)
8174 {
8175     TIntermAggregate* aggrNode = node->getAsAggregate();
8176     TOperator op = intermediate.mapTypeToConstructorOp(type);
8177
8178     // Combined texture-sampler constructors are completely semantic checked
8179     // in constructorTextureSamplerError()
8180     if (op == EOpConstructTextureSampler)
8181         return intermediate.setAggregateOperator(aggrNode, op, type, loc);
8182
8183     TTypeList::const_iterator memberTypes;
8184     if (op == EOpConstructStruct)
8185         memberTypes = type.getStruct()->begin();
8186
8187     TType elementType;
8188     if (type.isArray()) {
8189         TType dereferenced(type, 0);
8190         elementType.shallowCopy(dereferenced);
8191     } else
8192         elementType.shallowCopy(type);
8193
8194     bool singleArg;
8195     if (aggrNode != nullptr) {
8196         if (aggrNode->getOp() != EOpNull)
8197             singleArg = true;
8198         else
8199             singleArg = false;
8200     } else
8201         singleArg = true;
8202
8203     TIntermTyped *newNode;
8204     if (singleArg) {
8205         // Handle array -> array conversion
8206         // Constructing an array of one type from an array of another type is allowed,
8207         // assuming there are enough components available (semantic-checked earlier).
8208         if (type.isArray() && node->isArray())
8209             newNode = convertArray(node, type);
8210
8211         // If structure constructor or array constructor is being called
8212         // for only one parameter inside the aggregate, we need to call constructAggregate function once.
8213         else if (type.isArray())
8214             newNode = constructAggregate(node, elementType, 1, node->getLoc());
8215         else if (op == EOpConstructStruct)
8216             newNode = constructAggregate(node, *(*memberTypes).type, 1, node->getLoc());
8217         else {
8218             // shape conversion for matrix constructor from scalar.  HLSL semantics are: scalar
8219             // is replicated into every element of the matrix (not just the diagnonal), so
8220             // that is handled specially here.
8221             if (type.isMatrix() && node->getType().isScalarOrVec1())
8222                 node = intermediate.addShapeConversion(type, node);
8223
8224             newNode = constructBuiltIn(type, op, node, node->getLoc(), false);
8225         }
8226
8227         if (newNode && (type.isArray() || op == EOpConstructStruct))
8228             newNode = intermediate.setAggregateOperator(newNode, EOpConstructStruct, type, loc);
8229
8230         return newNode;
8231     }
8232
8233     //
8234     // Handle list of arguments.
8235     //
8236     TIntermSequence& sequenceVector = aggrNode->getSequence();    // Stores the information about the parameter to the constructor
8237     // if the structure constructor contains more than one parameter, then construct
8238     // each parameter
8239
8240     int paramCount = 0;  // keeps a track of the constructor parameter number being checked
8241
8242     // for each parameter to the constructor call, check to see if the right type is passed or convert them
8243     // to the right type if possible (and allowed).
8244     // for structure constructors, just check if the right type is passed, no conversion is allowed.
8245
8246     for (TIntermSequence::iterator p = sequenceVector.begin();
8247         p != sequenceVector.end(); p++, paramCount++) {
8248         if (type.isArray())
8249             newNode = constructAggregate(*p, elementType, paramCount + 1, node->getLoc());
8250         else if (op == EOpConstructStruct)
8251             newNode = constructAggregate(*p, *(memberTypes[paramCount]).type, paramCount + 1, node->getLoc());
8252         else
8253             newNode = constructBuiltIn(type, op, (*p)->getAsTyped(), node->getLoc(), true);
8254
8255         if (newNode)
8256             *p = newNode;
8257         else
8258             return nullptr;
8259     }
8260
8261     TIntermTyped* constructor = intermediate.setAggregateOperator(aggrNode, op, type, loc);
8262
8263     return constructor;
8264 }
8265
8266 // Function for constructor implementation. Calls addUnaryMath with appropriate EOp value
8267 // for the parameter to the constructor (passed to this function). Essentially, it converts
8268 // the parameter types correctly. If a constructor expects an int (like ivec2) and is passed a
8269 // float, then float is converted to int.
8270 //
8271 // Returns nullptr for an error or the constructed node.
8272 //
8273 TIntermTyped* HlslParseContext::constructBuiltIn(const TType& type, TOperator op, TIntermTyped* node,
8274                                                  const TSourceLoc& loc, bool subset)
8275 {
8276     TIntermTyped* newNode;
8277     TOperator basicOp;
8278
8279     //
8280     // First, convert types as needed.
8281     //
8282     switch (op) {
8283     case EOpConstructF16Vec2:
8284     case EOpConstructF16Vec3:
8285     case EOpConstructF16Vec4:
8286     case EOpConstructF16Mat2x2:
8287     case EOpConstructF16Mat2x3:
8288     case EOpConstructF16Mat2x4:
8289     case EOpConstructF16Mat3x2:
8290     case EOpConstructF16Mat3x3:
8291     case EOpConstructF16Mat3x4:
8292     case EOpConstructF16Mat4x2:
8293     case EOpConstructF16Mat4x3:
8294     case EOpConstructF16Mat4x4:
8295     case EOpConstructFloat16:
8296         basicOp = EOpConstructFloat16;
8297         break;
8298
8299     case EOpConstructVec2:
8300     case EOpConstructVec3:
8301     case EOpConstructVec4:
8302     case EOpConstructMat2x2:
8303     case EOpConstructMat2x3:
8304     case EOpConstructMat2x4:
8305     case EOpConstructMat3x2:
8306     case EOpConstructMat3x3:
8307     case EOpConstructMat3x4:
8308     case EOpConstructMat4x2:
8309     case EOpConstructMat4x3:
8310     case EOpConstructMat4x4:
8311     case EOpConstructFloat:
8312         basicOp = EOpConstructFloat;
8313         break;
8314
8315     case EOpConstructDVec2:
8316     case EOpConstructDVec3:
8317     case EOpConstructDVec4:
8318     case EOpConstructDMat2x2:
8319     case EOpConstructDMat2x3:
8320     case EOpConstructDMat2x4:
8321     case EOpConstructDMat3x2:
8322     case EOpConstructDMat3x3:
8323     case EOpConstructDMat3x4:
8324     case EOpConstructDMat4x2:
8325     case EOpConstructDMat4x3:
8326     case EOpConstructDMat4x4:
8327     case EOpConstructDouble:
8328         basicOp = EOpConstructDouble;
8329         break;
8330
8331     case EOpConstructI16Vec2:
8332     case EOpConstructI16Vec3:
8333     case EOpConstructI16Vec4:
8334     case EOpConstructInt16:
8335         basicOp = EOpConstructInt16;
8336         break;
8337
8338     case EOpConstructIVec2:
8339     case EOpConstructIVec3:
8340     case EOpConstructIVec4:
8341     case EOpConstructIMat2x2:
8342     case EOpConstructIMat2x3:
8343     case EOpConstructIMat2x4:
8344     case EOpConstructIMat3x2:
8345     case EOpConstructIMat3x3:
8346     case EOpConstructIMat3x4:
8347     case EOpConstructIMat4x2:
8348     case EOpConstructIMat4x3:
8349     case EOpConstructIMat4x4:
8350     case EOpConstructInt:
8351         basicOp = EOpConstructInt;
8352         break;
8353
8354     case EOpConstructU16Vec2:
8355     case EOpConstructU16Vec3:
8356     case EOpConstructU16Vec4:
8357     case EOpConstructUint16:
8358         basicOp = EOpConstructUint16;
8359         break;
8360
8361     case EOpConstructUVec2:
8362     case EOpConstructUVec3:
8363     case EOpConstructUVec4:
8364     case EOpConstructUMat2x2:
8365     case EOpConstructUMat2x3:
8366     case EOpConstructUMat2x4:
8367     case EOpConstructUMat3x2:
8368     case EOpConstructUMat3x3:
8369     case EOpConstructUMat3x4:
8370     case EOpConstructUMat4x2:
8371     case EOpConstructUMat4x3:
8372     case EOpConstructUMat4x4:
8373     case EOpConstructUint:
8374         basicOp = EOpConstructUint;
8375         break;
8376
8377     case EOpConstructBVec2:
8378     case EOpConstructBVec3:
8379     case EOpConstructBVec4:
8380     case EOpConstructBMat2x2:
8381     case EOpConstructBMat2x3:
8382     case EOpConstructBMat2x4:
8383     case EOpConstructBMat3x2:
8384     case EOpConstructBMat3x3:
8385     case EOpConstructBMat3x4:
8386     case EOpConstructBMat4x2:
8387     case EOpConstructBMat4x3:
8388     case EOpConstructBMat4x4:
8389     case EOpConstructBool:
8390         basicOp = EOpConstructBool;
8391         break;
8392
8393     default:
8394         error(loc, "unsupported construction", "", "");
8395
8396         return nullptr;
8397     }
8398     newNode = intermediate.addUnaryMath(basicOp, node, node->getLoc());
8399     if (newNode == nullptr) {
8400         error(loc, "can't convert", "constructor", "");
8401         return nullptr;
8402     }
8403
8404     //
8405     // Now, if there still isn't an operation to do the construction, and we need one, add one.
8406     //
8407
8408     // Otherwise, skip out early.
8409     if (subset || (newNode != node && newNode->getType() == type))
8410         return newNode;
8411
8412     // setAggregateOperator will insert a new node for the constructor, as needed.
8413     return intermediate.setAggregateOperator(newNode, op, type, loc);
8414 }
8415
8416 // Convert the array in node to the requested type, which is also an array.
8417 // Returns nullptr on failure, otherwise returns aggregate holding the list of
8418 // elements needed to construct the array.
8419 TIntermTyped* HlslParseContext::convertArray(TIntermTyped* node, const TType& type)
8420 {
8421     assert(node->isArray() && type.isArray());
8422     if (node->getType().computeNumComponents() < type.computeNumComponents())
8423         return nullptr;
8424
8425     // TODO: write an argument replicator, for the case the argument should not be
8426     // executed multiple times, yet multiple copies are needed.
8427
8428     TIntermTyped* constructee = node->getAsTyped();
8429     // track where we are in consuming the argument
8430     int constructeeElement = 0;
8431     int constructeeComponent = 0;
8432
8433     // bump up to the next component to consume
8434     const auto getNextComponent = [&]() {
8435         TIntermTyped* component;
8436         component = handleBracketDereference(node->getLoc(), constructee, 
8437                                              intermediate.addConstantUnion(constructeeElement, node->getLoc()));
8438         if (component->isVector())
8439             component = handleBracketDereference(node->getLoc(), component,
8440                                                  intermediate.addConstantUnion(constructeeComponent, node->getLoc()));
8441         // bump component pointer up
8442         ++constructeeComponent;
8443         if (constructeeComponent == constructee->getVectorSize()) {
8444             constructeeComponent = 0;
8445             ++constructeeElement;
8446         }
8447         return component;
8448     };
8449
8450     // make one subnode per constructed array element
8451     TIntermAggregate* constructor = nullptr;
8452     TType derefType(type, 0);
8453     TType speculativeComponentType(derefType, 0);
8454     TType* componentType = derefType.isVector() ? &speculativeComponentType : &derefType;
8455     TOperator componentOp = intermediate.mapTypeToConstructorOp(*componentType);
8456     TType crossType(node->getBasicType(), EvqTemporary, type.getVectorSize());
8457     for (int e = 0; e < type.getOuterArraySize(); ++e) {
8458         // construct an element
8459         TIntermTyped* elementArg;
8460         if (type.getVectorSize() == constructee->getVectorSize()) {
8461             // same element shape
8462             elementArg = handleBracketDereference(node->getLoc(), constructee,
8463                                                   intermediate.addConstantUnion(e, node->getLoc()));
8464         } else {
8465             // mismatched element shapes
8466             if (type.getVectorSize() == 1)
8467                 elementArg = getNextComponent();
8468             else {
8469                 // make a vector
8470                 TIntermAggregate* elementConstructee = nullptr;
8471                 for (int c = 0; c < type.getVectorSize(); ++c)
8472                     elementConstructee = intermediate.growAggregate(elementConstructee, getNextComponent());
8473                 elementArg = addConstructor(node->getLoc(), elementConstructee, crossType);
8474             }
8475         }
8476         // convert basic types
8477         elementArg = intermediate.addConversion(componentOp, derefType, elementArg);
8478         if (elementArg == nullptr)
8479             return nullptr;
8480         // combine with top-level constructor
8481         constructor = intermediate.growAggregate(constructor, elementArg);
8482     }
8483
8484     return constructor;
8485 }
8486
8487 // This function tests for the type of the parameters to the structure or array constructor. Raises
8488 // an error message if the expected type does not match the parameter passed to the constructor.
8489 //
8490 // Returns nullptr for an error or the input node itself if the expected and the given parameter types match.
8491 //
8492 TIntermTyped* HlslParseContext::constructAggregate(TIntermNode* node, const TType& type, int paramCount,
8493                                                    const TSourceLoc& loc)
8494 {
8495     // Handle cases that map more 1:1 between constructor arguments and constructed.
8496     TIntermTyped* converted = intermediate.addConversion(EOpConstructStruct, type, node->getAsTyped());
8497     if (converted == nullptr || converted->getType() != type) {
8498         error(loc, "", "constructor", "cannot convert parameter %d from '%s' to '%s'", paramCount,
8499             node->getAsTyped()->getType().getCompleteString().c_str(), type.getCompleteString().c_str());
8500
8501         return nullptr;
8502     }
8503
8504     return converted;
8505 }
8506
8507 //
8508 // Do everything needed to add an interface block.
8509 //
8510 void HlslParseContext::declareBlock(const TSourceLoc& loc, TType& type, const TString* instanceName)
8511 {
8512     assert(type.getWritableStruct() != nullptr);
8513
8514     // Clean up top-level decorations that don't belong.
8515     switch (type.getQualifier().storage) {
8516     case EvqUniform:
8517     case EvqBuffer:
8518         correctUniform(type.getQualifier());
8519         break;
8520     case EvqVaryingIn:
8521         correctInput(type.getQualifier());
8522         break;
8523     case EvqVaryingOut:
8524         correctOutput(type.getQualifier());
8525         break;
8526     default:
8527         break;
8528     }
8529
8530     TTypeList& typeList = *type.getWritableStruct();
8531     // fix and check for member storage qualifiers and types that don't belong within a block
8532     for (unsigned int member = 0; member < typeList.size(); ++member) {
8533         TType& memberType = *typeList[member].type;
8534         TQualifier& memberQualifier = memberType.getQualifier();
8535         const TSourceLoc& memberLoc = typeList[member].loc;
8536         globalQualifierFix(memberLoc, memberQualifier);
8537         memberQualifier.storage = type.getQualifier().storage;
8538
8539         if (memberType.isStruct()) {
8540             // clean up and pick up the right set of decorations
8541             auto it = ioTypeMap.find(memberType.getStruct());
8542             switch (type.getQualifier().storage) {
8543             case EvqUniform:
8544             case EvqBuffer:
8545                 correctUniform(type.getQualifier());
8546                 if (it != ioTypeMap.end() && it->second.uniform)
8547                     memberType.setStruct(it->second.uniform);
8548                 break;
8549             case EvqVaryingIn:
8550                 correctInput(type.getQualifier());
8551                 if (it != ioTypeMap.end() && it->second.input)
8552                     memberType.setStruct(it->second.input);
8553                 break;
8554             case EvqVaryingOut:
8555                 correctOutput(type.getQualifier());
8556                 if (it != ioTypeMap.end() && it->second.output)
8557                     memberType.setStruct(it->second.output);
8558                 break;
8559             default:
8560                 break;
8561             }
8562         }
8563     }
8564
8565     // Make default block qualification, and adjust the member qualifications
8566
8567     TQualifier defaultQualification;
8568     switch (type.getQualifier().storage) {
8569     case EvqUniform:    defaultQualification = globalUniformDefaults;    break;
8570     case EvqBuffer:     defaultQualification = globalBufferDefaults;     break;
8571     case EvqVaryingIn:  defaultQualification = globalInputDefaults;      break;
8572     case EvqVaryingOut: defaultQualification = globalOutputDefaults;     break;
8573     default:            defaultQualification.clear();                    break;
8574     }
8575
8576     // Special case for "push_constant uniform", which has a default of std430,
8577     // contrary to normal uniform defaults, and can't have a default tracked for it.
8578     if (type.getQualifier().layoutPushConstant && ! type.getQualifier().hasPacking())
8579         type.getQualifier().layoutPacking = ElpStd430;
8580
8581     // fix and check for member layout qualifiers
8582
8583     mergeObjectLayoutQualifiers(defaultQualification, type.getQualifier(), true);
8584
8585     bool memberWithLocation = false;
8586     bool memberWithoutLocation = false;
8587     for (unsigned int member = 0; member < typeList.size(); ++member) {
8588         TQualifier& memberQualifier = typeList[member].type->getQualifier();
8589         const TSourceLoc& memberLoc = typeList[member].loc;
8590         if (memberQualifier.hasStream()) {
8591             if (defaultQualification.layoutStream != memberQualifier.layoutStream)
8592                 error(memberLoc, "member cannot contradict block", "stream", "");
8593         }
8594
8595         // "This includes a block's inheritance of the
8596         // current global default buffer, a block member's inheritance of the block's
8597         // buffer, and the requirement that any *xfb_buffer* declared on a block
8598         // member must match the buffer inherited from the block."
8599         if (memberQualifier.hasXfbBuffer()) {
8600             if (defaultQualification.layoutXfbBuffer != memberQualifier.layoutXfbBuffer)
8601                 error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_buffer", "");
8602         }
8603
8604         if (memberQualifier.hasLocation()) {
8605             switch (type.getQualifier().storage) {
8606             case EvqVaryingIn:
8607             case EvqVaryingOut:
8608                 memberWithLocation = true;
8609                 break;
8610             default:
8611                 break;
8612             }
8613         } else
8614             memberWithoutLocation = true;
8615
8616         TQualifier newMemberQualification = defaultQualification;
8617         mergeQualifiers(newMemberQualification, memberQualifier);
8618         memberQualifier = newMemberQualification;
8619     }
8620
8621     // Process the members
8622     fixBlockLocations(loc, type.getQualifier(), typeList, memberWithLocation, memberWithoutLocation);
8623     fixBlockXfbOffsets(type.getQualifier(), typeList);
8624     fixBlockUniformOffsets(type.getQualifier(), typeList);
8625
8626     // reverse merge, so that currentBlockQualifier now has all layout information
8627     // (can't use defaultQualification directly, it's missing other non-layout-default-class qualifiers)
8628     mergeObjectLayoutQualifiers(type.getQualifier(), defaultQualification, true);
8629
8630     //
8631     // Build and add the interface block as a new type named 'blockName'
8632     //
8633
8634     // Use the instance name as the interface name if one exists, else the block name.
8635     const TString& interfaceName = (instanceName && !instanceName->empty()) ? *instanceName : type.getTypeName();
8636
8637     TType blockType(&typeList, interfaceName, type.getQualifier());
8638     if (type.isArray())
8639         blockType.transferArraySizes(type.getArraySizes());
8640
8641     // Add the variable, as anonymous or named instanceName.
8642     // Make an anonymous variable if no name was provided.
8643     if (instanceName == nullptr)
8644         instanceName = NewPoolTString("");
8645
8646     TVariable& variable = *new TVariable(instanceName, blockType);
8647     if (! symbolTable.insert(variable)) {
8648         if (*instanceName == "")
8649             error(loc, "nameless block contains a member that already has a name at global scope",
8650                   "" /* blockName->c_str() */, "");
8651         else
8652             error(loc, "block instance name redefinition", variable.getName().c_str(), "");
8653
8654         return;
8655     }
8656
8657     // Save it in the AST for linker use.
8658     if (symbolTable.atGlobalLevel())
8659         trackLinkage(variable);
8660 }
8661
8662 //
8663 // "For a block, this process applies to the entire block, or until the first member
8664 // is reached that has a location layout qualifier. When a block member is declared with a location
8665 // qualifier, its location comes from that qualifier: The member's location qualifier overrides the block-level
8666 // declaration. Subsequent members are again assigned consecutive locations, based on the newest location,
8667 // until the next member declared with a location qualifier. The values used for locations do not have to be
8668 // declared in increasing order."
8669 void HlslParseContext::fixBlockLocations(const TSourceLoc& loc, TQualifier& qualifier, TTypeList& typeList, bool memberWithLocation, bool memberWithoutLocation)
8670 {
8671     // "If a block has no block-level location layout qualifier, it is required that either all or none of its members
8672     // have a location layout qualifier, or a compile-time error results."
8673     if (! qualifier.hasLocation() && memberWithLocation && memberWithoutLocation)
8674         error(loc, "either the block needs a location, or all members need a location, or no members have a location", "location", "");
8675     else {
8676         if (memberWithLocation) {
8677             // remove any block-level location and make it per *every* member
8678             int nextLocation = 0;  // by the rule above, initial value is not relevant
8679             if (qualifier.hasAnyLocation()) {
8680                 nextLocation = qualifier.layoutLocation;
8681                 qualifier.layoutLocation = TQualifier::layoutLocationEnd;
8682                 if (qualifier.hasComponent()) {
8683                     // "It is a compile-time error to apply the *component* qualifier to a ... block"
8684                     error(loc, "cannot apply to a block", "component", "");
8685                 }
8686                 if (qualifier.hasIndex()) {
8687                     error(loc, "cannot apply to a block", "index", "");
8688                 }
8689             }
8690             for (unsigned int member = 0; member < typeList.size(); ++member) {
8691                 TQualifier& memberQualifier = typeList[member].type->getQualifier();
8692                 const TSourceLoc& memberLoc = typeList[member].loc;
8693                 if (! memberQualifier.hasLocation()) {
8694                     if (nextLocation >= (int)TQualifier::layoutLocationEnd)
8695                         error(memberLoc, "location is too large", "location", "");
8696                     memberQualifier.layoutLocation = nextLocation;
8697                     memberQualifier.layoutComponent = 0;
8698                 }
8699                 nextLocation = memberQualifier.layoutLocation +
8700                                intermediate.computeTypeLocationSize(*typeList[member].type, language);
8701             }
8702         }
8703     }
8704 }
8705
8706 void HlslParseContext::fixBlockXfbOffsets(TQualifier& qualifier, TTypeList& typeList)
8707 {
8708     // "If a block is qualified with xfb_offset, all its
8709     // members are assigned transform feedback buffer offsets. If a block is not qualified with xfb_offset, any
8710     // members of that block not qualified with an xfb_offset will not be assigned transform feedback buffer
8711     // offsets."
8712
8713     if (! qualifier.hasXfbBuffer() || ! qualifier.hasXfbOffset())
8714         return;
8715
8716     int nextOffset = qualifier.layoutXfbOffset;
8717     for (unsigned int member = 0; member < typeList.size(); ++member) {
8718         TQualifier& memberQualifier = typeList[member].type->getQualifier();
8719         bool containsDouble = false;
8720         int memberSize = intermediate.computeTypeXfbSize(*typeList[member].type, containsDouble);
8721         // see if we need to auto-assign an offset to this member
8722         if (! memberQualifier.hasXfbOffset()) {
8723             // "if applied to an aggregate containing a double, the offset must also be a multiple of 8"
8724             if (containsDouble)
8725                 RoundToPow2(nextOffset, 8);
8726             memberQualifier.layoutXfbOffset = nextOffset;
8727         } else
8728             nextOffset = memberQualifier.layoutXfbOffset;
8729         nextOffset += memberSize;
8730     }
8731
8732     // The above gave all block members an offset, so we can take it off the block now,
8733     // which will avoid double counting the offset usage.
8734     qualifier.layoutXfbOffset = TQualifier::layoutXfbOffsetEnd;
8735 }
8736
8737 // Calculate and save the offset of each block member, using the recursively
8738 // defined block offset rules and the user-provided offset and align.
8739 //
8740 // Also, compute and save the total size of the block. For the block's size, arrayness
8741 // is not taken into account, as each element is backed by a separate buffer.
8742 //
8743 void HlslParseContext::fixBlockUniformOffsets(const TQualifier& qualifier, TTypeList& typeList)
8744 {
8745     if (! qualifier.isUniformOrBuffer())
8746         return;
8747     if (qualifier.layoutPacking != ElpStd140 && qualifier.layoutPacking != ElpStd430)
8748         return;
8749
8750     int offset = 0;
8751     int memberSize;
8752     for (unsigned int member = 0; member < typeList.size(); ++member) {
8753         TQualifier& memberQualifier = typeList[member].type->getQualifier();
8754         const TSourceLoc& memberLoc = typeList[member].loc;
8755
8756         // "When align is applied to an array, it effects only the start of the array, not the array's internal stride."
8757
8758         // modify just the children's view of matrix layout, if there is one for this member
8759         TLayoutMatrix subMatrixLayout = typeList[member].type->getQualifier().layoutMatrix;
8760         int dummyStride;
8761         int memberAlignment = intermediate.getBaseAlignment(*typeList[member].type, memberSize, dummyStride,
8762                                                             qualifier.layoutPacking == ElpStd140,
8763                                                             subMatrixLayout != ElmNone
8764                                                                 ? subMatrixLayout == ElmRowMajor
8765                                                                 : qualifier.layoutMatrix == ElmRowMajor);
8766         if (memberQualifier.hasOffset()) {
8767             // "The specified offset must be a multiple
8768             // of the base alignment of the type of the block member it qualifies, or a compile-time error results."
8769             if (! IsMultipleOfPow2(memberQualifier.layoutOffset, memberAlignment))
8770                 error(memberLoc, "must be a multiple of the member's alignment", "offset", "");
8771
8772             // "The offset qualifier forces the qualified member to start at or after the specified
8773             // integral-constant expression, which will be its byte offset from the beginning of the buffer.
8774             // "The actual offset of a member is computed as
8775             // follows: If offset was declared, start with that offset, otherwise start with the next available offset."
8776             offset = std::max(offset, memberQualifier.layoutOffset);
8777         }
8778
8779         // "The actual alignment of a member will be the greater of the specified align alignment and the standard
8780         // (e.g., std140) base alignment for the member's type."
8781         if (memberQualifier.hasAlign())
8782             memberAlignment = std::max(memberAlignment, memberQualifier.layoutAlign);
8783
8784         // "If the resulting offset is not a multiple of the actual alignment,
8785         // increase it to the first offset that is a multiple of
8786         // the actual alignment."
8787         RoundToPow2(offset, memberAlignment);
8788         typeList[member].type->getQualifier().layoutOffset = offset;
8789         offset += memberSize;
8790     }
8791 }
8792
8793 // For an identifier that is already declared, add more qualification to it.
8794 void HlslParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, const TString& identifier)
8795 {
8796     TSymbol* symbol = symbolTable.find(identifier);
8797     if (symbol == nullptr) {
8798         error(loc, "identifier not previously declared", identifier.c_str(), "");
8799         return;
8800     }
8801     if (symbol->getAsFunction()) {
8802         error(loc, "cannot re-qualify a function name", identifier.c_str(), "");
8803         return;
8804     }
8805
8806     if (qualifier.isAuxiliary() ||
8807         qualifier.isMemory() ||
8808         qualifier.isInterpolation() ||
8809         qualifier.hasLayout() ||
8810         qualifier.storage != EvqTemporary ||
8811         qualifier.precision != EpqNone) {
8812         error(loc, "cannot add storage, auxiliary, memory, interpolation, layout, or precision qualifier to an existing variable", identifier.c_str(), "");
8813         return;
8814     }
8815
8816     // For read-only built-ins, add a new symbol for holding the modified qualifier.
8817     // This will bring up an entire block, if a block type has to be modified (e.g., gl_Position inside a block)
8818     if (symbol->isReadOnly())
8819         symbol = symbolTable.copyUp(symbol);
8820
8821     if (qualifier.invariant) {
8822         if (intermediate.inIoAccessed(identifier))
8823             error(loc, "cannot change qualification after use", "invariant", "");
8824         symbol->getWritableType().getQualifier().invariant = true;
8825     } else if (qualifier.noContraction) {
8826         if (intermediate.inIoAccessed(identifier))
8827             error(loc, "cannot change qualification after use", "precise", "");
8828         symbol->getWritableType().getQualifier().noContraction = true;
8829     } else if (qualifier.specConstant) {
8830         symbol->getWritableType().getQualifier().makeSpecConstant();
8831         if (qualifier.hasSpecConstantId())
8832             symbol->getWritableType().getQualifier().layoutSpecConstantId = qualifier.layoutSpecConstantId;
8833     } else
8834         warn(loc, "unknown requalification", "", "");
8835 }
8836
8837 void HlslParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, TIdentifierList& identifiers)
8838 {
8839     for (unsigned int i = 0; i < identifiers.size(); ++i)
8840         addQualifierToExisting(loc, qualifier, *identifiers[i]);
8841 }
8842
8843 //
8844 // Update the intermediate for the given input geometry
8845 //
8846 bool HlslParseContext::handleInputGeometry(const TSourceLoc& loc, const TLayoutGeometry& geometry)
8847 {
8848     switch (geometry) {
8849     case ElgPoints:             // fall through
8850     case ElgLines:              // ...
8851     case ElgTriangles:          // ...
8852     case ElgLinesAdjacency:     // ...
8853     case ElgTrianglesAdjacency: // ...
8854         if (! intermediate.setInputPrimitive(geometry)) {
8855             error(loc, "input primitive geometry redefinition", TQualifier::getGeometryString(geometry), "");
8856             return false;
8857         }
8858         break;
8859
8860     default:
8861         error(loc, "cannot apply to 'in'", TQualifier::getGeometryString(geometry), "");
8862         return false;
8863     }
8864
8865     return true;
8866 }
8867
8868 //
8869 // Update the intermediate for the given output geometry
8870 //
8871 bool HlslParseContext::handleOutputGeometry(const TSourceLoc& loc, const TLayoutGeometry& geometry)
8872 {
8873     // If this is not a geometry shader, ignore.  It might be a mixed shader including several stages.
8874     // Since that's an OK situation, return true for success.
8875     if (language != EShLangGeometry)
8876         return true;
8877
8878     switch (geometry) {
8879     case ElgPoints:
8880     case ElgLineStrip:
8881     case ElgTriangleStrip:
8882         if (! intermediate.setOutputPrimitive(geometry)) {
8883             error(loc, "output primitive geometry redefinition", TQualifier::getGeometryString(geometry), "");
8884             return false;
8885         }
8886         break;
8887     default:
8888         error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(geometry), "");
8889         return false;
8890     }
8891
8892     return true;
8893 }
8894
8895 //
8896 // Selection attributes
8897 //
8898 void HlslParseContext::handleSelectionAttributes(const TSourceLoc& loc, TIntermSelection* selection,
8899     const TAttributes& attributes)
8900 {
8901     if (selection == nullptr)
8902         return;
8903
8904     for (auto it = attributes.begin(); it != attributes.end(); ++it) {
8905         switch (it->name) {
8906         case EatFlatten:
8907             selection->setFlatten();
8908             break;
8909         case EatBranch:
8910             selection->setDontFlatten();
8911             break;
8912         default:
8913             warn(loc, "attribute does not apply to a selection", "", "");
8914             break;
8915         }
8916     }
8917 }
8918
8919 //
8920 // Switch attributes
8921 //
8922 void HlslParseContext::handleSwitchAttributes(const TSourceLoc& loc, TIntermSwitch* selection,
8923     const TAttributes& attributes)
8924 {
8925     if (selection == nullptr)
8926         return;
8927
8928     for (auto it = attributes.begin(); it != attributes.end(); ++it) {
8929         switch (it->name) {
8930         case EatFlatten:
8931             selection->setFlatten();
8932             break;
8933         case EatBranch:
8934             selection->setDontFlatten();
8935             break;
8936         default:
8937             warn(loc, "attribute does not apply to a switch", "", "");
8938             break;
8939         }
8940     }
8941 }
8942
8943 //
8944 // Loop attributes
8945 //
8946 void HlslParseContext::handleLoopAttributes(const TSourceLoc& loc, TIntermLoop* loop,
8947     const TAttributes& attributes)
8948 {
8949     if (loop == nullptr)
8950         return;
8951
8952     for (auto it = attributes.begin(); it != attributes.end(); ++it) {
8953         switch (it->name) {
8954         case EatUnroll:
8955             loop->setUnroll();
8956             break;
8957         case EatLoop:
8958             loop->setDontUnroll();
8959             break;
8960         default:
8961             warn(loc, "attribute does not apply to a loop", "", "");
8962             break;
8963         }
8964     }
8965 }
8966
8967 //
8968 // Updating default qualifier for the case of a declaration with just a qualifier,
8969 // no type, block, or identifier.
8970 //
8971 void HlslParseContext::updateStandaloneQualifierDefaults(const TSourceLoc& loc, const TPublicType& publicType)
8972 {
8973     if (publicType.shaderQualifiers.vertices != TQualifier::layoutNotSet) {
8974         assert(language == EShLangTessControl || language == EShLangGeometry);
8975         // const char* id = (language == EShLangTessControl) ? "vertices" : "max_vertices";
8976     }
8977     if (publicType.shaderQualifiers.invocations != TQualifier::layoutNotSet) {
8978         if (! intermediate.setInvocations(publicType.shaderQualifiers.invocations))
8979             error(loc, "cannot change previously set layout value", "invocations", "");
8980     }
8981     if (publicType.shaderQualifiers.geometry != ElgNone) {
8982         if (publicType.qualifier.storage == EvqVaryingIn) {
8983             switch (publicType.shaderQualifiers.geometry) {
8984             case ElgPoints:
8985             case ElgLines:
8986             case ElgLinesAdjacency:
8987             case ElgTriangles:
8988             case ElgTrianglesAdjacency:
8989             case ElgQuads:
8990             case ElgIsolines:
8991                 break;
8992             default:
8993                 error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry),
8994                       "");
8995             }
8996         } else if (publicType.qualifier.storage == EvqVaryingOut) {
8997             handleOutputGeometry(loc, publicType.shaderQualifiers.geometry);
8998         } else
8999             error(loc, "cannot apply to:", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry),
9000                   GetStorageQualifierString(publicType.qualifier.storage));
9001     }
9002     if (publicType.shaderQualifiers.spacing != EvsNone)
9003         intermediate.setVertexSpacing(publicType.shaderQualifiers.spacing);
9004     if (publicType.shaderQualifiers.order != EvoNone)
9005         intermediate.setVertexOrder(publicType.shaderQualifiers.order);
9006     if (publicType.shaderQualifiers.pointMode)
9007         intermediate.setPointMode();
9008     for (int i = 0; i < 3; ++i) {
9009         if (publicType.shaderQualifiers.localSize[i] > 1) {
9010             int max = 0;
9011             switch (i) {
9012             case 0: max = resources.maxComputeWorkGroupSizeX; break;
9013             case 1: max = resources.maxComputeWorkGroupSizeY; break;
9014             case 2: max = resources.maxComputeWorkGroupSizeZ; break;
9015             default: break;
9016             }
9017             if (intermediate.getLocalSize(i) > (unsigned int)max)
9018                 error(loc, "too large; see gl_MaxComputeWorkGroupSize", "local_size", "");
9019
9020             // Fix the existing constant gl_WorkGroupSize with this new information.
9021             TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
9022             workGroupSize->getWritableConstArray()[i].setUConst(intermediate.getLocalSize(i));
9023         }
9024         if (publicType.shaderQualifiers.localSizeSpecId[i] != TQualifier::layoutNotSet) {
9025             intermediate.setLocalSizeSpecId(i, publicType.shaderQualifiers.localSizeSpecId[i]);
9026             // Set the workgroup built-in variable as a specialization constant
9027             TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
9028             workGroupSize->getWritableType().getQualifier().specConstant = true;
9029         }
9030     }
9031     if (publicType.shaderQualifiers.earlyFragmentTests)
9032         intermediate.setEarlyFragmentTests();
9033
9034     const TQualifier& qualifier = publicType.qualifier;
9035
9036     switch (qualifier.storage) {
9037     case EvqUniform:
9038         if (qualifier.hasMatrix())
9039             globalUniformDefaults.layoutMatrix = qualifier.layoutMatrix;
9040         if (qualifier.hasPacking())
9041             globalUniformDefaults.layoutPacking = qualifier.layoutPacking;
9042         break;
9043     case EvqBuffer:
9044         if (qualifier.hasMatrix())
9045             globalBufferDefaults.layoutMatrix = qualifier.layoutMatrix;
9046         if (qualifier.hasPacking())
9047             globalBufferDefaults.layoutPacking = qualifier.layoutPacking;
9048         break;
9049     case EvqVaryingIn:
9050         break;
9051     case EvqVaryingOut:
9052         if (qualifier.hasStream())
9053             globalOutputDefaults.layoutStream = qualifier.layoutStream;
9054         if (qualifier.hasXfbBuffer())
9055             globalOutputDefaults.layoutXfbBuffer = qualifier.layoutXfbBuffer;
9056         if (globalOutputDefaults.hasXfbBuffer() && qualifier.hasXfbStride()) {
9057             if (! intermediate.setXfbBufferStride(globalOutputDefaults.layoutXfbBuffer, qualifier.layoutXfbStride))
9058                 error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d",
9059                       qualifier.layoutXfbBuffer);
9060         }
9061         break;
9062     default:
9063         error(loc, "default qualifier requires 'uniform', 'buffer', 'in', or 'out' storage qualification", "", "");
9064         return;
9065     }
9066 }
9067
9068 //
9069 // Take the sequence of statements that has been built up since the last case/default,
9070 // put it on the list of top-level nodes for the current (inner-most) switch statement,
9071 // and follow that by the case/default we are on now.  (See switch topology comment on
9072 // TIntermSwitch.)
9073 //
9074 void HlslParseContext::wrapupSwitchSubsequence(TIntermAggregate* statements, TIntermNode* branchNode)
9075 {
9076     TIntermSequence* switchSequence = switchSequenceStack.back();
9077
9078     if (statements) {
9079         statements->setOperator(EOpSequence);
9080         switchSequence->push_back(statements);
9081     }
9082     if (branchNode) {
9083         // check all previous cases for the same label (or both are 'default')
9084         for (unsigned int s = 0; s < switchSequence->size(); ++s) {
9085             TIntermBranch* prevBranch = (*switchSequence)[s]->getAsBranchNode();
9086             if (prevBranch) {
9087                 TIntermTyped* prevExpression = prevBranch->getExpression();
9088                 TIntermTyped* newExpression = branchNode->getAsBranchNode()->getExpression();
9089                 if (prevExpression == nullptr && newExpression == nullptr)
9090                     error(branchNode->getLoc(), "duplicate label", "default", "");
9091                 else if (prevExpression != nullptr &&
9092                     newExpression != nullptr &&
9093                     prevExpression->getAsConstantUnion() &&
9094                     newExpression->getAsConstantUnion() &&
9095                     prevExpression->getAsConstantUnion()->getConstArray()[0].getIConst() ==
9096                     newExpression->getAsConstantUnion()->getConstArray()[0].getIConst())
9097                     error(branchNode->getLoc(), "duplicated value", "case", "");
9098             }
9099         }
9100         switchSequence->push_back(branchNode);
9101     }
9102 }
9103
9104 //
9105 // Turn the top-level node sequence built up of wrapupSwitchSubsequence
9106 // into a switch node.
9107 //
9108 TIntermNode* HlslParseContext::addSwitch(const TSourceLoc& loc, TIntermTyped* expression,
9109                                          TIntermAggregate* lastStatements, const TAttributes& attributes)
9110 {
9111     wrapupSwitchSubsequence(lastStatements, nullptr);
9112
9113     if (expression == nullptr ||
9114         (expression->getBasicType() != EbtInt && expression->getBasicType() != EbtUint) ||
9115         expression->getType().isArray() || expression->getType().isMatrix() || expression->getType().isVector())
9116         error(loc, "condition must be a scalar integer expression", "switch", "");
9117
9118     // If there is nothing to do, drop the switch but still execute the expression
9119     TIntermSequence* switchSequence = switchSequenceStack.back();
9120     if (switchSequence->size() == 0)
9121         return expression;
9122
9123     if (lastStatements == nullptr) {
9124         // emulate a break for error recovery
9125         lastStatements = intermediate.makeAggregate(intermediate.addBranch(EOpBreak, loc));
9126         lastStatements->setOperator(EOpSequence);
9127         switchSequence->push_back(lastStatements);
9128     }
9129
9130     TIntermAggregate* body = new TIntermAggregate(EOpSequence);
9131     body->getSequence() = *switchSequenceStack.back();
9132     body->setLoc(loc);
9133
9134     TIntermSwitch* switchNode = new TIntermSwitch(expression, body);
9135     switchNode->setLoc(loc);
9136     handleSwitchAttributes(loc, switchNode, attributes);
9137
9138     return switchNode;
9139 }
9140
9141 // Make a new symbol-table level that is made out of the members of a structure.
9142 // This should be done as an anonymous struct (name is "") so that the symbol table
9143 // finds the members with no explicit reference to a 'this' variable.
9144 void HlslParseContext::pushThisScope(const TType& thisStruct, const TVector<TFunctionDeclarator>& functionDeclarators)
9145 {
9146     // member variables
9147     TVariable& thisVariable = *new TVariable(NewPoolTString(""), thisStruct);
9148     symbolTable.pushThis(thisVariable);
9149
9150     // member functions
9151     for (auto it = functionDeclarators.begin(); it != functionDeclarators.end(); ++it) {
9152         // member should have a prefix matching currentTypePrefix.back()
9153         // but, symbol lookup within the class scope will just use the
9154         // unprefixed name. Hence, there are two: one fully prefixed and
9155         // one with no prefix.
9156         TFunction& member = *it->function->clone();
9157         member.removePrefix(currentTypePrefix.back());
9158         symbolTable.insert(member);
9159     }
9160 }
9161
9162 // Track levels of class/struct/namespace nesting with a prefix string using
9163 // the type names separated by the scoping operator. E.g., two levels
9164 // would look like:
9165 //
9166 //   outer::inner
9167 //
9168 // The string is empty when at normal global level.
9169 //
9170 void HlslParseContext::pushNamespace(const TString& typeName)
9171 {
9172     // make new type prefix
9173     TString newPrefix;
9174     if (currentTypePrefix.size() > 0)
9175         newPrefix = currentTypePrefix.back();
9176     newPrefix.append(typeName);
9177     newPrefix.append(scopeMangler);
9178     currentTypePrefix.push_back(newPrefix);
9179 }
9180
9181 // Opposite of pushNamespace(), see above
9182 void HlslParseContext::popNamespace()
9183 {
9184     currentTypePrefix.pop_back();
9185 }
9186
9187 // Use the class/struct nesting string to create a global name for
9188 // a member of a class/struct.
9189 void HlslParseContext::getFullNamespaceName(TString*& name) const
9190 {
9191     if (currentTypePrefix.size() == 0)
9192         return;
9193
9194     TString* fullName = NewPoolTString(currentTypePrefix.back().c_str());
9195     fullName->append(*name);
9196     name = fullName;
9197 }
9198
9199 // Helper function to add the namespace scope mangling syntax to a string.
9200 void HlslParseContext::addScopeMangler(TString& name)
9201 {
9202     name.append(scopeMangler);
9203 }
9204
9205 // Return true if this has uniform-interface like decorations.
9206 bool HlslParseContext::hasUniform(const TQualifier& qualifier) const
9207 {
9208     return qualifier.hasUniformLayout() ||
9209            qualifier.layoutPushConstant;
9210 }
9211
9212 // Potentially not the opposite of hasUniform(), as if some characteristic is
9213 // ever used for more than one thing (e.g., uniform or input), hasUniform() should
9214 // say it exists, but clearUniform() should leave it in place.
9215 void HlslParseContext::clearUniform(TQualifier& qualifier)
9216 {
9217     qualifier.clearUniformLayout();
9218     qualifier.layoutPushConstant = false;
9219 }
9220
9221 // Return false if builtIn by itself doesn't force this qualifier to be an input qualifier.
9222 bool HlslParseContext::isInputBuiltIn(const TQualifier& qualifier) const
9223 {
9224     switch (qualifier.builtIn) {
9225     case EbvPosition:
9226     case EbvPointSize:
9227         return language != EShLangVertex && language != EShLangCompute && language != EShLangFragment;
9228     case EbvClipDistance:
9229     case EbvCullDistance:
9230         return language != EShLangVertex && language != EShLangCompute;
9231     case EbvFragCoord:
9232     case EbvFace:
9233     case EbvHelperInvocation:
9234     case EbvLayer:
9235     case EbvPointCoord:
9236     case EbvSampleId:
9237     case EbvSampleMask:
9238     case EbvSamplePosition:
9239     case EbvViewportIndex:
9240         return language == EShLangFragment;
9241     case EbvGlobalInvocationId:
9242     case EbvLocalInvocationIndex:
9243     case EbvLocalInvocationId:
9244     case EbvNumWorkGroups:
9245     case EbvWorkGroupId:
9246     case EbvWorkGroupSize:
9247         return language == EShLangCompute;
9248     case EbvInvocationId:
9249         return language == EShLangTessControl || language == EShLangTessEvaluation || language == EShLangGeometry;
9250     case EbvPatchVertices:
9251         return language == EShLangTessControl || language == EShLangTessEvaluation;
9252     case EbvInstanceId:
9253     case EbvInstanceIndex:
9254     case EbvVertexId:
9255     case EbvVertexIndex:
9256         return language == EShLangVertex;
9257     case EbvPrimitiveId:
9258         return language == EShLangGeometry || language == EShLangFragment || language == EShLangTessControl;
9259     case EbvTessLevelInner:
9260     case EbvTessLevelOuter:
9261         return language == EShLangTessEvaluation;
9262     case EbvTessCoord:
9263         return language == EShLangTessEvaluation;
9264     default:
9265         return false;
9266     }
9267 }
9268
9269 // Return true if there are decorations to preserve for input-like storage.
9270 bool HlslParseContext::hasInput(const TQualifier& qualifier) const
9271 {
9272     if (qualifier.hasAnyLocation())
9273         return true;
9274
9275     if (language == EShLangFragment && (qualifier.isInterpolation() || qualifier.centroid || qualifier.sample))
9276         return true;
9277
9278     if (language == EShLangTessEvaluation && qualifier.patch)
9279         return true;
9280
9281     if (isInputBuiltIn(qualifier))
9282         return true;
9283
9284     return false;
9285 }
9286
9287 // Return false if builtIn by itself doesn't force this qualifier to be an output qualifier.
9288 bool HlslParseContext::isOutputBuiltIn(const TQualifier& qualifier) const
9289 {
9290     switch (qualifier.builtIn) {
9291     case EbvPosition:
9292     case EbvPointSize:
9293     case EbvClipVertex:
9294     case EbvClipDistance:
9295     case EbvCullDistance:
9296         return language != EShLangFragment && language != EShLangCompute;
9297     case EbvFragDepth:
9298     case EbvFragDepthGreater:
9299     case EbvFragDepthLesser:
9300     case EbvSampleMask:
9301         return language == EShLangFragment;
9302     case EbvLayer:
9303     case EbvViewportIndex:
9304         return language == EShLangGeometry || language == EShLangVertex;
9305     case EbvPrimitiveId:
9306         return language == EShLangGeometry;
9307     case EbvTessLevelInner:
9308     case EbvTessLevelOuter:
9309         return language == EShLangTessControl;
9310     default:
9311         return false;
9312     }
9313 }
9314
9315 // Return true if there are decorations to preserve for output-like storage.
9316 bool HlslParseContext::hasOutput(const TQualifier& qualifier) const
9317 {
9318     if (qualifier.hasAnyLocation())
9319         return true;
9320
9321     if (language != EShLangFragment && language != EShLangCompute && qualifier.hasXfb())
9322         return true;
9323
9324     if (language == EShLangTessControl && qualifier.patch)
9325         return true;
9326
9327     if (language == EShLangGeometry && qualifier.hasStream())
9328         return true;
9329
9330     if (isOutputBuiltIn(qualifier))
9331         return true;
9332
9333     return false;
9334 }
9335
9336 // Make the IO decorations etc. be appropriate only for an input interface.
9337 void HlslParseContext::correctInput(TQualifier& qualifier)
9338 {
9339     clearUniform(qualifier);
9340     if (language == EShLangVertex)
9341         qualifier.clearInterstage();
9342     if (language != EShLangTessEvaluation)
9343         qualifier.patch = false;
9344     if (language != EShLangFragment) {
9345         qualifier.clearInterpolation();
9346         qualifier.sample = false;
9347     }
9348
9349     qualifier.clearStreamLayout();
9350     qualifier.clearXfbLayout();
9351
9352     if (! isInputBuiltIn(qualifier))
9353         qualifier.builtIn = EbvNone;
9354 }
9355
9356 // Make the IO decorations etc. be appropriate only for an output interface.
9357 void HlslParseContext::correctOutput(TQualifier& qualifier)
9358 {
9359     clearUniform(qualifier);
9360     if (language == EShLangFragment)
9361         qualifier.clearInterstage();
9362     if (language != EShLangGeometry)
9363         qualifier.clearStreamLayout();
9364     if (language == EShLangFragment)
9365         qualifier.clearXfbLayout();
9366     if (language != EShLangTessControl)
9367         qualifier.patch = false;
9368
9369     switch (qualifier.builtIn) {
9370     case EbvFragDepth:
9371         intermediate.setDepthReplacing();
9372         intermediate.setDepth(EldAny);
9373         break;
9374     case EbvFragDepthGreater:
9375         intermediate.setDepthReplacing();
9376         intermediate.setDepth(EldGreater);
9377         qualifier.builtIn = EbvFragDepth;
9378         break;
9379     case EbvFragDepthLesser:
9380         intermediate.setDepthReplacing();
9381         intermediate.setDepth(EldLess);
9382         qualifier.builtIn = EbvFragDepth;
9383         break;
9384     default:
9385         break;
9386     }
9387
9388     if (! isOutputBuiltIn(qualifier))
9389         qualifier.builtIn = EbvNone;
9390 }
9391
9392 // Make the IO decorations etc. be appropriate only for uniform type interfaces.
9393 void HlslParseContext::correctUniform(TQualifier& qualifier)
9394 {
9395     if (qualifier.declaredBuiltIn == EbvNone)
9396         qualifier.declaredBuiltIn = qualifier.builtIn;
9397
9398     qualifier.builtIn = EbvNone;
9399     qualifier.clearInterstage();
9400     qualifier.clearInterstageLayout();
9401 }
9402
9403 // Clear out all IO/Uniform stuff, so this has nothing to do with being an IO interface.
9404 void HlslParseContext::clearUniformInputOutput(TQualifier& qualifier)
9405 {
9406     clearUniform(qualifier);
9407     correctUniform(qualifier);
9408 }
9409
9410
9411 // Set texture return type.  Returns success (not all types are valid).
9412 bool HlslParseContext::setTextureReturnType(TSampler& sampler, const TType& retType, const TSourceLoc& loc)
9413 {
9414     // Seed the output with an invalid index.  We will set it to a valid one if we can.
9415     sampler.structReturnIndex = TSampler::noReturnStruct;
9416
9417     // Arrays aren't supported.
9418     if (retType.isArray()) {
9419         error(loc, "Arrays not supported in texture template types", "", "");
9420         return false;
9421     }
9422
9423     // If return type is a vector, remember the vector size in the sampler, and return.
9424     if (retType.isVector() || retType.isScalar()) {
9425         sampler.vectorSize = retType.getVectorSize();
9426         return true;
9427     }
9428
9429     // If it wasn't a vector, it must be a struct meeting certain requirements.  The requirements
9430     // are checked below: just check for struct-ness here.
9431     if (!retType.isStruct()) {
9432         error(loc, "Invalid texture template type", "", "");
9433         return false;
9434     }
9435
9436     // TODO: Subpass doesn't handle struct returns, due to some oddities with fn overloading.
9437     if (sampler.isSubpass()) {
9438         error(loc, "Unimplemented: structure template type in subpass input", "", "");
9439         return false;
9440     }
9441
9442     TTypeList* members = retType.getWritableStruct();
9443
9444     // Check for too many or not enough structure members.
9445     if (members->size() > 4 || members->size() == 0) {
9446         error(loc, "Invalid member count in texture template structure", "", "");
9447         return false;
9448     }
9449
9450     // Error checking: We must have <= 4 total components, all of the same basic type.
9451     unsigned totalComponents = 0;
9452     for (unsigned m = 0; m < members->size(); ++m) {
9453         // Check for bad member types
9454         if (!(*members)[m].type->isScalar() && !(*members)[m].type->isVector()) {
9455             error(loc, "Invalid texture template struct member type", "", "");
9456             return false;
9457         }
9458
9459         const unsigned memberVectorSize = (*members)[m].type->getVectorSize();
9460         totalComponents += memberVectorSize;
9461
9462         // too many total member components
9463         if (totalComponents > 4) {
9464             error(loc, "Too many components in texture template structure type", "", "");
9465             return false;
9466         }
9467
9468         // All members must be of a common basic type
9469         if ((*members)[m].type->getBasicType() != (*members)[0].type->getBasicType()) {
9470             error(loc, "Texture template structure members must same basic type", "", "");
9471             return false;
9472         }
9473     }
9474
9475     // If the structure in the return type already exists in the table, we'll use it.  Otherwise, we'll make
9476     // a new entry.  This is a linear search, but it hardly ever happens, and the list cannot be very large.
9477     for (unsigned int idx = 0; idx < textureReturnStruct.size(); ++idx) {
9478         if (textureReturnStruct[idx] == members) {
9479             sampler.structReturnIndex = idx;
9480             return true;
9481         }
9482     }
9483
9484     // It wasn't found as an existing entry.  See if we have room for a new one.
9485     if (textureReturnStruct.size() >= TSampler::structReturnSlots) {
9486         error(loc, "Texture template struct return slots exceeded", "", "");
9487         return false;
9488     }
9489
9490     // Insert it in the vector that tracks struct return types.
9491     sampler.structReturnIndex = unsigned(textureReturnStruct.size());
9492     textureReturnStruct.push_back(members);
9493     
9494     // Success!
9495     return true;
9496 }
9497
9498 // Return the sampler return type in retType.
9499 void HlslParseContext::getTextureReturnType(const TSampler& sampler, TType& retType) const
9500 {
9501     if (sampler.hasReturnStruct()) {
9502         assert(textureReturnStruct.size() >= sampler.structReturnIndex);
9503
9504         // We land here if the texture return is a structure.
9505         TTypeList* blockStruct = textureReturnStruct[sampler.structReturnIndex];
9506
9507         const TType resultType(blockStruct, "");
9508         retType.shallowCopy(resultType);
9509     } else {
9510         // We land here if the texture return is a vector or scalar.
9511         const TType resultType(sampler.type, EvqTemporary, sampler.getVectorSize());
9512         retType.shallowCopy(resultType);
9513     }
9514 }
9515
9516
9517 // Return a symbol for the tessellation linkage variable of the given TBuiltInVariable type
9518 TIntermSymbol* HlslParseContext::findTessLinkageSymbol(TBuiltInVariable biType) const
9519 {
9520     const auto it = builtInTessLinkageSymbols.find(biType);
9521     if (it == builtInTessLinkageSymbols.end())  // if it wasn't declared by the user, return nullptr
9522         return nullptr;
9523
9524     return intermediate.addSymbol(*it->second->getAsVariable());
9525 }
9526
9527 // Find the patch constant function (issues error, returns nullptr if not found)
9528 const TFunction* HlslParseContext::findPatchConstantFunction(const TSourceLoc& loc)
9529 {
9530     if (symbolTable.isFunctionNameVariable(patchConstantFunctionName)) {
9531         error(loc, "can't use variable in patch constant function", patchConstantFunctionName.c_str(), "");
9532         return nullptr;
9533     }
9534
9535     const TString mangledName = patchConstantFunctionName + "(";
9536
9537     // create list of PCF candidates
9538     TVector<const TFunction*> candidateList;
9539     bool builtIn;
9540     symbolTable.findFunctionNameList(mangledName, candidateList, builtIn);
9541     
9542     // We have to have one and only one, or we don't know which to pick: the patchconstantfunc does not
9543     // allow any disambiguation of overloads.
9544     if (candidateList.empty()) {
9545         error(loc, "patch constant function not found", patchConstantFunctionName.c_str(), "");
9546         return nullptr;
9547     }
9548
9549     // Based on directed experiments, it appears that if there are overloaded patchconstantfunctions,
9550     // HLSL picks the last one in shader source order.  Since that isn't yet implemented here, error
9551     // out if there is more than one candidate.
9552     if (candidateList.size() > 1) {
9553         error(loc, "ambiguous patch constant function", patchConstantFunctionName.c_str(), "");
9554         return nullptr;
9555     }
9556
9557     return candidateList[0];
9558 }
9559
9560 // Finalization step: Add patch constant function invocation
9561 void HlslParseContext::addPatchConstantInvocation()
9562 {
9563     TSourceLoc loc;
9564     loc.init();
9565
9566     // If there's no patch constant function, or we're not a HS, do nothing.
9567     if (patchConstantFunctionName.empty() || language != EShLangTessControl)
9568         return;
9569
9570     // Look for built-in variables in a function's parameter list.
9571     const auto findBuiltIns = [&](const TFunction& function, std::set<tInterstageIoData>& builtIns) {
9572         for (int p=0; p<function.getParamCount(); ++p) {
9573             TStorageQualifier storage = function[p].type->getQualifier().storage;
9574
9575             if (storage == EvqConstReadOnly) // treated identically to input
9576                 storage = EvqIn;
9577
9578             if (function[p].getDeclaredBuiltIn() != EbvNone)
9579                 builtIns.insert(HlslParseContext::tInterstageIoData(function[p].getDeclaredBuiltIn(), storage));
9580             else
9581                 builtIns.insert(HlslParseContext::tInterstageIoData(function[p].type->getQualifier().builtIn, storage));
9582         }
9583     };
9584
9585     // If we synthesize a built-in interface variable, we must add it to the linkage.
9586     const auto addToLinkage = [&](const TType& type, const TString* name, TIntermSymbol** symbolNode) {
9587         if (name == nullptr) {
9588             error(loc, "unable to locate patch function parameter name", "", "");
9589             return;
9590         } else {
9591             TVariable& variable = *new TVariable(name, type);
9592             if (! symbolTable.insert(variable)) {
9593                 error(loc, "unable to declare patch constant function interface variable", name->c_str(), "");
9594                 return;
9595             }
9596
9597             globalQualifierFix(loc, variable.getWritableType().getQualifier());
9598
9599             if (symbolNode != nullptr)
9600                 *symbolNode = intermediate.addSymbol(variable);
9601
9602             trackLinkage(variable);
9603         }
9604     };
9605
9606     const auto isOutputPatch = [](TFunction& patchConstantFunction, int param) {
9607         const TType& type = *patchConstantFunction[param].type;
9608         const TBuiltInVariable biType = patchConstantFunction[param].getDeclaredBuiltIn();
9609
9610         return type.isSizedArray() && biType == EbvOutputPatch;
9611     };
9612     
9613     // We will perform these steps.  Each is in a scoped block for separation: they could
9614     // become separate functions to make addPatchConstantInvocation shorter.
9615     // 
9616     // 1. Union the interfaces, and create built-ins for anything present in the PCF and
9617     //    declared as a built-in variable that isn't present in the entry point's signature.
9618     //
9619     // 2. Synthesizes a call to the patchconstfunction using built-in variables from either main,
9620     //    or the ones we created.  Matching is based on built-in type.  We may use synthesized
9621     //    variables from (1) above.
9622     // 
9623     // 2B: Synthesize per control point invocations of wrapped entry point if the PCF requires them.
9624     //
9625     // 3. Create a return sequence: copy the return value (if any) from the PCF to a
9626     //    (non-sanitized) output variable.  In case this may involve multiple copies, such as for
9627     //    an arrayed variable, a temporary copy of the PCF output is created to avoid multiple
9628     //    indirections into a complex R-value coming from the call to the PCF.
9629     // 
9630     // 4. Create a barrier.
9631     // 
9632     // 5/5B. Call the PCF inside an if test for (invocation id == 0).
9633
9634     TFunction* patchConstantFunctionPtr = const_cast<TFunction*>(findPatchConstantFunction(loc));
9635
9636     if (patchConstantFunctionPtr == nullptr)
9637         return;
9638
9639     TFunction& patchConstantFunction = *patchConstantFunctionPtr;
9640
9641     const int pcfParamCount = patchConstantFunction.getParamCount();
9642     TIntermSymbol* invocationIdSym = findTessLinkageSymbol(EbvInvocationId);
9643     TIntermSequence& epBodySeq = entryPointFunctionBody->getAsAggregate()->getSequence();
9644
9645     int outPatchParam = -1; // -1 means there isn't one.
9646
9647     // ================ Step 1A: Union Interfaces ================
9648     // Our patch constant function.
9649     {
9650         std::set<tInterstageIoData> pcfBuiltIns;  // patch constant function built-ins
9651         std::set<tInterstageIoData> epfBuiltIns;  // entry point function built-ins
9652
9653         assert(entryPointFunction);
9654         assert(entryPointFunctionBody);
9655
9656         findBuiltIns(patchConstantFunction, pcfBuiltIns);
9657         findBuiltIns(*entryPointFunction,   epfBuiltIns);
9658
9659         // Find the set of built-ins in the PCF that are not present in the entry point.
9660         std::set<tInterstageIoData> notInEntryPoint;
9661
9662         notInEntryPoint = pcfBuiltIns;
9663
9664         // std::set_difference not usable on unordered containers
9665         for (auto bi = epfBuiltIns.begin(); bi != epfBuiltIns.end(); ++bi)
9666             notInEntryPoint.erase(*bi);
9667
9668         // Now we'll add those to the entry and to the linkage.
9669         for (int p=0; p<pcfParamCount; ++p) {
9670             const TBuiltInVariable biType   = patchConstantFunction[p].getDeclaredBuiltIn();
9671             TStorageQualifier storage = patchConstantFunction[p].type->getQualifier().storage;
9672
9673             // Track whether there is an output patch param
9674             if (isOutputPatch(patchConstantFunction, p)) {
9675                 if (outPatchParam >= 0) {
9676                     // Presently we only support one per ctrl pt input.
9677                     error(loc, "unimplemented: multiple output patches in patch constant function", "", "");
9678                     return;
9679                 }
9680                 outPatchParam = p;
9681             }
9682
9683             if (biType != EbvNone) {
9684                 TType* paramType = patchConstantFunction[p].type->clone();
9685
9686                 if (storage == EvqConstReadOnly) // treated identically to input
9687                     storage = EvqIn;
9688
9689                 // Presently, the only non-built-in we support is InputPatch, which is treated as
9690                 // a pseudo-built-in.
9691                 if (biType == EbvInputPatch) {
9692                     builtInTessLinkageSymbols[biType] = inputPatch;
9693                 } else if (biType == EbvOutputPatch) {
9694                     // Nothing...
9695                 } else {
9696                     // Use the original declaration type for the linkage
9697                     paramType->getQualifier().builtIn = biType;
9698
9699                     if (notInEntryPoint.count(tInterstageIoData(biType, storage)) == 1)
9700                         addToLinkage(*paramType, patchConstantFunction[p].name, nullptr);
9701                 }
9702             }
9703         }
9704
9705         // If we didn't find it because the shader made one, add our own.
9706         if (invocationIdSym == nullptr) {
9707             TType invocationIdType(EbtUint, EvqIn, 1);
9708             TString* invocationIdName = NewPoolTString("InvocationId");
9709             invocationIdType.getQualifier().builtIn = EbvInvocationId;
9710             addToLinkage(invocationIdType, invocationIdName, &invocationIdSym);
9711         }
9712
9713         assert(invocationIdSym);
9714     }
9715
9716     TIntermTyped* pcfArguments = nullptr;
9717     TVariable* perCtrlPtVar = nullptr;
9718
9719     // ================ Step 1B: Argument synthesis ================
9720     // Create pcfArguments for synthesis of patchconstantfunction invocation
9721     {
9722         for (int p=0; p<pcfParamCount; ++p) {
9723             TIntermTyped* inputArg = nullptr;
9724
9725             if (p == outPatchParam) {
9726                 if (perCtrlPtVar == nullptr) {
9727                     perCtrlPtVar = makeInternalVariable(*patchConstantFunction[outPatchParam].name,
9728                                                         *patchConstantFunction[outPatchParam].type);
9729
9730                     perCtrlPtVar->getWritableType().getQualifier().makeTemporary();
9731                 }
9732                 inputArg = intermediate.addSymbol(*perCtrlPtVar, loc);
9733             } else {
9734                 // find which built-in it is
9735                 const TBuiltInVariable biType = patchConstantFunction[p].getDeclaredBuiltIn();
9736                 
9737                 if (biType == EbvInputPatch && inputPatch == nullptr) {
9738                     error(loc, "unimplemented: PCF input patch without entry point input patch parameter", "", "");
9739                     return;
9740                 }
9741
9742                 inputArg = findTessLinkageSymbol(biType);
9743
9744                 if (inputArg == nullptr) {
9745                     error(loc, "unable to find patch constant function built-in variable", "", "");
9746                     return;
9747                 }
9748             }
9749
9750             if (pcfParamCount == 1)
9751                 pcfArguments = inputArg;
9752             else
9753                 pcfArguments = intermediate.growAggregate(pcfArguments, inputArg);
9754         }
9755     }
9756
9757     // ================ Step 2: Synthesize call to PCF ================
9758     TIntermAggregate* pcfCallSequence = nullptr;
9759     TIntermTyped* pcfCall = nullptr;
9760
9761     {
9762         // Create a function call to the patchconstantfunction
9763         if (pcfArguments)
9764             addInputArgumentConversions(patchConstantFunction, pcfArguments);
9765
9766         // Synthetic call.
9767         pcfCall = intermediate.setAggregateOperator(pcfArguments, EOpFunctionCall, patchConstantFunction.getType(), loc);
9768         pcfCall->getAsAggregate()->setUserDefined();
9769         pcfCall->getAsAggregate()->setName(patchConstantFunction.getMangledName());
9770         intermediate.addToCallGraph(infoSink, intermediate.getEntryPointMangledName().c_str(),
9771                                     patchConstantFunction.getMangledName());
9772
9773         if (pcfCall->getAsAggregate()) {
9774             TQualifierList& qualifierList = pcfCall->getAsAggregate()->getQualifierList();
9775             for (int i = 0; i < patchConstantFunction.getParamCount(); ++i) {
9776                 TStorageQualifier qual = patchConstantFunction[i].type->getQualifier().storage;
9777                 qualifierList.push_back(qual);
9778             }
9779             pcfCall = addOutputArgumentConversions(patchConstantFunction, *pcfCall->getAsOperator());
9780         }
9781     }
9782
9783     // ================ Step 2B: Per Control Point synthesis ================
9784     // If there is per control point data, we must either emulate that with multiple
9785     // invocations of the entry point to build up an array, or (TODO:) use a yet
9786     // unavailable extension to look across the SIMD lanes.  This is the former
9787     // as a placeholder for the latter.
9788     if (outPatchParam >= 0) {
9789         // We must introduce a local temp variable of the type wanted by the PCF input.
9790         const int arraySize = patchConstantFunction[outPatchParam].type->getOuterArraySize();
9791
9792         if (entryPointFunction->getType().getBasicType() == EbtVoid) {
9793             error(loc, "entry point must return a value for use with patch constant function", "", "");
9794             return;
9795         }
9796
9797         // Create calls to wrapped main to fill in the array.  We will substitute fixed values
9798         // of invocation ID when calling the wrapped main.
9799
9800         // This is the type of the each member of the per ctrl point array.
9801         const TType derefType(perCtrlPtVar->getType(), 0);
9802
9803         for (int cpt = 0; cpt < arraySize; ++cpt) {
9804             // TODO: improve.  substr(1) here is to avoid the '@' that was grafted on but isn't in the symtab
9805             // for this function.
9806             const TString origName = entryPointFunction->getName().substr(1);
9807             TFunction callee(&origName, TType(EbtVoid));
9808             TIntermTyped* callingArgs = nullptr;
9809
9810             for (int i = 0; i < entryPointFunction->getParamCount(); i++) {
9811                 TParameter& param = (*entryPointFunction)[i];
9812                 TType& paramType = *param.type;
9813
9814                 if (paramType.getQualifier().isParamOutput()) {
9815                     error(loc, "unimplemented: entry point outputs in patch constant function invocation", "", "");
9816                     return;
9817                 }
9818
9819                 if (paramType.getQualifier().isParamInput())  {
9820                     TIntermTyped* arg = nullptr;
9821                     if ((*entryPointFunction)[i].getDeclaredBuiltIn() == EbvInvocationId) {
9822                         // substitute invocation ID with the array element ID
9823                         arg = intermediate.addConstantUnion(cpt, loc);
9824                     } else {
9825                         TVariable* argVar = makeInternalVariable(*param.name, *param.type);
9826                         argVar->getWritableType().getQualifier().makeTemporary();
9827                         arg = intermediate.addSymbol(*argVar);
9828                     }
9829
9830                     handleFunctionArgument(&callee, callingArgs, arg);
9831                 }
9832             }
9833
9834             // Call and assign to per ctrl point variable
9835             currentCaller = intermediate.getEntryPointMangledName().c_str();
9836             TIntermTyped* callReturn = handleFunctionCall(loc, &callee, callingArgs);
9837             TIntermTyped* index = intermediate.addConstantUnion(cpt, loc);
9838             TIntermSymbol* perCtrlPtSym = intermediate.addSymbol(*perCtrlPtVar, loc);
9839             TIntermTyped* element = intermediate.addIndex(EOpIndexDirect, perCtrlPtSym, index, loc);
9840             element->setType(derefType);
9841             element->setLoc(loc);
9842
9843             pcfCallSequence = intermediate.growAggregate(pcfCallSequence, 
9844                                                          handleAssign(loc, EOpAssign, element, callReturn));
9845         }
9846     }
9847
9848     // ================ Step 3: Create return Sequence ================
9849     // Return sequence: copy PCF result to a temporary, then to shader output variable.
9850     if (pcfCall->getBasicType() != EbtVoid) {
9851         const TType* retType = &patchConstantFunction.getType();  // return type from the PCF
9852         TType outType; // output type that goes with the return type.
9853         outType.shallowCopy(*retType);
9854
9855         // substitute the output type
9856         const auto newLists = ioTypeMap.find(retType->getStruct());
9857         if (newLists != ioTypeMap.end())
9858             outType.setStruct(newLists->second.output);
9859
9860         // Substitute the top level type's built-in type
9861         if (patchConstantFunction.getDeclaredBuiltInType() != EbvNone)
9862             outType.getQualifier().builtIn = patchConstantFunction.getDeclaredBuiltInType();
9863
9864         outType.getQualifier().patch = true; // make it a per-patch variable
9865
9866         TVariable* pcfOutput = makeInternalVariable("@patchConstantOutput", outType);
9867         pcfOutput->getWritableType().getQualifier().storage = EvqVaryingOut;
9868
9869         if (pcfOutput->getType().containsBuiltIn())
9870             split(*pcfOutput);
9871
9872         assignToInterface(*pcfOutput);
9873
9874         TIntermSymbol* pcfOutputSym = intermediate.addSymbol(*pcfOutput, loc);
9875
9876         // The call to the PCF is a complex R-value: we want to store it in a temp to avoid
9877         // repeated calls to the PCF:
9878         TVariable* pcfCallResult = makeInternalVariable("@patchConstantResult", *retType);
9879         pcfCallResult->getWritableType().getQualifier().makeTemporary();
9880
9881         TIntermSymbol* pcfResultVar = intermediate.addSymbol(*pcfCallResult, loc);
9882         TIntermNode* pcfResultAssign = handleAssign(loc, EOpAssign, pcfResultVar, pcfCall);
9883         TIntermNode* pcfResultToOut = handleAssign(loc, EOpAssign, pcfOutputSym,
9884                                                    intermediate.addSymbol(*pcfCallResult, loc));
9885
9886         pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfResultAssign);
9887         pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfResultToOut);
9888     } else {
9889         pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfCall);
9890     }
9891
9892     // ================ Step 4: Barrier ================    
9893     TIntermTyped* barrier = new TIntermAggregate(EOpBarrier);
9894     barrier->setLoc(loc);
9895     barrier->setType(TType(EbtVoid));
9896     epBodySeq.insert(epBodySeq.end(), barrier);
9897
9898     // ================ Step 5: Test on invocation ID ================
9899     TIntermTyped* zero = intermediate.addConstantUnion(0, loc, true);
9900     TIntermTyped* cmp =  intermediate.addBinaryNode(EOpEqual, invocationIdSym, zero, loc, TType(EbtBool));
9901
9902
9903     // ================ Step 5B: Create if statement on Invocation ID == 0 ================
9904     intermediate.setAggregateOperator(pcfCallSequence, EOpSequence, TType(EbtVoid), loc);
9905     TIntermTyped* invocationIdTest = new TIntermSelection(cmp, pcfCallSequence, nullptr);
9906     invocationIdTest->setLoc(loc);
9907
9908     // add our test sequence before the return.
9909     epBodySeq.insert(epBodySeq.end(), invocationIdTest);
9910 }
9911
9912 // Finalization step: remove unused buffer blocks from linkage (we don't know until the
9913 // shader is entirely compiled).
9914 // Preserve order of remaining symbols.
9915 void HlslParseContext::removeUnusedStructBufferCounters()
9916 {
9917     const auto endIt = std::remove_if(linkageSymbols.begin(), linkageSymbols.end(),
9918                                       [this](const TSymbol* sym) {
9919                                           const auto sbcIt = structBufferCounter.find(sym->getName());
9920                                           return sbcIt != structBufferCounter.end() && !sbcIt->second;
9921                                       });
9922
9923     linkageSymbols.erase(endIt, linkageSymbols.end());
9924 }
9925
9926 // Finalization step: patch texture shadow modes to match samplers they were combined with
9927 void HlslParseContext::fixTextureShadowModes()
9928 {
9929     for (auto symbol = linkageSymbols.begin(); symbol != linkageSymbols.end(); ++symbol) {
9930         TSampler& sampler = (*symbol)->getWritableType().getSampler();
9931
9932         if (sampler.isTexture()) {
9933             const auto shadowMode = textureShadowVariant.find((*symbol)->getUniqueId());
9934             if (shadowMode != textureShadowVariant.end()) {
9935
9936                 if (shadowMode->second->overloaded())
9937                     // Texture needs legalization if it's been seen with both shadow and non-shadow modes.
9938                     intermediate.setNeedsLegalization();
9939
9940                 sampler.shadow = shadowMode->second->isShadowId((*symbol)->getUniqueId());
9941             }
9942         }
9943     }
9944 }
9945
9946 // Finalization step: patch append methods to use proper stream output, which isn't known until
9947 // main is parsed, which could happen after the append method is parsed.
9948 void HlslParseContext::finalizeAppendMethods()
9949 {
9950     TSourceLoc loc;
9951     loc.init();
9952
9953     // Nothing to do: bypass test for valid stream output.
9954     if (gsAppends.empty())
9955         return;
9956
9957     if (gsStreamOutput == nullptr) {
9958         error(loc, "unable to find output symbol for Append()", "", "");
9959         return;
9960     }
9961
9962     // Patch append sequences, now that we know the stream output symbol.
9963     for (auto append = gsAppends.begin(); append != gsAppends.end(); ++append) {
9964         append->node->getSequence()[0] = 
9965             handleAssign(append->loc, EOpAssign,
9966                          intermediate.addSymbol(*gsStreamOutput, append->loc),
9967                          append->node->getSequence()[0]->getAsTyped());
9968     }
9969 }
9970
9971 // post-processing
9972 void HlslParseContext::finish()
9973 {
9974     // Error check: There was a dangling .mips operator.  These are not nested constructs in the grammar, so
9975     // cannot be detected there.  This is not strictly needed in a non-validating parser; it's just helpful.
9976     if (! mipsOperatorMipArg.empty()) {
9977         error(mipsOperatorMipArg.back().loc, "unterminated mips operator:", "", "");
9978     }
9979
9980     removeUnusedStructBufferCounters();
9981     addPatchConstantInvocation();
9982     fixTextureShadowModes();
9983     finalizeAppendMethods();
9984
9985     // Communicate out (esp. for command line) that we formed AST that will make
9986     // illegal AST SPIR-V and it needs transforms to legalize it.
9987     if (intermediate.needsLegalization() && (messages & EShMsgHlslLegalization))
9988         infoSink.info << "WARNING: AST will form illegal SPIR-V; need to transform to legalize";
9989
9990     TParseContextBase::finish();
9991 }
9992
9993 } // end namespace glslang