• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // Copyright (C) 2013 LunarG, Inc.
3 // Copyright (C) 2017 ARM Limited.
4 // Copyright (C) 2015-2018 Google, Inc.
5 //
6 // All rights reserved.
7 //
8 // Redistribution and use in source and binary forms, with or without
9 // modification, are permitted provided that the following conditions
10 // are met:
11 //
12 //    Redistributions of source code must retain the above copyright
13 //    notice, this list of conditions and the following disclaimer.
14 //
15 //    Redistributions in binary form must reproduce the above
16 //    copyright notice, this list of conditions and the following
17 //    disclaimer in the documentation and/or other materials provided
18 //    with the distribution.
19 //
20 //    Neither the name of 3Dlabs Inc. Ltd. nor the names of its
21 //    contributors may be used to endorse or promote products derived
22 //    from this software without specific prior written permission.
23 //
24 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28 // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30 // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35 // POSSIBILITY OF SUCH DAMAGE.
36 //
37 
38 //
39 // Do link-time merging and validation of intermediate representations.
40 //
41 // Basic model is that during compilation, each compilation unit (shader) is
42 // compiled into one TIntermediate instance.  Then, at link time, multiple
43 // units for the same stage can be merged together, which can generate errors.
44 // Then, after all merging, a single instance of TIntermediate represents
45 // the whole stage.  A final error check can be done on the resulting stage,
46 // even if no merging was done (i.e., the stage was only one compilation unit).
47 //
48 
49 #include "localintermediate.h"
50 #include "../Include/InfoSink.h"
51 
52 namespace glslang {
53 
54 //
55 // Link-time error emitter.
56 //
error(TInfoSink & infoSink,const char * message)57 void TIntermediate::error(TInfoSink& infoSink, const char* message)
58 {
59 #ifndef GLSLANG_WEB
60     infoSink.info.prefix(EPrefixError);
61     infoSink.info << "Linking " << StageName(language) << " stage: " << message << "\n";
62 #endif
63 
64     ++numErrors;
65 }
66 
67 // Link-time warning.
warn(TInfoSink & infoSink,const char * message)68 void TIntermediate::warn(TInfoSink& infoSink, const char* message)
69 {
70 #ifndef GLSLANG_WEB
71     infoSink.info.prefix(EPrefixWarning);
72     infoSink.info << "Linking " << StageName(language) << " stage: " << message << "\n";
73 #endif
74 }
75 
76 // TODO: 4.4 offset/align:  "Two blocks linked together in the same program with the same block
77 // name must have the exact same set of members qualified with offset and their integral-constant
78 // expression values must be the same, or a link-time error results."
79 
80 //
81 // Merge the information from 'unit' into 'this'
82 //
merge(TInfoSink & infoSink,TIntermediate & unit)83 void TIntermediate::merge(TInfoSink& infoSink, TIntermediate& unit)
84 {
85 #if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
86     mergeCallGraphs(infoSink, unit);
87     mergeModes(infoSink, unit);
88     mergeTrees(infoSink, unit);
89 #endif
90 }
91 
mergeCallGraphs(TInfoSink & infoSink,TIntermediate & unit)92 void TIntermediate::mergeCallGraphs(TInfoSink& infoSink, TIntermediate& unit)
93 {
94     if (unit.getNumEntryPoints() > 0) {
95         if (getNumEntryPoints() > 0)
96             error(infoSink, "can't handle multiple entry points per stage");
97         else {
98             entryPointName = unit.getEntryPointName();
99             entryPointMangledName = unit.getEntryPointMangledName();
100         }
101     }
102     numEntryPoints += unit.getNumEntryPoints();
103 
104     callGraph.insert(callGraph.end(), unit.callGraph.begin(), unit.callGraph.end());
105 }
106 
107 #if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
108 
109 #define MERGE_MAX(member) member = std::max(member, unit.member)
110 #define MERGE_TRUE(member) if (unit.member) member = unit.member;
111 
mergeModes(TInfoSink & infoSink,TIntermediate & unit)112 void TIntermediate::mergeModes(TInfoSink& infoSink, TIntermediate& unit)
113 {
114     if (language != unit.language)
115         error(infoSink, "stages must match when linking into a single stage");
116 
117     if (getSource() == EShSourceNone)
118         setSource(unit.getSource());
119     if (getSource() != unit.getSource())
120         error(infoSink, "can't link compilation units from different source languages");
121 
122     if (treeRoot == nullptr) {
123         profile = unit.profile;
124         version = unit.version;
125         requestedExtensions = unit.requestedExtensions;
126     } else {
127         if ((isEsProfile()) != (unit.isEsProfile()))
128             error(infoSink, "Cannot cross link ES and desktop profiles");
129         else if (unit.profile == ECompatibilityProfile)
130             profile = ECompatibilityProfile;
131         version = std::max(version, unit.version);
132         requestedExtensions.insert(unit.requestedExtensions.begin(), unit.requestedExtensions.end());
133     }
134 
135     MERGE_MAX(spvVersion.spv);
136     MERGE_MAX(spvVersion.vulkanGlsl);
137     MERGE_MAX(spvVersion.vulkan);
138     MERGE_MAX(spvVersion.openGl);
139 
140     numErrors += unit.getNumErrors();
141     // Only one push_constant is allowed, mergeLinkerObjects() will ensure the push_constant
142     // is the same for all units.
143     if (numPushConstants > 1 || unit.numPushConstants > 1)
144         error(infoSink, "Only one push_constant block is allowed per stage");
145     numPushConstants = std::min(numPushConstants + unit.numPushConstants, 1);
146 
147     if (unit.invocations != TQualifier::layoutNotSet) {
148         if (invocations == TQualifier::layoutNotSet)
149             invocations = unit.invocations;
150         else if (invocations != unit.invocations)
151             error(infoSink, "number of invocations must match between compilation units");
152     }
153 
154     if (vertices == TQualifier::layoutNotSet)
155         vertices = unit.vertices;
156     else if (unit.vertices != TQualifier::layoutNotSet && vertices != unit.vertices) {
157         if (language == EShLangGeometry || language == EShLangMeshNV)
158             error(infoSink, "Contradictory layout max_vertices values");
159         else if (language == EShLangTessControl)
160             error(infoSink, "Contradictory layout vertices values");
161         else
162             assert(0);
163     }
164     if (primitives == TQualifier::layoutNotSet)
165         primitives = unit.primitives;
166     else if (primitives != unit.primitives) {
167         if (language == EShLangMeshNV)
168             error(infoSink, "Contradictory layout max_primitives values");
169         else
170             assert(0);
171     }
172 
173     if (inputPrimitive == ElgNone)
174         inputPrimitive = unit.inputPrimitive;
175     else if (unit.inputPrimitive != ElgNone && inputPrimitive != unit.inputPrimitive)
176         error(infoSink, "Contradictory input layout primitives");
177 
178     if (outputPrimitive == ElgNone)
179         outputPrimitive = unit.outputPrimitive;
180     else if (unit.outputPrimitive != ElgNone && outputPrimitive != unit.outputPrimitive)
181         error(infoSink, "Contradictory output layout primitives");
182 
183     if (originUpperLeft != unit.originUpperLeft || pixelCenterInteger != unit.pixelCenterInteger)
184         error(infoSink, "gl_FragCoord redeclarations must match across shaders");
185 
186     if (vertexSpacing == EvsNone)
187         vertexSpacing = unit.vertexSpacing;
188     else if (vertexSpacing != unit.vertexSpacing)
189         error(infoSink, "Contradictory input vertex spacing");
190 
191     if (vertexOrder == EvoNone)
192         vertexOrder = unit.vertexOrder;
193     else if (vertexOrder != unit.vertexOrder)
194         error(infoSink, "Contradictory triangle ordering");
195 
196     MERGE_TRUE(pointMode);
197 
198     for (int i = 0; i < 3; ++i) {
199         if (!localSizeNotDefault[i] && unit.localSizeNotDefault[i]) {
200             localSize[i] = unit.localSize[i];
201             localSizeNotDefault[i] = true;
202         }
203         else if (localSize[i] != unit.localSize[i])
204             error(infoSink, "Contradictory local size");
205 
206         if (localSizeSpecId[i] == TQualifier::layoutNotSet)
207             localSizeSpecId[i] = unit.localSizeSpecId[i];
208         else if (localSizeSpecId[i] != unit.localSizeSpecId[i])
209             error(infoSink, "Contradictory local size specialization ids");
210     }
211 
212     MERGE_TRUE(earlyFragmentTests);
213     MERGE_TRUE(postDepthCoverage);
214 
215     if (depthLayout == EldNone)
216         depthLayout = unit.depthLayout;
217     else if (depthLayout != unit.depthLayout)
218         error(infoSink, "Contradictory depth layouts");
219 
220     MERGE_TRUE(depthReplacing);
221     MERGE_TRUE(hlslFunctionality1);
222 
223     blendEquations |= unit.blendEquations;
224 
225     MERGE_TRUE(xfbMode);
226 
227     for (size_t b = 0; b < xfbBuffers.size(); ++b) {
228         if (xfbBuffers[b].stride == TQualifier::layoutXfbStrideEnd)
229             xfbBuffers[b].stride = unit.xfbBuffers[b].stride;
230         else if (xfbBuffers[b].stride != unit.xfbBuffers[b].stride)
231             error(infoSink, "Contradictory xfb_stride");
232         xfbBuffers[b].implicitStride = std::max(xfbBuffers[b].implicitStride, unit.xfbBuffers[b].implicitStride);
233         if (unit.xfbBuffers[b].contains64BitType)
234             xfbBuffers[b].contains64BitType = true;
235         if (unit.xfbBuffers[b].contains32BitType)
236             xfbBuffers[b].contains32BitType = true;
237         if (unit.xfbBuffers[b].contains16BitType)
238             xfbBuffers[b].contains16BitType = true;
239         // TODO: 4.4 link: enhanced layouts: compare ranges
240     }
241 
242     MERGE_TRUE(multiStream);
243     MERGE_TRUE(layoutOverrideCoverage);
244     MERGE_TRUE(geoPassthroughEXT);
245 
246     for (unsigned int i = 0; i < unit.shiftBinding.size(); ++i) {
247         if (unit.shiftBinding[i] > 0)
248             setShiftBinding((TResourceType)i, unit.shiftBinding[i]);
249     }
250 
251     for (unsigned int i = 0; i < unit.shiftBindingForSet.size(); ++i) {
252         for (auto it = unit.shiftBindingForSet[i].begin(); it != unit.shiftBindingForSet[i].end(); ++it)
253             setShiftBindingForSet((TResourceType)i, it->second, it->first);
254     }
255 
256     resourceSetBinding.insert(resourceSetBinding.end(), unit.resourceSetBinding.begin(), unit.resourceSetBinding.end());
257 
258     MERGE_TRUE(autoMapBindings);
259     MERGE_TRUE(autoMapLocations);
260     MERGE_TRUE(invertY);
261     MERGE_TRUE(flattenUniformArrays);
262     MERGE_TRUE(useUnknownFormat);
263     MERGE_TRUE(hlslOffsets);
264     MERGE_TRUE(useStorageBuffer);
265     MERGE_TRUE(hlslIoMapping);
266 
267     // TODO: sourceFile
268     // TODO: sourceText
269     // TODO: processes
270 
271     MERGE_TRUE(needToLegalize);
272     MERGE_TRUE(binaryDoubleOutput);
273     MERGE_TRUE(usePhysicalStorageBuffer);
274 }
275 
276 //
277 // Merge the 'unit' AST into 'this' AST.
278 // That includes rationalizing the unique IDs, which were set up independently,
279 // and might have overlaps that are not the same symbol, or might have different
280 // IDs for what should be the same shared symbol.
281 //
mergeTrees(TInfoSink & infoSink,TIntermediate & unit)282 void TIntermediate::mergeTrees(TInfoSink& infoSink, TIntermediate& unit)
283 {
284     if (unit.treeRoot == nullptr)
285         return;
286 
287     if (treeRoot == nullptr) {
288         treeRoot = unit.treeRoot;
289         return;
290     }
291 
292     // Getting this far means we have two existing trees to merge...
293     numShaderRecordBlocks += unit.numShaderRecordBlocks;
294     numTaskNVBlocks += unit.numTaskNVBlocks;
295 
296     // Get the top-level globals of each unit
297     TIntermSequence& globals = treeRoot->getAsAggregate()->getSequence();
298     TIntermSequence& unitGlobals = unit.treeRoot->getAsAggregate()->getSequence();
299 
300     // Get the linker-object lists
301     TIntermSequence& linkerObjects = findLinkerObjects()->getSequence();
302     const TIntermSequence& unitLinkerObjects = unit.findLinkerObjects()->getSequence();
303 
304     // Map by global name to unique ID to rationalize the same object having
305     // differing IDs in different trees.
306     TIdMaps idMaps;
307     int maxId;
308     seedIdMap(idMaps, maxId);
309     remapIds(idMaps, maxId + 1, unit);
310 
311     mergeBodies(infoSink, globals, unitGlobals);
312     mergeLinkerObjects(infoSink, linkerObjects, unitLinkerObjects);
313     ioAccessed.insert(unit.ioAccessed.begin(), unit.ioAccessed.end());
314 }
315 
316 #endif
317 
getNameForIdMap(TIntermSymbol * symbol)318 static const TString& getNameForIdMap(TIntermSymbol* symbol)
319 {
320     TShaderInterface si = symbol->getType().getShaderInterface();
321     if (si == EsiNone)
322         return symbol->getName();
323     else
324         return symbol->getType().getTypeName();
325 }
326 
327 
328 
329 // Traverser that seeds an ID map with all built-ins, and tracks the
330 // maximum ID used.
331 // (It would be nice to put this in a function, but that causes warnings
332 // on having no bodies for the copy-constructor/operator=.)
333 class TBuiltInIdTraverser : public TIntermTraverser {
334 public:
TBuiltInIdTraverser(TIdMaps & idMaps)335     TBuiltInIdTraverser(TIdMaps& idMaps) : idMaps(idMaps), maxId(0) { }
336     // If it's a built in, add it to the map.
337     // Track the max ID.
visitSymbol(TIntermSymbol * symbol)338     virtual void visitSymbol(TIntermSymbol* symbol)
339     {
340         const TQualifier& qualifier = symbol->getType().getQualifier();
341         if (qualifier.builtIn != EbvNone) {
342             TShaderInterface si = symbol->getType().getShaderInterface();
343             idMaps[si][getNameForIdMap(symbol)] = symbol->getId();
344         }
345         maxId = std::max(maxId, symbol->getId());
346     }
getMaxId() const347     int getMaxId() const { return maxId; }
348 protected:
349     TBuiltInIdTraverser(TBuiltInIdTraverser&);
350     TBuiltInIdTraverser& operator=(TBuiltInIdTraverser&);
351     TIdMaps& idMaps;
352     int maxId;
353 };
354 
355 // Traverser that seeds an ID map with non-builtins.
356 // (It would be nice to put this in a function, but that causes warnings
357 // on having no bodies for the copy-constructor/operator=.)
358 class TUserIdTraverser : public TIntermTraverser {
359 public:
TUserIdTraverser(TIdMaps & idMaps)360     TUserIdTraverser(TIdMaps& idMaps) : idMaps(idMaps) { }
361     // If its a non-built-in global, add it to the map.
visitSymbol(TIntermSymbol * symbol)362     virtual void visitSymbol(TIntermSymbol* symbol)
363     {
364         const TQualifier& qualifier = symbol->getType().getQualifier();
365         if (qualifier.builtIn == EbvNone) {
366             TShaderInterface si = symbol->getType().getShaderInterface();
367             idMaps[si][getNameForIdMap(symbol)] = symbol->getId();
368         }
369     }
370 
371 protected:
372     TUserIdTraverser(TUserIdTraverser&);
373     TUserIdTraverser& operator=(TUserIdTraverser&);
374     TIdMaps& idMaps; // over biggest id
375 };
376 
377 // Initialize the the ID map with what we know of 'this' AST.
seedIdMap(TIdMaps & idMaps,int & maxId)378 void TIntermediate::seedIdMap(TIdMaps& idMaps, int& maxId)
379 {
380     // all built-ins everywhere need to align on IDs and contribute to the max ID
381     TBuiltInIdTraverser builtInIdTraverser(idMaps);
382     treeRoot->traverse(&builtInIdTraverser);
383     maxId = builtInIdTraverser.getMaxId();
384 
385     // user variables in the linker object list need to align on ids
386     TUserIdTraverser userIdTraverser(idMaps);
387     findLinkerObjects()->traverse(&userIdTraverser);
388 }
389 
390 // Traverser to map an AST ID to what was known from the seeding AST.
391 // (It would be nice to put this in a function, but that causes warnings
392 // on having no bodies for the copy-constructor/operator=.)
393 class TRemapIdTraverser : public TIntermTraverser {
394 public:
TRemapIdTraverser(const TIdMaps & idMaps,int idShift)395     TRemapIdTraverser(const TIdMaps& idMaps, int idShift) : idMaps(idMaps), idShift(idShift) { }
396     // Do the mapping:
397     //  - if the same symbol, adopt the 'this' ID
398     //  - otherwise, ensure a unique ID by shifting to a new space
visitSymbol(TIntermSymbol * symbol)399     virtual void visitSymbol(TIntermSymbol* symbol)
400     {
401         const TQualifier& qualifier = symbol->getType().getQualifier();
402         bool remapped = false;
403         if (qualifier.isLinkable() || qualifier.builtIn != EbvNone) {
404             TShaderInterface si = symbol->getType().getShaderInterface();
405             auto it = idMaps[si].find(getNameForIdMap(symbol));
406             if (it != idMaps[si].end()) {
407                 symbol->changeId(it->second);
408                 remapped = true;
409             }
410         }
411         if (!remapped)
412             symbol->changeId(symbol->getId() + idShift);
413     }
414 protected:
415     TRemapIdTraverser(TRemapIdTraverser&);
416     TRemapIdTraverser& operator=(TRemapIdTraverser&);
417     const TIdMaps& idMaps;
418     int idShift;
419 };
420 
remapIds(const TIdMaps & idMaps,int idShift,TIntermediate & unit)421 void TIntermediate::remapIds(const TIdMaps& idMaps, int idShift, TIntermediate& unit)
422 {
423     // Remap all IDs to either share or be unique, as dictated by the idMap and idShift.
424     TRemapIdTraverser idTraverser(idMaps, idShift);
425     unit.getTreeRoot()->traverse(&idTraverser);
426 }
427 
428 //
429 // Merge the function bodies and global-level initializers from unitGlobals into globals.
430 // Will error check duplication of function bodies for the same signature.
431 //
mergeBodies(TInfoSink & infoSink,TIntermSequence & globals,const TIntermSequence & unitGlobals)432 void TIntermediate::mergeBodies(TInfoSink& infoSink, TIntermSequence& globals, const TIntermSequence& unitGlobals)
433 {
434     // TODO: link-time performance: Processing in alphabetical order will be faster
435 
436     // Error check the global objects, not including the linker objects
437     for (unsigned int child = 0; child < globals.size() - 1; ++child) {
438         for (unsigned int unitChild = 0; unitChild < unitGlobals.size() - 1; ++unitChild) {
439             TIntermAggregate* body = globals[child]->getAsAggregate();
440             TIntermAggregate* unitBody = unitGlobals[unitChild]->getAsAggregate();
441             if (body && unitBody && body->getOp() == EOpFunction && unitBody->getOp() == EOpFunction && body->getName() == unitBody->getName()) {
442                 error(infoSink, "Multiple function bodies in multiple compilation units for the same signature in the same stage:");
443                 infoSink.info << "    " << globals[child]->getAsAggregate()->getName() << "\n";
444             }
445         }
446     }
447 
448     // Merge the global objects, just in front of the linker objects
449     globals.insert(globals.end() - 1, unitGlobals.begin(), unitGlobals.end() - 1);
450 }
451 
452 //
453 // Merge the linker objects from unitLinkerObjects into linkerObjects.
454 // Duplication is expected and filtered out, but contradictions are an error.
455 //
mergeLinkerObjects(TInfoSink & infoSink,TIntermSequence & linkerObjects,const TIntermSequence & unitLinkerObjects)456 void TIntermediate::mergeLinkerObjects(TInfoSink& infoSink, TIntermSequence& linkerObjects, const TIntermSequence& unitLinkerObjects)
457 {
458     // Error check and merge the linker objects (duplicates should not be created)
459     std::size_t initialNumLinkerObjects = linkerObjects.size();
460     for (unsigned int unitLinkObj = 0; unitLinkObj < unitLinkerObjects.size(); ++unitLinkObj) {
461         bool merge = true;
462         for (std::size_t linkObj = 0; linkObj < initialNumLinkerObjects; ++linkObj) {
463             TIntermSymbol* symbol = linkerObjects[linkObj]->getAsSymbolNode();
464             TIntermSymbol* unitSymbol = unitLinkerObjects[unitLinkObj]->getAsSymbolNode();
465             assert(symbol && unitSymbol);
466 
467             bool isSameSymbol = false;
468             // If they are both blocks in the same shader interface,
469             // match by the block-name, not the identifier name.
470             if (symbol->getType().getBasicType() == EbtBlock && unitSymbol->getType().getBasicType() == EbtBlock) {
471                 if (symbol->getType().getShaderInterface() == unitSymbol->getType().getShaderInterface()) {
472                     isSameSymbol = symbol->getType().getTypeName() == unitSymbol->getType().getTypeName();
473                 }
474             }
475             else if (symbol->getName() == unitSymbol->getName())
476                 isSameSymbol = true;
477 
478             if (isSameSymbol) {
479                 // filter out copy
480                 merge = false;
481 
482                 // but if one has an initializer and the other does not, update
483                 // the initializer
484                 if (symbol->getConstArray().empty() && ! unitSymbol->getConstArray().empty())
485                     symbol->setConstArray(unitSymbol->getConstArray());
486 
487                 // Similarly for binding
488                 if (! symbol->getQualifier().hasBinding() && unitSymbol->getQualifier().hasBinding())
489                     symbol->getQualifier().layoutBinding = unitSymbol->getQualifier().layoutBinding;
490 
491                 // Update implicit array sizes
492                 mergeImplicitArraySizes(symbol->getWritableType(), unitSymbol->getType());
493 
494                 // Check for consistent types/qualification/initializers etc.
495                 mergeErrorCheck(infoSink, *symbol, *unitSymbol, false);
496             }
497             // If different symbols, verify they arn't push_constant since there can only be one per stage
498             else if (symbol->getQualifier().isPushConstant() && unitSymbol->getQualifier().isPushConstant())
499                 error(infoSink, "Only one push_constant block is allowed per stage");
500         }
501         if (merge)
502             linkerObjects.push_back(unitLinkerObjects[unitLinkObj]);
503     }
504 }
505 
506 // TODO 4.5 link functionality: cull distance array size checking
507 
508 // Recursively merge the implicit array sizes through the objects' respective type trees.
mergeImplicitArraySizes(TType & type,const TType & unitType)509 void TIntermediate::mergeImplicitArraySizes(TType& type, const TType& unitType)
510 {
511     if (type.isUnsizedArray()) {
512         if (unitType.isUnsizedArray()) {
513             type.updateImplicitArraySize(unitType.getImplicitArraySize());
514             if (unitType.isArrayVariablyIndexed())
515                 type.setArrayVariablyIndexed();
516         } else if (unitType.isSizedArray())
517             type.changeOuterArraySize(unitType.getOuterArraySize());
518     }
519 
520     // Type mismatches are caught and reported after this, just be careful for now.
521     if (! type.isStruct() || ! unitType.isStruct() || type.getStruct()->size() != unitType.getStruct()->size())
522         return;
523 
524     for (int i = 0; i < (int)type.getStruct()->size(); ++i)
525         mergeImplicitArraySizes(*(*type.getStruct())[i].type, *(*unitType.getStruct())[i].type);
526 }
527 
528 //
529 // Compare two global objects from two compilation units and see if they match
530 // well enough.  Rules can be different for intra- vs. cross-stage matching.
531 //
532 // This function only does one of intra- or cross-stage matching per call.
533 //
mergeErrorCheck(TInfoSink & infoSink,const TIntermSymbol & symbol,const TIntermSymbol & unitSymbol,bool crossStage)534 void TIntermediate::mergeErrorCheck(TInfoSink& infoSink, const TIntermSymbol& symbol, const TIntermSymbol& unitSymbol, bool crossStage)
535 {
536 #if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
537     bool writeTypeComparison = false;
538 
539     // Types have to match
540     if (symbol.getType() != unitSymbol.getType()) {
541         // but, we make an exception if one is an implicit array and the other is sized
542         if (! (symbol.getType().isArray() && unitSymbol.getType().isArray() &&
543                 symbol.getType().sameElementType(unitSymbol.getType()) &&
544                 (symbol.getType().isUnsizedArray() || unitSymbol.getType().isUnsizedArray()))) {
545             error(infoSink, "Types must match:");
546             writeTypeComparison = true;
547         }
548     }
549 
550     // Qualifiers have to (almost) match
551 
552     // Storage...
553     if (symbol.getQualifier().storage != unitSymbol.getQualifier().storage) {
554         error(infoSink, "Storage qualifiers must match:");
555         writeTypeComparison = true;
556     }
557 
558     // Uniform and buffer blocks must either both have an instance name, or
559     // must both be anonymous. The names don't need to match though.
560     if (symbol.getQualifier().isUniformOrBuffer() &&
561         (IsAnonymous(symbol.getName()) != IsAnonymous(unitSymbol.getName()))) {
562         error(infoSink, "Matched Uniform or Storage blocks must all be anonymous,"
563                         " or all be named:");
564         writeTypeComparison = true;
565     }
566 
567     if (symbol.getQualifier().storage == unitSymbol.getQualifier().storage &&
568         (IsAnonymous(symbol.getName()) != IsAnonymous(unitSymbol.getName()) ||
569          (!IsAnonymous(symbol.getName()) && symbol.getName() != unitSymbol.getName()))) {
570         warn(infoSink, "Matched shader interfaces are using different instance names.");
571         writeTypeComparison = true;
572     }
573 
574     // Precision...
575     if (symbol.getQualifier().precision != unitSymbol.getQualifier().precision) {
576         error(infoSink, "Precision qualifiers must match:");
577         writeTypeComparison = true;
578     }
579 
580     // Invariance...
581     if (! crossStage && symbol.getQualifier().invariant != unitSymbol.getQualifier().invariant) {
582         error(infoSink, "Presence of invariant qualifier must match:");
583         writeTypeComparison = true;
584     }
585 
586     // Precise...
587     if (! crossStage && symbol.getQualifier().isNoContraction() != unitSymbol.getQualifier().isNoContraction()) {
588         error(infoSink, "Presence of precise qualifier must match:");
589         writeTypeComparison = true;
590     }
591 
592     // Auxiliary and interpolation...
593     if (symbol.getQualifier().centroid  != unitSymbol.getQualifier().centroid ||
594         symbol.getQualifier().smooth    != unitSymbol.getQualifier().smooth ||
595         symbol.getQualifier().flat      != unitSymbol.getQualifier().flat ||
596         symbol.getQualifier().isSample()!= unitSymbol.getQualifier().isSample() ||
597         symbol.getQualifier().isPatch() != unitSymbol.getQualifier().isPatch() ||
598         symbol.getQualifier().isNonPerspective() != unitSymbol.getQualifier().isNonPerspective()) {
599         error(infoSink, "Interpolation and auxiliary storage qualifiers must match:");
600         writeTypeComparison = true;
601     }
602 
603     // Memory...
604     if (symbol.getQualifier().coherent          != unitSymbol.getQualifier().coherent ||
605         symbol.getQualifier().devicecoherent    != unitSymbol.getQualifier().devicecoherent ||
606         symbol.getQualifier().queuefamilycoherent  != unitSymbol.getQualifier().queuefamilycoherent ||
607         symbol.getQualifier().workgroupcoherent != unitSymbol.getQualifier().workgroupcoherent ||
608         symbol.getQualifier().subgroupcoherent  != unitSymbol.getQualifier().subgroupcoherent ||
609         symbol.getQualifier().shadercallcoherent!= unitSymbol.getQualifier().shadercallcoherent ||
610         symbol.getQualifier().nonprivate        != unitSymbol.getQualifier().nonprivate ||
611         symbol.getQualifier().volatil           != unitSymbol.getQualifier().volatil ||
612         symbol.getQualifier().restrict          != unitSymbol.getQualifier().restrict ||
613         symbol.getQualifier().readonly          != unitSymbol.getQualifier().readonly ||
614         symbol.getQualifier().writeonly         != unitSymbol.getQualifier().writeonly) {
615         error(infoSink, "Memory qualifiers must match:");
616         writeTypeComparison = true;
617     }
618 
619     // Layouts...
620     // TODO: 4.4 enhanced layouts: Generalize to include offset/align: current spec
621     //       requires separate user-supplied offset from actual computed offset, but
622     //       current implementation only has one offset.
623     if (symbol.getQualifier().layoutMatrix    != unitSymbol.getQualifier().layoutMatrix ||
624         symbol.getQualifier().layoutPacking   != unitSymbol.getQualifier().layoutPacking ||
625         symbol.getQualifier().layoutLocation  != unitSymbol.getQualifier().layoutLocation ||
626         symbol.getQualifier().layoutComponent != unitSymbol.getQualifier().layoutComponent ||
627         symbol.getQualifier().layoutIndex     != unitSymbol.getQualifier().layoutIndex ||
628         symbol.getQualifier().layoutBinding   != unitSymbol.getQualifier().layoutBinding ||
629         (symbol.getQualifier().hasBinding() && (symbol.getQualifier().layoutOffset != unitSymbol.getQualifier().layoutOffset))) {
630         error(infoSink, "Layout qualification must match:");
631         writeTypeComparison = true;
632     }
633 
634     // Initializers have to match, if both are present, and if we don't already know the types don't match
635     if (! writeTypeComparison) {
636         if (! symbol.getConstArray().empty() && ! unitSymbol.getConstArray().empty()) {
637             if (symbol.getConstArray() != unitSymbol.getConstArray()) {
638                 error(infoSink, "Initializers must match:");
639                 infoSink.info << "    " << symbol.getName() << "\n";
640             }
641         }
642     }
643 
644     if (writeTypeComparison) {
645         infoSink.info << "    " << symbol.getName() << ": \"" << symbol.getType().getCompleteString() << "\" versus ";
646         if (symbol.getName() != unitSymbol.getName())
647             infoSink.info << unitSymbol.getName() << ": ";
648 
649         infoSink.info << "\"" << unitSymbol.getType().getCompleteString() << "\"\n";
650     }
651 #endif
652 }
653 
654 //
655 // Do final link-time error checking of a complete (merged) intermediate representation.
656 // (Much error checking was done during merging).
657 //
658 // Also, lock in defaults of things not set, including array sizes.
659 //
finalCheck(TInfoSink & infoSink,bool keepUncalled)660 void TIntermediate::finalCheck(TInfoSink& infoSink, bool keepUncalled)
661 {
662     if (getTreeRoot() == nullptr)
663         return;
664 
665     if (numEntryPoints < 1) {
666         if (getSource() == EShSourceGlsl)
667             error(infoSink, "Missing entry point: Each stage requires one entry point");
668         else
669             warn(infoSink, "Entry point not found");
670     }
671 
672     // recursion and missing body checking
673     checkCallGraphCycles(infoSink);
674     checkCallGraphBodies(infoSink, keepUncalled);
675 
676     // overlap/alias/missing I/O, etc.
677     inOutLocationCheck(infoSink);
678 
679 #ifndef GLSLANG_WEB
680     if (getNumPushConstants() > 1)
681         error(infoSink, "Only one push_constant block is allowed per stage");
682 
683     // invocations
684     if (invocations == TQualifier::layoutNotSet)
685         invocations = 1;
686 
687     if (inIoAccessed("gl_ClipDistance") && inIoAccessed("gl_ClipVertex"))
688         error(infoSink, "Can only use one of gl_ClipDistance or gl_ClipVertex (gl_ClipDistance is preferred)");
689     if (inIoAccessed("gl_CullDistance") && inIoAccessed("gl_ClipVertex"))
690         error(infoSink, "Can only use one of gl_CullDistance or gl_ClipVertex (gl_ClipDistance is preferred)");
691 
692     if (userOutputUsed() && (inIoAccessed("gl_FragColor") || inIoAccessed("gl_FragData")))
693         error(infoSink, "Cannot use gl_FragColor or gl_FragData when using user-defined outputs");
694     if (inIoAccessed("gl_FragColor") && inIoAccessed("gl_FragData"))
695         error(infoSink, "Cannot use both gl_FragColor and gl_FragData");
696 
697     for (size_t b = 0; b < xfbBuffers.size(); ++b) {
698         if (xfbBuffers[b].contains64BitType)
699             RoundToPow2(xfbBuffers[b].implicitStride, 8);
700         else if (xfbBuffers[b].contains32BitType)
701             RoundToPow2(xfbBuffers[b].implicitStride, 4);
702         else if (xfbBuffers[b].contains16BitType)
703             RoundToPow2(xfbBuffers[b].implicitStride, 2);
704 
705         // "It is a compile-time or link-time error to have
706         // any xfb_offset that overflows xfb_stride, whether stated on declarations before or after the xfb_stride, or
707         // in different compilation units. While xfb_stride can be declared multiple times for the same buffer, it is a
708         // compile-time or link-time error to have different values specified for the stride for the same buffer."
709         if (xfbBuffers[b].stride != TQualifier::layoutXfbStrideEnd && xfbBuffers[b].implicitStride > xfbBuffers[b].stride) {
710             error(infoSink, "xfb_stride is too small to hold all buffer entries:");
711             infoSink.info.prefix(EPrefixError);
712             infoSink.info << "    xfb_buffer " << (unsigned int)b << ", xfb_stride " << xfbBuffers[b].stride << ", minimum stride needed: " << xfbBuffers[b].implicitStride << "\n";
713         }
714         if (xfbBuffers[b].stride == TQualifier::layoutXfbStrideEnd)
715             xfbBuffers[b].stride = xfbBuffers[b].implicitStride;
716 
717         // "If the buffer is capturing any
718         // outputs with double-precision or 64-bit integer components, the stride must be a multiple of 8, otherwise it must be a
719         // multiple of 4, or a compile-time or link-time error results."
720         if (xfbBuffers[b].contains64BitType && ! IsMultipleOfPow2(xfbBuffers[b].stride, 8)) {
721             error(infoSink, "xfb_stride must be multiple of 8 for buffer holding a double or 64-bit integer:");
722             infoSink.info.prefix(EPrefixError);
723             infoSink.info << "    xfb_buffer " << (unsigned int)b << ", xfb_stride " << xfbBuffers[b].stride << "\n";
724         } else if (xfbBuffers[b].contains32BitType && ! IsMultipleOfPow2(xfbBuffers[b].stride, 4)) {
725             error(infoSink, "xfb_stride must be multiple of 4:");
726             infoSink.info.prefix(EPrefixError);
727             infoSink.info << "    xfb_buffer " << (unsigned int)b << ", xfb_stride " << xfbBuffers[b].stride << "\n";
728         }
729         // "If the buffer is capturing any
730         // outputs with half-precision or 16-bit integer components, the stride must be a multiple of 2"
731         else if (xfbBuffers[b].contains16BitType && ! IsMultipleOfPow2(xfbBuffers[b].stride, 2)) {
732             error(infoSink, "xfb_stride must be multiple of 2 for buffer holding a half float or 16-bit integer:");
733             infoSink.info.prefix(EPrefixError);
734             infoSink.info << "    xfb_buffer " << (unsigned int)b << ", xfb_stride " << xfbBuffers[b].stride << "\n";
735         }
736 
737         // "The resulting stride (implicit or explicit), when divided by 4, must be less than or equal to the
738         // implementation-dependent constant gl_MaxTransformFeedbackInterleavedComponents."
739         if (xfbBuffers[b].stride > (unsigned int)(4 * resources->maxTransformFeedbackInterleavedComponents)) {
740             error(infoSink, "xfb_stride is too large:");
741             infoSink.info.prefix(EPrefixError);
742             infoSink.info << "    xfb_buffer " << (unsigned int)b << ", components (1/4 stride) needed are " << xfbBuffers[b].stride/4 << ", gl_MaxTransformFeedbackInterleavedComponents is " << resources->maxTransformFeedbackInterleavedComponents << "\n";
743         }
744     }
745 
746     switch (language) {
747     case EShLangVertex:
748         break;
749     case EShLangTessControl:
750         if (vertices == TQualifier::layoutNotSet)
751             error(infoSink, "At least one shader must specify an output layout(vertices=...)");
752         break;
753     case EShLangTessEvaluation:
754         if (getSource() == EShSourceGlsl) {
755             if (inputPrimitive == ElgNone)
756                 error(infoSink, "At least one shader must specify an input layout primitive");
757             if (vertexSpacing == EvsNone)
758                 vertexSpacing = EvsEqual;
759             if (vertexOrder == EvoNone)
760                 vertexOrder = EvoCcw;
761         }
762         break;
763     case EShLangGeometry:
764         if (inputPrimitive == ElgNone)
765             error(infoSink, "At least one shader must specify an input layout primitive");
766         if (outputPrimitive == ElgNone)
767             error(infoSink, "At least one shader must specify an output layout primitive");
768         if (vertices == TQualifier::layoutNotSet)
769             error(infoSink, "At least one shader must specify a layout(max_vertices = value)");
770         break;
771     case EShLangFragment:
772         // for GL_ARB_post_depth_coverage, EarlyFragmentTest is set automatically in
773         // ParseHelper.cpp. So if we reach here, this must be GL_EXT_post_depth_coverage
774         // requiring explicit early_fragment_tests
775         if (getPostDepthCoverage() && !getEarlyFragmentTests())
776             error(infoSink, "post_depth_coverage requires early_fragment_tests");
777         break;
778     case EShLangCompute:
779         break;
780     case EShLangRayGen:
781     case EShLangIntersect:
782     case EShLangAnyHit:
783     case EShLangClosestHit:
784     case EShLangMiss:
785     case EShLangCallable:
786         if (numShaderRecordBlocks > 1)
787             error(infoSink, "Only one shaderRecordNV buffer block is allowed per stage");
788         break;
789     case EShLangMeshNV:
790         // NV_mesh_shader doesn't allow use of both single-view and per-view builtins.
791         if (inIoAccessed("gl_Position") && inIoAccessed("gl_PositionPerViewNV"))
792             error(infoSink, "Can only use one of gl_Position or gl_PositionPerViewNV");
793         if (inIoAccessed("gl_ClipDistance") && inIoAccessed("gl_ClipDistancePerViewNV"))
794             error(infoSink, "Can only use one of gl_ClipDistance or gl_ClipDistancePerViewNV");
795         if (inIoAccessed("gl_CullDistance") && inIoAccessed("gl_CullDistancePerViewNV"))
796             error(infoSink, "Can only use one of gl_CullDistance or gl_CullDistancePerViewNV");
797         if (inIoAccessed("gl_Layer") && inIoAccessed("gl_LayerPerViewNV"))
798             error(infoSink, "Can only use one of gl_Layer or gl_LayerPerViewNV");
799         if (inIoAccessed("gl_ViewportMask") && inIoAccessed("gl_ViewportMaskPerViewNV"))
800             error(infoSink, "Can only use one of gl_ViewportMask or gl_ViewportMaskPerViewNV");
801         if (outputPrimitive == ElgNone)
802             error(infoSink, "At least one shader must specify an output layout primitive");
803         if (vertices == TQualifier::layoutNotSet)
804             error(infoSink, "At least one shader must specify a layout(max_vertices = value)");
805         if (primitives == TQualifier::layoutNotSet)
806             error(infoSink, "At least one shader must specify a layout(max_primitives = value)");
807         // fall through
808     case EShLangTaskNV:
809         if (numTaskNVBlocks > 1)
810             error(infoSink, "Only one taskNV interface block is allowed per shader");
811         break;
812     default:
813         error(infoSink, "Unknown Stage.");
814         break;
815     }
816 
817     // Process the tree for any node-specific work.
818     class TFinalLinkTraverser : public TIntermTraverser {
819     public:
820         TFinalLinkTraverser() { }
821         virtual ~TFinalLinkTraverser() { }
822 
823         virtual void visitSymbol(TIntermSymbol* symbol)
824         {
825             // Implicitly size arrays.
826             // If an unsized array is left as unsized, it effectively
827             // becomes run-time sized.
828             symbol->getWritableType().adoptImplicitArraySizes(false);
829         }
830     } finalLinkTraverser;
831 
832     treeRoot->traverse(&finalLinkTraverser);
833 #endif
834 }
835 
836 //
837 // See if the call graph contains any static recursion, which is disallowed
838 // by the specification.
839 //
checkCallGraphCycles(TInfoSink & infoSink)840 void TIntermediate::checkCallGraphCycles(TInfoSink& infoSink)
841 {
842     // Clear fields we'll use for this.
843     for (TGraph::iterator call = callGraph.begin(); call != callGraph.end(); ++call) {
844         call->visited = false;
845         call->currentPath = false;
846         call->errorGiven = false;
847     }
848 
849     //
850     // Loop, looking for a new connected subgraph.  One subgraph is handled per loop iteration.
851     //
852 
853     TCall* newRoot;
854     do {
855         // See if we have unvisited parts of the graph.
856         newRoot = 0;
857         for (TGraph::iterator call = callGraph.begin(); call != callGraph.end(); ++call) {
858             if (! call->visited) {
859                 newRoot = &(*call);
860                 break;
861             }
862         }
863 
864         // If not, we are done.
865         if (! newRoot)
866             break;
867 
868         // Otherwise, we found a new subgraph, process it:
869         // See what all can be reached by this new root, and if any of
870         // that is recursive.  This is done by depth-first traversals, seeing
871         // if a new call is found that was already in the currentPath (a back edge),
872         // thereby detecting recursion.
873         std::list<TCall*> stack;
874         newRoot->currentPath = true; // currentPath will be true iff it is on the stack
875         stack.push_back(newRoot);
876         while (! stack.empty()) {
877             // get a caller
878             TCall* call = stack.back();
879 
880             // Add to the stack just one callee.
881             // This algorithm always terminates, because only !visited and !currentPath causes a push
882             // and all pushes change currentPath to true, and all pops change visited to true.
883             TGraph::iterator child = callGraph.begin();
884             for (; child != callGraph.end(); ++child) {
885 
886                 // If we already visited this node, its whole subgraph has already been processed, so skip it.
887                 if (child->visited)
888                     continue;
889 
890                 if (call->callee == child->caller) {
891                     if (child->currentPath) {
892                         // Then, we found a back edge
893                         if (! child->errorGiven) {
894                             error(infoSink, "Recursion detected:");
895                             infoSink.info << "    " << call->callee << " calling " << child->callee << "\n";
896                             child->errorGiven = true;
897                             recursive = true;
898                         }
899                     } else {
900                         child->currentPath = true;
901                         stack.push_back(&(*child));
902                         break;
903                     }
904                 }
905             }
906             if (child == callGraph.end()) {
907                 // no more callees, we bottomed out, never look at this node again
908                 stack.back()->currentPath = false;
909                 stack.back()->visited = true;
910                 stack.pop_back();
911             }
912         }  // end while, meaning nothing left to process in this subtree
913 
914     } while (newRoot);  // redundant loop check; should always exit via the 'break' above
915 }
916 
917 //
918 // See which functions are reachable from the entry point and which have bodies.
919 // Reachable ones with missing bodies are errors.
920 // Unreachable bodies are dead code.
921 //
checkCallGraphBodies(TInfoSink & infoSink,bool keepUncalled)922 void TIntermediate::checkCallGraphBodies(TInfoSink& infoSink, bool keepUncalled)
923 {
924     // Clear fields we'll use for this.
925     for (TGraph::iterator call = callGraph.begin(); call != callGraph.end(); ++call) {
926         call->visited = false;
927         call->calleeBodyPosition = -1;
928     }
929 
930     // The top level of the AST includes function definitions (bodies).
931     // Compare these to function calls in the call graph.
932     // We'll end up knowing which have bodies, and if so,
933     // how to map the call-graph node to the location in the AST.
934     TIntermSequence &functionSequence = getTreeRoot()->getAsAggregate()->getSequence();
935     std::vector<bool> reachable(functionSequence.size(), true); // so that non-functions are reachable
936     for (int f = 0; f < (int)functionSequence.size(); ++f) {
937         glslang::TIntermAggregate* node = functionSequence[f]->getAsAggregate();
938         if (node && (node->getOp() == glslang::EOpFunction)) {
939             if (node->getName().compare(getEntryPointMangledName().c_str()) != 0)
940                 reachable[f] = false; // so that function bodies are unreachable, until proven otherwise
941             for (TGraph::iterator call = callGraph.begin(); call != callGraph.end(); ++call) {
942                 if (call->callee == node->getName())
943                     call->calleeBodyPosition = f;
944             }
945         }
946     }
947 
948     // Start call-graph traversal by visiting the entry point nodes.
949     for (TGraph::iterator call = callGraph.begin(); call != callGraph.end(); ++call) {
950         if (call->caller.compare(getEntryPointMangledName().c_str()) == 0)
951             call->visited = true;
952     }
953 
954     // Propagate 'visited' through the call-graph to every part of the graph it
955     // can reach (seeded with the entry-point setting above).
956     bool changed;
957     do {
958         changed = false;
959         for (auto call1 = callGraph.begin(); call1 != callGraph.end(); ++call1) {
960             if (call1->visited) {
961                 for (TGraph::iterator call2 = callGraph.begin(); call2 != callGraph.end(); ++call2) {
962                     if (! call2->visited) {
963                         if (call1->callee == call2->caller) {
964                             changed = true;
965                             call2->visited = true;
966                         }
967                     }
968                 }
969             }
970         }
971     } while (changed);
972 
973     // Any call-graph node set to visited but without a callee body is an error.
974     for (TGraph::iterator call = callGraph.begin(); call != callGraph.end(); ++call) {
975         if (call->visited) {
976             if (call->calleeBodyPosition == -1) {
977                 error(infoSink, "No function definition (body) found: ");
978                 infoSink.info << "    " << call->callee << "\n";
979             } else
980                 reachable[call->calleeBodyPosition] = true;
981         }
982     }
983 
984     // Bodies in the AST not reached by the call graph are dead;
985     // clear them out, since they can't be reached and also can't
986     // be translated further due to possibility of being ill defined.
987     if (! keepUncalled) {
988         for (int f = 0; f < (int)functionSequence.size(); ++f) {
989             if (! reachable[f])
990                 functionSequence[f] = nullptr;
991         }
992         functionSequence.erase(std::remove(functionSequence.begin(), functionSequence.end(), nullptr), functionSequence.end());
993     }
994 }
995 
996 //
997 // Satisfy rules for location qualifiers on inputs and outputs
998 //
inOutLocationCheck(TInfoSink & infoSink)999 void TIntermediate::inOutLocationCheck(TInfoSink& infoSink)
1000 {
1001     // ES 3.0 requires all outputs to have location qualifiers if there is more than one output
1002     bool fragOutWithNoLocation = false;
1003     int numFragOut = 0;
1004 
1005     // TODO: linker functionality: location collision checking
1006 
1007     TIntermSequence& linkObjects = findLinkerObjects()->getSequence();
1008     for (size_t i = 0; i < linkObjects.size(); ++i) {
1009         const TType& type = linkObjects[i]->getAsTyped()->getType();
1010         const TQualifier& qualifier = type.getQualifier();
1011         if (language == EShLangFragment) {
1012             if (qualifier.storage == EvqVaryingOut && qualifier.builtIn == EbvNone) {
1013                 ++numFragOut;
1014                 if (!qualifier.hasAnyLocation())
1015                     fragOutWithNoLocation = true;
1016             }
1017         }
1018     }
1019 
1020     if (isEsProfile()) {
1021         if (numFragOut > 1 && fragOutWithNoLocation)
1022             error(infoSink, "when more than one fragment shader output, all must have location qualifiers");
1023     }
1024 }
1025 
findLinkerObjects() const1026 TIntermAggregate* TIntermediate::findLinkerObjects() const
1027 {
1028     // Get the top-level globals
1029     TIntermSequence& globals = treeRoot->getAsAggregate()->getSequence();
1030 
1031     // Get the last member of the sequences, expected to be the linker-object lists
1032     assert(globals.back()->getAsAggregate()->getOp() == EOpLinkerObjects);
1033 
1034     return globals.back()->getAsAggregate();
1035 }
1036 
1037 // See if a variable was both a user-declared output and used.
1038 // Note: the spec discusses writing to one, but this looks at read or write, which
1039 // is more useful, and perhaps the spec should be changed to reflect that.
userOutputUsed() const1040 bool TIntermediate::userOutputUsed() const
1041 {
1042     const TIntermSequence& linkerObjects = findLinkerObjects()->getSequence();
1043 
1044     bool found = false;
1045     for (size_t i = 0; i < linkerObjects.size(); ++i) {
1046         const TIntermSymbol& symbolNode = *linkerObjects[i]->getAsSymbolNode();
1047         if (symbolNode.getQualifier().storage == EvqVaryingOut &&
1048             symbolNode.getName().compare(0, 3, "gl_") != 0 &&
1049             inIoAccessed(symbolNode.getName())) {
1050             found = true;
1051             break;
1052         }
1053     }
1054 
1055     return found;
1056 }
1057 
1058 // Accumulate locations used for inputs, outputs, and uniforms, and check for collisions
1059 // as the accumulation is done.
1060 //
1061 // Returns < 0 if no collision, >= 0 if collision and the value returned is a colliding value.
1062 //
1063 // typeCollision is set to true if there is no direct collision, but the types in the same location
1064 // are different.
1065 //
addUsedLocation(const TQualifier & qualifier,const TType & type,bool & typeCollision)1066 int TIntermediate::addUsedLocation(const TQualifier& qualifier, const TType& type, bool& typeCollision)
1067 {
1068     typeCollision = false;
1069 
1070     int set;
1071     if (qualifier.isPipeInput())
1072         set = 0;
1073     else if (qualifier.isPipeOutput())
1074         set = 1;
1075     else if (qualifier.storage == EvqUniform)
1076         set = 2;
1077     else if (qualifier.storage == EvqBuffer)
1078         set = 3;
1079     else
1080         return -1;
1081 
1082     int size;
1083     if (qualifier.isUniformOrBuffer() || qualifier.isTaskMemory()) {
1084         if (type.isSizedArray())
1085             size = type.getCumulativeArraySize();
1086         else
1087             size = 1;
1088     } else {
1089         // Strip off the outer array dimension for those having an extra one.
1090         if (type.isArray() && qualifier.isArrayedIo(language)) {
1091             TType elementType(type, 0);
1092             size = computeTypeLocationSize(elementType, language);
1093         } else
1094             size = computeTypeLocationSize(type, language);
1095     }
1096 
1097     // Locations, and components within locations.
1098     //
1099     // Almost always, dealing with components means a single location is involved.
1100     // The exception is a dvec3. From the spec:
1101     //
1102     // "A dvec3 will consume all four components of the first location and components 0 and 1 of
1103     // the second location. This leaves components 2 and 3 available for other component-qualified
1104     // declarations."
1105     //
1106     // That means, without ever mentioning a component, a component range
1107     // for a different location gets specified, if it's not a vertex shader input. (!)
1108     // (A vertex shader input will show using only one location, even for a dvec3/4.)
1109     //
1110     // So, for the case of dvec3, we need two independent ioRanges.
1111 
1112     int collision = -1; // no collision
1113 #ifndef GLSLANG_WEB
1114     if (size == 2 && type.getBasicType() == EbtDouble && type.getVectorSize() == 3 &&
1115         (qualifier.isPipeInput() || qualifier.isPipeOutput())) {
1116         // Dealing with dvec3 in/out split across two locations.
1117         // Need two io-ranges.
1118         // The case where the dvec3 doesn't start at component 0 was previously caught as overflow.
1119 
1120         // First range:
1121         TRange locationRange(qualifier.layoutLocation, qualifier.layoutLocation);
1122         TRange componentRange(0, 3);
1123         TIoRange range(locationRange, componentRange, type.getBasicType(), 0);
1124 
1125         // check for collisions
1126         collision = checkLocationRange(set, range, type, typeCollision);
1127         if (collision < 0) {
1128             usedIo[set].push_back(range);
1129 
1130             // Second range:
1131             TRange locationRange2(qualifier.layoutLocation + 1, qualifier.layoutLocation + 1);
1132             TRange componentRange2(0, 1);
1133             TIoRange range2(locationRange2, componentRange2, type.getBasicType(), 0);
1134 
1135             // check for collisions
1136             collision = checkLocationRange(set, range2, type, typeCollision);
1137             if (collision < 0)
1138                 usedIo[set].push_back(range2);
1139         }
1140     } else
1141 #endif
1142     {
1143         // Not a dvec3 in/out split across two locations, generic path.
1144         // Need a single IO-range block.
1145 
1146         TRange locationRange(qualifier.layoutLocation, qualifier.layoutLocation + size - 1);
1147         TRange componentRange(0, 3);
1148         if (qualifier.hasComponent() || type.getVectorSize() > 0) {
1149             int consumedComponents = type.getVectorSize() * (type.getBasicType() == EbtDouble ? 2 : 1);
1150             if (qualifier.hasComponent())
1151                 componentRange.start = qualifier.layoutComponent;
1152             componentRange.last  = componentRange.start + consumedComponents - 1;
1153         }
1154 
1155         // combine location and component ranges
1156         TIoRange range(locationRange, componentRange, type.getBasicType(), qualifier.hasIndex() ? qualifier.getIndex() : 0);
1157 
1158         // check for collisions, except for vertex inputs on desktop targeting OpenGL
1159         if (! (!isEsProfile() && language == EShLangVertex && qualifier.isPipeInput()) || spvVersion.vulkan > 0)
1160             collision = checkLocationRange(set, range, type, typeCollision);
1161 
1162         if (collision < 0)
1163             usedIo[set].push_back(range);
1164     }
1165 
1166     return collision;
1167 }
1168 
1169 // Compare a new (the passed in) 'range' against the existing set, and see
1170 // if there are any collisions.
1171 //
1172 // Returns < 0 if no collision, >= 0 if collision and the value returned is a colliding value.
1173 //
checkLocationRange(int set,const TIoRange & range,const TType & type,bool & typeCollision)1174 int TIntermediate::checkLocationRange(int set, const TIoRange& range, const TType& type, bool& typeCollision)
1175 {
1176     for (size_t r = 0; r < usedIo[set].size(); ++r) {
1177         if (range.overlap(usedIo[set][r])) {
1178             // there is a collision; pick one
1179             return std::max(range.location.start, usedIo[set][r].location.start);
1180         } else if (range.location.overlap(usedIo[set][r].location) && type.getBasicType() != usedIo[set][r].basicType) {
1181             // aliased-type mismatch
1182             typeCollision = true;
1183             return std::max(range.location.start, usedIo[set][r].location.start);
1184         }
1185     }
1186 
1187     return -1; // no collision
1188 }
1189 
1190 // Accumulate bindings and offsets, and check for collisions
1191 // as the accumulation is done.
1192 //
1193 // Returns < 0 if no collision, >= 0 if collision and the value returned is a colliding value.
1194 //
addUsedOffsets(int binding,int offset,int numOffsets)1195 int TIntermediate::addUsedOffsets(int binding, int offset, int numOffsets)
1196 {
1197     TRange bindingRange(binding, binding);
1198     TRange offsetRange(offset, offset + numOffsets - 1);
1199     TOffsetRange range(bindingRange, offsetRange);
1200 
1201     // check for collisions, except for vertex inputs on desktop
1202     for (size_t r = 0; r < usedAtomics.size(); ++r) {
1203         if (range.overlap(usedAtomics[r])) {
1204             // there is a collision; pick one
1205             return std::max(offset, usedAtomics[r].offset.start);
1206         }
1207     }
1208 
1209     usedAtomics.push_back(range);
1210 
1211     return -1; // no collision
1212 }
1213 
1214 // Accumulate used constant_id values.
1215 //
1216 // Return false is one was already used.
addUsedConstantId(int id)1217 bool TIntermediate::addUsedConstantId(int id)
1218 {
1219     if (usedConstantId.find(id) != usedConstantId.end())
1220         return false;
1221 
1222     usedConstantId.insert(id);
1223 
1224     return true;
1225 }
1226 
1227 // Recursively figure out how many locations are used up by an input or output type.
1228 // Return the size of type, as measured by "locations".
computeTypeLocationSize(const TType & type,EShLanguage stage)1229 int TIntermediate::computeTypeLocationSize(const TType& type, EShLanguage stage)
1230 {
1231     // "If the declared input is an array of size n and each element takes m locations, it will be assigned m * n
1232     // consecutive locations..."
1233     if (type.isArray()) {
1234         // TODO: perf: this can be flattened by using getCumulativeArraySize(), and a deref that discards all arrayness
1235         // TODO: are there valid cases of having an unsized array with a location?  If so, running this code too early.
1236         TType elementType(type, 0);
1237         if (type.isSizedArray() && !type.getQualifier().isPerView())
1238             return type.getOuterArraySize() * computeTypeLocationSize(elementType, stage);
1239         else {
1240 #ifndef GLSLANG_WEB
1241             // unset perViewNV attributes for arrayed per-view outputs: "perviewNV vec4 v[MAX_VIEWS][3];"
1242             elementType.getQualifier().perViewNV = false;
1243 #endif
1244             return computeTypeLocationSize(elementType, stage);
1245         }
1246     }
1247 
1248     // "The locations consumed by block and structure members are determined by applying the rules above
1249     // recursively..."
1250     if (type.isStruct()) {
1251         int size = 0;
1252         for (int member = 0; member < (int)type.getStruct()->size(); ++member) {
1253             TType memberType(type, member);
1254             size += computeTypeLocationSize(memberType, stage);
1255         }
1256         return size;
1257     }
1258 
1259     // ES: "If a shader input is any scalar or vector type, it will consume a single location."
1260 
1261     // Desktop: "If a vertex shader input is any scalar or vector type, it will consume a single location. If a non-vertex
1262     // shader input is a scalar or vector type other than dvec3 or dvec4, it will consume a single location, while
1263     // types dvec3 or dvec4 will consume two consecutive locations. Inputs of type double and dvec2 will
1264     // consume only a single location, in all stages."
1265     if (type.isScalar())
1266         return 1;
1267     if (type.isVector()) {
1268         if (stage == EShLangVertex && type.getQualifier().isPipeInput())
1269             return 1;
1270         if (type.getBasicType() == EbtDouble && type.getVectorSize() > 2)
1271             return 2;
1272         else
1273             return 1;
1274     }
1275 
1276     // "If the declared input is an n x m single- or double-precision matrix, ...
1277     // The number of locations assigned for each matrix will be the same as
1278     // for an n-element array of m-component vectors..."
1279     if (type.isMatrix()) {
1280         TType columnType(type, 0);
1281         return type.getMatrixCols() * computeTypeLocationSize(columnType, stage);
1282     }
1283 
1284     assert(0);
1285     return 1;
1286 }
1287 
1288 // Same as computeTypeLocationSize but for uniforms
computeTypeUniformLocationSize(const TType & type)1289 int TIntermediate::computeTypeUniformLocationSize(const TType& type)
1290 {
1291     // "Individual elements of a uniform array are assigned
1292     // consecutive locations with the first element taking location
1293     // location."
1294     if (type.isArray()) {
1295         // TODO: perf: this can be flattened by using getCumulativeArraySize(), and a deref that discards all arrayness
1296         TType elementType(type, 0);
1297         if (type.isSizedArray()) {
1298             return type.getOuterArraySize() * computeTypeUniformLocationSize(elementType);
1299         } else {
1300             // TODO: are there valid cases of having an implicitly-sized array with a location?  If so, running this code too early.
1301             return computeTypeUniformLocationSize(elementType);
1302         }
1303     }
1304 
1305     // "Each subsequent inner-most member or element gets incremental
1306     // locations for the entire structure or array."
1307     if (type.isStruct()) {
1308         int size = 0;
1309         for (int member = 0; member < (int)type.getStruct()->size(); ++member) {
1310             TType memberType(type, member);
1311             size += computeTypeUniformLocationSize(memberType);
1312         }
1313         return size;
1314     }
1315 
1316     return 1;
1317 }
1318 
1319 #ifndef GLSLANG_WEB
1320 
1321 // Accumulate xfb buffer ranges and check for collisions as the accumulation is done.
1322 //
1323 // Returns < 0 if no collision, >= 0 if collision and the value returned is a colliding value.
1324 //
addXfbBufferOffset(const TType & type)1325 int TIntermediate::addXfbBufferOffset(const TType& type)
1326 {
1327     const TQualifier& qualifier = type.getQualifier();
1328 
1329     assert(qualifier.hasXfbOffset() && qualifier.hasXfbBuffer());
1330     TXfbBuffer& buffer = xfbBuffers[qualifier.layoutXfbBuffer];
1331 
1332     // compute the range
1333     unsigned int size = computeTypeXfbSize(type, buffer.contains64BitType, buffer.contains32BitType, buffer.contains16BitType);
1334     buffer.implicitStride = std::max(buffer.implicitStride, qualifier.layoutXfbOffset + size);
1335     TRange range(qualifier.layoutXfbOffset, qualifier.layoutXfbOffset + size - 1);
1336 
1337     // check for collisions
1338     for (size_t r = 0; r < buffer.ranges.size(); ++r) {
1339         if (range.overlap(buffer.ranges[r])) {
1340             // there is a collision; pick an example to return
1341             return std::max(range.start, buffer.ranges[r].start);
1342         }
1343     }
1344 
1345     buffer.ranges.push_back(range);
1346 
1347     return -1;  // no collision
1348 }
1349 
1350 // Recursively figure out how many bytes of xfb buffer are used by the given type.
1351 // Return the size of type, in bytes.
1352 // Sets contains64BitType to true if the type contains a 64-bit data type.
1353 // Sets contains32BitType to true if the type contains a 32-bit data type.
1354 // Sets contains16BitType to true if the type contains a 16-bit data type.
1355 // N.B. Caller must set contains64BitType, contains32BitType, and contains16BitType to false before calling.
computeTypeXfbSize(const TType & type,bool & contains64BitType,bool & contains32BitType,bool & contains16BitType) const1356 unsigned int TIntermediate::computeTypeXfbSize(const TType& type, bool& contains64BitType, bool& contains32BitType, bool& contains16BitType) const
1357 {
1358     // "...if applied to an aggregate containing a double or 64-bit integer, the offset must also be a multiple of 8,
1359     // and the space taken in the buffer will be a multiple of 8.
1360     // ...within the qualified entity, subsequent components are each
1361     // assigned, in order, to the next available offset aligned to a multiple of
1362     // that component's size.  Aggregate types are flattened down to the component
1363     // level to get this sequence of components."
1364 
1365     if (type.isSizedArray()) {
1366         // TODO: perf: this can be flattened by using getCumulativeArraySize(), and a deref that discards all arrayness
1367         // Unsized array use to xfb should be a compile error.
1368         TType elementType(type, 0);
1369         return type.getOuterArraySize() * computeTypeXfbSize(elementType, contains64BitType, contains16BitType, contains16BitType);
1370     }
1371 
1372     if (type.isStruct()) {
1373         unsigned int size = 0;
1374         bool structContains64BitType = false;
1375         bool structContains32BitType = false;
1376         bool structContains16BitType = false;
1377         for (int member = 0; member < (int)type.getStruct()->size(); ++member) {
1378             TType memberType(type, member);
1379             // "... if applied to
1380             // an aggregate containing a double or 64-bit integer, the offset must also be a multiple of 8,
1381             // and the space taken in the buffer will be a multiple of 8."
1382             bool memberContains64BitType = false;
1383             bool memberContains32BitType = false;
1384             bool memberContains16BitType = false;
1385             int memberSize = computeTypeXfbSize(memberType, memberContains64BitType, memberContains32BitType, memberContains16BitType);
1386             if (memberContains64BitType) {
1387                 structContains64BitType = true;
1388                 RoundToPow2(size, 8);
1389             } else if (memberContains32BitType) {
1390                 structContains32BitType = true;
1391                 RoundToPow2(size, 4);
1392             } else if (memberContains16BitType) {
1393                 structContains16BitType = true;
1394                 RoundToPow2(size, 2);
1395             }
1396             size += memberSize;
1397         }
1398 
1399         if (structContains64BitType) {
1400             contains64BitType = true;
1401             RoundToPow2(size, 8);
1402         } else if (structContains32BitType) {
1403             contains32BitType = true;
1404             RoundToPow2(size, 4);
1405         } else if (structContains16BitType) {
1406             contains16BitType = true;
1407             RoundToPow2(size, 2);
1408         }
1409         return size;
1410     }
1411 
1412     int numComponents;
1413     if (type.isScalar())
1414         numComponents = 1;
1415     else if (type.isVector())
1416         numComponents = type.getVectorSize();
1417     else if (type.isMatrix())
1418         numComponents = type.getMatrixCols() * type.getMatrixRows();
1419     else {
1420         assert(0);
1421         numComponents = 1;
1422     }
1423 
1424     if (type.getBasicType() == EbtDouble || type.getBasicType() == EbtInt64 || type.getBasicType() == EbtUint64) {
1425         contains64BitType = true;
1426         return 8 * numComponents;
1427     } else if (type.getBasicType() == EbtFloat16 || type.getBasicType() == EbtInt16 || type.getBasicType() == EbtUint16) {
1428         contains16BitType = true;
1429         return 2 * numComponents;
1430     } else if (type.getBasicType() == EbtInt8 || type.getBasicType() == EbtUint8)
1431         return numComponents;
1432     else {
1433         contains32BitType = true;
1434         return 4 * numComponents;
1435     }
1436 }
1437 
1438 #endif
1439 
1440 const int baseAlignmentVec4Std140 = 16;
1441 
1442 // Return the size and alignment of a component of the given type.
1443 // The size is returned in the 'size' parameter
1444 // Return value is the alignment..
getBaseAlignmentScalar(const TType & type,int & size)1445 int TIntermediate::getBaseAlignmentScalar(const TType& type, int& size)
1446 {
1447 #ifdef GLSLANG_WEB
1448     size = 4; return 4;
1449 #endif
1450 
1451     switch (type.getBasicType()) {
1452     case EbtInt64:
1453     case EbtUint64:
1454     case EbtDouble:  size = 8; return 8;
1455     case EbtFloat16: size = 2; return 2;
1456     case EbtInt8:
1457     case EbtUint8:   size = 1; return 1;
1458     case EbtInt16:
1459     case EbtUint16:  size = 2; return 2;
1460     case EbtReference: size = 8; return 8;
1461     default:         size = 4; return 4;
1462     }
1463 }
1464 
1465 // Implement base-alignment and size rules from section 7.6.2.2 Standard Uniform Block Layout
1466 // Operates recursively.
1467 //
1468 // If std140 is true, it does the rounding up to vec4 size required by std140,
1469 // otherwise it does not, yielding std430 rules.
1470 //
1471 // The size is returned in the 'size' parameter
1472 //
1473 // The stride is only non-0 for arrays or matrices, and is the stride of the
1474 // top-level object nested within the type.  E.g., for an array of matrices,
1475 // it is the distances needed between matrices, despite the rules saying the
1476 // stride comes from the flattening down to vectors.
1477 //
1478 // Return value is the alignment of the type.
getBaseAlignment(const TType & type,int & size,int & stride,TLayoutPacking layoutPacking,bool rowMajor)1479 int TIntermediate::getBaseAlignment(const TType& type, int& size, int& stride, TLayoutPacking layoutPacking, bool rowMajor)
1480 {
1481     int alignment;
1482 
1483     bool std140 = layoutPacking == glslang::ElpStd140;
1484     // When using the std140 storage layout, structures will be laid out in buffer
1485     // storage with its members stored in monotonically increasing order based on their
1486     // location in the declaration. A structure and each structure member have a base
1487     // offset and a base alignment, from which an aligned offset is computed by rounding
1488     // the base offset up to a multiple of the base alignment. The base offset of the first
1489     // member of a structure is taken from the aligned offset of the structure itself. The
1490     // base offset of all other structure members is derived by taking the offset of the
1491     // last basic machine unit consumed by the previous member and adding one. Each
1492     // structure member is stored in memory at its aligned offset. The members of a top-
1493     // level uniform block are laid out in buffer storage by treating the uniform block as
1494     // a structure with a base offset of zero.
1495     //
1496     //   1. If the member is a scalar consuming N basic machine units, the base alignment is N.
1497     //
1498     //   2. If the member is a two- or four-component vector with components consuming N basic
1499     //      machine units, the base alignment is 2N or 4N, respectively.
1500     //
1501     //   3. If the member is a three-component vector with components consuming N
1502     //      basic machine units, the base alignment is 4N.
1503     //
1504     //   4. If the member is an array of scalars or vectors, the base alignment and array
1505     //      stride are set to match the base alignment of a single array element, according
1506     //      to rules (1), (2), and (3), and rounded up to the base alignment of a vec4. The
1507     //      array may have padding at the end; the base offset of the member following
1508     //      the array is rounded up to the next multiple of the base alignment.
1509     //
1510     //   5. If the member is a column-major matrix with C columns and R rows, the
1511     //      matrix is stored identically to an array of C column vectors with R
1512     //      components each, according to rule (4).
1513     //
1514     //   6. If the member is an array of S column-major matrices with C columns and
1515     //      R rows, the matrix is stored identically to a row of S X C column vectors
1516     //      with R components each, according to rule (4).
1517     //
1518     //   7. If the member is a row-major matrix with C columns and R rows, the matrix
1519     //      is stored identically to an array of R row vectors with C components each,
1520     //      according to rule (4).
1521     //
1522     //   8. If the member is an array of S row-major matrices with C columns and R
1523     //      rows, the matrix is stored identically to a row of S X R row vectors with C
1524     //      components each, according to rule (4).
1525     //
1526     //   9. If the member is a structure, the base alignment of the structure is N , where
1527     //      N is the largest base alignment value of any    of its members, and rounded
1528     //      up to the base alignment of a vec4. The individual members of this substructure
1529     //      are then assigned offsets by applying this set of rules recursively,
1530     //      where the base offset of the first member of the sub-structure is equal to the
1531     //      aligned offset of the structure. The structure may have padding at the end;
1532     //      the base offset of the member following the sub-structure is rounded up to
1533     //      the next multiple of the base alignment of the structure.
1534     //
1535     //   10. If the member is an array of S structures, the S elements of the array are laid
1536     //       out in order, according to rule (9).
1537     //
1538     //   Assuming, for rule 10:  The stride is the same as the size of an element.
1539 
1540     stride = 0;
1541     int dummyStride;
1542 
1543     // rules 4, 6, 8, and 10
1544     if (type.isArray()) {
1545         // TODO: perf: this might be flattened by using getCumulativeArraySize(), and a deref that discards all arrayness
1546         TType derefType(type, 0);
1547         alignment = getBaseAlignment(derefType, size, dummyStride, layoutPacking, rowMajor);
1548         if (std140)
1549             alignment = std::max(baseAlignmentVec4Std140, alignment);
1550         RoundToPow2(size, alignment);
1551         stride = size;  // uses full matrix size for stride of an array of matrices (not quite what rule 6/8, but what's expected)
1552                         // uses the assumption for rule 10 in the comment above
1553         // use one element to represent the last member of SSBO which is unsized array
1554         int arraySize = (type.isUnsizedArray() && (type.getOuterArraySize() == 0)) ? 1 : type.getOuterArraySize();
1555         size = stride * arraySize;
1556         return alignment;
1557     }
1558 
1559     // rule 9
1560     if (type.getBasicType() == EbtStruct) {
1561         const TTypeList& memberList = *type.getStruct();
1562 
1563         size = 0;
1564         int maxAlignment = std140 ? baseAlignmentVec4Std140 : 0;
1565         for (size_t m = 0; m < memberList.size(); ++m) {
1566             int memberSize;
1567             // modify just the children's view of matrix layout, if there is one for this member
1568             TLayoutMatrix subMatrixLayout = memberList[m].type->getQualifier().layoutMatrix;
1569             int memberAlignment = getBaseAlignment(*memberList[m].type, memberSize, dummyStride, layoutPacking,
1570                                                    (subMatrixLayout != ElmNone) ? (subMatrixLayout == ElmRowMajor) : rowMajor);
1571             maxAlignment = std::max(maxAlignment, memberAlignment);
1572             RoundToPow2(size, memberAlignment);
1573             size += memberSize;
1574         }
1575 
1576         // The structure may have padding at the end; the base offset of
1577         // the member following the sub-structure is rounded up to the next
1578         // multiple of the base alignment of the structure.
1579         RoundToPow2(size, maxAlignment);
1580 
1581         return maxAlignment;
1582     }
1583 
1584     // rule 1
1585     if (type.isScalar())
1586         return getBaseAlignmentScalar(type, size);
1587 
1588     // rules 2 and 3
1589     if (type.isVector()) {
1590         int scalarAlign = getBaseAlignmentScalar(type, size);
1591         switch (type.getVectorSize()) {
1592         case 1: // HLSL has this, GLSL does not
1593             return scalarAlign;
1594         case 2:
1595             size *= 2;
1596             return 2 * scalarAlign;
1597         default:
1598             size *= type.getVectorSize();
1599             return 4 * scalarAlign;
1600         }
1601     }
1602 
1603     // rules 5 and 7
1604     if (type.isMatrix()) {
1605         // rule 5: deref to row, not to column, meaning the size of vector is num columns instead of num rows
1606         TType derefType(type, 0, rowMajor);
1607 
1608         alignment = getBaseAlignment(derefType, size, dummyStride, layoutPacking, rowMajor);
1609         if (std140)
1610             alignment = std::max(baseAlignmentVec4Std140, alignment);
1611         RoundToPow2(size, alignment);
1612         stride = size;  // use intra-matrix stride for stride of a just a matrix
1613         if (rowMajor)
1614             size = stride * type.getMatrixRows();
1615         else
1616             size = stride * type.getMatrixCols();
1617 
1618         return alignment;
1619     }
1620 
1621     assert(0);  // all cases should be covered above
1622     size = baseAlignmentVec4Std140;
1623     return baseAlignmentVec4Std140;
1624 }
1625 
1626 // To aid the basic HLSL rule about crossing vec4 boundaries.
improperStraddle(const TType & type,int size,int offset)1627 bool TIntermediate::improperStraddle(const TType& type, int size, int offset)
1628 {
1629     if (! type.isVector() || type.isArray())
1630         return false;
1631 
1632     return size <= 16 ? offset / 16 != (offset + size - 1) / 16
1633                       : offset % 16 != 0;
1634 }
1635 
getScalarAlignment(const TType & type,int & size,int & stride,bool rowMajor)1636 int TIntermediate::getScalarAlignment(const TType& type, int& size, int& stride, bool rowMajor)
1637 {
1638     int alignment;
1639 
1640     stride = 0;
1641     int dummyStride;
1642 
1643     if (type.isArray()) {
1644         TType derefType(type, 0);
1645         alignment = getScalarAlignment(derefType, size, dummyStride, rowMajor);
1646 
1647         stride = size;
1648         RoundToPow2(stride, alignment);
1649 
1650         size = stride * (type.getOuterArraySize() - 1) + size;
1651         return alignment;
1652     }
1653 
1654     if (type.getBasicType() == EbtStruct) {
1655         const TTypeList& memberList = *type.getStruct();
1656 
1657         size = 0;
1658         int maxAlignment = 0;
1659         for (size_t m = 0; m < memberList.size(); ++m) {
1660             int memberSize;
1661             // modify just the children's view of matrix layout, if there is one for this member
1662             TLayoutMatrix subMatrixLayout = memberList[m].type->getQualifier().layoutMatrix;
1663             int memberAlignment = getScalarAlignment(*memberList[m].type, memberSize, dummyStride,
1664                                                      (subMatrixLayout != ElmNone) ? (subMatrixLayout == ElmRowMajor) : rowMajor);
1665             maxAlignment = std::max(maxAlignment, memberAlignment);
1666             RoundToPow2(size, memberAlignment);
1667             size += memberSize;
1668         }
1669 
1670         return maxAlignment;
1671     }
1672 
1673     if (type.isScalar())
1674         return getBaseAlignmentScalar(type, size);
1675 
1676     if (type.isVector()) {
1677         int scalarAlign = getBaseAlignmentScalar(type, size);
1678 
1679         size *= type.getVectorSize();
1680         return scalarAlign;
1681     }
1682 
1683     if (type.isMatrix()) {
1684         TType derefType(type, 0, rowMajor);
1685 
1686         alignment = getScalarAlignment(derefType, size, dummyStride, rowMajor);
1687 
1688         stride = size;  // use intra-matrix stride for stride of a just a matrix
1689         if (rowMajor)
1690             size = stride * type.getMatrixRows();
1691         else
1692             size = stride * type.getMatrixCols();
1693 
1694         return alignment;
1695     }
1696 
1697     assert(0);  // all cases should be covered above
1698     size = 1;
1699     return 1;
1700 }
1701 
getMemberAlignment(const TType & type,int & size,int & stride,TLayoutPacking layoutPacking,bool rowMajor)1702 int TIntermediate::getMemberAlignment(const TType& type, int& size, int& stride, TLayoutPacking layoutPacking, bool rowMajor)
1703 {
1704     if (layoutPacking == glslang::ElpScalar) {
1705         return getScalarAlignment(type, size, stride, rowMajor);
1706     } else {
1707         return getBaseAlignment(type, size, stride, layoutPacking, rowMajor);
1708     }
1709 }
1710 
1711 // shared calculation by getOffset and getOffsets
updateOffset(const TType & parentType,const TType & memberType,int & offset,int & memberSize)1712 void TIntermediate::updateOffset(const TType& parentType, const TType& memberType, int& offset, int& memberSize)
1713 {
1714     int dummyStride;
1715 
1716     // modify just the children's view of matrix layout, if there is one for this member
1717     TLayoutMatrix subMatrixLayout = memberType.getQualifier().layoutMatrix;
1718     int memberAlignment = getMemberAlignment(memberType, memberSize, dummyStride,
1719                                              parentType.getQualifier().layoutPacking,
1720                                              subMatrixLayout != ElmNone
1721                                                  ? subMatrixLayout == ElmRowMajor
1722                                                  : parentType.getQualifier().layoutMatrix == ElmRowMajor);
1723     RoundToPow2(offset, memberAlignment);
1724 }
1725 
1726 // Lookup or calculate the offset of a block member, using the recursively
1727 // defined block offset rules.
getOffset(const TType & type,int index)1728 int TIntermediate::getOffset(const TType& type, int index)
1729 {
1730     const TTypeList& memberList = *type.getStruct();
1731 
1732     // Don't calculate offset if one is present, it could be user supplied
1733     // and different than what would be calculated.  That is, this is faster,
1734     // but not just an optimization.
1735     if (memberList[index].type->getQualifier().hasOffset())
1736         return memberList[index].type->getQualifier().layoutOffset;
1737 
1738     int memberSize = 0;
1739     int offset = 0;
1740     for (int m = 0; m <= index; ++m) {
1741         updateOffset(type, *memberList[m].type, offset, memberSize);
1742 
1743         if (m < index)
1744             offset += memberSize;
1745     }
1746 
1747     return offset;
1748 }
1749 
1750 // Calculate the block data size.
1751 // Block arrayness is not taken into account, each element is backed by a separate buffer.
getBlockSize(const TType & blockType)1752 int TIntermediate::getBlockSize(const TType& blockType)
1753 {
1754     const TTypeList& memberList = *blockType.getStruct();
1755     int lastIndex = (int)memberList.size() - 1;
1756     int lastOffset = getOffset(blockType, lastIndex);
1757 
1758     int lastMemberSize;
1759     int dummyStride;
1760     getMemberAlignment(*memberList[lastIndex].type, lastMemberSize, dummyStride,
1761                        blockType.getQualifier().layoutPacking,
1762                        blockType.getQualifier().layoutMatrix == ElmRowMajor);
1763 
1764     return lastOffset + lastMemberSize;
1765 }
1766 
computeBufferReferenceTypeSize(const TType & type)1767 int TIntermediate::computeBufferReferenceTypeSize(const TType& type)
1768 {
1769     assert(type.isReference());
1770     int size = getBlockSize(*type.getReferentType());
1771 
1772     int align = type.getBufferReferenceAlignment();
1773 
1774     if (align) {
1775         size = (size + align - 1) & ~(align-1);
1776     }
1777 
1778     return size;
1779 }
1780 
1781 } // end namespace glslang
1782