1 //
2 // Copyright (C) 2016-2018 Google, Inc.
3 // Copyright (C) 2016 LunarG, Inc.
4 //
5 // All rights reserved.
6 //
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
9 // are met:
10 //
11 //    Redistributions of source code must retain the above copyright
12 //    notice, this list of conditions and the following disclaimer.
13 //
14 //    Redistributions in binary form must reproduce the above
15 //    copyright notice, this list of conditions and the following
16 //    disclaimer in the documentation and/or other materials provided
17 //    with the distribution.
18 //
19 //    Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20 //    contributors may be used to endorse or promote products derived
21 //    from this software without specific prior written permission.
22 //
23 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27 // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29 // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34 // POSSIBILITY OF SUCH DAMAGE.
35 //
36 #ifndef HLSL_PARSE_INCLUDED_
37 #define HLSL_PARSE_INCLUDED_
38 
39 #include "../MachineIndependent/parseVersions.h"
40 #include "../MachineIndependent/ParseHelper.h"
41 #include "../MachineIndependent/attribute.h"
42 
43 #include <array>
44 
45 namespace glslang {
46 
47 class TFunctionDeclarator;
48 
49 class HlslParseContext : public TParseContextBase {
50 public:
51     HlslParseContext(TSymbolTable&, TIntermediate&, bool parsingBuiltins,
52                      int version, EProfile, const SpvVersion& spvVersion, EShLanguage, TInfoSink&,
53                      const TString sourceEntryPointName,
54                      bool forwardCompatible = false, EShMessages messages = EShMsgDefault);
55     virtual ~HlslParseContext();
56     void initializeExtensionBehavior() override;
57 
58     void setLimits(const TBuiltInResource&) override;
59     bool parseShaderStrings(TPpContext&, TInputScanner& input, bool versionWillBeError = false) override;
getGlobalUniformBlockName()60     virtual const char* getGlobalUniformBlockName() const override { return "$Global"; }
setUniformBlockDefaults(TType & block)61     virtual void setUniformBlockDefaults(TType& block) const override
62     {
63         block.getQualifier().layoutPacking = globalUniformDefaults.layoutPacking;
64         block.getQualifier().layoutMatrix = globalUniformDefaults.layoutMatrix;
65     }
66 
reservedPpErrorCheck(const TSourceLoc &,const char *,const char *)67     void reservedPpErrorCheck(const TSourceLoc&, const char* /*name*/, const char* /*op*/) override { }
lineContinuationCheck(const TSourceLoc &,bool)68     bool lineContinuationCheck(const TSourceLoc&, bool /*endOfComment*/) override { return true; }
lineDirectiveShouldSetNextLine()69     bool lineDirectiveShouldSetNextLine() const override { return true; }
70     bool builtInName(const TString&);
71 
72     void handlePragma(const TSourceLoc&, const TVector<TString>&) override;
73     TIntermTyped* handleVariable(const TSourceLoc&, const TString* string);
74     TIntermTyped* handleBracketDereference(const TSourceLoc&, TIntermTyped* base, TIntermTyped* index);
75     TIntermTyped* handleBracketOperator(const TSourceLoc&, TIntermTyped* base, TIntermTyped* index);
76 
77     TIntermTyped* handleBinaryMath(const TSourceLoc&, const char* str, TOperator op, TIntermTyped* left, TIntermTyped* right);
78     TIntermTyped* handleUnaryMath(const TSourceLoc&, const char* str, TOperator op, TIntermTyped* childNode);
79     TIntermTyped* handleDotDereference(const TSourceLoc&, TIntermTyped* base, const TString& field);
80     bool isBuiltInMethod(const TSourceLoc&, TIntermTyped* base, const TString& field);
81     void assignToInterface(TVariable& variable);
82     void handleFunctionDeclarator(const TSourceLoc&, TFunction& function, bool prototype);
83     TIntermAggregate* handleFunctionDefinition(const TSourceLoc&, TFunction&, const TAttributes&, TIntermNode*& entryPointTree);
84     TIntermNode* transformEntryPoint(const TSourceLoc&, TFunction&, const TAttributes&);
85     void handleEntryPointAttributes(const TSourceLoc&, const TAttributes&);
86     void transferTypeAttributes(const TSourceLoc&, const TAttributes&, TType&, bool allowEntry = false);
87     void handleFunctionBody(const TSourceLoc&, TFunction&, TIntermNode* functionBody, TIntermNode*& node);
88     void remapEntryPointIO(TFunction& function, TVariable*& returnValue, TVector<TVariable*>& inputs, TVector<TVariable*>& outputs);
89     void remapNonEntryPointIO(TFunction& function);
90     TIntermNode* handleReturnValue(const TSourceLoc&, TIntermTyped*);
91     void handleFunctionArgument(TFunction*, TIntermTyped*& arguments, TIntermTyped* newArg);
92     TIntermTyped* handleAssign(const TSourceLoc&, TOperator, TIntermTyped* left, TIntermTyped* right);
93     TIntermTyped* handleAssignToMatrixSwizzle(const TSourceLoc&, TOperator, TIntermTyped* left, TIntermTyped* right);
94     TIntermTyped* handleFunctionCall(const TSourceLoc&, TFunction*, TIntermTyped*);
95     TIntermAggregate* assignClipCullDistance(const TSourceLoc&, TOperator, int semanticId, TIntermTyped* left, TIntermTyped* right);
96     TIntermTyped* assignPosition(const TSourceLoc&, TOperator, TIntermTyped* left, TIntermTyped* right);
97     void decomposeIntrinsic(const TSourceLoc&, TIntermTyped*& node, TIntermNode* arguments);
98     void decomposeSampleMethods(const TSourceLoc&, TIntermTyped*& node, TIntermNode* arguments);
99     void decomposeStructBufferMethods(const TSourceLoc&, TIntermTyped*& node, TIntermNode* arguments);
100     void decomposeGeometryMethods(const TSourceLoc&, TIntermTyped*& node, TIntermNode* arguments);
101     void pushFrontArguments(TIntermTyped* front, TIntermTyped*& arguments);
102     void addInputArgumentConversions(const TFunction&, TIntermTyped*&);
103     void expandArguments(const TSourceLoc&, const TFunction&, TIntermTyped*&);
104     TIntermTyped* addOutputArgumentConversions(const TFunction&, TIntermOperator&);
105     void builtInOpCheck(const TSourceLoc&, const TFunction&, TIntermOperator&);
106     TFunction* makeConstructorCall(const TSourceLoc&, const TType&);
107     void handleSemantic(TSourceLoc, TQualifier&, TBuiltInVariable, const TString& upperCase);
108     void handlePackOffset(const TSourceLoc&, TQualifier&, const glslang::TString& location,
109                           const glslang::TString* component);
110     void handleRegister(const TSourceLoc&, TQualifier&, const glslang::TString* profile, const glslang::TString& desc,
111                         int subComponent, const glslang::TString*);
112     TIntermTyped* convertConditionalExpression(const TSourceLoc&, TIntermTyped*, bool mustBeScalar = true);
113     TIntermAggregate* handleSamplerTextureCombine(const TSourceLoc& loc, TIntermTyped* argTex, TIntermTyped* argSampler);
114 
115     bool parseMatrixSwizzleSelector(const TSourceLoc&, const TString&, int cols, int rows, TSwizzleSelectors<TMatrixSelector>&);
116     int getMatrixComponentsColumn(int rows, const TSwizzleSelectors<TMatrixSelector>&);
117     void assignError(const TSourceLoc&, const char* op, TString left, TString right);
118     void unaryOpError(const TSourceLoc&, const char* op, TString operand);
119     void binaryOpError(const TSourceLoc&, const char* op, TString left, TString right);
120     void variableCheck(TIntermTyped*& nodePtr);
121     void constantValueCheck(TIntermTyped* node, const char* token);
122     void integerCheck(const TIntermTyped* node, const char* token);
123     void globalCheck(const TSourceLoc&, const char* token);
124     bool constructorError(const TSourceLoc&, TIntermNode*, TFunction&, TOperator, TType&);
125     void arraySizeCheck(const TSourceLoc&, TIntermTyped* expr, TArraySize&);
126     void arraySizeRequiredCheck(const TSourceLoc&, const TArraySizes&);
127     void structArrayCheck(const TSourceLoc&, const TType& structure);
128     bool voidErrorCheck(const TSourceLoc&, const TString&, TBasicType);
129     void globalQualifierFix(const TSourceLoc&, TQualifier&);
130     bool structQualifierErrorCheck(const TSourceLoc&, const TPublicType& pType);
131     void mergeQualifiers(TQualifier& dst, const TQualifier& src);
132     int computeSamplerTypeIndex(TSampler&);
133     TSymbol* redeclareBuiltinVariable(const TSourceLoc&, const TString&, const TQualifier&, const TShaderQualifiers&);
134     void paramFix(TType& type);
135     void specializationCheck(const TSourceLoc&, const TType&, const char* op);
136 
137     void setLayoutQualifier(const TSourceLoc&, TQualifier&, TString&);
138     void setLayoutQualifier(const TSourceLoc&, TQualifier&, TString&, const TIntermTyped*);
139     void setSpecConstantId(const TSourceLoc&, TQualifier&, int value);
140     void mergeObjectLayoutQualifiers(TQualifier& dest, const TQualifier& src, bool inheritOnly);
141     void checkNoShaderLayouts(const TSourceLoc&, const TShaderQualifiers&);
142 
143     const TFunction* findFunction(const TSourceLoc& loc, TFunction& call, bool& builtIn, int& thisDepth, TIntermTyped*& args);
144     void addGenMulArgumentConversion(const TSourceLoc& loc, TFunction& call, TIntermTyped*& args);
145     void declareTypedef(const TSourceLoc&, const TString& identifier, const TType&);
146     void declareStruct(const TSourceLoc&, TString& structName, TType&);
147     TSymbol* lookupUserType(const TString&, TType&);
148     TIntermNode* declareVariable(const TSourceLoc&, const TString& identifier, TType&, TIntermTyped* initializer = 0);
149     void lengthenList(const TSourceLoc&, TIntermSequence& list, int size, TIntermTyped* scalarInit);
150     TIntermTyped* handleConstructor(const TSourceLoc&, TIntermTyped*, const TType&);
151     TIntermTyped* addConstructor(const TSourceLoc&, TIntermTyped*, const TType&);
152     TIntermTyped* convertArray(TIntermTyped*, const TType&);
153     TIntermTyped* constructAggregate(TIntermNode*, const TType&, int, const TSourceLoc&);
154     TIntermTyped* constructBuiltIn(const TType&, TOperator, TIntermTyped*, const TSourceLoc&, bool subset);
155     void declareBlock(const TSourceLoc&, TType&, const TString* instanceName = 0);
156     void declareStructBufferCounter(const TSourceLoc& loc, const TType& bufferType, const TString& name);
157     void fixBlockLocations(const TSourceLoc&, TQualifier&, TTypeList&, bool memberWithLocation, bool memberWithoutLocation);
158     void fixXfbOffsets(TQualifier&, TTypeList&);
159     void fixBlockUniformOffsets(const TQualifier&, TTypeList&);
160     void addQualifierToExisting(const TSourceLoc&, TQualifier, const TString& identifier);
161     void addQualifierToExisting(const TSourceLoc&, TQualifier, TIdentifierList&);
162     void updateStandaloneQualifierDefaults(const TSourceLoc&, const TPublicType&);
163     void wrapupSwitchSubsequence(TIntermAggregate* statements, TIntermNode* branchNode);
164     TIntermNode* addSwitch(const TSourceLoc&, TIntermTyped* expression, TIntermAggregate* body, const TAttributes&);
165 
nestLooping()166     void nestLooping()       { ++loopNestingLevel; }
unnestLooping()167     void unnestLooping()     { --loopNestingLevel; }
nestAnnotations()168     void nestAnnotations()   { ++annotationNestingLevel; }
unnestAnnotations()169     void unnestAnnotations() { --annotationNestingLevel; }
getAnnotationNestingLevel()170     int getAnnotationNestingLevel() { return annotationNestingLevel; }
pushScope()171     void pushScope()         { symbolTable.push(); }
popScope()172     void popScope()          { symbolTable.pop(0); }
173 
174     void pushThisScope(const TType&, const TVector<TFunctionDeclarator>&);
popThisScope()175     void popThisScope()      { symbolTable.pop(0); }
176 
pushImplicitThis(TVariable * thisParameter)177     void pushImplicitThis(TVariable* thisParameter) { implicitThisStack.push_back(thisParameter); }
popImplicitThis()178     void popImplicitThis() { implicitThisStack.pop_back(); }
getImplicitThis(int thisDepth)179     TVariable* getImplicitThis(int thisDepth) const { return implicitThisStack[implicitThisStack.size() - thisDepth]; }
180 
181     void pushNamespace(const TString& name);
182     void popNamespace();
183     void getFullNamespaceName(TString*&) const;
184     void addScopeMangler(TString&);
185 
beginParameterParsing(TFunction & function)186     void beginParameterParsing(TFunction& function)
187     {
188         parsingEntrypointParameters = isEntrypointName(function.getName());
189     }
190 
pushSwitchSequence(TIntermSequence * sequence)191     void pushSwitchSequence(TIntermSequence* sequence) { switchSequenceStack.push_back(sequence); }
popSwitchSequence()192     void popSwitchSequence() { switchSequenceStack.pop_back(); }
193 
194     virtual void growGlobalUniformBlock(const TSourceLoc&, TType&, const TString& memberName,
195         TTypeList* typeList = nullptr) override;
196 
197     // Apply L-value conversions.  E.g, turning a write to a RWTexture into an ImageStore.
198     TIntermTyped* handleLvalue(const TSourceLoc&, const char* op, TIntermTyped*& node);
199     bool lValueErrorCheck(const TSourceLoc&, const char* op, TIntermTyped*) override;
200 
201     TLayoutFormat getLayoutFromTxType(const TSourceLoc&, const TType&);
202 
203     bool handleOutputGeometry(const TSourceLoc&, const TLayoutGeometry& geometry);
204     bool handleInputGeometry(const TSourceLoc&, const TLayoutGeometry& geometry);
205 
206     // Determine selection control from attributes
207     void handleSelectionAttributes(const TSourceLoc& loc, TIntermSelection*, const TAttributes& attributes);
208     void handleSwitchAttributes(const TSourceLoc& loc, TIntermSwitch*, const TAttributes& attributes);
209 
210     // Determine loop control from attributes
211     void handleLoopAttributes(const TSourceLoc& loc, TIntermLoop*, const TAttributes& attributes);
212 
213     // Share struct buffer deep types
214     void shareStructBufferType(TType&);
215 
216     // Set texture return type of the given sampler.  Returns success (not all types are valid).
217     bool setTextureReturnType(TSampler& sampler, const TType& retType, const TSourceLoc& loc);
218 
219     // Obtain the sampler return type of the given sampler in retType.
220     void getTextureReturnType(const TSampler& sampler, TType& retType) const;
221 
222     TAttributeType attributeFromName(const TString& nameSpace, const TString& name) const;
223 
224 protected:
225     struct TFlattenData {
TFlattenDataTFlattenData226         TFlattenData() : nextBinding(TQualifier::layoutBindingEnd),
227                          nextLocation(TQualifier::layoutLocationEnd) { }
TFlattenDataTFlattenData228         TFlattenData(int nb, int nl) : nextBinding(nb), nextLocation(nl) { }
229 
230         TVector<TVariable*> members;     // individual flattened variables
231         TVector<int> offsets;            // offset to next tree level
232         unsigned int nextBinding;        // next binding to use.
233         unsigned int nextLocation;       // next location to use
234     };
235 
236     void fixConstInit(const TSourceLoc&, const TString& identifier, TType& type, TIntermTyped*& initializer);
237     void inheritGlobalDefaults(TQualifier& dst) const;
238     TVariable* makeInternalVariable(const char* name, const TType&) const;
makeInternalVariable(const TString & name,const TType & type)239     TVariable* makeInternalVariable(const TString& name, const TType& type) const {
240         return makeInternalVariable(name.c_str(), type);
241     }
242     TIntermSymbol* makeInternalVariableNode(const TSourceLoc&, const char* name, const TType&) const;
243     TVariable* declareNonArray(const TSourceLoc&, const TString& identifier, const TType&, bool track);
244     void declareArray(const TSourceLoc&, const TString& identifier, const TType&, TSymbol*&, bool track);
245     TIntermNode* executeInitializer(const TSourceLoc&, TIntermTyped* initializer, TVariable* variable);
246     TIntermTyped* convertInitializerList(const TSourceLoc&, const TType&, TIntermTyped* initializer, TIntermTyped* scalarInit);
247     bool isScalarConstructor(const TIntermNode*);
248     TOperator mapAtomicOp(const TSourceLoc& loc, TOperator op, bool isImage);
isEntrypointName(const TString & name)249     bool isEntrypointName(const TString& name) { return name.compare(intermediate.getEntryPointName().c_str()) == 0; }
250 
251     // Return true if this node requires L-value conversion (e.g, to an imageStore).
252     bool shouldConvertLValue(const TIntermNode*) const;
253 
254     // Array and struct flattening
255     TIntermTyped* flattenAccess(TIntermTyped* base, int member);
256     TIntermTyped* flattenAccess(int uniqueId, int member, TStorageQualifier outerStorage, const TType&, int subset = -1);
257     int findSubtreeOffset(const TIntermNode&) const;
258     int findSubtreeOffset(const TType&, int subset, const TVector<int>& offsets) const;
259     bool shouldFlatten(const TType&, TStorageQualifier, bool topLevel) const;
260     bool wasFlattened(const TIntermTyped* node) const;
wasFlattened(int id)261     bool wasFlattened(int id) const { return flattenMap.find(id) != flattenMap.end(); }
262     int  addFlattenedMember(const TVariable&, const TType&, TFlattenData&, const TString& name, bool linkage,
263                             const TQualifier& outerQualifier, const TArraySizes* builtInArraySizes);
264 
265     // Structure splitting (splits interstage built-in types into its own struct)
266     void split(const TVariable&);
267     void splitBuiltIn(const TString& baseName, const TType& memberType, const TArraySizes*, const TQualifier&);
268     const TType& split(const TType& type, const TString& name, const TQualifier&);
269     bool wasSplit(const TIntermTyped* node) const;
wasSplit(int id)270     bool wasSplit(int id) const { return splitNonIoVars.find(id) != splitNonIoVars.end(); }
271     TVariable* getSplitNonIoVar(int id) const;
272     void addPatchConstantInvocation();
273     void fixTextureShadowModes();
274     void finalizeAppendMethods();
275     TIntermTyped* makeIntegerIndex(TIntermTyped*);
276 
277     void fixBuiltInIoType(TType&);
278 
279     void flatten(const TVariable& variable, bool linkage, bool arrayed = false);
280     int flatten(const TVariable& variable, const TType&, TFlattenData&, TString name, bool linkage,
281                 const TQualifier& outerQualifier, const TArraySizes* builtInArraySizes);
282     int flattenStruct(const TVariable& variable, const TType&, TFlattenData&, TString name, bool linkage,
283                       const TQualifier& outerQualifier, const TArraySizes* builtInArraySizes);
284     int flattenArray(const TVariable& variable, const TType&, TFlattenData&, TString name, bool linkage,
285                      const TQualifier& outerQualifier);
286 
287     bool hasUniform(const TQualifier& qualifier) const;
288     void clearUniform(TQualifier& qualifier);
289     bool isInputBuiltIn(const TQualifier& qualifier) const;
290     bool hasInput(const TQualifier& qualifier) const;
291     void correctOutput(TQualifier& qualifier);
292     bool isOutputBuiltIn(const TQualifier& qualifier) const;
293     bool hasOutput(const TQualifier& qualifier) const;
294     void correctInput(TQualifier& qualifier);
295     void correctUniform(TQualifier& qualifier);
296     void clearUniformInputOutput(TQualifier& qualifier);
297 
298     // Test method names
299     bool isStructBufferMethod(const TString& name) const;
300     void counterBufferType(const TSourceLoc& loc, TType& type);
301 
302     // Return standard sample position array
303     TIntermConstantUnion* getSamplePosArray(int count);
304 
305     TType* getStructBufferContentType(const TType& type) const;
isStructBufferType(const TType & type)306     bool isStructBufferType(const TType& type) const { return getStructBufferContentType(type) != nullptr; }
307     TIntermTyped* indexStructBufferContent(const TSourceLoc& loc, TIntermTyped* buffer) const;
308     TIntermTyped* getStructBufferCounter(const TSourceLoc& loc, TIntermTyped* buffer);
309     TString getStructBuffCounterName(const TString&) const;
310     void addStructBuffArguments(const TSourceLoc& loc, TIntermAggregate*&);
311     void addStructBufferHiddenCounterParam(const TSourceLoc& loc, TParameter&, TIntermAggregate*&);
312 
313     // Return true if this type is a reference.  This is not currently a type method in case that's
314     // a language specific answer.
isReference(const TType & type)315     bool isReference(const TType& type) const { return isStructBufferType(type); }
316 
317     // Return true if this a buffer type that has an associated counter buffer.
318     bool hasStructBuffCounter(const TType&) const;
319 
320     // Finalization step: remove unused buffer blocks from linkage (we don't know until the
321     // shader is entirely compiled)
322     void removeUnusedStructBufferCounters();
323 
324     static bool isClipOrCullDistance(TBuiltInVariable);
isClipOrCullDistance(const TQualifier & qual)325     static bool isClipOrCullDistance(const TQualifier& qual) { return isClipOrCullDistance(qual.builtIn); }
isClipOrCullDistance(const TType & type)326     static bool isClipOrCullDistance(const TType& type) { return isClipOrCullDistance(type.getQualifier()); }
327 
328     // Find the patch constant function (issues error, returns nullptr if not found)
329     const TFunction* findPatchConstantFunction(const TSourceLoc& loc);
330 
331     // Pass through to base class after remembering built-in mappings.
332     using TParseContextBase::trackLinkage;
333     void trackLinkage(TSymbol& variable) override;
334 
335     void finish() override; // post-processing
336 
337     // Linkage symbol helpers
338     TIntermSymbol* findTessLinkageSymbol(TBuiltInVariable biType) const;
339 
340     // Current state of parsing
341     int annotationNestingLevel;  // 0 if outside all annotations
342 
343     HlslParseContext(HlslParseContext&);
344     HlslParseContext& operator=(HlslParseContext&);
345 
346     static const int maxSamplerIndex = EsdNumDims * (EbtNumTypes * (2 * 2 * 2)); // see computeSamplerTypeIndex()
347     TQualifier globalBufferDefaults;
348     TQualifier globalUniformDefaults;
349     TQualifier globalInputDefaults;
350     TQualifier globalOutputDefaults;
351     TString currentCaller;        // name of last function body entered (not valid when at global scope)
352     TIdSetType inductiveLoopIds;
353     TVector<TIntermTyped*> needsIndexLimitationChecking;
354 
355     //
356     // Geometry shader input arrays:
357     //  - array sizing is based on input primitive and/or explicit size
358     //
359     // Tessellation control output arrays:
360     //  - array sizing is based on output layout(vertices=...) and/or explicit size
361     //
362     // Both:
363     //  - array sizing is retroactive
364     //  - built-in block redeclarations interact with this
365     //
366     // Design:
367     //  - use a per-context "resize-list", a list of symbols whose array sizes
368     //    can be fixed
369     //
370     //  - the resize-list starts empty at beginning of user-shader compilation, it does
371     //    not have built-ins in it
372     //
373     //  - on built-in array use: copyUp() symbol and add it to the resize-list
374     //
375     //  - on user array declaration: add it to the resize-list
376     //
377     //  - on block redeclaration: copyUp() symbol and add it to the resize-list
378     //     * note, that appropriately gives an error if redeclaring a block that
379     //       was already used and hence already copied-up
380     //
381     //  - on seeing a layout declaration that sizes the array, fix everything in the
382     //    resize-list, giving errors for mismatch
383     //
384     //  - on seeing an array size declaration, give errors on mismatch between it and previous
385     //    array-sizing declarations
386     //
387     TVector<TSymbol*> ioArraySymbolResizeList;
388 
389     TMap<int, TFlattenData> flattenMap;
390 
391     // IO-type map. Maps a pure symbol-table form of a structure-member list into
392     // each of the (up to) three kinds of IO, as each as different allowed decorations,
393     // but HLSL allows mixing all in the same structure.
394     struct tIoKinds {
395         TTypeList* input;
396         TTypeList* output;
397         TTypeList* uniform;
398     };
399     TMap<const TTypeList*, tIoKinds> ioTypeMap;
400 
401     // Structure splitting data:
402     TMap<int, TVariable*> splitNonIoVars;  // variables with the built-in interstage IO removed, indexed by unique ID.
403 
404     // Structuredbuffer shared types.  Typically there are only a few.
405     TVector<TType*> structBufferTypes;
406 
407     // This tracks texture sample user structure return types.  Only a limited number are supported, as
408     // may fit in TSampler::structReturnIndex.
409     TVector<TTypeList*> textureReturnStruct;
410 
411     TMap<TString, bool> structBufferCounter;  // true if counter buffer is in use
412 
413     // The built-in interstage IO map considers e.g, EvqPosition on input and output separately, so that we
414     // can build the linkage correctly if position appears on both sides.  Otherwise, multiple positions
415     // are considered identical.
416     struct tInterstageIoData {
tInterstageIoDatatInterstageIoData417         tInterstageIoData(TBuiltInVariable bi, TStorageQualifier q) :
418             builtIn(bi), storage(q) { }
419 
420         TBuiltInVariable  builtIn;
421         TStorageQualifier storage;
422 
423         // ordering for maps
424         bool operator<(const tInterstageIoData d) const {
425             return (builtIn != d.builtIn) ? (builtIn < d.builtIn) : (storage < d.storage);
426         }
427     };
428 
429     TMap<tInterstageIoData, TVariable*> splitBuiltIns; // split built-ins, indexed by built-in type.
430     TVariable* inputPatch; // input patch is special for PCF: it's the only non-builtin PCF input,
431                            // and is handled as a pseudo-builtin.
432 
433     unsigned int nextInLocation;
434     unsigned int nextOutLocation;
435 
436     TFunction* entryPointFunction;
437     TIntermNode* entryPointFunctionBody;
438 
439     TString patchConstantFunctionName; // hull shader patch constant function name, from function level attribute.
440     TMap<TBuiltInVariable, TSymbol*> builtInTessLinkageSymbols; // used for tessellation, finding declared built-ins
441 
442     TVector<TString> currentTypePrefix;      // current scoping prefix for nested structures
443     TVector<TVariable*> implicitThisStack;   // currently active 'this' variables for nested structures
444 
445     TVariable* gsStreamOutput;               // geometry shader stream outputs, for emit (Append method)
446 
447     TVariable* clipDistanceOutput;           // synthesized clip distance out variable (shader might have >1)
448     TVariable* cullDistanceOutput;           // synthesized cull distance out variable (shader might have >1)
449     TVariable* clipDistanceInput;            // synthesized clip distance in variable (shader might have >1)
450     TVariable* cullDistanceInput;            // synthesized cull distance in variable (shader might have >1)
451 
452     static const int maxClipCullRegs = 2;
453     std::array<int, maxClipCullRegs> clipSemanticNSizeIn;  // vector, indexed by clip semantic ID
454     std::array<int, maxClipCullRegs> cullSemanticNSizeIn;  // vector, indexed by cull semantic ID
455     std::array<int, maxClipCullRegs> clipSemanticNSizeOut; // vector, indexed by clip semantic ID
456     std::array<int, maxClipCullRegs> cullSemanticNSizeOut; // vector, indexed by cull semantic ID
457 
458     // This tracks the first (mip level) argument to the .mips[][] operator.  Since this can be nested as
459     // in tx.mips[tx.mips[0][1].x][2], we need a stack.  We also track the TSourceLoc for error reporting
460     // purposes.
461     struct tMipsOperatorData {
tMipsOperatorDatatMipsOperatorData462         tMipsOperatorData(TSourceLoc l, TIntermTyped* m) : loc(l), mipLevel(m) { }
463         TSourceLoc loc;
464         TIntermTyped* mipLevel;
465     };
466 
467     TVector<tMipsOperatorData> mipsOperatorMipArg;
468 
469     // The geometry output stream is not copied out from the entry point as a typical output variable
470     // is.  It's written via EmitVertex (hlsl=Append), which may happen in arbitrary control flow.
471     // For this we need the real output symbol.  Since it may not be known at the time and Append()
472     // method is parsed, the sequence will be patched during finalization.
473     struct tGsAppendData {
474         TIntermAggregate* node;
475         TSourceLoc loc;
476     };
477 
478     TVector<tGsAppendData> gsAppends;
479 
480     // A texture object may be used with shadow and non-shadow samplers, but both may not be
481     // alive post-DCE in the same shader.  We do not know at compilation time which are alive: that's
482     // only known post-DCE.  If a texture is used both ways, we create two textures, and
483     // leave the elimiation of one to the optimizer.  This maps the shader variant to
484     // the shadow variant.
485     //
486     // This can be removed if and when the texture shadow code in
487     // HlslParseContext::handleSamplerTextureCombine is removed.
488     struct tShadowTextureSymbols {
tShadowTextureSymbolstShadowTextureSymbols489         tShadowTextureSymbols() { symId.fill(-1); }
490 
settShadowTextureSymbols491         void set(bool shadow, int id) { symId[int(shadow)] = id; }
gettShadowTextureSymbols492         int get(bool shadow) const { return symId[int(shadow)]; }
493 
494         // True if this texture has been seen with both shadow and non-shadow modes
overloadedtShadowTextureSymbols495         bool overloaded() const { return symId[0] != -1 && symId[1] != -1; }
isShadowIdtShadowTextureSymbols496         bool isShadowId(int id) const { return symId[1] == id; }
497 
498     private:
499         std::array<int, 2> symId;
500     };
501 
502     TMap<int, tShadowTextureSymbols*> textureShadowVariant;
503     bool parsingEntrypointParameters;
504 };
505 
506 // This is the prefix we use for built-in methods to avoid namespace collisions with
507 // global scope user functions.
508 // TODO: this would be better as a nonparseable character, but that would
509 // require changing the scanner.
510 #define BUILTIN_PREFIX "__BI_"
511 
512 } // end namespace glslang
513 
514 #endif // HLSL_PARSE_INCLUDED_
515