blob: f1ca015530685a71255967ce4b12a210d95d7853 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
John Kessenichb23d2322018-12-14 10:47:35 -07003// Copyright (C) 2015-2018 Google, Inc.
John Kessenich66011cb2018-03-06 16:12:04 -07004// Copyright (C) 2017 ARM Limited.
John Kessenich140f3df2015-06-26 16:58:36 -06005//
John Kessenich927608b2017-01-06 12:34:14 -07006// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06007//
John Kessenich927608b2017-01-06 12:34:14 -07008// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions
10// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060011//
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//
John Kessenich927608b2017-01-06 12:34:14 -070024// 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.
John Kessenich140f3df2015-06-26 16:58:36 -060036
37//
John Kessenich140f3df2015-06-26 16:58:36 -060038// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080046 #include "GLSL.std.450.h"
47 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070048 #include "GLSL.ext.EXT.h"
Rex Xu51596642016-09-21 18:56:12 +080049 #include "GLSL.ext.AMD.h"
chaoc0ad6a4e2016-12-19 16:29:34 -080050 #include "GLSL.ext.NV.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060051}
John Kessenich140f3df2015-06-26 16:58:36 -060052
53// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020054#include "../glslang/MachineIndependent/localintermediate.h"
55#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060056#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050057#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060058
John Kessenich140f3df2015-06-26 16:58:36 -060059#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050060#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040061#include <list>
62#include <map>
63#include <stack>
64#include <string>
65#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060066
67namespace {
68
qining4c912612016-04-01 10:35:16 -040069namespace {
70class SpecConstantOpModeGuard {
71public:
72 SpecConstantOpModeGuard(spv::Builder* builder)
73 : builder_(builder) {
74 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040075 }
76 ~SpecConstantOpModeGuard() {
77 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
78 : builder_->setToNormalCodeGenMode();
79 }
qining40887662016-04-03 22:20:42 -040080 void turnOnSpecConstantOpMode() {
81 builder_->setToSpecConstCodeGenMode();
82 }
qining4c912612016-04-01 10:35:16 -040083
84private:
85 spv::Builder* builder_;
86 bool previous_flag_;
87};
John Kessenichead86222018-03-28 18:01:20 -060088
89struct OpDecorations {
John Kessenichb9197c82019-08-11 07:41:45 -060090 public:
91 OpDecorations(spv::Decoration precision, spv::Decoration noContraction, spv::Decoration nonUniform) :
92 precision(precision)
93#ifndef GLSLANG_WEB
94 ,
95 noContraction(noContraction),
96 nonUniform(nonUniform)
97#endif
98 { }
99
John Kessenichead86222018-03-28 18:01:20 -0600100 spv::Decoration precision;
John Kessenichb9197c82019-08-11 07:41:45 -0600101
102#ifdef GLSLANG_WEB
Ryan Harrison7c9accb2019-10-11 11:00:57 -0400103 void addNoContraction(spv::Builder&, spv::Id) const { }
104 void addNonUniform(spv::Builder&, spv::Id) const { }
John Kessenichb9197c82019-08-11 07:41:45 -0600105#else
Ryan Harrison7c9accb2019-10-11 11:00:57 -0400106 void addNoContraction(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, noContraction); }
107 void addNonUniform(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, nonUniform); }
John Kessenichb9197c82019-08-11 07:41:45 -0600108 protected:
109 spv::Decoration noContraction;
110 spv::Decoration nonUniform;
111#endif
112
John Kessenichead86222018-03-28 18:01:20 -0600113};
114
115} // namespace
qining4c912612016-04-01 10:35:16 -0400116
John Kessenich140f3df2015-06-26 16:58:36 -0600117//
118// The main holder of information for translating glslang to SPIR-V.
119//
120// Derives from the AST walking base class.
121//
122class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
123public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700124 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
125 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700126 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600127
128 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
129 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
130 void visitConstantUnion(glslang::TIntermConstantUnion*);
131 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
132 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
133 void visitSymbol(glslang::TIntermSymbol* symbol);
134 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
135 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
136 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
137
John Kessenichfca82622016-11-26 13:23:20 -0700138 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700139 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600140
141protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700142 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
143 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
144
Rex Xu17ff3432016-10-14 17:41:45 +0800145 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800146 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600147 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500148 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
149 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
150 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
151 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100152 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700153 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700154 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
155 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenich1f4d0462019-01-12 17:31:41 +0700156 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, std::vector<unsigned int>& operands) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600157 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600158 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich9c14f772019-06-17 08:38:35 -0600159 spv::Id createSpvVariable(const glslang::TIntermSymbol*, spv::Id forcedType);
John Kessenich140f3df2015-06-26 16:58:36 -0600160 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600161 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
162 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
163 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600164 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
John Kessenichead86222018-03-28 18:01:20 -0600165 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600166 bool lastBufferBlockMember, bool forwardReferenceOnly = false);
John Kessenich0e737842017-03-24 18:38:16 -0600167 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600168 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
169 glslang::TLayoutPacking, const glslang::TQualifier&);
170 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
171 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700172 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700173 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800174 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600175 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700176 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700177 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
178 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700179 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
180 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100181 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600182
John Kessenich6fccb3c2016-09-19 16:01:41 -0600183 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600184 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600185 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600186 void makeFunctions(const glslang::TIntermSequence&);
187 void makeGlobalInitializers(const glslang::TIntermSequence&);
188 void visitFunctions(const glslang::TIntermSequence&);
189 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500190 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -0600191 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
192 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600193 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
194
John Kessenichead86222018-03-28 18:01:20 -0600195 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
196 glslang::TBasicType typeProxy, bool reduceComparison = true);
197 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
198 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500199 glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -0600200 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
201 glslang::TBasicType typeProxy);
202 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
203 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600204 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600205 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500206 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
Rex Xu51596642016-09-21 18:56:12 +0800207 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800208 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich66011cb2018-03-06 16:12:04 -0700209 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600210 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800211 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600212 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700213 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
qining08408382016-03-21 09:51:37 -0400214 spv::Id createSpvConstant(const glslang::TIntermTyped&);
215 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600216 bool isTrivialLeaf(const glslang::TIntermTyped* node);
217 bool isTrivial(const glslang::TIntermTyped* node);
218 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800219 spv::Id getExtBuiltins(const char* name);
John Kessenich9c14f772019-06-17 08:38:35 -0600220 std::pair<spv::Id, spv::Id> getForcedType(spv::BuiltIn, const glslang::TType&);
221 spv::Id translateForcedType(spv::Id object);
Jeff Bolz53134492019-06-25 13:31:10 -0500222 spv::Id createCompositeConstruct(spv::Id typeId, std::vector<spv::Id> constituents);
John Kessenich140f3df2015-06-26 16:58:36 -0600223
John Kessenich121853f2017-05-31 17:11:16 -0600224 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600225 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600226 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700227 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600228 int sequenceDepth;
229
Lei Zhang17535f72016-05-04 15:55:59 -0400230 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400231
John Kessenich140f3df2015-06-26 16:58:36 -0600232 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
233 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700234 bool inEntryPoint;
235 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700236 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700237 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600238 const glslang::TIntermediate* glslangIntermediate;
John Kessenich605afc72019-06-17 23:33:09 -0600239 bool nanMinMaxClamp; // true if use NMin/NMax/NClamp instead of FMin/FMax/FClamp
John Kessenich140f3df2015-06-26 16:58:36 -0600240 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800241 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600242
John Kessenich2f273362015-07-18 22:34:27 -0600243 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600244 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600245 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700246 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700247 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
248 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600249 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700250 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600251 // Map pointee types for EbtReference to their forward pointers
252 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich9c14f772019-06-17 08:38:35 -0600253 // Type forcing, for when SPIR-V wants a different type than the AST,
254 // requiring local translation to and from SPIR-V type on every access.
255 // Maps <builtin-variable-id -> AST-required-type-id>
256 std::unordered_map<spv::Id, spv::Id> forceType;
John Kessenich140f3df2015-06-26 16:58:36 -0600257};
258
259//
260// Helper functions for translating glslang representations to SPIR-V enumerants.
261//
262
263// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700264spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600265{
John Kessenich155d3512019-08-08 23:29:20 -0600266#ifdef GLSLANG_WEB
267 return spv::SourceLanguageESSL;
268#endif
269
John Kessenich66e2faf2016-03-12 18:34:36 -0700270 switch (source) {
271 case glslang::EShSourceGlsl:
272 switch (profile) {
273 case ENoProfile:
274 case ECoreProfile:
275 case ECompatibilityProfile:
276 return spv::SourceLanguageGLSL;
277 case EEsProfile:
278 return spv::SourceLanguageESSL;
279 default:
280 return spv::SourceLanguageUnknown;
281 }
282 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600283 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600284 default:
285 return spv::SourceLanguageUnknown;
286 }
287}
288
289// Translate glslang language (stage) to SPIR-V execution model.
290spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
291{
292 switch (stage) {
293 case EShLangVertex: return spv::ExecutionModelVertex;
John Kessenicha28f7a72019-08-06 07:00:58 -0600294 case EShLangFragment: return spv::ExecutionModelFragment;
John Kessenicha28f7a72019-08-06 07:00:58 -0600295 case EShLangCompute: return spv::ExecutionModelGLCompute;
John Kessenich51ed01c2019-10-10 11:40:11 -0600296#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -0600297 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
298 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
299 case EShLangGeometry: return spv::ExecutionModelGeometry;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700300 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNV;
301 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNV;
302 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNV;
303 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNV;
304 case EShLangMissNV: return spv::ExecutionModelMissNV;
305 case EShLangCallableNV: return spv::ExecutionModelCallableNV;
Chao Chen3c366992018-09-19 11:41:59 -0700306 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
307 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
308#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600309 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700310 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600311 return spv::ExecutionModelFragment;
312 }
313}
314
John Kessenich140f3df2015-06-26 16:58:36 -0600315// Translate glslang sampler type to SPIR-V dimensionality.
316spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
317{
318 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700319 case glslang::Esd1D: return spv::Dim1D;
320 case glslang::Esd2D: return spv::Dim2D;
321 case glslang::Esd3D: return spv::Dim3D;
322 case glslang::EsdCube: return spv::DimCube;
323 case glslang::EsdRect: return spv::DimRect;
324 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700325 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600326 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700327 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600328 return spv::Dim2D;
329 }
330}
331
John Kessenichf6640762016-08-01 19:44:00 -0600332// Translate glslang precision to SPIR-V precision decorations.
333spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600334{
John Kessenichf6640762016-08-01 19:44:00 -0600335 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700336 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600337 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600338 default:
339 return spv::NoPrecision;
340 }
341}
342
John Kessenichf6640762016-08-01 19:44:00 -0600343// Translate glslang type to SPIR-V precision decorations.
344spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
345{
346 return TranslatePrecisionDecoration(type.getQualifier().precision);
347}
348
John Kessenich140f3df2015-06-26 16:58:36 -0600349// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600350spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600351{
352 if (type.getBasicType() == glslang::EbtBlock) {
353 switch (type.getQualifier().storage) {
354 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600355 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600356 case glslang::EvqVaryingIn: return spv::DecorationBlock;
357 case glslang::EvqVaryingOut: return spv::DecorationBlock;
John Kessenicha28f7a72019-08-06 07:00:58 -0600358#ifndef GLSLANG_WEB
Chao Chenb50c02e2018-09-19 11:42:24 -0700359 case glslang::EvqPayloadNV: return spv::DecorationBlock;
360 case glslang::EvqPayloadInNV: return spv::DecorationBlock;
361 case glslang::EvqHitAttrNV: return spv::DecorationBlock;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700362 case glslang::EvqCallableDataNV: return spv::DecorationBlock;
363 case glslang::EvqCallableDataInNV: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700364#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600365 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700366 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600367 break;
368 }
369 }
370
John Kessenich4016e382016-07-15 11:53:56 -0600371 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600372}
373
Rex Xu1da878f2016-02-21 20:59:01 +0800374// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500375void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800376{
John Kessenichb9197c82019-08-11 07:41:45 -0600377#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -0500378 if (!useVulkanMemoryModel) {
379 if (qualifier.coherent)
380 memory.push_back(spv::DecorationCoherent);
381 if (qualifier.volatil) {
382 memory.push_back(spv::DecorationVolatile);
383 memory.push_back(spv::DecorationCoherent);
384 }
John Kessenich14b85d32018-06-04 15:36:03 -0600385 }
Rex Xu1da878f2016-02-21 20:59:01 +0800386 if (qualifier.restrict)
387 memory.push_back(spv::DecorationRestrict);
John Kessenichdeec1932019-08-13 08:00:30 -0600388 if (qualifier.isReadOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800389 memory.push_back(spv::DecorationNonWritable);
John Kessenichdeec1932019-08-13 08:00:30 -0600390 if (qualifier.isWriteOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800391 memory.push_back(spv::DecorationNonReadable);
John Kessenichb9197c82019-08-11 07:41:45 -0600392#endif
Rex Xu1da878f2016-02-21 20:59:01 +0800393}
394
John Kessenich140f3df2015-06-26 16:58:36 -0600395// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700396spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600397{
398 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700399 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600400 case glslang::ElmRowMajor:
401 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700402 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600403 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700404 default:
405 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600406 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600407 }
408 } else {
409 switch (type.getBasicType()) {
410 default:
John Kessenich4016e382016-07-15 11:53:56 -0600411 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600412 break;
413 case glslang::EbtBlock:
414 switch (type.getQualifier().storage) {
415 case glslang::EvqUniform:
416 case glslang::EvqBuffer:
417 switch (type.getQualifier().layoutPacking) {
418 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600419 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
420 default:
John Kessenich4016e382016-07-15 11:53:56 -0600421 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600422 }
423 case glslang::EvqVaryingIn:
424 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700425 if (type.getQualifier().isTaskMemory()) {
426 switch (type.getQualifier().layoutPacking) {
427 case glslang::ElpShared: return spv::DecorationGLSLShared;
428 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
429 default: break;
430 }
431 } else {
432 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
433 }
John Kessenich4016e382016-07-15 11:53:56 -0600434 return spv::DecorationMax;
John Kessenicha28f7a72019-08-06 07:00:58 -0600435#ifndef GLSLANG_WEB
Chao Chenb50c02e2018-09-19 11:42:24 -0700436 case glslang::EvqPayloadNV:
437 case glslang::EvqPayloadInNV:
438 case glslang::EvqHitAttrNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700439 case glslang::EvqCallableDataNV:
440 case glslang::EvqCallableDataInNV:
Chao Chenb50c02e2018-09-19 11:42:24 -0700441 return spv::DecorationMax;
442#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600443 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700444 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600445 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600446 }
447 }
448 }
449}
450
451// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600452// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700453// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800454spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600455{
Rex Xubbceed72016-05-21 09:40:44 +0800456 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700457 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600458 return spv::DecorationMax;
John Kessenich7015bd62019-08-01 03:28:08 -0600459 else if (qualifier.isNonPerspective())
John Kessenich55e7d112015-11-15 21:33:39 -0700460 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700461 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600462 return spv::DecorationFlat;
John Kessenicha28f7a72019-08-06 07:00:58 -0600463 else if (qualifier.isExplicitInterpolation()) {
Rex Xu17ff3432016-10-14 17:41:45 +0800464 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800465 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800466 }
Rex Xubbceed72016-05-21 09:40:44 +0800467 else
John Kessenich4016e382016-07-15 11:53:56 -0600468 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800469}
470
471// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600472// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800473// should be applied.
474spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
475{
John Kessenichb9197c82019-08-11 07:41:45 -0600476 if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600477 return spv::DecorationCentroid;
John Kessenichb9197c82019-08-11 07:41:45 -0600478#ifndef GLSLANG_WEB
479 else if (qualifier.patch)
480 return spv::DecorationPatch;
John Kessenich5e801132016-02-15 11:09:46 -0700481 else if (qualifier.sample) {
482 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600483 return spv::DecorationSample;
John Kessenichb9197c82019-08-11 07:41:45 -0600484 }
485#endif
486
487 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600488}
489
John Kessenich92187592016-02-01 13:45:25 -0700490// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700491spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600492{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700493 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600494 return spv::DecorationInvariant;
495 else
John Kessenich4016e382016-07-15 11:53:56 -0600496 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600497}
498
qining9220dbb2016-05-04 17:34:38 -0400499// If glslang type is noContraction, return SPIR-V NoContraction decoration.
500spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
501{
John Kessenichb9197c82019-08-11 07:41:45 -0600502#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -0600503 if (qualifier.isNoContraction())
qining9220dbb2016-05-04 17:34:38 -0400504 return spv::DecorationNoContraction;
505 else
John Kessenichb9197c82019-08-11 07:41:45 -0600506#endif
John Kessenich4016e382016-07-15 11:53:56 -0600507 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400508}
509
John Kessenich5611c6d2018-04-05 11:25:02 -0600510// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
511spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
512{
John Kessenichb9197c82019-08-11 07:41:45 -0600513#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -0600514 if (qualifier.isNonUniform()) {
John Kessenich8317e6c2019-08-18 23:58:08 -0600515 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -0600516 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
517 return spv::DecorationNonUniformEXT;
518 } else
John Kessenichb9197c82019-08-11 07:41:45 -0600519#endif
John Kessenich5611c6d2018-04-05 11:25:02 -0600520 return spv::DecorationMax;
521}
522
John Kessenichb9197c82019-08-11 07:41:45 -0600523spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(
524 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500525{
Jeff Bolz36831c92018-09-05 10:11:41 -0500526 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600527
528#ifndef GLSLANG_WEB
529 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage)
530 return mask;
531
Jeff Bolz36831c92018-09-05 10:11:41 -0500532 if (coherentFlags.volatil ||
533 coherentFlags.coherent ||
534 coherentFlags.devicecoherent ||
535 coherentFlags.queuefamilycoherent ||
536 coherentFlags.workgroupcoherent ||
537 coherentFlags.subgroupcoherent) {
538 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
539 spv::MemoryAccessMakePointerVisibleKHRMask;
540 }
541 if (coherentFlags.nonprivate) {
542 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
543 }
544 if (coherentFlags.volatil) {
545 mask = mask | spv::MemoryAccessVolatileMask;
546 }
547 if (mask != spv::MemoryAccessMaskNone) {
548 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
549 }
John Kessenichb9197c82019-08-11 07:41:45 -0600550#endif
551
Jeff Bolz36831c92018-09-05 10:11:41 -0500552 return mask;
553}
554
John Kessenichb9197c82019-08-11 07:41:45 -0600555spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(
556 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500557{
Jeff Bolz36831c92018-09-05 10:11:41 -0500558 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600559
560#ifndef GLSLANG_WEB
561 if (!glslangIntermediate->usingVulkanMemoryModel())
562 return mask;
563
Jeff Bolz36831c92018-09-05 10:11:41 -0500564 if (coherentFlags.volatil ||
565 coherentFlags.coherent ||
566 coherentFlags.devicecoherent ||
567 coherentFlags.queuefamilycoherent ||
568 coherentFlags.workgroupcoherent ||
569 coherentFlags.subgroupcoherent) {
570 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
571 spv::ImageOperandsMakeTexelVisibleKHRMask;
572 }
573 if (coherentFlags.nonprivate) {
574 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
575 }
576 if (coherentFlags.volatil) {
577 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
578 }
579 if (mask != spv::ImageOperandsMaskNone) {
580 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
581 }
John Kessenichb9197c82019-08-11 07:41:45 -0600582#endif
583
Jeff Bolz36831c92018-09-05 10:11:41 -0500584 return mask;
585}
586
587spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
588{
John Kessenichb9197c82019-08-11 07:41:45 -0600589 spv::Builder::AccessChain::CoherentFlags flags = {};
590#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -0500591 flags.coherent = type.getQualifier().coherent;
592 flags.devicecoherent = type.getQualifier().devicecoherent;
593 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
594 // shared variables are implicitly workgroupcoherent in GLSL.
595 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
596 type.getQualifier().storage == glslang::EvqShared;
597 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600598 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500599 // *coherent variables are implicitly nonprivate in GLSL
600 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500601 flags.subgroupcoherent ||
602 flags.workgroupcoherent ||
603 flags.queuefamilycoherent ||
604 flags.devicecoherent ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600605 flags.coherent ||
606 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500607 flags.isImage = type.getBasicType() == glslang::EbtSampler;
John Kessenichb9197c82019-08-11 07:41:45 -0600608#endif
Jeff Bolz36831c92018-09-05 10:11:41 -0500609 return flags;
610}
611
John Kessenichb9197c82019-08-11 07:41:45 -0600612spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(
613 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500614{
John Kessenichb9197c82019-08-11 07:41:45 -0600615 spv::Scope scope = spv::ScopeMax;
616
617#ifndef GLSLANG_WEB
Jeff Bolz38cbad12019-03-05 14:40:07 -0600618 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500619 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
620 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
621 } else if (coherentFlags.devicecoherent) {
622 scope = spv::ScopeDevice;
623 } else if (coherentFlags.queuefamilycoherent) {
624 scope = spv::ScopeQueueFamilyKHR;
625 } else if (coherentFlags.workgroupcoherent) {
626 scope = spv::ScopeWorkgroup;
627 } else if (coherentFlags.subgroupcoherent) {
628 scope = spv::ScopeSubgroup;
Jeff Bolz36831c92018-09-05 10:11:41 -0500629 }
630 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
631 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
632 }
John Kessenichb9197c82019-08-11 07:41:45 -0600633#endif
634
Jeff Bolz36831c92018-09-05 10:11:41 -0500635 return scope;
636}
637
David Netoa901ffe2016-06-08 14:11:40 +0100638// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
639// associated capabilities when required. For some built-in variables, a capability
640// is generated only when using the variable in an executable instruction, but not when
641// just declaring a struct member variable with it. This is true for PointSize,
642// ClipDistance, and CullDistance.
643spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600644{
645 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700646 case glslang::EbvPointSize:
John Kessenich155d3512019-08-08 23:29:20 -0600647#ifndef GLSLANG_WEB
John Kessenich78a45572016-07-08 14:05:15 -0600648 // Defer adding the capability until the built-in is actually used.
649 if (! memberDeclaration) {
650 switch (glslangIntermediate->getStage()) {
651 case EShLangGeometry:
652 builder.addCapability(spv::CapabilityGeometryPointSize);
653 break;
654 case EShLangTessControl:
655 case EShLangTessEvaluation:
656 builder.addCapability(spv::CapabilityTessellationPointSize);
657 break;
658 default:
659 break;
660 }
John Kessenich92187592016-02-01 13:45:25 -0700661 }
John Kessenich155d3512019-08-08 23:29:20 -0600662#endif
John Kessenich92187592016-02-01 13:45:25 -0700663 return spv::BuiltInPointSize;
664
John Kessenicha28f7a72019-08-06 07:00:58 -0600665 case glslang::EbvPosition: return spv::BuiltInPosition;
666 case glslang::EbvVertexId: return spv::BuiltInVertexId;
667 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
668 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
669 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
670
671 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
672 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
673 case glslang::EbvFace: return spv::BuiltInFrontFacing;
674 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
675
John Kessenich3dd1ce52019-10-17 07:08:40 -0600676 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
677 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
678 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
679 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
680 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
681 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
682
John Kessenicha28f7a72019-08-06 07:00:58 -0600683#ifndef GLSLANG_WEB
John Kessenichebb50532016-05-16 19:22:05 -0600684 // These *Distance capabilities logically belong here, but if the member is declared and
685 // then never used, consumers of SPIR-V prefer the capability not be declared.
686 // They are now generated when used, rather than here when declared.
687 // Potentially, the specification should be more clear what the minimum
688 // use needed is to trigger the capability.
689 //
John Kessenich92187592016-02-01 13:45:25 -0700690 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100691 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800692 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700693 return spv::BuiltInClipDistance;
694
695 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100696 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800697 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700698 return spv::BuiltInCullDistance;
699
700 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600701 builder.addCapability(spv::CapabilityMultiViewport);
702 if (glslangIntermediate->getStage() == EShLangVertex ||
703 glslangIntermediate->getStage() == EShLangTessControl ||
704 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800705
John Kessenich8317e6c2019-08-18 23:58:08 -0600706 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600707 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800708 }
John Kessenich92187592016-02-01 13:45:25 -0700709 return spv::BuiltInViewportIndex;
710
John Kessenich5e801132016-02-15 11:09:46 -0700711 case glslang::EbvSampleId:
712 builder.addCapability(spv::CapabilitySampleRateShading);
713 return spv::BuiltInSampleId;
714
715 case glslang::EbvSamplePosition:
716 builder.addCapability(spv::CapabilitySampleRateShading);
717 return spv::BuiltInSamplePosition;
718
719 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700720 return spv::BuiltInSampleMask;
721
John Kessenich78a45572016-07-08 14:05:15 -0600722 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700723 if (glslangIntermediate->getStage() == EShLangMeshNV) {
724 return spv::BuiltInLayer;
725 }
John Kessenichba6a3c22017-09-13 13:22:50 -0600726 builder.addCapability(spv::CapabilityGeometry);
727 if (glslangIntermediate->getStage() == EShLangVertex ||
728 glslangIntermediate->getStage() == EShLangTessControl ||
729 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800730
John Kessenich8317e6c2019-08-18 23:58:08 -0600731 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600732 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800733 }
John Kessenich78a45572016-07-08 14:05:15 -0600734 return spv::BuiltInLayer;
735
John Kessenichda581a22015-10-14 14:10:30 -0600736 case glslang::EbvBaseVertex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600737 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800738 builder.addCapability(spv::CapabilityDrawParameters);
739 return spv::BuiltInBaseVertex;
740
John Kessenichda581a22015-10-14 14:10:30 -0600741 case glslang::EbvBaseInstance:
John Kessenich8317e6c2019-08-18 23:58:08 -0600742 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800743 builder.addCapability(spv::CapabilityDrawParameters);
744 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200745
John Kessenichda581a22015-10-14 14:10:30 -0600746 case glslang::EbvDrawId:
John Kessenich8317e6c2019-08-18 23:58:08 -0600747 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800748 builder.addCapability(spv::CapabilityDrawParameters);
749 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200750
751 case glslang::EbvPrimitiveId:
752 if (glslangIntermediate->getStage() == EShLangFragment)
753 builder.addCapability(spv::CapabilityGeometry);
754 return spv::BuiltInPrimitiveId;
755
Rex Xu37cdcee2017-06-29 17:46:34 +0800756 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800757 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
758 builder.addCapability(spv::CapabilityStencilExportEXT);
759 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800760
John Kessenich140f3df2015-06-26 16:58:36 -0600761 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600762 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
763 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
764 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
765 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
John Kessenich140f3df2015-06-26 16:58:36 -0600766 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
Rex Xu51596642016-09-21 18:56:12 +0800767
Rex Xu574ab042016-04-14 16:53:07 +0800768 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800769 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800770 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
771 return spv::BuiltInSubgroupSize;
772
Rex Xu574ab042016-04-14 16:53:07 +0800773 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800774 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800775 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
776 return spv::BuiltInSubgroupLocalInvocationId;
777
Rex Xu574ab042016-04-14 16:53:07 +0800778 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800779 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
780 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600781 return spv::BuiltInSubgroupEqMask;
Rex Xu51596642016-09-21 18:56:12 +0800782
Rex Xu574ab042016-04-14 16:53:07 +0800783 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800784 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
785 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600786 return spv::BuiltInSubgroupGeMask;
Rex Xu51596642016-09-21 18:56:12 +0800787
Rex Xu574ab042016-04-14 16:53:07 +0800788 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800789 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
790 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600791 return spv::BuiltInSubgroupGtMask;
Rex Xu51596642016-09-21 18:56:12 +0800792
Rex Xu574ab042016-04-14 16:53:07 +0800793 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800794 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
795 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600796 return spv::BuiltInSubgroupLeMask;
Rex Xu51596642016-09-21 18:56:12 +0800797
Rex Xu574ab042016-04-14 16:53:07 +0800798 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800799 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
800 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600801 return spv::BuiltInSubgroupLtMask;
Rex Xu51596642016-09-21 18:56:12 +0800802
John Kessenich66011cb2018-03-06 16:12:04 -0700803 case glslang::EbvNumSubgroups:
804 builder.addCapability(spv::CapabilityGroupNonUniform);
805 return spv::BuiltInNumSubgroups;
806
807 case glslang::EbvSubgroupID:
808 builder.addCapability(spv::CapabilityGroupNonUniform);
809 return spv::BuiltInSubgroupId;
810
811 case glslang::EbvSubgroupSize2:
812 builder.addCapability(spv::CapabilityGroupNonUniform);
813 return spv::BuiltInSubgroupSize;
814
815 case glslang::EbvSubgroupInvocation2:
816 builder.addCapability(spv::CapabilityGroupNonUniform);
817 return spv::BuiltInSubgroupLocalInvocationId;
818
819 case glslang::EbvSubgroupEqMask2:
820 builder.addCapability(spv::CapabilityGroupNonUniform);
821 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
822 return spv::BuiltInSubgroupEqMask;
823
824 case glslang::EbvSubgroupGeMask2:
825 builder.addCapability(spv::CapabilityGroupNonUniform);
826 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
827 return spv::BuiltInSubgroupGeMask;
828
829 case glslang::EbvSubgroupGtMask2:
830 builder.addCapability(spv::CapabilityGroupNonUniform);
831 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
832 return spv::BuiltInSubgroupGtMask;
833
834 case glslang::EbvSubgroupLeMask2:
835 builder.addCapability(spv::CapabilityGroupNonUniform);
836 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
837 return spv::BuiltInSubgroupLeMask;
838
839 case glslang::EbvSubgroupLtMask2:
840 builder.addCapability(spv::CapabilityGroupNonUniform);
841 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
842 return spv::BuiltInSubgroupLtMask;
John Kessenich9c14f772019-06-17 08:38:35 -0600843
Rex Xu17ff3432016-10-14 17:41:45 +0800844 case glslang::EbvBaryCoordNoPersp:
845 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
846 return spv::BuiltInBaryCoordNoPerspAMD;
847
848 case glslang::EbvBaryCoordNoPerspCentroid:
849 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
850 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
851
852 case glslang::EbvBaryCoordNoPerspSample:
853 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
854 return spv::BuiltInBaryCoordNoPerspSampleAMD;
855
856 case glslang::EbvBaryCoordSmooth:
857 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
858 return spv::BuiltInBaryCoordSmoothAMD;
859
860 case glslang::EbvBaryCoordSmoothCentroid:
861 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
862 return spv::BuiltInBaryCoordSmoothCentroidAMD;
863
864 case glslang::EbvBaryCoordSmoothSample:
865 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
866 return spv::BuiltInBaryCoordSmoothSampleAMD;
867
868 case glslang::EbvBaryCoordPullModel:
869 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
870 return spv::BuiltInBaryCoordPullModelAMD;
chaoc771d89f2017-01-13 01:10:53 -0800871
John Kessenich6c8aaac2017-02-27 01:20:51 -0700872 case glslang::EbvDeviceIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600873 builder.addIncorporatedExtension(spv::E_SPV_KHR_device_group, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700874 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700875 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700876
877 case glslang::EbvViewIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600878 builder.addIncorporatedExtension(spv::E_SPV_KHR_multiview, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700879 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700880 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700881
Daniel Koch5154db52018-11-26 10:01:58 -0500882 case glslang::EbvFragSizeEXT:
883 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
884 builder.addCapability(spv::CapabilityFragmentDensityEXT);
885 return spv::BuiltInFragSizeEXT;
886
887 case glslang::EbvFragInvocationCountEXT:
888 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
889 builder.addCapability(spv::CapabilityFragmentDensityEXT);
890 return spv::BuiltInFragInvocationCountEXT;
891
chaoc771d89f2017-01-13 01:10:53 -0800892 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800893 if (!memberDeclaration) {
894 builder.addExtension(spv::E_SPV_NV_viewport_array2);
895 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
896 }
chaoc771d89f2017-01-13 01:10:53 -0800897 return spv::BuiltInViewportMaskNV;
898 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800899 if (!memberDeclaration) {
900 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
901 builder.addCapability(spv::CapabilityShaderStereoViewNV);
902 }
chaoc771d89f2017-01-13 01:10:53 -0800903 return spv::BuiltInSecondaryPositionNV;
904 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800905 if (!memberDeclaration) {
906 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
907 builder.addCapability(spv::CapabilityShaderStereoViewNV);
908 }
chaoc771d89f2017-01-13 01:10:53 -0800909 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800910 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800911 if (!memberDeclaration) {
912 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
913 builder.addCapability(spv::CapabilityPerViewAttributesNV);
914 }
chaocdf3956c2017-02-14 14:52:34 -0800915 return spv::BuiltInPositionPerViewNV;
916 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800917 if (!memberDeclaration) {
918 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
919 builder.addCapability(spv::CapabilityPerViewAttributesNV);
920 }
chaocdf3956c2017-02-14 14:52:34 -0800921 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700922 case glslang::EbvFragFullyCoveredNV:
923 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
924 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
925 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700926 case glslang::EbvFragmentSizeNV:
927 builder.addExtension(spv::E_SPV_NV_shading_rate);
928 builder.addCapability(spv::CapabilityShadingRateNV);
929 return spv::BuiltInFragmentSizeNV;
930 case glslang::EbvInvocationsPerPixelNV:
931 builder.addExtension(spv::E_SPV_NV_shading_rate);
932 builder.addCapability(spv::CapabilityShadingRateNV);
933 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700934
Daniel Koch593a4e02019-05-27 16:46:31 -0400935 // ray tracing
Chao Chenb50c02e2018-09-19 11:42:24 -0700936 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700937 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700938 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700939 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700940 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700941 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700942 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700943 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700944 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700945 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700946 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700947 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700948 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700949 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700950 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700951 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700952 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700953 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700954 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700955 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700956 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700957 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700958 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700959 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700960 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700961 return spv::BuiltInWorldToObjectNV;
962 case glslang::EbvIncomingRayFlagsNV:
963 return spv::BuiltInIncomingRayFlagsNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400964
965 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700966 case glslang::EbvBaryCoordNV:
967 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
968 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
969 return spv::BuiltInBaryCoordNV;
970 case glslang::EbvBaryCoordNoPerspNV:
971 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
972 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
973 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400974
975 // mesh shaders
976 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700977 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400978 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700979 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400980 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700981 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400982 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700983 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400984 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700985 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400986 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700987 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400988 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700989 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400990 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700991 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch2cb2f192019-06-04 08:43:32 -0400992
993 // sm builtins
994 case glslang::EbvWarpsPerSM:
995 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
996 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
997 return spv::BuiltInWarpsPerSMNV;
998 case glslang::EbvSMCount:
999 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1000 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1001 return spv::BuiltInSMCountNV;
1002 case glslang::EbvWarpID:
1003 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1004 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1005 return spv::BuiltInWarpIDNV;
1006 case glslang::EbvSMID:
1007 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1008 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1009 return spv::BuiltInSMIDNV;
John Kessenicha28f7a72019-08-06 07:00:58 -06001010#endif
1011
Rex Xu3e783f92017-02-22 16:44:48 +08001012 default:
1013 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -06001014 }
1015}
1016
Rex Xufc618912015-09-09 16:42:49 +08001017// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -07001018spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +08001019{
1020 assert(type.getBasicType() == glslang::EbtSampler);
1021
John Kessenichb9197c82019-08-11 07:41:45 -06001022#ifdef GLSLANG_WEB
1023 return spv::ImageFormatUnknown;
1024#endif
1025
John Kessenich5d0fa972016-02-15 11:57:00 -07001026 // Check for capabilities
John Kessenich7015bd62019-08-01 03:28:08 -06001027 switch (type.getQualifier().getFormat()) {
John Kessenich5d0fa972016-02-15 11:57:00 -07001028 case glslang::ElfRg32f:
1029 case glslang::ElfRg16f:
1030 case glslang::ElfR11fG11fB10f:
1031 case glslang::ElfR16f:
1032 case glslang::ElfRgba16:
1033 case glslang::ElfRgb10A2:
1034 case glslang::ElfRg16:
1035 case glslang::ElfRg8:
1036 case glslang::ElfR16:
1037 case glslang::ElfR8:
1038 case glslang::ElfRgba16Snorm:
1039 case glslang::ElfRg16Snorm:
1040 case glslang::ElfRg8Snorm:
1041 case glslang::ElfR16Snorm:
1042 case glslang::ElfR8Snorm:
1043
1044 case glslang::ElfRg32i:
1045 case glslang::ElfRg16i:
1046 case glslang::ElfRg8i:
1047 case glslang::ElfR16i:
1048 case glslang::ElfR8i:
1049
1050 case glslang::ElfRgb10a2ui:
1051 case glslang::ElfRg32ui:
1052 case glslang::ElfRg16ui:
1053 case glslang::ElfRg8ui:
1054 case glslang::ElfR16ui:
1055 case glslang::ElfR8ui:
1056 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1057 break;
1058
1059 default:
1060 break;
1061 }
1062
1063 // do the translation
John Kessenich7015bd62019-08-01 03:28:08 -06001064 switch (type.getQualifier().getFormat()) {
Rex Xufc618912015-09-09 16:42:49 +08001065 case glslang::ElfNone: return spv::ImageFormatUnknown;
1066 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1067 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1068 case glslang::ElfR32f: return spv::ImageFormatR32f;
1069 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1070 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1071 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1072 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1073 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1074 case glslang::ElfR16f: return spv::ImageFormatR16f;
1075 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1076 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1077 case glslang::ElfRg16: return spv::ImageFormatRg16;
1078 case glslang::ElfRg8: return spv::ImageFormatRg8;
1079 case glslang::ElfR16: return spv::ImageFormatR16;
1080 case glslang::ElfR8: return spv::ImageFormatR8;
1081 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1082 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1083 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1084 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1085 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1086 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1087 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1088 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1089 case glslang::ElfR32i: return spv::ImageFormatR32i;
1090 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1091 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1092 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1093 case glslang::ElfR16i: return spv::ImageFormatR16i;
1094 case glslang::ElfR8i: return spv::ImageFormatR8i;
1095 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1096 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1097 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1098 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1099 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1100 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1101 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1102 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1103 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1104 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001105 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001106 }
1107}
1108
John Kesseniche18fd202018-01-30 11:01:39 -07001109spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001110{
John Kesseniche18fd202018-01-30 11:01:39 -07001111 if (selectionNode.getFlatten())
1112 return spv::SelectionControlFlattenMask;
1113 if (selectionNode.getDontFlatten())
1114 return spv::SelectionControlDontFlattenMask;
1115 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001116}
1117
John Kesseniche18fd202018-01-30 11:01:39 -07001118spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001119{
John Kesseniche18fd202018-01-30 11:01:39 -07001120 if (switchNode.getFlatten())
1121 return spv::SelectionControlFlattenMask;
1122 if (switchNode.getDontFlatten())
1123 return spv::SelectionControlDontFlattenMask;
1124 return spv::SelectionControlMaskNone;
1125}
1126
John Kessenicha2858d92018-01-31 08:11:18 -07001127// return a non-0 dependency if the dependency argument must be set
1128spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001129 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001130{
1131 spv::LoopControlMask control = spv::LoopControlMaskNone;
1132
1133 if (loopNode.getDontUnroll())
1134 control = control | spv::LoopControlDontUnrollMask;
1135 if (loopNode.getUnroll())
1136 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001137 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001138 control = control | spv::LoopControlDependencyInfiniteMask;
1139 else if (loopNode.getLoopDependency() > 0) {
1140 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001141 operands.push_back((unsigned int)loopNode.getLoopDependency());
1142 }
1143 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1144 if (loopNode.getMinIterations() > 0) {
1145 control = control | spv::LoopControlMinIterationsMask;
1146 operands.push_back(loopNode.getMinIterations());
1147 }
1148 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1149 control = control | spv::LoopControlMaxIterationsMask;
1150 operands.push_back(loopNode.getMaxIterations());
1151 }
1152 if (loopNode.getIterationMultiple() > 1) {
1153 control = control | spv::LoopControlIterationMultipleMask;
1154 operands.push_back(loopNode.getIterationMultiple());
1155 }
1156 if (loopNode.getPeelCount() > 0) {
1157 control = control | spv::LoopControlPeelCountMask;
1158 operands.push_back(loopNode.getPeelCount());
1159 }
1160 if (loopNode.getPartialCount() > 0) {
1161 control = control | spv::LoopControlPartialCountMask;
1162 operands.push_back(loopNode.getPartialCount());
1163 }
John Kessenicha2858d92018-01-31 08:11:18 -07001164 }
John Kesseniche18fd202018-01-30 11:01:39 -07001165
1166 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001167}
1168
John Kessenicha5c5fb62017-05-05 05:09:58 -06001169// Translate glslang type to SPIR-V storage class.
1170spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1171{
1172 if (type.getQualifier().isPipeInput())
1173 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001174 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001175 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001176
1177 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
John Kessenicha28f7a72019-08-06 07:00:58 -06001178 type.getQualifier().storage == glslang::EvqUniform) {
John Kessenichdeec1932019-08-13 08:00:30 -06001179 if (type.isAtomic())
John Kessenichbed4e4f2017-09-08 02:38:07 -06001180 return spv::StorageClassAtomicCounter;
1181 if (type.containsOpaque())
1182 return spv::StorageClassUniformConstant;
1183 }
1184
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001185 if (type.getQualifier().isUniformOrBuffer() &&
John Kessenichdeec1932019-08-13 08:00:30 -06001186 type.getQualifier().isShaderRecordNV()) {
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001187 return spv::StorageClassShaderRecordBufferNV;
1188 }
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001189
John Kessenichbed4e4f2017-09-08 02:38:07 -06001190 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001191 builder.addIncorporatedExtension(spv::E_SPV_KHR_storage_buffer_storage_class, spv::Spv_1_3);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001192 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001193 }
1194
1195 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich7015bd62019-08-01 03:28:08 -06001196 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001197 return spv::StorageClassPushConstant;
1198 if (type.getBasicType() == glslang::EbtBlock)
1199 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001200 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001201 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001202
1203 switch (type.getQualifier().storage) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06001204 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1205 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1206 case glslang::EvqTemporary: return spv::StorageClassFunction;
John Kessenichdeec1932019-08-13 08:00:30 -06001207 case glslang::EvqShared: return spv::StorageClassWorkgroup;
John Kessenich3dd1ce52019-10-17 07:08:40 -06001208#ifndef GLSLANG_WEB
Ashwin Leleff1783d2018-10-22 16:41:44 -07001209 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1210 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1211 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1212 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1213 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001214#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001215 default:
1216 assert(0);
1217 break;
1218 }
1219
1220 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001221}
1222
John Kessenich5611c6d2018-04-05 11:25:02 -06001223// Add capabilities pertaining to how an array is indexed.
1224void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1225 const glslang::TType& indexType)
1226{
John Kessenichb9197c82019-08-11 07:41:45 -06001227#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06001228 if (indexType.getQualifier().isNonUniform()) {
1229 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001230 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001231 if (baseType.getBasicType() == glslang::EbtSampler) {
1232 if (baseType.getQualifier().hasAttachment())
1233 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001234 else if (baseType.isImage() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001235 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001236 else if (baseType.isTexture() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001237 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1238 else if (baseType.isImage())
1239 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1240 else if (baseType.isTexture())
1241 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1242 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1243 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1244 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1245 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1246 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1247 }
1248 } else {
1249 // assume a dynamically uniform index
1250 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001251 if (baseType.getQualifier().hasAttachment()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001252 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001253 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001254 } else if (baseType.isImage() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001255 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001256 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001257 } else if (baseType.isTexture() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001258 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001259 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001260 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001261 }
1262 }
John Kessenichb9197c82019-08-11 07:41:45 -06001263#endif
John Kessenich5611c6d2018-04-05 11:25:02 -06001264}
1265
qining25262b32016-05-06 17:25:16 -04001266// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001267// descriptor set.
1268bool IsDescriptorResource(const glslang::TType& type)
1269{
John Kessenichf7497e22016-03-08 21:36:22 -07001270 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001271 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001272 return type.getQualifier().isUniformOrBuffer() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001273 ! type.getQualifier().isShaderRecordNV() &&
1274 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001275
1276 // non block...
1277 // basically samplerXXX/subpass/sampler/texture are all included
1278 // if they are the global-scope-class, not the function parameter
1279 // (or local, if they ever exist) class.
1280 if (type.getBasicType() == glslang::EbtSampler)
1281 return type.getQualifier().isUniformOrBuffer();
1282
1283 // None of the above.
1284 return false;
1285}
1286
John Kesseniche0b6cad2015-12-24 10:30:13 -07001287void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1288{
1289 if (child.layoutMatrix == glslang::ElmNone)
1290 child.layoutMatrix = parent.layoutMatrix;
1291
1292 if (parent.invariant)
1293 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001294 if (parent.flat)
1295 child.flat = true;
1296 if (parent.centroid)
1297 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001298#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001299 if (parent.nopersp)
1300 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001301 if (parent.explicitInterp)
1302 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001303 if (parent.perPrimitiveNV)
1304 child.perPrimitiveNV = true;
1305 if (parent.perViewNV)
1306 child.perViewNV = true;
1307 if (parent.perTaskNV)
1308 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001309 if (parent.patch)
1310 child.patch = true;
1311 if (parent.sample)
1312 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001313 if (parent.coherent)
1314 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001315 if (parent.devicecoherent)
1316 child.devicecoherent = true;
1317 if (parent.queuefamilycoherent)
1318 child.queuefamilycoherent = true;
1319 if (parent.workgroupcoherent)
1320 child.workgroupcoherent = true;
1321 if (parent.subgroupcoherent)
1322 child.subgroupcoherent = true;
1323 if (parent.nonprivate)
1324 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001325 if (parent.volatil)
1326 child.volatil = true;
1327 if (parent.restrict)
1328 child.restrict = true;
1329 if (parent.readonly)
1330 child.readonly = true;
1331 if (parent.writeonly)
1332 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001333#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001334}
1335
John Kessenichf2b7f332016-09-01 17:05:23 -06001336bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001337{
John Kessenich7b9fa252016-01-21 18:56:57 -07001338 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001339 // - struct members might inherit from a struct declaration
1340 // (note that non-block structs don't explicitly inherit,
1341 // only implicitly, meaning no decoration involved)
1342 // - affect decorations on the struct members
1343 // (note smooth does not, and expecting something like volatile
1344 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001345 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001346 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001347}
1348
John Kessenich140f3df2015-06-26 16:58:36 -06001349//
1350// Implement the TGlslangToSpvTraverser class.
1351//
1352
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001353TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001354 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1355 : TIntermTraverser(true, false, true),
1356 options(options),
1357 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001358 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001359 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001360 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich605afc72019-06-17 23:33:09 -06001361 glslangIntermediate(glslangIntermediate),
1362 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp())
John Kessenich140f3df2015-06-26 16:58:36 -06001363{
1364 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1365
1366 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001367 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1368 glslangIntermediate->getVersion());
1369
John Kessenich121853f2017-05-31 17:11:16 -06001370 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001371 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001372 builder.setSourceFile(glslangIntermediate->getSourceFile());
1373
1374 // Set the source shader's text. If for SPV version 1.0, include
1375 // a preamble in comments stating the OpModuleProcessed instructions.
1376 // Otherwise, emit those as actual instructions.
1377 std::string text;
1378 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1379 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001380 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001381 text.append("// OpModuleProcessed ");
1382 text.append(processes[p]);
1383 text.append("\n");
1384 } else
1385 builder.addModuleProcessed(processes[p]);
1386 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001387 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001388 text.append("#line 1\n");
1389 text.append(glslangIntermediate->getSourceText());
1390 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001391 // Pass name and text for all included files
1392 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1393 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1394 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001395 }
John Kessenich140f3df2015-06-26 16:58:36 -06001396 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001397
1398 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1399 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1400
1401 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1402 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
John Kessenich1ff0c182019-10-10 12:01:13 -06001403 builder.addIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer, spv::Spv_1_5);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001404 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
1405 };
Jeff Bolz36831c92018-09-05 10:11:41 -05001406 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001407 memoryModel = spv::MemoryModelVulkanKHR;
1408 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
John Kessenich8317e6c2019-08-18 23:58:08 -06001409 builder.addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
Jeff Bolz36831c92018-09-05 10:11:41 -05001410 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001411 builder.setMemoryModel(addressingModel, memoryModel);
1412
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001413 if (glslangIntermediate->usingVariablePointers()) {
1414 builder.addCapability(spv::CapabilityVariablePointers);
1415 }
1416
John Kessenicheee9d532016-09-19 18:09:30 -06001417 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1418 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001419
1420 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001421 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1422 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001423 builder.addSourceExtension(it->c_str());
1424
1425 // Add the top-level modes for this shader.
1426
John Kessenich92187592016-02-01 13:45:25 -07001427 if (glslangIntermediate->getXfbMode()) {
1428 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001429 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001430 }
John Kessenich140f3df2015-06-26 16:58:36 -06001431
1432 unsigned int mode;
1433 switch (glslangIntermediate->getStage()) {
1434 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001435 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001436 break;
1437
John Kessenicha28f7a72019-08-06 07:00:58 -06001438 case EShLangFragment:
1439 builder.addCapability(spv::CapabilityShader);
1440 if (glslangIntermediate->getPixelCenterInteger())
1441 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1442
1443 if (glslangIntermediate->getOriginUpperLeft())
1444 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1445 else
1446 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1447
1448 if (glslangIntermediate->getEarlyFragmentTests())
1449 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1450
1451 if (glslangIntermediate->getPostDepthCoverage()) {
1452 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1453 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1454 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1455 }
1456
John Kessenichb9197c82019-08-11 07:41:45 -06001457 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1458 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1459
1460#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -06001461 switch(glslangIntermediate->getDepth()) {
1462 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1463 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1464 default: mode = spv::ExecutionModeMax; break;
1465 }
1466 if (mode != spv::ExecutionModeMax)
1467 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kessenicha28f7a72019-08-06 07:00:58 -06001468 switch (glslangIntermediate->getInterlockOrdering()) {
1469 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT; break;
1470 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT; break;
1471 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT; break;
1472 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT; break;
1473 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT; break;
1474 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT; break;
1475 default: mode = spv::ExecutionModeMax; break;
1476 }
1477 if (mode != spv::ExecutionModeMax) {
1478 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1479 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1480 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1481 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1482 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1483 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1484 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1485 } else {
1486 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1487 }
1488 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1489 }
John Kessenichb9197c82019-08-11 07:41:45 -06001490#endif
John Kessenicha28f7a72019-08-06 07:00:58 -06001491 break;
1492
John Kessenicha28f7a72019-08-06 07:00:58 -06001493 case EShLangCompute:
1494 builder.addCapability(spv::CapabilityShader);
1495 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1496 glslangIntermediate->getLocalSize(1),
1497 glslangIntermediate->getLocalSize(2));
John Kessenich51ed01c2019-10-10 11:40:11 -06001498#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -06001499 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1500 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1501 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1502 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1503 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1504 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1505 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1506 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1507 }
John Kessenich51ed01c2019-10-10 11:40:11 -06001508#endif
John Kessenicha28f7a72019-08-06 07:00:58 -06001509 break;
John Kessenich51ed01c2019-10-10 11:40:11 -06001510#ifndef GLSLANG_WEB
steve-lunarge7412492017-03-23 11:56:07 -06001511 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001512 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001513 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001514
steve-lunarge7412492017-03-23 11:56:07 -06001515 glslang::TLayoutGeometry primitive;
1516
1517 if (glslangIntermediate->getStage() == EShLangTessControl) {
1518 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1519 primitive = glslangIntermediate->getOutputPrimitive();
1520 } else {
1521 primitive = glslangIntermediate->getInputPrimitive();
1522 }
1523
1524 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001525 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1526 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1527 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001528 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001529 }
John Kessenich4016e382016-07-15 11:53:56 -06001530 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001531 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1532
John Kesseniche6903322015-10-13 16:29:02 -06001533 switch (glslangIntermediate->getVertexSpacing()) {
1534 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1535 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1536 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001537 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001538 }
John Kessenich4016e382016-07-15 11:53:56 -06001539 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001540 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1541
1542 switch (glslangIntermediate->getVertexOrder()) {
1543 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1544 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001545 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001546 }
John Kessenich4016e382016-07-15 11:53:56 -06001547 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001548 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1549
1550 if (glslangIntermediate->getPointMode())
1551 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001552 break;
1553
1554 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001555 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001556 switch (glslangIntermediate->getInputPrimitive()) {
1557 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1558 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1559 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001560 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001561 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001562 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001563 }
John Kessenich4016e382016-07-15 11:53:56 -06001564 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001565 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001566
John Kessenich140f3df2015-06-26 16:58:36 -06001567 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1568
1569 switch (glslangIntermediate->getOutputPrimitive()) {
1570 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1571 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1572 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001573 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001574 }
John Kessenich4016e382016-07-15 11:53:56 -06001575 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001576 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1577 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1578 break;
1579
Chao Chenb50c02e2018-09-19 11:42:24 -07001580 case EShLangRayGenNV:
1581 case EShLangIntersectNV:
1582 case EShLangAnyHitNV:
1583 case EShLangClosestHitNV:
1584 case EShLangMissNV:
1585 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001586 builder.addCapability(spv::CapabilityRayTracingNV);
1587 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001588 break;
Chao Chen3c366992018-09-19 11:41:59 -07001589 case EShLangTaskNV:
1590 case EShLangMeshNV:
1591 builder.addCapability(spv::CapabilityMeshShadingNV);
1592 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1593 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1594 glslangIntermediate->getLocalSize(1),
1595 glslangIntermediate->getLocalSize(2));
1596 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1597 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1598 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1599
1600 switch (glslangIntermediate->getOutputPrimitive()) {
1601 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1602 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1603 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1604 default: mode = spv::ExecutionModeMax; break;
1605 }
1606 if (mode != spv::ExecutionModeMax)
1607 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1608 }
1609 break;
1610#endif
1611
John Kessenich140f3df2015-06-26 16:58:36 -06001612 default:
1613 break;
1614 }
John Kessenich140f3df2015-06-26 16:58:36 -06001615}
1616
John Kessenichfca82622016-11-26 13:23:20 -07001617// Finish creating SPV, after the traversal is complete.
1618void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001619{
John Kessenichf04c51b2018-08-03 15:56:12 -06001620 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001621 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001622 builder.setBuildPoint(shaderEntry->getLastBlock());
1623 builder.leaveFunction();
1624 }
1625
John Kessenich7ba63412015-12-20 17:37:07 -07001626 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001627 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1628 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001629
John Kessenich23d27752019-07-28 02:12:10 -06001630#ifndef GLSLANG_WEB
John Kessenichf04c51b2018-08-03 15:56:12 -06001631 // Add capabilities, extensions, remove unneeded decorations, etc.,
1632 // based on the resulting SPIR-V.
1633 builder.postProcess();
John Kessenich23d27752019-07-28 02:12:10 -06001634#endif
John Kessenich7ba63412015-12-20 17:37:07 -07001635}
1636
John Kessenichfca82622016-11-26 13:23:20 -07001637// Write the SPV into 'out'.
1638void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001639{
John Kessenichfca82622016-11-26 13:23:20 -07001640 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001641}
1642
1643//
1644// Implement the traversal functions.
1645//
1646// Return true from interior nodes to have the external traversal
1647// continue on to children. Return false if children were
1648// already processed.
1649//
1650
1651//
qining25262b32016-05-06 17:25:16 -04001652// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001653// - uniform/input reads
1654// - output writes
1655// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1656// - something simple that degenerates into the last bullet
1657//
1658void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1659{
qining75d1d802016-04-06 14:42:01 -04001660 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1661 if (symbol->getType().getQualifier().isSpecConstant())
1662 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1663
John Kessenich140f3df2015-06-26 16:58:36 -06001664 // getSymbolId() will set up all the IO decorations on the first call.
1665 // Formal function parameters were mapped during makeFunctions().
1666 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001667
John Kessenich7ba63412015-12-20 17:37:07 -07001668 if (builder.isPointer(id)) {
John Kessenich9c14f772019-06-17 08:38:35 -06001669 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
John Kessenich7c7731e2019-01-04 16:47:06 +07001670 // Consider adding to the OpEntryPoint interface list.
1671 // Only looking at structures if they have at least one member.
1672 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1673 spv::StorageClass sc = builder.getStorageClass(id);
1674 // Before SPIR-V 1.4, we only want to include Input and Output.
1675 // Starting with SPIR-V 1.4, we want all globals.
1676 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1677 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001678 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001679 }
John Kessenich5f77d862017-09-19 11:09:59 -06001680 }
John Kessenich9c14f772019-06-17 08:38:35 -06001681
1682 // If the SPIR-V type is required to be different than the AST type,
1683 // translate now from the SPIR-V type to the AST type, for the consuming
1684 // operation.
1685 // Note this turns it from an l-value to an r-value.
1686 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1687 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1688 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001689 }
1690
1691 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001692 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001693 // Prepare to generate code for the access
1694
1695 // L-value chains will be computed left to right. We're on the symbol now,
1696 // which is the left-most part of the access chain, so now is "clear" time,
1697 // followed by setting the base.
1698 builder.clearAccessChain();
1699
1700 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001701 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001702 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001703 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001704 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001705 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001706 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001707 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001708 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1709 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001710 builder.setAccessChainRValue(id);
1711 else
1712 builder.setAccessChainLValue(id);
1713 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001714
John Kessenichb9197c82019-08-11 07:41:45 -06001715#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001716 // Process linkage-only nodes for any special additional interface work.
1717 if (linkageOnly) {
1718 if (glslangIntermediate->getHlslFunctionality1()) {
1719 // Map implicit counter buffers to their originating buffers, which should have been
1720 // seen by now, given earlier pruning of unused counters, and preservation of order
1721 // of declaration.
1722 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1723 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1724 // Save possible originating buffers for counter buffers, keyed by
1725 // making the potential counter-buffer name.
1726 std::string keyName = symbol->getName().c_str();
1727 keyName = glslangIntermediate->addCounterBufferName(keyName);
1728 counterOriginator[keyName] = symbol;
1729 } else {
1730 // Handle a counter buffer, by finding the saved originating buffer.
1731 std::string keyName = symbol->getName().c_str();
1732 auto it = counterOriginator.find(keyName);
1733 if (it != counterOriginator.end()) {
1734 id = getSymbolId(it->second);
1735 if (id != spv::NoResult) {
1736 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001737 if (counterId != spv::NoResult) {
1738 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001739 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001740 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001741 }
1742 }
1743 }
1744 }
1745 }
1746 }
John Kessenich155d3512019-08-08 23:29:20 -06001747#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001748}
1749
1750bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1751{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001752 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001753
qining40887662016-04-03 22:20:42 -04001754 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1755 if (node->getType().getQualifier().isSpecConstant())
1756 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1757
John Kessenich140f3df2015-06-26 16:58:36 -06001758 // First, handle special cases
1759 switch (node->getOp()) {
1760 case glslang::EOpAssign:
1761 case glslang::EOpAddAssign:
1762 case glslang::EOpSubAssign:
1763 case glslang::EOpMulAssign:
1764 case glslang::EOpVectorTimesMatrixAssign:
1765 case glslang::EOpVectorTimesScalarAssign:
1766 case glslang::EOpMatrixTimesScalarAssign:
1767 case glslang::EOpMatrixTimesMatrixAssign:
1768 case glslang::EOpDivAssign:
1769 case glslang::EOpModAssign:
1770 case glslang::EOpAndAssign:
1771 case glslang::EOpInclusiveOrAssign:
1772 case glslang::EOpExclusiveOrAssign:
1773 case glslang::EOpLeftShiftAssign:
1774 case glslang::EOpRightShiftAssign:
1775 // A bin-op assign "a += b" means the same thing as "a = a + b"
1776 // where a is evaluated before b. For a simple assignment, GLSL
1777 // says to evaluate the left before the right. So, always, left
1778 // node then right node.
1779 {
1780 // get the left l-value, save it away
1781 builder.clearAccessChain();
1782 node->getLeft()->traverse(this);
1783 spv::Builder::AccessChain lValue = builder.getAccessChain();
1784
1785 // evaluate the right
1786 builder.clearAccessChain();
1787 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001788 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001789
1790 if (node->getOp() != glslang::EOpAssign) {
1791 // the left is also an r-value
1792 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001793 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001794
1795 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001796 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001797 TranslateNoContractionDecoration(node->getType().getQualifier()),
1798 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001799 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001800 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1801 node->getType().getBasicType());
1802
1803 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001804 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001805 }
1806
1807 // store the result
1808 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001809 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001810
1811 // assignments are expressions having an rValue after they are evaluated...
1812 builder.clearAccessChain();
1813 builder.setAccessChainRValue(rValue);
1814 }
1815 return false;
1816 case glslang::EOpIndexDirect:
1817 case glslang::EOpIndexDirectStruct:
1818 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001819 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001820 // Get the left part of the access chain.
1821 node->getLeft()->traverse(this);
1822
1823 // Add the next element in the chain
1824
David Netoa901ffe2016-06-08 14:11:40 +01001825 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001826 if (! node->getLeft()->getType().isArray() &&
1827 node->getLeft()->getType().isVector() &&
1828 node->getOp() == glslang::EOpIndexDirect) {
1829 // This is essentially a hard-coded vector swizzle of size 1,
1830 // so short circuit the access-chain stuff with a swizzle.
1831 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001832 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001833 int dummySize;
1834 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1835 TranslateCoherent(node->getLeft()->getType()),
1836 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001837 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001838
1839 // Load through a block reference is performed with a dot operator that
1840 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1841 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001842 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001843 !node->getLeft()->getType().isArray() &&
1844 node->getOp() == glslang::EOpIndexDirectStruct)
1845 {
1846 spv::Id left = accessChainLoad(node->getLeft()->getType());
1847 builder.clearAccessChain();
1848 builder.setAccessChainLValue(left);
1849 }
1850
David Netoa901ffe2016-06-08 14:11:40 +01001851 int spvIndex = glslangIndex;
1852 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1853 node->getOp() == glslang::EOpIndexDirectStruct)
1854 {
1855 // This may be, e.g., an anonymous block-member selection, which generally need
1856 // index remapping due to hidden members in anonymous blocks.
1857 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1858 assert(remapper.size() > 0);
1859 spvIndex = remapper[glslangIndex];
1860 }
John Kessenichebb50532016-05-16 19:22:05 -06001861
David Netoa901ffe2016-06-08 14:11:40 +01001862 // normal case for indexing array or structure or block
Jeff Bolz7895e472019-03-06 13:34:10 -06001863 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001864
1865 // Add capabilities here for accessing PointSize and clip/cull distance.
1866 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001867 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001868 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001869 }
1870 }
1871 return false;
1872 case glslang::EOpIndexIndirect:
1873 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001874 // Array, matrix, or vector indirection with variable index.
1875 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001876 // matrices are arrays of vectors, so will also work for a matrix.
1877 // Will use the access chain's 'component' for variable index into a vector.
1878
1879 // This adapter is building access chains left to right.
1880 // Set up the access chain to the left.
1881 node->getLeft()->traverse(this);
1882
1883 // save it so that computing the right side doesn't trash it
1884 spv::Builder::AccessChain partial = builder.getAccessChain();
1885
1886 // compute the next index in the chain
1887 builder.clearAccessChain();
1888 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001889 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001890
John Kessenich5611c6d2018-04-05 11:25:02 -06001891 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1892
John Kessenich140f3df2015-06-26 16:58:36 -06001893 // restore the saved access chain
1894 builder.setAccessChain(partial);
1895
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001896 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1897 int dummySize;
1898 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1899 TranslateCoherent(node->getLeft()->getType()),
1900 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1901 } else
Jeff Bolz7895e472019-03-06 13:34:10 -06001902 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001903 }
1904 return false;
1905 case glslang::EOpVectorSwizzle:
1906 {
1907 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001908 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001909 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001910 int dummySize;
1911 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1912 TranslateCoherent(node->getLeft()->getType()),
1913 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001914 }
1915 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001916 case glslang::EOpMatrixSwizzle:
1917 logger->missingFunctionality("matrix swizzle");
1918 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001919 case glslang::EOpLogicalOr:
1920 case glslang::EOpLogicalAnd:
1921 {
1922
1923 // These may require short circuiting, but can sometimes be done as straight
1924 // binary operations. The right operand must be short circuited if it has
1925 // side effects, and should probably be if it is complex.
1926 if (isTrivial(node->getRight()->getAsTyped()))
1927 break; // handle below as a normal binary operation
1928 // otherwise, we need to do dynamic short circuiting on the right operand
1929 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1930 builder.clearAccessChain();
1931 builder.setAccessChainRValue(result);
1932 }
1933 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001934 default:
1935 break;
1936 }
1937
1938 // Assume generic binary op...
1939
John Kessenich32cfd492016-02-02 12:37:46 -07001940 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001941 builder.clearAccessChain();
1942 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001943 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001944
John Kessenich32cfd492016-02-02 12:37:46 -07001945 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001946 builder.clearAccessChain();
1947 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001948 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001949
John Kessenich32cfd492016-02-02 12:37:46 -07001950 // get result
John Kessenichead86222018-03-28 18:01:20 -06001951 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001952 TranslateNoContractionDecoration(node->getType().getQualifier()),
1953 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001954 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001955 convertGlslangToSpvType(node->getType()), left, right,
1956 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001957
John Kessenich50e57562015-12-21 21:21:11 -07001958 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001959 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001960 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001961 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001962 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001963 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001964 return false;
1965 }
John Kessenich140f3df2015-06-26 16:58:36 -06001966}
1967
John Kessenich9c14f772019-06-17 08:38:35 -06001968// Figure out what, if any, type changes are needed when accessing a specific built-in.
1969// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
1970// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
1971std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(spv::BuiltIn builtIn,
1972 const glslang::TType& glslangType)
1973{
1974 switch(builtIn)
1975 {
1976 case spv::BuiltInSubgroupEqMask:
1977 case spv::BuiltInSubgroupGeMask:
1978 case spv::BuiltInSubgroupGtMask:
1979 case spv::BuiltInSubgroupLeMask:
1980 case spv::BuiltInSubgroupLtMask: {
1981 // these require changing a 64-bit scaler -> a vector of 32-bit components
1982 if (glslangType.isVector())
1983 break;
1984 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
1985 builder.makeUintType(64));
1986 return ret;
1987 }
1988 default:
1989 break;
1990 }
1991
1992 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
1993 return ret;
1994}
1995
1996// For an object previously identified (see getForcedType() and forceType)
1997// as needing type translations, do the translation needed for a load, turning
1998// an L-value into in R-value.
1999spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2000{
2001 const auto forceIt = forceType.find(object);
2002 if (forceIt == forceType.end())
2003 return object;
2004
2005 spv::Id desiredTypeId = forceIt->second;
2006 spv::Id objectTypeId = builder.getTypeId(object);
2007 assert(builder.isPointerType(objectTypeId));
2008 objectTypeId = builder.getContainedTypeId(objectTypeId);
2009 if (builder.isVectorType(objectTypeId) &&
2010 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2011 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2012 // handle 32-bit v.xy* -> 64-bit
2013 builder.clearAccessChain();
2014 builder.setAccessChainLValue(object);
2015 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2016 std::vector<spv::Id> components;
2017 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2018 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2019
2020 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2021 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2022 builder.createCompositeConstruct(vecType, components));
2023 } else {
2024 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2025 }
2026 } else {
2027 logger->missingFunctionality("forcing non 32-bit vector type");
2028 }
2029
2030 return object;
2031}
2032
John Kessenich140f3df2015-06-26 16:58:36 -06002033bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2034{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002035 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002036
qining40887662016-04-03 22:20:42 -04002037 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2038 if (node->getType().getQualifier().isSpecConstant())
2039 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2040
John Kessenichfc51d282015-08-19 13:34:18 -06002041 spv::Id result = spv::NoResult;
2042
2043 // try texturing first
2044 result = createImageTextureFunctionCall(node);
2045 if (result != spv::NoResult) {
2046 builder.clearAccessChain();
2047 builder.setAccessChainRValue(result);
2048
2049 return false; // done with this node
2050 }
2051
2052 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002053
2054 if (node->getOp() == glslang::EOpArrayLength) {
2055 // Quite special; won't want to evaluate the operand.
2056
John Kessenich5611c6d2018-04-05 11:25:02 -06002057 // Currently, the front-end does not allow .length() on an array until it is sized,
2058 // except for the last block membeor of an SSBO.
2059 // TODO: If this changes, link-time sized arrays might show up here, and need their
2060 // size extracted.
2061
John Kessenichc9a80832015-09-12 12:17:44 -06002062 // Normal .length() would have been constant folded by the front-end.
2063 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002064 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002065
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002066 spv::Id length;
2067 if (node->getOperand()->getType().isCoopMat()) {
2068 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2069
2070 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2071 assert(builder.isCooperativeMatrixType(typeId));
2072
2073 length = builder.createCooperativeMatrixLength(typeId);
2074 } else {
2075 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2076 block->traverse(this);
2077 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
2078 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2079 }
John Kessenichc9a80832015-09-12 12:17:44 -06002080
John Kessenich8c869672018-11-28 07:01:37 -07002081 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2082 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2083 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002084 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2085 if (builder.isInSpecConstCodeGenMode()) {
2086 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2087 } else {
2088 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2089 }
2090 }
John Kessenich8c869672018-11-28 07:01:37 -07002091
John Kessenichc9a80832015-09-12 12:17:44 -06002092 builder.clearAccessChain();
2093 builder.setAccessChainRValue(length);
2094
2095 return false;
2096 }
2097
John Kessenichfc51d282015-08-19 13:34:18 -06002098 // Start by evaluating the operand
2099
John Kessenich8c8505c2016-07-26 12:50:38 -06002100 // Does it need a swizzle inversion? If so, evaluation is inverted;
2101 // operate first on the swizzle base, then apply the swizzle.
2102 spv::Id invertedType = spv::NoType;
2103 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
2104 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2105 invertedType = getInvertedSwizzleType(*node->getOperand());
2106
John Kessenich140f3df2015-06-26 16:58:36 -06002107 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002108 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002109 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002110 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002111 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002112 operandNode = node->getOperand();
2113
2114 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002115
Rex Xufc618912015-09-09 16:42:49 +08002116 spv::Id operand = spv::NoResult;
2117
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002118 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2119
John Kessenichfb4f2332019-08-09 03:49:15 -06002120#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002121 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2122 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002123 node->getOp() == glslang::EOpAtomicCounter ||
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002124 node->getOp() == glslang::EOpInterpolateAtCentroid) {
Rex Xufc618912015-09-09 16:42:49 +08002125 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002126 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2127 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2128 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002129#endif
2130 {
John Kessenich32cfd492016-02-02 12:37:46 -07002131 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002132 }
John Kessenich140f3df2015-06-26 16:58:36 -06002133
John Kessenichead86222018-03-28 18:01:20 -06002134 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002135 TranslateNoContractionDecoration(node->getType().getQualifier()),
2136 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002137
2138 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002139 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06002140 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002141
2142 // if not, then possibly an operation
2143 if (! result)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002144 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002145
2146 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002147 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002148 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002149 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002150 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002151
John Kessenich140f3df2015-06-26 16:58:36 -06002152 builder.clearAccessChain();
2153 builder.setAccessChainRValue(result);
2154
2155 return false; // done with this node
2156 }
2157
2158 // it must be a special case, check...
2159 switch (node->getOp()) {
2160 case glslang::EOpPostIncrement:
2161 case glslang::EOpPostDecrement:
2162 case glslang::EOpPreIncrement:
2163 case glslang::EOpPreDecrement:
2164 {
2165 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002166 spv::Id one = 0;
2167 if (node->getBasicType() == glslang::EbtFloat)
2168 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002169#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002170 else if (node->getBasicType() == glslang::EbtDouble)
2171 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002172 else if (node->getBasicType() == glslang::EbtFloat16)
2173 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002174 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2175 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002176 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2177 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002178 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2179 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002180#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002181 else
2182 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002183 glslang::TOperator op;
2184 if (node->getOp() == glslang::EOpPreIncrement ||
2185 node->getOp() == glslang::EOpPostIncrement)
2186 op = glslang::EOpAdd;
2187 else
2188 op = glslang::EOpSub;
2189
John Kessenichead86222018-03-28 18:01:20 -06002190 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002191 convertGlslangToSpvType(node->getType()), operand, one,
2192 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002193 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002194
2195 // The result of operation is always stored, but conditionally the
2196 // consumed result. The consumed result is always an r-value.
2197 builder.accessChainStore(result);
2198 builder.clearAccessChain();
2199 if (node->getOp() == glslang::EOpPreIncrement ||
2200 node->getOp() == glslang::EOpPreDecrement)
2201 builder.setAccessChainRValue(result);
2202 else
2203 builder.setAccessChainRValue(operand);
2204 }
2205
2206 return false;
2207
John Kessenich155d3512019-08-08 23:29:20 -06002208#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002209 case glslang::EOpEmitStreamVertex:
2210 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2211 return false;
2212 case glslang::EOpEndStreamPrimitive:
2213 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2214 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002215#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002216
2217 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002218 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002219 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002220 }
John Kessenich140f3df2015-06-26 16:58:36 -06002221}
2222
Jeff Bolz53134492019-06-25 13:31:10 -05002223// Construct a composite object, recursively copying members if their types don't match
2224spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2225{
2226 for (int c = 0; c < (int)constituents.size(); ++c) {
2227 spv::Id& constituent = constituents[c];
2228 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2229 spv::Id rType = builder.getTypeId(constituent);
2230 if (lType != rType) {
2231 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2232 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2233 } else if (builder.isStructType(rType)) {
2234 std::vector<spv::Id> rTypeConstituents;
2235 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2236 for (int i = 0; i < numrTypeConstituents; ++i) {
2237 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, builder.getContainedTypeId(rType, i), i));
2238 }
2239 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2240 } else {
2241 assert(builder.isArrayType(rType));
2242 std::vector<spv::Id> rTypeConstituents;
2243 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2244
2245 spv::Id elementRType = builder.getContainedTypeId(rType);
2246 for (int i = 0; i < numrTypeConstituents; ++i) {
2247 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2248 }
2249 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2250 }
2251 }
2252 }
2253 return builder.createCompositeConstruct(resultTypeId, constituents);
2254}
2255
John Kessenich140f3df2015-06-26 16:58:36 -06002256bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2257{
qining27e04a02016-04-14 16:40:20 -04002258 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2259 if (node->getType().getQualifier().isSpecConstant())
2260 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2261
John Kessenichfc51d282015-08-19 13:34:18 -06002262 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002263 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2264 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002265
2266 // try texturing
2267 result = createImageTextureFunctionCall(node);
2268 if (result != spv::NoResult) {
2269 builder.clearAccessChain();
2270 builder.setAccessChainRValue(result);
2271
2272 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002273 }
2274#ifndef GLSLANG_WEB
2275 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002276 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002277 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002278 // "imageStore" is a special case, which has no result
2279 return false;
2280 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002281#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002282
John Kessenich140f3df2015-06-26 16:58:36 -06002283 glslang::TOperator binOp = glslang::EOpNull;
2284 bool reduceComparison = true;
2285 bool isMatrix = false;
2286 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002287 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002288
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002289 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2290
John Kessenich140f3df2015-06-26 16:58:36 -06002291 assert(node->getOp());
2292
John Kessenichf6640762016-08-01 19:44:00 -06002293 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002294
2295 switch (node->getOp()) {
2296 case glslang::EOpSequence:
2297 {
2298 if (preVisit)
2299 ++sequenceDepth;
2300 else
2301 --sequenceDepth;
2302
2303 if (sequenceDepth == 1) {
2304 // If this is the parent node of all the functions, we want to see them
2305 // early, so all call points have actual SPIR-V functions to reference.
2306 // In all cases, still let the traverser visit the children for us.
2307 makeFunctions(node->getAsAggregate()->getSequence());
2308
John Kessenich6fccb3c2016-09-19 16:01:41 -06002309 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002310 // anything else gets there, so visit out of order, doing them all now.
2311 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2312
John Kessenich6a60c2f2016-12-08 21:01:59 -07002313 // Initializers are done, don't want to visit again, but functions and link objects need to be processed,
John Kessenich140f3df2015-06-26 16:58:36 -06002314 // so do them manually.
2315 visitFunctions(node->getAsAggregate()->getSequence());
2316
2317 return false;
2318 }
2319
2320 return true;
2321 }
2322 case glslang::EOpLinkerObjects:
2323 {
2324 if (visit == glslang::EvPreVisit)
2325 linkageOnly = true;
2326 else
2327 linkageOnly = false;
2328
2329 return true;
2330 }
2331 case glslang::EOpComma:
2332 {
2333 // processing from left to right naturally leaves the right-most
2334 // lying around in the access chain
2335 glslang::TIntermSequence& glslangOperands = node->getSequence();
2336 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2337 glslangOperands[i]->traverse(this);
2338
2339 return false;
2340 }
2341 case glslang::EOpFunction:
2342 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002343 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002344 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002345 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002346 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002347 } else {
2348 handleFunctionEntry(node);
2349 }
2350 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002351 if (inEntryPoint)
2352 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002353 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002354 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002355 }
2356
2357 return true;
2358 case glslang::EOpParameters:
2359 // Parameters will have been consumed by EOpFunction processing, but not
2360 // the body, so we still visited the function node's children, making this
2361 // child redundant.
2362 return false;
2363 case glslang::EOpFunctionCall:
2364 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002365 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002366 if (node->isUserDefined())
2367 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002368 // assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
John Kessenich6c292d32016-02-15 20:58:50 -07002369 if (result) {
2370 builder.clearAccessChain();
2371 builder.setAccessChainRValue(result);
2372 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002373 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002374
2375 return false;
2376 }
2377 case glslang::EOpConstructMat2x2:
2378 case glslang::EOpConstructMat2x3:
2379 case glslang::EOpConstructMat2x4:
2380 case glslang::EOpConstructMat3x2:
2381 case glslang::EOpConstructMat3x3:
2382 case glslang::EOpConstructMat3x4:
2383 case glslang::EOpConstructMat4x2:
2384 case glslang::EOpConstructMat4x3:
2385 case glslang::EOpConstructMat4x4:
2386 case glslang::EOpConstructDMat2x2:
2387 case glslang::EOpConstructDMat2x3:
2388 case glslang::EOpConstructDMat2x4:
2389 case glslang::EOpConstructDMat3x2:
2390 case glslang::EOpConstructDMat3x3:
2391 case glslang::EOpConstructDMat3x4:
2392 case glslang::EOpConstructDMat4x2:
2393 case glslang::EOpConstructDMat4x3:
2394 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002395 case glslang::EOpConstructIMat2x2:
2396 case glslang::EOpConstructIMat2x3:
2397 case glslang::EOpConstructIMat2x4:
2398 case glslang::EOpConstructIMat3x2:
2399 case glslang::EOpConstructIMat3x3:
2400 case glslang::EOpConstructIMat3x4:
2401 case glslang::EOpConstructIMat4x2:
2402 case glslang::EOpConstructIMat4x3:
2403 case glslang::EOpConstructIMat4x4:
2404 case glslang::EOpConstructUMat2x2:
2405 case glslang::EOpConstructUMat2x3:
2406 case glslang::EOpConstructUMat2x4:
2407 case glslang::EOpConstructUMat3x2:
2408 case glslang::EOpConstructUMat3x3:
2409 case glslang::EOpConstructUMat3x4:
2410 case glslang::EOpConstructUMat4x2:
2411 case glslang::EOpConstructUMat4x3:
2412 case glslang::EOpConstructUMat4x4:
2413 case glslang::EOpConstructBMat2x2:
2414 case glslang::EOpConstructBMat2x3:
2415 case glslang::EOpConstructBMat2x4:
2416 case glslang::EOpConstructBMat3x2:
2417 case glslang::EOpConstructBMat3x3:
2418 case glslang::EOpConstructBMat3x4:
2419 case glslang::EOpConstructBMat4x2:
2420 case glslang::EOpConstructBMat4x3:
2421 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002422 case glslang::EOpConstructF16Mat2x2:
2423 case glslang::EOpConstructF16Mat2x3:
2424 case glslang::EOpConstructF16Mat2x4:
2425 case glslang::EOpConstructF16Mat3x2:
2426 case glslang::EOpConstructF16Mat3x3:
2427 case glslang::EOpConstructF16Mat3x4:
2428 case glslang::EOpConstructF16Mat4x2:
2429 case glslang::EOpConstructF16Mat4x3:
2430 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002431 isMatrix = true;
2432 // fall through
2433 case glslang::EOpConstructFloat:
2434 case glslang::EOpConstructVec2:
2435 case glslang::EOpConstructVec3:
2436 case glslang::EOpConstructVec4:
2437 case glslang::EOpConstructDouble:
2438 case glslang::EOpConstructDVec2:
2439 case glslang::EOpConstructDVec3:
2440 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002441 case glslang::EOpConstructFloat16:
2442 case glslang::EOpConstructF16Vec2:
2443 case glslang::EOpConstructF16Vec3:
2444 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002445 case glslang::EOpConstructBool:
2446 case glslang::EOpConstructBVec2:
2447 case glslang::EOpConstructBVec3:
2448 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002449 case glslang::EOpConstructInt8:
2450 case glslang::EOpConstructI8Vec2:
2451 case glslang::EOpConstructI8Vec3:
2452 case glslang::EOpConstructI8Vec4:
2453 case glslang::EOpConstructUint8:
2454 case glslang::EOpConstructU8Vec2:
2455 case glslang::EOpConstructU8Vec3:
2456 case glslang::EOpConstructU8Vec4:
2457 case glslang::EOpConstructInt16:
2458 case glslang::EOpConstructI16Vec2:
2459 case glslang::EOpConstructI16Vec3:
2460 case glslang::EOpConstructI16Vec4:
2461 case glslang::EOpConstructUint16:
2462 case glslang::EOpConstructU16Vec2:
2463 case glslang::EOpConstructU16Vec3:
2464 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002465 case glslang::EOpConstructInt:
2466 case glslang::EOpConstructIVec2:
2467 case glslang::EOpConstructIVec3:
2468 case glslang::EOpConstructIVec4:
2469 case glslang::EOpConstructUint:
2470 case glslang::EOpConstructUVec2:
2471 case glslang::EOpConstructUVec3:
2472 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002473 case glslang::EOpConstructInt64:
2474 case glslang::EOpConstructI64Vec2:
2475 case glslang::EOpConstructI64Vec3:
2476 case glslang::EOpConstructI64Vec4:
2477 case glslang::EOpConstructUint64:
2478 case glslang::EOpConstructU64Vec2:
2479 case glslang::EOpConstructU64Vec3:
2480 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002481 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002482 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002483 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002484 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002485 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002486 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002487 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002488 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002489 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002490 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002491 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002492 else if (node->getOp() == glslang::EOpConstructStruct ||
2493 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2494 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002495 std::vector<spv::Id> constituents;
2496 for (int c = 0; c < (int)arguments.size(); ++c)
2497 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002498 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002499 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002500 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002501 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002502 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002503
2504 builder.clearAccessChain();
2505 builder.setAccessChainRValue(constructed);
2506
2507 return false;
2508 }
2509
2510 // These six are component-wise compares with component-wise results.
2511 // Forward on to createBinaryOperation(), requesting a vector result.
2512 case glslang::EOpLessThan:
2513 case glslang::EOpGreaterThan:
2514 case glslang::EOpLessThanEqual:
2515 case glslang::EOpGreaterThanEqual:
2516 case glslang::EOpVectorEqual:
2517 case glslang::EOpVectorNotEqual:
2518 {
2519 // Map the operation to a binary
2520 binOp = node->getOp();
2521 reduceComparison = false;
2522 switch (node->getOp()) {
2523 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2524 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2525 default: binOp = node->getOp(); break;
2526 }
2527
2528 break;
2529 }
2530 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002531 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002532 binOp = glslang::EOpMul;
2533 break;
2534 case glslang::EOpOuterProduct:
2535 // two vectors multiplied to make a matrix
2536 binOp = glslang::EOpOuterProduct;
2537 break;
2538 case glslang::EOpDot:
2539 {
qining25262b32016-05-06 17:25:16 -04002540 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002541 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002542 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002543 binOp = glslang::EOpMul;
2544 break;
2545 }
2546 case glslang::EOpMod:
2547 // when an aggregate, this is the floating-point mod built-in function,
2548 // which can be emitted by the one in createBinaryOperation()
2549 binOp = glslang::EOpMod;
2550 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002551
John Kessenich140f3df2015-06-26 16:58:36 -06002552 case glslang::EOpEmitVertex:
2553 case glslang::EOpEndPrimitive:
2554 case glslang::EOpBarrier:
2555 case glslang::EOpMemoryBarrier:
2556 case glslang::EOpMemoryBarrierAtomicCounter:
2557 case glslang::EOpMemoryBarrierBuffer:
2558 case glslang::EOpMemoryBarrierImage:
2559 case glslang::EOpMemoryBarrierShared:
2560 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002561 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002562 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002563 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002564 case glslang::EOpWorkgroupMemoryBarrier:
2565 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002566 case glslang::EOpSubgroupBarrier:
2567 case glslang::EOpSubgroupMemoryBarrier:
2568 case glslang::EOpSubgroupMemoryBarrierBuffer:
2569 case glslang::EOpSubgroupMemoryBarrierImage:
2570 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002571 noReturnValue = true;
2572 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2573 break;
2574
John Kessenich426394d2015-07-23 10:22:48 -06002575 case glslang::EOpAtomicAdd:
2576 case glslang::EOpAtomicMin:
2577 case glslang::EOpAtomicMax:
2578 case glslang::EOpAtomicAnd:
2579 case glslang::EOpAtomicOr:
2580 case glslang::EOpAtomicXor:
2581 case glslang::EOpAtomicExchange:
2582 case glslang::EOpAtomicCompSwap:
2583 atomic = true;
2584 break;
2585
John Kesseniche5eee8f2019-10-18 01:03:11 -06002586#ifndef GLSLANG_WEB
2587 case glslang::EOpAtomicStore:
2588 noReturnValue = true;
2589 // fallthrough
2590 case glslang::EOpAtomicLoad:
2591 atomic = true;
2592 break;
2593
John Kessenich0d0c6d32017-07-23 16:08:26 -06002594 case glslang::EOpAtomicCounterAdd:
2595 case glslang::EOpAtomicCounterSubtract:
2596 case glslang::EOpAtomicCounterMin:
2597 case glslang::EOpAtomicCounterMax:
2598 case glslang::EOpAtomicCounterAnd:
2599 case glslang::EOpAtomicCounterOr:
2600 case glslang::EOpAtomicCounterXor:
2601 case glslang::EOpAtomicCounterExchange:
2602 case glslang::EOpAtomicCounterCompSwap:
2603 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2604 builder.addCapability(spv::CapabilityAtomicStorageOps);
2605 atomic = true;
2606 break;
2607
Chao Chenb50c02e2018-09-19 11:42:24 -07002608 case glslang::EOpIgnoreIntersectionNV:
2609 case glslang::EOpTerminateRayNV:
2610 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002611 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002612 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2613 noReturnValue = true;
2614 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002615 case glslang::EOpCooperativeMatrixLoad:
2616 case glslang::EOpCooperativeMatrixStore:
2617 noReturnValue = true;
2618 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002619 case glslang::EOpBeginInvocationInterlock:
2620 case glslang::EOpEndInvocationInterlock:
2621 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2622 noReturnValue = true;
2623 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002624#endif
Chao Chen3c366992018-09-19 11:41:59 -07002625
John Kessenich140f3df2015-06-26 16:58:36 -06002626 default:
2627 break;
2628 }
2629
2630 //
2631 // See if it maps to a regular operation.
2632 //
John Kessenich140f3df2015-06-26 16:58:36 -06002633 if (binOp != glslang::EOpNull) {
2634 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2635 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2636 assert(left && right);
2637
2638 builder.clearAccessChain();
2639 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002640 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002641
2642 builder.clearAccessChain();
2643 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002644 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002645
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002646 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002647 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002648 TranslateNoContractionDecoration(node->getType().getQualifier()),
2649 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002650 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002651 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002652 left->getType().getBasicType(), reduceComparison);
2653
2654 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002655 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002656 builder.clearAccessChain();
2657 builder.setAccessChainRValue(result);
2658
2659 return false;
2660 }
2661
John Kessenich426394d2015-07-23 10:22:48 -06002662 //
2663 // Create the list of operands.
2664 //
John Kessenich140f3df2015-06-26 16:58:36 -06002665 glslang::TIntermSequence& glslangOperands = node->getSequence();
2666 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002667 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002668 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002669 // special case l-value operands; there are just a few
2670 bool lvalue = false;
2671 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002672 case glslang::EOpModf:
2673 if (arg == 1)
2674 lvalue = true;
2675 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002676
2677 case glslang::EOpAtomicAdd:
2678 case glslang::EOpAtomicMin:
2679 case glslang::EOpAtomicMax:
2680 case glslang::EOpAtomicAnd:
2681 case glslang::EOpAtomicOr:
2682 case glslang::EOpAtomicXor:
2683 case glslang::EOpAtomicExchange:
2684 case glslang::EOpAtomicCompSwap:
2685 if (arg == 0)
2686 lvalue = true;
2687 break;
2688
John Kessenicha28f7a72019-08-06 07:00:58 -06002689#ifndef GLSLANG_WEB
2690 case glslang::EOpFrexp:
2691 if (arg == 1)
2692 lvalue = true;
2693 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002694 case glslang::EOpInterpolateAtSample:
2695 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002696 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002697 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002698 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002699
2700 // Does it need a swizzle inversion? If so, evaluation is inverted;
2701 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002702 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002703 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2704 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2705 }
Rex Xu7a26c172015-12-08 17:12:09 +08002706 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05002707 case glslang::EOpAtomicLoad:
2708 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002709 case glslang::EOpAtomicCounterAdd:
2710 case glslang::EOpAtomicCounterSubtract:
2711 case glslang::EOpAtomicCounterMin:
2712 case glslang::EOpAtomicCounterMax:
2713 case glslang::EOpAtomicCounterAnd:
2714 case glslang::EOpAtomicCounterOr:
2715 case glslang::EOpAtomicCounterXor:
2716 case glslang::EOpAtomicCounterExchange:
2717 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002718 if (arg == 0)
2719 lvalue = true;
2720 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002721 case glslang::EOpAddCarry:
2722 case glslang::EOpSubBorrow:
2723 if (arg == 2)
2724 lvalue = true;
2725 break;
2726 case glslang::EOpUMulExtended:
2727 case glslang::EOpIMulExtended:
2728 if (arg >= 2)
2729 lvalue = true;
2730 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002731 case glslang::EOpCooperativeMatrixLoad:
2732 if (arg == 0 || arg == 1)
2733 lvalue = true;
2734 break;
2735 case glslang::EOpCooperativeMatrixStore:
2736 if (arg == 1)
2737 lvalue = true;
2738 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002739#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002740 default:
2741 break;
2742 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002743 builder.clearAccessChain();
2744 if (invertedType != spv::NoType && arg == 0)
2745 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2746 else
2747 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002748
John Kessenichb9197c82019-08-11 07:41:45 -06002749#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002750 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2751 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2752
2753 if (arg == 1) {
2754 // fold "element" parameter into the access chain
2755 spv::Builder::AccessChain save = builder.getAccessChain();
2756 builder.clearAccessChain();
2757 glslangOperands[2]->traverse(this);
2758
2759 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2760
2761 builder.setAccessChain(save);
2762
2763 // Point to the first element of the array.
2764 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
Jeff Bolz7895e472019-03-06 13:34:10 -06002765 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002766
2767 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2768 unsigned int alignment = builder.getAccessChain().alignment;
2769
2770 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2771 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2772 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2773 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2774 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2775 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2776 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2777 }
2778
2779 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2780
2781 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2782 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2783 }
2784
2785 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2786 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2787 }
2788 } else if (arg == 2) {
2789 continue;
2790 }
2791 }
John Kessenichb9197c82019-08-11 07:41:45 -06002792#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002793
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002794 if (lvalue) {
John Kessenich140f3df2015-06-26 16:58:36 -06002795 operands.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002796 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2797 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2798 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002799 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002800 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002801 }
John Kessenich140f3df2015-06-26 16:58:36 -06002802 }
John Kessenich426394d2015-07-23 10:22:48 -06002803
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002804 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06002805#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002806 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2807 std::vector<spv::IdImmediate> idImmOps;
2808
2809 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2810 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2811 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2812 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2813 // get the pointee type
2814 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2815 assert(builder.isCooperativeMatrixType(typeId));
2816 // do the op
2817 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2818 // store the result to the pointer (out param 'm')
2819 builder.createStore(result, operands[0]);
2820 result = 0;
2821 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2822 std::vector<spv::IdImmediate> idImmOps;
2823
2824 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2825 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2826 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2827 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2828 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2829
2830 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2831 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06002832 } else
2833#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06002834 if (atomic) {
2835 // Handle all atomics
2836 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
2837 } else {
John Kessenich426394d2015-07-23 10:22:48 -06002838 // Pass through to generic operations.
2839 switch (glslangOperands.size()) {
2840 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002841 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002842 break;
2843 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002844 {
2845 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002846 TranslateNoContractionDecoration(node->getType().getQualifier()),
2847 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002848 result = createUnaryOperation(
2849 node->getOp(), decorations,
2850 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002851 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06002852 }
John Kessenich426394d2015-07-23 10:22:48 -06002853 break;
2854 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002855 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002856 break;
2857 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002858 if (invertedType)
2859 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002860 }
2861
2862 if (noReturnValue)
2863 return false;
2864
2865 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002866 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002867 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002868 } else {
2869 builder.clearAccessChain();
2870 builder.setAccessChainRValue(result);
2871 return false;
2872 }
2873}
2874
John Kessenich433e9ff2017-01-26 20:31:11 -07002875// This path handles both if-then-else and ?:
2876// The if-then-else has a node type of void, while
2877// ?: has either a void or a non-void node type
2878//
2879// Leaving the result, when not void:
2880// GLSL only has r-values as the result of a :?, but
2881// if we have an l-value, that can be more efficient if it will
2882// become the base of a complex r-value expression, because the
2883// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002884bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2885{
John Kessenich0c1e71a2019-01-10 18:23:06 +07002886 // see if OpSelect can handle it
2887 const auto isOpSelectable = [&]() {
2888 if (node->getBasicType() == glslang::EbtVoid)
2889 return false;
2890 // OpSelect can do all other types starting with SPV 1.4
2891 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2892 // pre-1.4, only scalars and vectors can be handled
2893 if ((!node->getType().isScalar() && !node->getType().isVector()))
2894 return false;
2895 }
2896 return true;
2897 };
2898
John Kessenich4bee5312018-02-20 21:29:05 -07002899 // See if it simple and safe, or required, to execute both sides.
2900 // Crucially, side effects must be either semantically required or avoided,
2901 // and there are performance trade-offs.
2902 // Return true if required or a good idea (and safe) to execute both sides,
2903 // false otherwise.
2904 const auto bothSidesPolicy = [&]() -> bool {
2905 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002906 if (node->getTrueBlock() == nullptr ||
2907 node->getFalseBlock() == nullptr)
2908 return false;
2909
John Kessenich4bee5312018-02-20 21:29:05 -07002910 // required? (unless we write additional code to look for side effects
2911 // and make performance trade-offs if none are present)
2912 if (!node->getShortCircuit())
2913 return true;
2914
2915 // if not required to execute both, decide based on performance/practicality...
2916
John Kessenich0c1e71a2019-01-10 18:23:06 +07002917 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07002918 return false;
2919
John Kessenich433e9ff2017-01-26 20:31:11 -07002920 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2921 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2922
2923 // return true if a single operand to ? : is okay for OpSelect
2924 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002925 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002926 };
2927
2928 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2929 operandOkay(node->getFalseBlock()->getAsTyped());
2930 };
2931
John Kessenich4bee5312018-02-20 21:29:05 -07002932 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2933 // emit the condition before doing anything with selection
2934 node->getCondition()->traverse(this);
2935 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2936
2937 // Find a way of executing both sides and selecting the right result.
2938 const auto executeBothSides = [&]() -> void {
2939 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002940 node->getTrueBlock()->traverse(this);
2941 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2942 node->getFalseBlock()->traverse(this);
2943 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2944
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002945 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002946
John Kessenich4bee5312018-02-20 21:29:05 -07002947 // done if void
2948 if (node->getBasicType() == glslang::EbtVoid)
2949 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002950
John Kessenich4bee5312018-02-20 21:29:05 -07002951 // emit code to select between trueValue and falseValue
2952
2953 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07002954 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07002955 // Emit OpSelect for this selection.
2956
2957 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07002958 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
2959 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07002960 condition = builder.smearScalar(spv::NoPrecision, condition,
2961 builder.makeVectorType(builder.makeBoolType(),
2962 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07002963 }
John Kessenich4bee5312018-02-20 21:29:05 -07002964
2965 // OpSelect
2966 result = builder.createTriOp(spv::OpSelect,
2967 convertGlslangToSpvType(node->getType()), condition,
2968 trueValue, falseValue);
2969
2970 builder.clearAccessChain();
2971 builder.setAccessChainRValue(result);
2972 } else {
2973 // We need control flow to select the result.
2974 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2975 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2976
2977 // Selection control:
2978 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2979
2980 // make an "if" based on the value created by the condition
2981 spv::Builder::If ifBuilder(condition, control, builder);
2982
2983 // emit the "then" statement
2984 builder.createStore(trueValue, result);
2985 ifBuilder.makeBeginElse();
2986 // emit the "else" statement
2987 builder.createStore(falseValue, result);
2988
2989 // finish off the control flow
2990 ifBuilder.makeEndIf();
2991
2992 builder.clearAccessChain();
2993 builder.setAccessChainLValue(result);
2994 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002995 };
2996
John Kessenich4bee5312018-02-20 21:29:05 -07002997 // Execute the one side needed, as per the condition
2998 const auto executeOneSide = [&]() {
2999 // Always emit control flow.
3000 if (node->getBasicType() != glslang::EbtVoid)
3001 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07003002
John Kessenich4bee5312018-02-20 21:29:05 -07003003 // Selection control:
3004 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3005
3006 // make an "if" based on the value created by the condition
3007 spv::Builder::If ifBuilder(condition, control, builder);
3008
3009 // emit the "then" statement
3010 if (node->getTrueBlock() != nullptr) {
3011 node->getTrueBlock()->traverse(this);
3012 if (result != spv::NoResult)
3013 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3014 }
3015
3016 if (node->getFalseBlock() != nullptr) {
3017 ifBuilder.makeBeginElse();
3018 // emit the "else" statement
3019 node->getFalseBlock()->traverse(this);
3020 if (result != spv::NoResult)
3021 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3022 }
3023
3024 // finish off the control flow
3025 ifBuilder.makeEndIf();
3026
3027 if (result != spv::NoResult) {
3028 builder.clearAccessChain();
3029 builder.setAccessChainLValue(result);
3030 }
3031 };
3032
3033 // Try for OpSelect (or a requirement to execute both sides)
3034 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003035 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3036 if (node->getType().getQualifier().isSpecConstant())
3037 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003038 executeBothSides();
3039 } else
3040 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003041
3042 return false;
3043}
3044
3045bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3046{
3047 // emit and get the condition before doing anything with switch
3048 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003049 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003050
Rex Xu57e65922017-07-04 23:23:40 +08003051 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003052 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003053
John Kessenich140f3df2015-06-26 16:58:36 -06003054 // browse the children to sort out code segments
3055 int defaultSegment = -1;
3056 std::vector<TIntermNode*> codeSegments;
3057 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3058 std::vector<int> caseValues;
3059 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3060 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3061 TIntermNode* child = *c;
3062 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003063 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003064 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003065 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003066 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
3067 } else
3068 codeSegments.push_back(child);
3069 }
3070
qining25262b32016-05-06 17:25:16 -04003071 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003072 // statements between the last case and the end of the switch statement
3073 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3074 (int)codeSegments.size() == defaultSegment)
3075 codeSegments.push_back(nullptr);
3076
3077 // make the switch statement
3078 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08003079 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003080
3081 // emit all the code in the segments
3082 breakForLoop.push(false);
3083 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3084 builder.nextSwitchSegment(segmentBlocks, s);
3085 if (codeSegments[s])
3086 codeSegments[s]->traverse(this);
3087 else
3088 builder.addSwitchBreak();
3089 }
3090 breakForLoop.pop();
3091
3092 builder.endSwitch(segmentBlocks);
3093
3094 return false;
3095}
3096
3097void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3098{
3099 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003100 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003101
3102 builder.clearAccessChain();
3103 builder.setAccessChainRValue(constant);
3104}
3105
3106bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3107{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003108 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003109 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003110
3111 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003112 std::vector<unsigned int> operands;
3113 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003114
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003115 // Spec requires back edges to target header blocks, and every header block
3116 // must dominate its merge block. Make a header block first to ensure these
3117 // conditions are met. By definition, it will contain OpLoopMerge, followed
3118 // by a block-ending branch. But we don't want to put any other body/test
3119 // instructions in it, since the body/test may have arbitrary instructions,
3120 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003121 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003122 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003123 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003124 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003125 spv::Block& test = builder.makeNewBlock();
3126 builder.createBranch(&test);
3127
3128 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003129 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003130 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003131 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3132
3133 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003134 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003135 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003136 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003137 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003138 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003139
3140 builder.setBuildPoint(&blocks.continue_target);
3141 if (node->getTerminal())
3142 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003143 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003144 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003145 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003146 builder.createBranch(&blocks.body);
3147
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003148 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003149 builder.setBuildPoint(&blocks.body);
3150 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003151 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003152 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003153 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003154
3155 builder.setBuildPoint(&blocks.continue_target);
3156 if (node->getTerminal())
3157 node->getTerminal()->traverse(this);
3158 if (node->getTest()) {
3159 node->getTest()->traverse(this);
3160 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003161 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003162 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003163 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003164 // TODO: unless there was a break/return/discard instruction
3165 // somewhere in the body, this is an infinite loop, so we should
3166 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003167 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003168 }
John Kessenich140f3df2015-06-26 16:58:36 -06003169 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003170 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003171 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003172 return false;
3173}
3174
3175bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3176{
3177 if (node->getExpression())
3178 node->getExpression()->traverse(this);
3179
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003180 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003181
John Kessenich140f3df2015-06-26 16:58:36 -06003182 switch (node->getFlowOp()) {
3183 case glslang::EOpKill:
3184 builder.makeDiscard();
3185 break;
3186 case glslang::EOpBreak:
3187 if (breakForLoop.top())
3188 builder.createLoopExit();
3189 else
3190 builder.addSwitchBreak();
3191 break;
3192 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003193 builder.createLoopContinue();
3194 break;
3195 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003196 if (node->getExpression()) {
3197 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3198 spv::Id returnId = accessChainLoad(glslangReturnType);
3199 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3200 builder.clearAccessChain();
3201 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3202 builder.setAccessChainLValue(copyId);
3203 multiTypeStore(glslangReturnType, returnId);
3204 returnId = builder.createLoad(copyId);
3205 }
3206 builder.makeReturn(false, returnId);
3207 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003208 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003209
3210 builder.clearAccessChain();
3211 break;
3212
John Kessenichb9197c82019-08-11 07:41:45 -06003213#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003214 case glslang::EOpDemote:
3215 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3216 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3217 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3218 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003219#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003220
John Kessenich140f3df2015-06-26 16:58:36 -06003221 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003222 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003223 break;
3224 }
3225
3226 return false;
3227}
3228
John Kessenich9c14f772019-06-17 08:38:35 -06003229spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003230{
qining25262b32016-05-06 17:25:16 -04003231 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003232 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003233 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003234 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003235 spv::Id result = createSpvConstant(*node);
3236 if (result != spv::NoResult)
3237 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003238 }
3239
3240 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003241 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003242 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3243 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003244
John Kessenichb9197c82019-08-11 07:41:45 -06003245 const bool contains16BitType = node->getType().contains16BitFloat() ||
3246 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003247 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003248 switch (storageClass) {
3249 case spv::StorageClassInput:
3250 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003251 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003252 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003253 break;
John Kessenich18310872018-05-14 22:08:53 -06003254 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003255 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003256 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3257 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003258 else
3259 builder.addCapability(spv::CapabilityStorageUniform16);
3260 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003261#ifndef GLSLANG_WEB
3262 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003263 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003264 builder.addCapability(spv::CapabilityStoragePushConstant16);
3265 break;
John Kessenich18310872018-05-14 22:08:53 -06003266 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003267 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003268 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003269 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3270 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003271#endif
John Kessenich18310872018-05-14 22:08:53 -06003272 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003273 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003274 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003275 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003276 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003277 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003278 }
3279 }
Rex Xuf89ad982017-04-07 23:22:33 +08003280
John Kessenichb9197c82019-08-11 07:41:45 -06003281 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003282 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003283 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003284 builder.addCapability(spv::CapabilityStoragePushConstant8);
3285 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003286 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003287 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003288 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003289 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003290 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003291 } else {
3292 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003293 }
3294 }
3295
John Kessenich140f3df2015-06-26 16:58:36 -06003296 const char* name = node->getName().c_str();
3297 if (glslang::IsAnonymous(name))
3298 name = "";
3299
3300 return builder.createVariable(storageClass, spvType, name);
3301}
3302
3303// Return type Id of the sampled type.
3304spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3305{
3306 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003307 case glslang::EbtInt: return builder.makeIntType(32);
3308 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003309 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003310#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003311 case glslang::EbtFloat16:
3312 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3313 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3314 return builder.makeFloatType(16);
3315#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003316 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003317 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003318 return builder.makeFloatType(32);
3319 }
3320}
3321
John Kessenich8c8505c2016-07-26 12:50:38 -06003322// If node is a swizzle operation, return the type that should be used if
3323// the swizzle base is first consumed by another operation, before the swizzle
3324// is applied.
3325spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3326{
John Kessenichecba76f2017-01-06 00:34:48 -07003327 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003328 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3329 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3330 else
3331 return spv::NoType;
3332}
3333
3334// When inverting a swizzle with a parent op, this function
3335// will apply the swizzle operation to a completed parent operation.
3336spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3337{
3338 std::vector<unsigned> swizzle;
3339 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3340 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3341}
3342
John Kessenich8c8505c2016-07-26 12:50:38 -06003343// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3344void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3345{
3346 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3347 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3348 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3349}
3350
John Kessenich3ac051e2015-12-20 11:29:16 -07003351// Convert from a glslang type to an SPV type, by calling into a
3352// recursive version of this function. This establishes the inherited
3353// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003354spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003355{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003356 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003357}
3358
3359// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003360// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003361// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003362spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003363 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3364 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003365{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003366 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003367
3368 switch (type.getBasicType()) {
3369 case glslang::EbtVoid:
3370 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003371 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003372 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003373 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003374 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3375 // a 32-bit int where non-0 means true.
3376 if (explicitLayout != glslang::ElpNone)
3377 spvType = builder.makeUintType(32);
3378 else
3379 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003380 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003381 case glslang::EbtInt:
3382 spvType = builder.makeIntType(32);
3383 break;
3384 case glslang::EbtUint:
3385 spvType = builder.makeUintType(32);
3386 break;
3387 case glslang::EbtFloat:
3388 spvType = builder.makeFloatType(32);
3389 break;
3390#ifndef GLSLANG_WEB
3391 case glslang::EbtDouble:
3392 spvType = builder.makeFloatType(64);
3393 break;
3394 case glslang::EbtFloat16:
3395 spvType = builder.makeFloatType(16);
3396 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003397 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003398 spvType = builder.makeIntType(8);
3399 break;
3400 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003401 spvType = builder.makeUintType(8);
3402 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003403 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003404 spvType = builder.makeIntType(16);
3405 break;
3406 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003407 spvType = builder.makeUintType(16);
3408 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003409 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003410 spvType = builder.makeIntType(64);
3411 break;
3412 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003413 spvType = builder.makeUintType(64);
3414 break;
John Kessenich426394d2015-07-23 10:22:48 -06003415 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003416 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003417 spvType = builder.makeUintType(32);
3418 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003419 case glslang::EbtAccStructNV:
3420 spvType = builder.makeAccelerationStructureNVType();
3421 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003422 case glslang::EbtReference:
3423 {
3424 // Make the forward pointer, then recurse to convert the structure type, then
3425 // patch up the forward pointer with a real pointer type.
3426 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3427 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3428 forwardPointers[type.getReferentType()] = forwardId;
3429 }
3430 spvType = forwardPointers[type.getReferentType()];
3431 if (!forwardReferenceOnly) {
3432 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3433 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3434 forwardPointers[type.getReferentType()],
3435 referentType);
3436 }
3437 }
3438 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003439#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003440 case glslang::EbtSampler:
3441 {
3442 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003443 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003444 spvType = builder.makeSamplerType();
3445 } else {
3446 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003447 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3448 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3449 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3450 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003451 // already has both image and sampler, make the combined type
3452 spvType = builder.makeSampledImageType(spvType);
3453 }
John Kessenich55e7d112015-11-15 21:33:39 -07003454 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003455 }
John Kessenich140f3df2015-06-26 16:58:36 -06003456 break;
3457 case glslang::EbtStruct:
3458 case glslang::EbtBlock:
3459 {
3460 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003461 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003462
3463 // Try to share structs for different layouts, but not yet for other
3464 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003465 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003466 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003467 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003468 break;
3469
3470 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003471 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003472 memberRemapper[glslangMembers].resize(glslangMembers->size());
3473 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003474 }
3475 break;
3476 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003477 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003478 break;
3479 }
3480
3481 if (type.isMatrix())
3482 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3483 else {
3484 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3485 if (type.getVectorSize() > 1)
3486 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3487 }
3488
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003489 if (type.isCoopMat()) {
3490 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3491 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3492 if (type.getBasicType() == glslang::EbtFloat16)
3493 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003494 if (type.getBasicType() == glslang::EbtUint8 ||
3495 type.getBasicType() == glslang::EbtInt8) {
3496 builder.addCapability(spv::CapabilityInt8);
3497 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003498
3499 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3500 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3501 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3502
3503 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3504 }
3505
John Kessenich140f3df2015-06-26 16:58:36 -06003506 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003507 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3508
John Kessenichc9a80832015-09-12 12:17:44 -06003509 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003510 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003511 // We need to decorate array strides for types needing explicit layout, except blocks.
3512 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003513 // Use a dummy glslang type for querying internal strides of
3514 // arrays of arrays, but using just a one-dimensional array.
3515 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003516 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3517 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003518
3519 // Will compute the higher-order strides here, rather than making a whole
3520 // pile of types and doing repetitive recursion on their contents.
3521 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3522 }
John Kessenichf8842e52016-01-04 19:22:56 -07003523
3524 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003525 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003526 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003527 if (stride > 0)
3528 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003529 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003530 }
3531 } else {
3532 // single-dimensional array, and don't yet have stride
3533
John Kessenichf8842e52016-01-04 19:22:56 -07003534 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003535 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3536 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003537 }
John Kessenich31ed4832015-09-09 17:51:38 -06003538
John Kessenichead86222018-03-28 18:01:20 -06003539 // Do the outer dimension, which might not be known for a runtime-sized array.
3540 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3541 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003542 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003543 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003544#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003545 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003546 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003547 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3548 }
John Kessenichb9197c82019-08-11 07:41:45 -06003549#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003550 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003551 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003552 if (stride > 0)
3553 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003554 }
3555
3556 return spvType;
3557}
3558
John Kessenich0e737842017-03-24 18:38:16 -06003559// TODO: this functionality should exist at a higher level, in creating the AST
3560//
3561// Identify interface members that don't have their required extension turned on.
3562//
3563bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3564{
John Kessenicha28f7a72019-08-06 07:00:58 -06003565#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003566 auto& extensions = glslangIntermediate->getRequestedExtensions();
3567
Rex Xubcf291a2017-03-29 23:01:36 +08003568 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3569 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3570 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003571 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3572 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3573 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003574
3575 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3576 if (member.getFieldName() == "gl_ViewportMask" &&
3577 extensions.find("GL_NV_viewport_array2") == extensions.end())
3578 return true;
3579 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3580 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3581 return true;
3582 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3583 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3584 return true;
3585 }
3586#endif
John Kessenich0e737842017-03-24 18:38:16 -06003587
3588 return false;
3589};
3590
John Kessenich6090df02016-06-30 21:18:02 -06003591// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3592// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3593// Mutually recursive with convertGlslangToSpvType().
3594spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3595 const glslang::TTypeList* glslangMembers,
3596 glslang::TLayoutPacking explicitLayout,
3597 const glslang::TQualifier& qualifier)
3598{
3599 // Create a vector of struct types for SPIR-V to consume
3600 std::vector<spv::Id> spvMembers;
3601 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003602 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003603 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3604 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3605 if (glslangMember.hiddenMember()) {
3606 ++memberDelta;
3607 if (type.getBasicType() == glslang::EbtBlock)
3608 memberRemapper[glslangMembers][i] = -1;
3609 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003610 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003611 if (filterMember(glslangMember)) {
3612 memberDelta++;
3613 memberRemapper[glslangMembers][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003614 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003615 }
3616 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003617 }
John Kessenich6090df02016-06-30 21:18:02 -06003618 // modify just this child's view of the qualifier
3619 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3620 InheritQualifiers(memberQualifier, qualifier);
3621
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003622 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003623 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003624 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003625
3626 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003627 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3628 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003629
3630 // Make forward pointers for any pointer members, and create a list of members to
3631 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003632 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003633 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3634 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3635 }
3636 spvMembers.push_back(
3637 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3638 } else {
3639 spvMembers.push_back(
3640 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3641 }
John Kessenich6090df02016-06-30 21:18:02 -06003642 }
3643 }
3644
3645 // Make the SPIR-V type
3646 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003647 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003648 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3649
3650 // Decorate it
3651 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3652
John Kessenichd72f4882019-01-16 14:55:37 +07003653 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003654 auto it = deferredForwardPointers[i];
3655 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3656 }
3657
John Kessenich6090df02016-06-30 21:18:02 -06003658 return spvType;
3659}
3660
3661void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3662 const glslang::TTypeList* glslangMembers,
3663 glslang::TLayoutPacking explicitLayout,
3664 const glslang::TQualifier& qualifier,
3665 spv::Id spvType)
3666{
3667 // Name and decorate the non-hidden members
3668 int offset = -1;
3669 int locationOffset = 0; // for use within the members of this struct
3670 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3671 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3672 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003673 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003674 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003675 if (filterMember(glslangMember))
3676 continue;
3677 }
John Kessenich6090df02016-06-30 21:18:02 -06003678
3679 // modify just this child's view of the qualifier
3680 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3681 InheritQualifiers(memberQualifier, qualifier);
3682
3683 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003684 if (member < 0)
3685 continue;
3686
3687 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3688 builder.addMemberDecoration(spvType, member,
3689 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3690 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3691 // Add interpolation and auxiliary storage decorations only to
3692 // top-level members of Input and Output storage classes
3693 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3694 type.getQualifier().storage == glslang::EvqVaryingOut) {
3695 if (type.getBasicType() == glslang::EbtBlock ||
3696 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3697 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3698 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003699#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003700 addMeshNVDecoration(spvType, member, memberQualifier);
3701#endif
John Kessenich6090df02016-06-30 21:18:02 -06003702 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003703 }
3704 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003705
John Kessenichb9197c82019-08-11 07:41:45 -06003706#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003707 if (type.getBasicType() == glslang::EbtBlock &&
3708 qualifier.storage == glslang::EvqBuffer) {
3709 // Add memory decorations only to top-level members of shader storage block
3710 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003711 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003712 for (unsigned int i = 0; i < memory.size(); ++i)
3713 builder.addMemberDecoration(spvType, member, memory[i]);
3714 }
John Kessenichb9197c82019-08-11 07:41:45 -06003715#endif
John Kessenich6090df02016-06-30 21:18:02 -06003716
John Kessenich5d610ee2018-03-07 18:05:55 -07003717 // Location assignment was already completed correctly by the front end,
3718 // just track whether a member needs to be decorated.
3719 // Ignore member locations if the container is an array, as that's
3720 // ill-specified and decisions have been made to not allow this.
3721 if (! type.isArray() && memberQualifier.hasLocation())
3722 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003723
John Kessenich5d610ee2018-03-07 18:05:55 -07003724 if (qualifier.hasLocation()) // track for upcoming inheritance
3725 locationOffset += glslangIntermediate->computeTypeLocationSize(
3726 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003727
John Kessenich5d610ee2018-03-07 18:05:55 -07003728 // component, XFB, others
3729 if (glslangMember.getQualifier().hasComponent())
3730 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3731 glslangMember.getQualifier().layoutComponent);
3732 if (glslangMember.getQualifier().hasXfbOffset())
3733 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3734 glslangMember.getQualifier().layoutXfbOffset);
3735 else if (explicitLayout != glslang::ElpNone) {
3736 // figure out what to do with offset, which is accumulating
3737 int nextOffset;
3738 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3739 if (offset >= 0)
3740 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3741 offset = nextOffset;
3742 }
John Kessenich6090df02016-06-30 21:18:02 -06003743
John Kessenich5d610ee2018-03-07 18:05:55 -07003744 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3745 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3746 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003747
John Kessenich5d610ee2018-03-07 18:05:55 -07003748 // built-in variable decorations
3749 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3750 if (builtIn != spv::BuiltInMax)
3751 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003752
John Kessenichb9197c82019-08-11 07:41:45 -06003753#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003754 // nonuniform
3755 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3756
John Kessenichead86222018-03-28 18:01:20 -06003757 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3758 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3759 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3760 memberQualifier.semanticName);
3761 }
3762
John Kessenich5d610ee2018-03-07 18:05:55 -07003763 if (builtIn == spv::BuiltInLayer) {
3764 // SPV_NV_viewport_array2 extension
3765 if (glslangMember.getQualifier().layoutViewportRelative){
3766 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3767 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3768 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003769 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003770 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3771 builder.addMemberDecoration(spvType, member,
3772 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3773 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3774 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3775 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003776 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003777 }
3778 if (glslangMember.getQualifier().layoutPassthrough) {
3779 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3780 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3781 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3782 }
chaoc771d89f2017-01-13 01:10:53 -08003783#endif
John Kessenich6090df02016-06-30 21:18:02 -06003784 }
3785
3786 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003787 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3788 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003789}
3790
John Kessenich6c292d32016-02-15 20:58:50 -07003791// Turn the expression forming the array size into an id.
3792// This is not quite trivial, because of specialization constants.
3793// Sometimes, a raw constant is turned into an Id, and sometimes
3794// a specialization constant expression is.
3795spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3796{
3797 // First, see if this is sized with a node, meaning a specialization constant:
3798 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3799 if (specNode != nullptr) {
3800 builder.clearAccessChain();
3801 specNode->traverse(this);
3802 return accessChainLoad(specNode->getAsTyped()->getType());
3803 }
qining25262b32016-05-06 17:25:16 -04003804
John Kessenich6c292d32016-02-15 20:58:50 -07003805 // Otherwise, need a compile-time (front end) size, get it:
3806 int size = arraySizes.getDimSize(dim);
3807 assert(size > 0);
3808 return builder.makeUintConstant(size);
3809}
3810
John Kessenich103bef92016-02-08 21:38:15 -07003811// Wrap the builder's accessChainLoad to:
3812// - localize handling of RelaxedPrecision
3813// - use the SPIR-V inferred type instead of another conversion of the glslang type
3814// (avoids unnecessary work and possible type punning for structures)
3815// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003816spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3817{
John Kessenich103bef92016-02-08 21:38:15 -07003818 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003819
3820 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3821 coherentFlags |= TranslateCoherent(type);
3822
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003823 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003824 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003825
John Kessenich5611c6d2018-04-05 11:25:02 -06003826 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003827 TranslateNonUniformDecoration(type.getQualifier()),
3828 nominalTypeId,
3829 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003830 TranslateMemoryScope(coherentFlags),
3831 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003832
3833 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003834 if (type.getBasicType() == glslang::EbtBool) {
3835 if (builder.isScalarType(nominalTypeId)) {
3836 // Conversion for bool
3837 spv::Id boolType = builder.makeBoolType();
3838 if (nominalTypeId != boolType)
3839 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3840 } else if (builder.isVectorType(nominalTypeId)) {
3841 // Conversion for bvec
3842 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3843 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3844 if (nominalTypeId != bvecType)
3845 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3846 }
3847 }
John Kessenich103bef92016-02-08 21:38:15 -07003848
3849 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003850}
3851
Rex Xu27253232016-02-23 17:51:09 +08003852// Wrap the builder's accessChainStore to:
3853// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003854//
3855// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003856void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3857{
3858 // Need to convert to abstract types when necessary
3859 if (type.getBasicType() == glslang::EbtBool) {
3860 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3861
3862 if (builder.isScalarType(nominalTypeId)) {
3863 // Conversion for bool
3864 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003865 if (nominalTypeId != boolType) {
3866 // keep these outside arguments, for determinant order-of-evaluation
3867 spv::Id one = builder.makeUintConstant(1);
3868 spv::Id zero = builder.makeUintConstant(0);
3869 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3870 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003871 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003872 } else if (builder.isVectorType(nominalTypeId)) {
3873 // Conversion for bvec
3874 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3875 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003876 if (nominalTypeId != bvecType) {
3877 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003878 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3879 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3880 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003881 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003882 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3883 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003884 }
3885 }
3886
Jeff Bolz36831c92018-09-05 10:11:41 -05003887 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3888 coherentFlags |= TranslateCoherent(type);
3889
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003890 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003891 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003892
Jeff Bolz36831c92018-09-05 10:11:41 -05003893 builder.accessChainStore(rvalue,
3894 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003895 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003896}
3897
John Kessenich4bf71552016-09-02 11:20:21 -06003898// For storing when types match at the glslang level, but not might match at the
3899// SPIR-V level.
3900//
3901// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003902// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003903// as in a member-decorated way.
3904//
3905// NOTE: This function can handle any store request; if it's not special it
3906// simplifies to a simple OpStore.
3907//
3908// Implicitly uses the existing builder.accessChain as the storage target.
3909void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3910{
John Kessenichb3e24e42016-09-11 12:33:43 -06003911 // we only do the complex path here if it's an aggregate
3912 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003913 accessChainStore(type, rValue);
3914 return;
3915 }
3916
John Kessenichb3e24e42016-09-11 12:33:43 -06003917 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003918 spv::Id rType = builder.getTypeId(rValue);
3919 spv::Id lValue = builder.accessChainGetLValue();
3920 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3921 if (lType == rType) {
3922 accessChainStore(type, rValue);
3923 return;
3924 }
3925
John Kessenichb3e24e42016-09-11 12:33:43 -06003926 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003927 // where the two types were the same type in GLSL. This requires member
3928 // by member copy, recursively.
3929
John Kessenichfbb6bdf2019-01-15 21:48:27 +07003930 // SPIR-V 1.4 added an instruction to do help do this.
3931 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
3932 // However, bool in uniform space is changed to int, so
3933 // OpCopyLogical does not work for that.
3934 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
3935 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
3936 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
3937 if (lBool == rBool) {
3938 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
3939 accessChainStore(type, logicalCopy);
3940 return;
3941 }
3942 }
3943
John Kessenichb3e24e42016-09-11 12:33:43 -06003944 // If an array, copy element by element.
3945 if (type.isArray()) {
3946 glslang::TType glslangElementType(type, 0);
3947 spv::Id elementRType = builder.getContainedTypeId(rType);
3948 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3949 // get the source member
3950 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003951
John Kessenichb3e24e42016-09-11 12:33:43 -06003952 // set up the target storage
3953 builder.clearAccessChain();
3954 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003955 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003956
John Kessenichb3e24e42016-09-11 12:33:43 -06003957 // store the member
3958 multiTypeStore(glslangElementType, elementRValue);
3959 }
3960 } else {
3961 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003962
John Kessenichb3e24e42016-09-11 12:33:43 -06003963 // loop over structure members
3964 const glslang::TTypeList& members = *type.getStruct();
3965 for (int m = 0; m < (int)members.size(); ++m) {
3966 const glslang::TType& glslangMemberType = *members[m].type;
3967
3968 // get the source member
3969 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3970 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3971
3972 // set up the target storage
3973 builder.clearAccessChain();
3974 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003975 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003976
3977 // store the member
3978 multiTypeStore(glslangMemberType, memberRValue);
3979 }
John Kessenich4bf71552016-09-02 11:20:21 -06003980 }
3981}
3982
John Kessenichf85e8062015-12-19 13:57:10 -07003983// Decide whether or not this type should be
3984// decorated with offsets and strides, and if so
3985// whether std140 or std430 rules should be applied.
3986glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003987{
John Kessenichf85e8062015-12-19 13:57:10 -07003988 // has to be a block
3989 if (type.getBasicType() != glslang::EbtBlock)
3990 return glslang::ElpNone;
3991
Chao Chen3c366992018-09-19 11:41:59 -07003992 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003993 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003994 type.getQualifier().storage != glslang::EvqBuffer &&
3995 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003996 return glslang::ElpNone;
3997
3998 // return the layout to use
3999 switch (type.getQualifier().layoutPacking) {
4000 case glslang::ElpStd140:
4001 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004002 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004003 return type.getQualifier().layoutPacking;
4004 default:
4005 return glslang::ElpNone;
4006 }
John Kessenich31ed4832015-09-09 17:51:38 -06004007}
4008
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004009// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07004010int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004011{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004012 int size;
John Kessenich49987892015-12-29 17:11:44 -07004013 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004014 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004015
4016 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004017}
4018
John Kessenich49987892015-12-29 17:11:44 -07004019// Given a matrix type, or array (of array) of matrixes type, returns the integer stride required for that matrix
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004020// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07004021int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004022{
John Kessenich49987892015-12-29 17:11:44 -07004023 glslang::TType elementType;
4024 elementType.shallowCopy(matrixType);
4025 elementType.clearArraySizes();
4026
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004027 int size;
John Kessenich49987892015-12-29 17:11:44 -07004028 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004029 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004030
4031 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004032}
4033
John Kessenich5e4b1242015-08-06 22:53:06 -06004034// Given a member type of a struct, realign the current offset for it, and compute
4035// the next (not yet aligned) offset for the next member, which will get aligned
4036// on the next call.
4037// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4038// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4039// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06004040void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07004041 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004042{
4043 // this will get a positive value when deemed necessary
4044 nextOffset = -1;
4045
John Kessenich5e4b1242015-08-06 22:53:06 -06004046 // override anything in currentOffset with user-set offset
4047 if (memberType.getQualifier().hasOffset())
4048 currentOffset = memberType.getQualifier().layoutOffset;
4049
4050 // It could be that current linker usage in glslang updated all the layoutOffset,
4051 // in which case the following code does not matter. But, that's not quite right
4052 // once cross-compilation unit GLSL validation is done, as the original user
4053 // settings are needed in layoutOffset, and then the following will come into play.
4054
John Kessenichf85e8062015-12-19 13:57:10 -07004055 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004056 if (! memberType.getQualifier().hasOffset())
4057 currentOffset = -1;
4058
4059 return;
4060 }
4061
John Kessenichf85e8062015-12-19 13:57:10 -07004062 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004063 if (currentOffset < 0)
4064 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004065
John Kessenich5e4b1242015-08-06 22:53:06 -06004066 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4067 // but possibly not yet correctly aligned.
4068
4069 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004070 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004071 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004072
4073 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004074 // TODO: make this consistent in early phases of code:
4075 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4076 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4077 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004078 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004079 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004080 int dummySize;
4081 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4082 if (componentAlignment <= 4)
4083 memberAlignment = componentAlignment;
4084 }
4085
4086 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004087 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004088
4089 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004090 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004091 glslang::RoundToPow2(currentOffset, 16);
4092
John Kessenich5e4b1242015-08-06 22:53:06 -06004093 nextOffset = currentOffset + memberSize;
4094}
4095
David Netoa901ffe2016-06-08 14:11:40 +01004096void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004097{
David Netoa901ffe2016-06-08 14:11:40 +01004098 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4099 switch (glslangBuiltIn)
4100 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004101 case glslang::EbvPointSize:
4102#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004103 case glslang::EbvClipDistance:
4104 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004105 case glslang::EbvViewportMaskNV:
4106 case glslang::EbvSecondaryPositionNV:
4107 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004108 case glslang::EbvPositionPerViewNV:
4109 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004110 case glslang::EbvTaskCountNV:
4111 case glslang::EbvPrimitiveCountNV:
4112 case glslang::EbvPrimitiveIndicesNV:
4113 case glslang::EbvClipDistancePerViewNV:
4114 case glslang::EbvCullDistancePerViewNV:
4115 case glslang::EbvLayerPerViewNV:
4116 case glslang::EbvMeshViewCountNV:
4117 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004118#endif
David Netoa901ffe2016-06-08 14:11:40 +01004119 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4120 // Alternately, we could just call this for any glslang built-in, since the
4121 // capability already guards against duplicates.
4122 TranslateBuiltInDecoration(glslangBuiltIn, false);
4123 break;
4124 default:
4125 // Capabilities were already generated when the struct was declared.
4126 break;
4127 }
John Kessenichebb50532016-05-16 19:22:05 -06004128}
4129
John Kessenich6fccb3c2016-09-19 16:01:41 -06004130bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004131{
John Kessenicheee9d532016-09-19 18:09:30 -06004132 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004133}
4134
John Kessenichd41993d2017-09-10 15:21:05 -06004135// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004136// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4137// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004138bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004139{
John Kessenich6a14f782017-12-04 02:48:10 -07004140 assert(qualifier == glslang::EvqIn ||
4141 qualifier == glslang::EvqOut ||
4142 qualifier == glslang::EvqInOut ||
4143 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06004144 return qualifier != glslang::EvqConstReadOnly;
4145}
4146
4147// Is parameter pass-by-original?
4148bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4149 bool implicitThisParam)
4150{
4151 if (implicitThisParam) // implicit this
4152 return true;
4153 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004154 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004155 return paramType.containsOpaque() || // sampler, etc.
4156 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4157}
4158
John Kessenich140f3df2015-06-26 16:58:36 -06004159// Make all the functions, skeletally, without actually visiting their bodies.
4160void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4161{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004162 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004163 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4164 if (paramPrecision != spv::NoPrecision)
4165 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004166 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004167 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004168 // Original and non-writable params pass the pointer directly and
4169 // use restrict/aliased, others are stored to a pointer in Function
4170 // memory and use RestrictPointer/AliasedPointer.
4171 if (originalParam(type.getQualifier().storage, type, false) ||
4172 !writableParam(type.getQualifier().storage)) {
4173 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
4174 } else {
4175 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
4176 }
4177 }
John Kessenichfad62972017-07-18 02:35:46 -06004178 };
4179
John Kessenich140f3df2015-06-26 16:58:36 -06004180 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4181 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004182 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004183 continue;
4184
4185 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004186 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004187 //
qining25262b32016-05-06 17:25:16 -04004188 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004189 // function. What it is an address of varies:
4190 //
John Kessenich4bf71552016-09-02 11:20:21 -06004191 // - "in" parameters not marked as "const" can be written to without modifying the calling
4192 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004193 //
4194 // - "const in" parameters can just be the r-value, as no writes need occur.
4195 //
John Kessenich4bf71552016-09-02 11:20:21 -06004196 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4197 // GLSL has copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
John Kessenich140f3df2015-06-26 16:58:36 -06004198
4199 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004200 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004201 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4202
John Kessenich155d3512019-08-08 23:29:20 -06004203#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004204 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4205 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004206#else
4207 bool implicitThis = false;
4208#endif
John Kessenich37789792017-03-21 23:56:40 -06004209
John Kessenichfad62972017-07-18 02:35:46 -06004210 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004211 for (int p = 0; p < (int)parameters.size(); ++p) {
4212 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4213 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004214 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004215 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004216 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004217 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4218 else
John Kessenich4bf71552016-09-02 11:20:21 -06004219 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004220 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004221 paramTypes.push_back(typeId);
4222 }
4223
4224 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004225 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4226 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004227 glslFunction->getName().c_str(), paramTypes,
4228 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004229 if (implicitThis)
4230 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004231
4232 // Track function to emit/call later
4233 functionMap[glslFunction->getName().c_str()] = function;
4234
4235 // Set the parameter id's
4236 for (int p = 0; p < (int)parameters.size(); ++p) {
4237 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4238 // give a name too
4239 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004240
4241 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004242 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004243 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004244 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004245 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004246 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004247 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004248 }
4249 }
4250}
4251
4252// Process all the initializers, while skipping the functions and link objects
4253void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4254{
4255 builder.setBuildPoint(shaderEntry->getLastBlock());
4256 for (int i = 0; i < (int)initializers.size(); ++i) {
4257 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
4258 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
4259
4260 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004261 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004262 initializer->traverse(this);
4263 }
4264 }
4265}
4266
4267// Process all the functions, while skipping initializers.
4268void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4269{
4270 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4271 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004272 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004273 node->traverse(this);
4274 }
4275}
4276
4277void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4278{
qining25262b32016-05-06 17:25:16 -04004279 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004280 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004281 currentFunction = functionMap[node->getName().c_str()];
4282 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004283 builder.setBuildPoint(functionBlock);
4284}
4285
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004286void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004287{
Rex Xufc618912015-09-09 16:42:49 +08004288 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004289
4290 glslang::TSampler sampler = {};
4291 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004292#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004293 bool f16ShadowCompare = false;
4294#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004295 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004296 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4297 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004298#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004299 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
4300#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004301 }
4302
John Kessenich140f3df2015-06-26 16:58:36 -06004303 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4304 builder.clearAccessChain();
4305 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004306
John Kessenicha28f7a72019-08-06 07:00:58 -06004307#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004308 // Special case l-value operands
4309 bool lvalue = false;
4310 switch (node.getOp()) {
4311 case glslang::EOpImageAtomicAdd:
4312 case glslang::EOpImageAtomicMin:
4313 case glslang::EOpImageAtomicMax:
4314 case glslang::EOpImageAtomicAnd:
4315 case glslang::EOpImageAtomicOr:
4316 case glslang::EOpImageAtomicXor:
4317 case glslang::EOpImageAtomicExchange:
4318 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004319 case glslang::EOpImageAtomicLoad:
4320 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004321 if (i == 0)
4322 lvalue = true;
4323 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004324 case glslang::EOpSparseImageLoad:
4325 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4326 lvalue = true;
4327 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004328 case glslang::EOpSparseTexture:
4329 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4330 lvalue = true;
4331 break;
4332 case glslang::EOpSparseTextureClamp:
4333 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4334 lvalue = true;
4335 break;
4336 case glslang::EOpSparseTextureLod:
4337 case glslang::EOpSparseTextureOffset:
4338 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4339 lvalue = true;
4340 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004341 case glslang::EOpSparseTextureFetch:
4342 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4343 lvalue = true;
4344 break;
4345 case glslang::EOpSparseTextureFetchOffset:
4346 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4347 lvalue = true;
4348 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004349 case glslang::EOpSparseTextureLodOffset:
4350 case glslang::EOpSparseTextureGrad:
4351 case glslang::EOpSparseTextureOffsetClamp:
4352 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4353 lvalue = true;
4354 break;
4355 case glslang::EOpSparseTextureGradOffset:
4356 case glslang::EOpSparseTextureGradClamp:
4357 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4358 lvalue = true;
4359 break;
4360 case glslang::EOpSparseTextureGradOffsetClamp:
4361 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4362 lvalue = true;
4363 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004364 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004365 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4366 lvalue = true;
4367 break;
4368 case glslang::EOpSparseTextureGatherOffset:
4369 case glslang::EOpSparseTextureGatherOffsets:
4370 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4371 lvalue = true;
4372 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004373 case glslang::EOpSparseTextureGatherLod:
4374 if (i == 3)
4375 lvalue = true;
4376 break;
4377 case glslang::EOpSparseTextureGatherLodOffset:
4378 case glslang::EOpSparseTextureGatherLodOffsets:
4379 if (i == 4)
4380 lvalue = true;
4381 break;
Rex Xu129799a2017-07-05 17:23:28 +08004382 case glslang::EOpSparseImageLoadLod:
4383 if (i == 3)
4384 lvalue = true;
4385 break;
Chao Chen3a137962018-09-19 11:41:27 -07004386 case glslang::EOpImageSampleFootprintNV:
4387 if (i == 4)
4388 lvalue = true;
4389 break;
4390 case glslang::EOpImageSampleFootprintClampNV:
4391 case glslang::EOpImageSampleFootprintLodNV:
4392 if (i == 5)
4393 lvalue = true;
4394 break;
4395 case glslang::EOpImageSampleFootprintGradNV:
4396 if (i == 6)
4397 lvalue = true;
4398 break;
4399 case glslang::EOpImageSampleFootprintGradClampNV:
4400 if (i == 7)
4401 lvalue = true;
4402 break;
Rex Xufc618912015-09-09 16:42:49 +08004403 default:
4404 break;
4405 }
4406
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004407 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004408 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004409 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4410 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4411 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004412#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004413 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004414 }
4415}
4416
John Kessenichfc51d282015-08-19 13:34:18 -06004417void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004418{
John Kessenichfc51d282015-08-19 13:34:18 -06004419 builder.clearAccessChain();
4420 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004421 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004422}
John Kessenich140f3df2015-06-26 16:58:36 -06004423
John Kessenichfc51d282015-08-19 13:34:18 -06004424spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4425{
John Kesseniche485c7a2017-05-31 18:50:53 -06004426 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004427 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004428
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004429 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004430
John Kessenichfc51d282015-08-19 13:34:18 -06004431 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004432
John Kessenichf43c7392019-03-31 10:51:57 -06004433 const glslang::TType &imageType = node->getAsAggregate()
4434 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4435 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004436 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004437#ifdef GLSLANG_WEB
4438 const bool f16ShadowCompare = false;
4439#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004440 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004441 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4442 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004443#endif
4444
John Kessenichf43c7392019-03-31 10:51:57 -06004445 const auto signExtensionMask = [&]() {
4446 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4447 if (sampler.type == glslang::EbtUint)
4448 return spv::ImageOperandsZeroExtendMask;
4449 else if (sampler.type == glslang::EbtInt)
4450 return spv::ImageOperandsSignExtendMask;
4451 }
4452 return spv::ImageOperandsMaskNone;
4453 };
4454
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004455 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4456
John Kessenichfc51d282015-08-19 13:34:18 -06004457 std::vector<spv::Id> arguments;
4458 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004459 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004460 else
4461 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004462 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004463
4464 spv::Builder::TextureParameters params = { };
4465 params.sampler = arguments[0];
4466
Rex Xu04db3f52015-09-16 11:44:02 +08004467 glslang::TCrackedTextureOp cracked;
4468 node->crackTexture(sampler, cracked);
4469
amhagan05506bb2017-06-13 16:53:02 -04004470 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004471
John Kessenichfc51d282015-08-19 13:34:18 -06004472 // Check for queries
4473 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004474 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4475 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004476 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004477
John Kessenichfc51d282015-08-19 13:34:18 -06004478 switch (node->getOp()) {
4479 case glslang::EOpImageQuerySize:
4480 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004481 if (arguments.size() > 1) {
4482 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004483 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004484 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004485 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004486#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004487 case glslang::EOpImageQuerySamples:
4488 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004489 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004490 case glslang::EOpTextureQueryLod:
4491 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004492 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004493 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004494 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004495 case glslang::EOpSparseTexelsResident:
4496 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004497#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004498 default:
4499 assert(0);
4500 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004501 }
John Kessenich140f3df2015-06-26 16:58:36 -06004502 }
4503
LoopDawg4425f242018-02-18 11:40:01 -07004504 int components = node->getType().getVectorSize();
4505
4506 if (node->getOp() == glslang::EOpTextureFetch) {
4507 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4508 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4509 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4510 // here around e.g. which ones return scalars or other types.
4511 components = 4;
4512 }
4513
4514 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4515
4516 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4517
Rex Xufc618912015-09-09 16:42:49 +08004518 // Check for image functions other than queries
4519 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004520 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004521 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004522 spv::IdImmediate image = { true, *(opIt++) };
4523 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004524
4525 // Handle subpass operations
4526 // TODO: GLSL should change to have the "MS" only on the type rather than the
4527 // built-in function.
4528 if (cracked.subpass) {
4529 // add on the (0,0) coordinate
4530 spv::Id zero = builder.makeIntConstant(0);
4531 std::vector<spv::Id> comps;
4532 comps.push_back(zero);
4533 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004534 spv::IdImmediate coord = { true,
4535 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4536 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004537 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4538 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004539 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004540 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4541 }
4542 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004543 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004544 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004545 spv::IdImmediate imageOperand = { true, *(opIt++) };
4546 operands.push_back(imageOperand);
4547 }
John Kessenich6c292d32016-02-15 20:58:50 -07004548 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004549 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4550 builder.setPrecision(result, precision);
4551 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004552 }
4553
John Kessenich149afc32018-08-14 13:31:43 -06004554 spv::IdImmediate coord = { true, *(opIt++) };
4555 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004556 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004557 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004558 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004559 mask = mask | spv::ImageOperandsSampleMask;
4560 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004561 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004562 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4563 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004564 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004565 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004566 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4567 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004568 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004569 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004570 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4571 operands.push_back(imageOperands);
4572 }
4573 if (mask & spv::ImageOperandsSampleMask) {
4574 spv::IdImmediate imageOperand = { true, *opIt++ };
4575 operands.push_back(imageOperand);
4576 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004577 if (mask & spv::ImageOperandsLodMask) {
4578 spv::IdImmediate imageOperand = { true, *opIt++ };
4579 operands.push_back(imageOperand);
4580 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004581 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004582 spv::IdImmediate imageOperand = { true,
4583 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004584 operands.push_back(imageOperand);
4585 }
4586
John Kessenich149afc32018-08-14 13:31:43 -06004587 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004588 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004589
John Kessenich149afc32018-08-14 13:31:43 -06004590 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004591 builder.setPrecision(result[0], precision);
4592
4593 // If needed, add a conversion constructor to the proper size.
4594 if (components != node->getType().getVectorSize())
4595 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4596
4597 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004598 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004599
Jeff Bolz36831c92018-09-05 10:11:41 -05004600 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004601 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004602 spv::IdImmediate texel = { true, *(opIt + 1) };
4603 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004604 } else {
4605 spv::IdImmediate texel = { true, *opIt };
4606 operands.push_back(texel);
4607 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004608
4609 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004610 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004611 mask = mask | spv::ImageOperandsSampleMask;
4612 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004613 if (cracked.lod) {
4614 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4615 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4616 mask = mask | spv::ImageOperandsLodMask;
4617 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004618 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4619 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004620 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004621 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004622 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4623 operands.push_back(imageOperands);
4624 }
4625 if (mask & spv::ImageOperandsSampleMask) {
4626 spv::IdImmediate imageOperand = { true, *opIt++ };
4627 operands.push_back(imageOperand);
4628 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004629 if (mask & spv::ImageOperandsLodMask) {
4630 spv::IdImmediate imageOperand = { true, *opIt++ };
4631 operands.push_back(imageOperand);
4632 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004633 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004634 spv::IdImmediate imageOperand = { true,
4635 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004636 operands.push_back(imageOperand);
4637 }
4638
John Kessenich56bab042015-09-16 10:54:31 -06004639 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004640 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004641 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004642 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004643 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4644 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004645 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004646 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004647 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4648
Jeff Bolz36831c92018-09-05 10:11:41 -05004649 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004650 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004651 mask = mask | spv::ImageOperandsSampleMask;
4652 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004653 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004654 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4655 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4656
Jeff Bolz36831c92018-09-05 10:11:41 -05004657 mask = mask | spv::ImageOperandsLodMask;
4658 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004659 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4660 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004661 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004662 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004663 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004664 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004665 }
4666 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004667 spv::IdImmediate imageOperand = { true, *opIt++ };
4668 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004669 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004670 if (mask & spv::ImageOperandsLodMask) {
4671 spv::IdImmediate imageOperand = { true, *opIt++ };
4672 operands.push_back(imageOperand);
4673 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004674 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4675 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4676 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004677 }
4678
4679 // Create the return type that was a special structure
4680 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004681 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004682 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4683 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4684
4685 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4686
4687 // Decode the return type
4688 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4689 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004690 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004691 // Process image atomic operations
4692
4693 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4694 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004695 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004696 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004697 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004698
Jeff Bolz36831c92018-09-05 10:11:41 -05004699 spv::Id resultTypeId;
4700 // imageAtomicStore has a void return type so base the pointer type on
4701 // the type of the value operand.
4702 if (node->getOp() == glslang::EOpImageAtomicStore) {
4703 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4704 } else {
4705 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4706 }
John Kessenich56bab042015-09-16 10:54:31 -06004707 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004708
4709 std::vector<spv::Id> operands;
4710 operands.push_back(pointer);
4711 for (; opIt != arguments.end(); ++opIt)
4712 operands.push_back(*opIt);
4713
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004714 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004715 }
4716 }
4717
John Kessenicha28f7a72019-08-06 07:00:58 -06004718#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04004719 // Check for fragment mask functions other than queries
4720 if (cracked.fragMask) {
4721 assert(sampler.ms);
4722
4723 auto opIt = arguments.begin();
4724 std::vector<spv::Id> operands;
4725
4726 // Extract the image if necessary
4727 if (builder.isSampledImage(params.sampler))
4728 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4729
4730 operands.push_back(params.sampler);
4731 ++opIt;
4732
4733 if (sampler.isSubpass()) {
4734 // add on the (0,0) coordinate
4735 spv::Id zero = builder.makeIntConstant(0);
4736 std::vector<spv::Id> comps;
4737 comps.push_back(zero);
4738 comps.push_back(zero);
4739 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4740 }
4741
4742 for (; opIt != arguments.end(); ++opIt)
4743 operands.push_back(*opIt);
4744
4745 spv::Op fragMaskOp = spv::OpNop;
4746 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4747 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4748 else if (node->getOp() == glslang::EOpFragmentFetch)
4749 fragMaskOp = spv::OpFragmentFetchAMD;
4750
4751 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4752 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4753 return builder.createOp(fragMaskOp, resultType(), operands);
4754 }
4755#endif
4756
Rex Xufc618912015-09-09 16:42:49 +08004757 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004758 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004759 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004760 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08004761
John Kessenichfc51d282015-08-19 13:34:18 -06004762 // check for bias argument
4763 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004764 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004765 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004766 if (cracked.gather)
4767 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004768
4769 if (f16ShadowCompare)
4770 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004771 if (cracked.offset)
4772 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004773 else if (cracked.offsets)
4774 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004775 if (cracked.grad)
4776 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004777 if (cracked.lodClamp)
4778 ++nonBiasArgCount;
4779 if (sparse)
4780 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004781 if (imageFootprint)
4782 //Following three extra arguments
4783 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4784 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06004785 if ((int)arguments.size() > nonBiasArgCount)
4786 bias = true;
4787 }
4788
John Kessenicha5c33d62016-06-02 23:45:21 -06004789 // See if the sampler param should really be just the SPV image part
4790 if (cracked.fetch) {
4791 // a fetch needs to have the image extracted first
4792 if (builder.isSampledImage(params.sampler))
4793 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4794 }
4795
John Kessenicha28f7a72019-08-06 07:00:58 -06004796#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08004797 if (cracked.gather) {
4798 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4799 if (bias || cracked.lod ||
4800 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4801 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004802 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004803 }
4804 }
4805#endif
4806
John Kessenichfc51d282015-08-19 13:34:18 -06004807 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004808
John Kessenichfc51d282015-08-19 13:34:18 -06004809 params.coords = arguments[1];
4810 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004811 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004812
4813 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004814 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004815 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004816 ++extraArgs;
4817 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004818 params.Dref = arguments[2];
4819 ++extraArgs;
4820 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004821 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004822 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004823 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004824 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004825 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004826 dRefComp = builder.getNumComponents(params.coords) - 1;
4827 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004828 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4829 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004830
4831 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004832 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004833 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004834 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06004835 } else if (glslangIntermediate->getStage() != EShLangFragment &&
4836 !(glslangIntermediate->getStage() == EShLangCompute &&
4837 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07004838 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4839 noImplicitLod = true;
4840 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004841
4842 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004843 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004844 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004845 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004846 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004847
4848 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004849 if (cracked.grad) {
4850 params.gradX = arguments[2 + extraArgs];
4851 params.gradY = arguments[3 + extraArgs];
4852 extraArgs += 2;
4853 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004854
4855 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004856 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004857 params.offset = arguments[2 + extraArgs];
4858 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004859 } else if (cracked.offsets) {
4860 params.offsets = arguments[2 + extraArgs];
4861 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004862 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004863
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004864#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06004865 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004866 if (cracked.lodClamp) {
4867 params.lodClamp = arguments[2 + extraArgs];
4868 ++extraArgs;
4869 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004870 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004871 if (sparse) {
4872 params.texelOut = arguments[2 + extraArgs];
4873 ++extraArgs;
4874 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004875 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004876 if (cracked.gather && ! sampler.shadow) {
4877 // default component is 0, if missing, otherwise an argument
4878 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004879 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004880 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004881 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004882 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004883 }
Chao Chen3a137962018-09-19 11:41:27 -07004884 spv::Id resultStruct = spv::NoResult;
4885 if (imageFootprint) {
4886 //Following three extra arguments
4887 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4888 params.granularity = arguments[2 + extraArgs];
4889 params.coarse = arguments[3 + extraArgs];
4890 resultStruct = arguments[4 + extraArgs];
4891 extraArgs += 3;
4892 }
4893#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004894 // bias
4895 if (bias) {
4896 params.bias = arguments[2 + extraArgs];
4897 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004898 }
John Kessenichfc51d282015-08-19 13:34:18 -06004899
John Kessenicha28f7a72019-08-06 07:00:58 -06004900#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07004901 if (imageFootprint) {
4902 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4903 builder.addCapability(spv::CapabilityImageFootprintNV);
4904
4905
4906 //resultStructType(OpenGL type) contains 5 elements:
4907 //struct gl_TextureFootprint2DNV {
4908 // uvec2 anchor;
4909 // uvec2 offset;
4910 // uvec2 mask;
4911 // uint lod;
4912 // uint granularity;
4913 //};
4914 //or
4915 //struct gl_TextureFootprint3DNV {
4916 // uvec3 anchor;
4917 // uvec3 offset;
4918 // uvec2 mask;
4919 // uint lod;
4920 // uint granularity;
4921 //};
4922 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4923 assert(builder.isStructType(resultStructType));
4924
4925 //resType (SPIR-V type) contains 6 elements:
4926 //Member 0 must be a Boolean type scalar(LOD),
4927 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4928 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4929 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4930 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4931 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4932 std::vector<spv::Id> members;
4933 members.push_back(resultType());
4934 for (int i = 0; i < 5; i++) {
4935 members.push_back(builder.getContainedTypeId(resultStructType, i));
4936 }
4937 spv::Id resType = builder.makeStructType(members, "ResType");
4938
4939 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06004940 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
4941 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07004942
4943 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4944 for (int i = 0; i < 5; i++) {
4945 builder.clearAccessChain();
4946 builder.setAccessChainLValue(resultStruct);
4947
4948 //Accessing to a struct we created, no coherent flag is set
4949 spv::Builder::AccessChain::CoherentFlags flags;
4950 flags.clear();
4951
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004952 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004953 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4954 }
4955 return builder.createCompositeExtract(res, resultType(), 0);
4956 }
4957#endif
4958
John Kessenich65336482016-06-16 14:06:26 -06004959 // projective component (might not to move)
4960 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4961 // are divided by the last component of P."
4962 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4963 // unused components will appear after all used components."
4964 if (cracked.proj) {
4965 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4966 int projTargetComp;
4967 switch (sampler.dim) {
4968 case glslang::Esd1D: projTargetComp = 1; break;
4969 case glslang::Esd2D: projTargetComp = 2; break;
4970 case glslang::EsdRect: projTargetComp = 2; break;
4971 default: projTargetComp = projSourceComp; break;
4972 }
4973 // copy the projective coordinate if we have to
4974 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004975 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004976 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4977 projSourceComp);
4978 params.coords = builder.createCompositeInsert(projComp, params.coords,
4979 builder.getTypeId(params.coords), projTargetComp);
4980 }
4981 }
4982
Jeff Bolz36831c92018-09-05 10:11:41 -05004983 // nonprivate
4984 if (imageType.getQualifier().nonprivate) {
4985 params.nonprivate = true;
4986 }
4987
4988 // volatile
4989 if (imageType.getQualifier().volatil) {
4990 params.volatil = true;
4991 }
4992
St0fFa1184dd2018-04-09 21:08:14 +02004993 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06004994 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
4995 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02004996 );
LoopDawg4425f242018-02-18 11:40:01 -07004997
4998 if (components != node->getType().getVectorSize())
4999 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5000
5001 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005002}
5003
5004spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5005{
5006 // Grab the function's pointer from the previously created function
5007 spv::Function* function = functionMap[node->getName().c_str()];
5008 if (! function)
5009 return 0;
5010
5011 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5012 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5013
5014 // See comments in makeFunctions() for details about the semantics for parameter passing.
5015 //
5016 // These imply we need a four step process:
5017 // 1. Evaluate the arguments
5018 // 2. Allocate and make copies of in, out, and inout arguments
5019 // 3. Make the call
5020 // 4. Copy back the results
5021
John Kessenichd3ed90b2018-05-04 11:43:03 -06005022 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005023 std::vector<spv::Builder::AccessChain> lValues;
5024 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005025 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005026 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005027 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005028 // build l-value
5029 builder.clearAccessChain();
5030 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005031 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005032 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005033 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005034 // save l-value
5035 lValues.push_back(builder.getAccessChain());
5036 } else {
5037 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005038 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005039 }
5040 }
5041
5042 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5043 // copy the original into that space.
5044 //
5045 // Also, build up the list of actual arguments to pass in for the call
5046 int lValueCount = 0;
5047 int rValueCount = 0;
5048 std::vector<spv::Id> spvArgs;
5049 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5050 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005051 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005052 builder.setAccessChain(lValues[lValueCount]);
5053 arg = builder.accessChainGetLValue();
5054 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005055 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005056 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06005057 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005058 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5059 // need to copy the input into output space
5060 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005061 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005062 builder.clearAccessChain();
5063 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005064 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005065 }
5066 ++lValueCount;
5067 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005068 // process r-value, which involves a copy for a type mismatch
5069 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
5070 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
5071 builder.clearAccessChain();
5072 builder.setAccessChainLValue(argCopy);
5073 multiTypeStore(*argTypes[a], rValues[rValueCount]);
5074 arg = builder.createLoad(argCopy);
5075 } else
5076 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005077 ++rValueCount;
5078 }
5079 spvArgs.push_back(arg);
5080 }
5081
5082 // 3. Make the call.
5083 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005084 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005085
5086 // 4. Copy back out an "out" arguments.
5087 lValueCount = 0;
5088 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005089 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005090 ++lValueCount;
5091 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005092 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5093 spv::Id copy = builder.createLoad(spvArgs[a]);
5094 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005095 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005096 }
5097 ++lValueCount;
5098 }
5099 }
5100
5101 return result;
5102}
5103
5104// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005105spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005106 spv::Id typeId, spv::Id left, spv::Id right,
5107 glslang::TBasicType typeProxy, bool reduceComparison)
5108{
John Kessenich66011cb2018-03-06 16:12:04 -07005109 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5110 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005111 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005112
5113 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005114 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005115 bool comparison = false;
5116
5117 switch (op) {
5118 case glslang::EOpAdd:
5119 case glslang::EOpAddAssign:
5120 if (isFloat)
5121 binOp = spv::OpFAdd;
5122 else
5123 binOp = spv::OpIAdd;
5124 break;
5125 case glslang::EOpSub:
5126 case glslang::EOpSubAssign:
5127 if (isFloat)
5128 binOp = spv::OpFSub;
5129 else
5130 binOp = spv::OpISub;
5131 break;
5132 case glslang::EOpMul:
5133 case glslang::EOpMulAssign:
5134 if (isFloat)
5135 binOp = spv::OpFMul;
5136 else
5137 binOp = spv::OpIMul;
5138 break;
5139 case glslang::EOpVectorTimesScalar:
5140 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005141 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005142 if (builder.isVector(right))
5143 std::swap(left, right);
5144 assert(builder.isScalar(right));
5145 needMatchingVectors = false;
5146 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005147 } else if (isFloat)
5148 binOp = spv::OpFMul;
5149 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005150 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005151 break;
5152 case glslang::EOpVectorTimesMatrix:
5153 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005154 binOp = spv::OpVectorTimesMatrix;
5155 break;
5156 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005157 binOp = spv::OpMatrixTimesVector;
5158 break;
5159 case glslang::EOpMatrixTimesScalar:
5160 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005161 binOp = spv::OpMatrixTimesScalar;
5162 break;
5163 case glslang::EOpMatrixTimesMatrix:
5164 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005165 binOp = spv::OpMatrixTimesMatrix;
5166 break;
5167 case glslang::EOpOuterProduct:
5168 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005169 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005170 break;
5171
5172 case glslang::EOpDiv:
5173 case glslang::EOpDivAssign:
5174 if (isFloat)
5175 binOp = spv::OpFDiv;
5176 else if (isUnsigned)
5177 binOp = spv::OpUDiv;
5178 else
5179 binOp = spv::OpSDiv;
5180 break;
5181 case glslang::EOpMod:
5182 case glslang::EOpModAssign:
5183 if (isFloat)
5184 binOp = spv::OpFMod;
5185 else if (isUnsigned)
5186 binOp = spv::OpUMod;
5187 else
5188 binOp = spv::OpSMod;
5189 break;
5190 case glslang::EOpRightShift:
5191 case glslang::EOpRightShiftAssign:
5192 if (isUnsigned)
5193 binOp = spv::OpShiftRightLogical;
5194 else
5195 binOp = spv::OpShiftRightArithmetic;
5196 break;
5197 case glslang::EOpLeftShift:
5198 case glslang::EOpLeftShiftAssign:
5199 binOp = spv::OpShiftLeftLogical;
5200 break;
5201 case glslang::EOpAnd:
5202 case glslang::EOpAndAssign:
5203 binOp = spv::OpBitwiseAnd;
5204 break;
5205 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005206 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005207 binOp = spv::OpLogicalAnd;
5208 break;
5209 case glslang::EOpInclusiveOr:
5210 case glslang::EOpInclusiveOrAssign:
5211 binOp = spv::OpBitwiseOr;
5212 break;
5213 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005214 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005215 binOp = spv::OpLogicalOr;
5216 break;
5217 case glslang::EOpExclusiveOr:
5218 case glslang::EOpExclusiveOrAssign:
5219 binOp = spv::OpBitwiseXor;
5220 break;
5221 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005222 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005223 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005224 break;
5225
5226 case glslang::EOpLessThan:
5227 case glslang::EOpGreaterThan:
5228 case glslang::EOpLessThanEqual:
5229 case glslang::EOpGreaterThanEqual:
5230 case glslang::EOpEqual:
5231 case glslang::EOpNotEqual:
5232 case glslang::EOpVectorEqual:
5233 case glslang::EOpVectorNotEqual:
5234 comparison = true;
5235 break;
5236 default:
5237 break;
5238 }
5239
John Kessenich7c1aa102015-10-15 13:29:11 -06005240 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005241 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005242 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005243 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5244 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005245 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005246
5247 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005248 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005249 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005250
qining25262b32016-05-06 17:25:16 -04005251 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005252 decorations.addNoContraction(builder, result);
5253 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005254 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005255 }
5256
5257 if (! comparison)
5258 return 0;
5259
John Kessenich7c1aa102015-10-15 13:29:11 -06005260 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005261
John Kessenich4583b612016-08-07 19:14:22 -06005262 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005263 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5264 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005265 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005266 return result;
5267 }
John Kessenich140f3df2015-06-26 16:58:36 -06005268
5269 switch (op) {
5270 case glslang::EOpLessThan:
5271 if (isFloat)
5272 binOp = spv::OpFOrdLessThan;
5273 else if (isUnsigned)
5274 binOp = spv::OpULessThan;
5275 else
5276 binOp = spv::OpSLessThan;
5277 break;
5278 case glslang::EOpGreaterThan:
5279 if (isFloat)
5280 binOp = spv::OpFOrdGreaterThan;
5281 else if (isUnsigned)
5282 binOp = spv::OpUGreaterThan;
5283 else
5284 binOp = spv::OpSGreaterThan;
5285 break;
5286 case glslang::EOpLessThanEqual:
5287 if (isFloat)
5288 binOp = spv::OpFOrdLessThanEqual;
5289 else if (isUnsigned)
5290 binOp = spv::OpULessThanEqual;
5291 else
5292 binOp = spv::OpSLessThanEqual;
5293 break;
5294 case glslang::EOpGreaterThanEqual:
5295 if (isFloat)
5296 binOp = spv::OpFOrdGreaterThanEqual;
5297 else if (isUnsigned)
5298 binOp = spv::OpUGreaterThanEqual;
5299 else
5300 binOp = spv::OpSGreaterThanEqual;
5301 break;
5302 case glslang::EOpEqual:
5303 case glslang::EOpVectorEqual:
5304 if (isFloat)
5305 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005306 else if (isBool)
5307 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005308 else
5309 binOp = spv::OpIEqual;
5310 break;
5311 case glslang::EOpNotEqual:
5312 case glslang::EOpVectorNotEqual:
5313 if (isFloat)
5314 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005315 else if (isBool)
5316 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005317 else
5318 binOp = spv::OpINotEqual;
5319 break;
5320 default:
5321 break;
5322 }
5323
qining25262b32016-05-06 17:25:16 -04005324 if (binOp != spv::OpNop) {
5325 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005326 decorations.addNoContraction(builder, result);
5327 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005328 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005329 }
John Kessenich140f3df2015-06-26 16:58:36 -06005330
5331 return 0;
5332}
5333
John Kessenich04bb8a02015-12-12 12:28:14 -07005334//
5335// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5336// These can be any of:
5337//
5338// matrix * scalar
5339// scalar * matrix
5340// matrix * matrix linear algebraic
5341// matrix * vector
5342// vector * matrix
5343// matrix * matrix componentwise
5344// matrix op matrix op in {+, -, /}
5345// matrix op scalar op in {+, -, /}
5346// scalar op matrix op in {+, -, /}
5347//
John Kessenichead86222018-03-28 18:01:20 -06005348spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5349 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005350{
5351 bool firstClass = true;
5352
5353 // First, handle first-class matrix operations (* and matrix/scalar)
5354 switch (op) {
5355 case spv::OpFDiv:
5356 if (builder.isMatrix(left) && builder.isScalar(right)) {
5357 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005358 spv::Id resultType = builder.getTypeId(right);
5359 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005360 op = spv::OpMatrixTimesScalar;
5361 } else
5362 firstClass = false;
5363 break;
5364 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005365 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005366 std::swap(left, right);
5367 assert(builder.isScalar(right));
5368 break;
5369 case spv::OpVectorTimesMatrix:
5370 assert(builder.isVector(left));
5371 assert(builder.isMatrix(right));
5372 break;
5373 case spv::OpMatrixTimesVector:
5374 assert(builder.isMatrix(left));
5375 assert(builder.isVector(right));
5376 break;
5377 case spv::OpMatrixTimesMatrix:
5378 assert(builder.isMatrix(left));
5379 assert(builder.isMatrix(right));
5380 break;
5381 default:
5382 firstClass = false;
5383 break;
5384 }
5385
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005386 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5387 firstClass = true;
5388
qining25262b32016-05-06 17:25:16 -04005389 if (firstClass) {
5390 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005391 decorations.addNoContraction(builder, result);
5392 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005393 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005394 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005395
LoopDawg592860c2016-06-09 08:57:35 -06005396 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005397 // The result type of all of them is the same type as the (a) matrix operand.
5398 // The algorithm is to:
5399 // - break the matrix(es) into vectors
5400 // - smear any scalar to a vector
5401 // - do vector operations
5402 // - make a matrix out the vector results
5403 switch (op) {
5404 case spv::OpFAdd:
5405 case spv::OpFSub:
5406 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005407 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005408 case spv::OpFMul:
5409 {
5410 // one time set up...
5411 bool leftMat = builder.isMatrix(left);
5412 bool rightMat = builder.isMatrix(right);
5413 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5414 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5415 spv::Id scalarType = builder.getScalarTypeId(typeId);
5416 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5417 std::vector<spv::Id> results;
5418 spv::Id smearVec = spv::NoResult;
5419 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005420 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005421 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005422 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005423
5424 // do each vector op
5425 for (unsigned int c = 0; c < numCols; ++c) {
5426 std::vector<unsigned int> indexes;
5427 indexes.push_back(c);
5428 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5429 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005430 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005431 decorations.addNoContraction(builder, result);
5432 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005433 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005434 }
5435
5436 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005437 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005438 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005439 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005440 }
5441 default:
5442 assert(0);
5443 return spv::NoResult;
5444 }
5445}
5446
John Kessenichead86222018-03-28 18:01:20 -06005447spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005448 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005449{
5450 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005451 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005452 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005453 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5454 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005455
5456 switch (op) {
5457 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005458 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005459 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005460 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005461 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005462 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005463 unaryOp = spv::OpSNegate;
5464 break;
5465
5466 case glslang::EOpLogicalNot:
5467 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005468 unaryOp = spv::OpLogicalNot;
5469 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005470 case glslang::EOpBitwiseNot:
5471 unaryOp = spv::OpNot;
5472 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005473
John Kessenich140f3df2015-06-26 16:58:36 -06005474 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005475 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005476 break;
5477 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005478 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005479 break;
5480 case glslang::EOpTranspose:
5481 unaryOp = spv::OpTranspose;
5482 break;
5483
5484 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005485 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005486 break;
5487 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005488 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005489 break;
5490 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005491 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005492 break;
5493 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005494 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005495 break;
5496 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005497 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005498 break;
5499 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005500 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005501 break;
5502 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005503 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005504 break;
5505 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005506 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005507 break;
5508
5509 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005510 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005511 break;
5512 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005513 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005514 break;
5515 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005516 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005517 break;
5518 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005519 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005520 break;
5521 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005522 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005523 break;
5524 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005525 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005526 break;
5527
5528 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005529 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005530 break;
5531 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005532 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005533 break;
5534
5535 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005536 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005537 break;
5538 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005539 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005540 break;
5541 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005542 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005543 break;
5544 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005545 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005546 break;
5547 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005548 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005549 break;
5550 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005551 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005552 break;
5553
5554 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005555 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005556 break;
5557 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005558 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005559 break;
5560 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005561 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005562 break;
5563 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005564 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005565 break;
5566 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005567 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005568 break;
5569 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005570 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005571 break;
5572
5573 case glslang::EOpIsNan:
5574 unaryOp = spv::OpIsNan;
5575 break;
5576 case glslang::EOpIsInf:
5577 unaryOp = spv::OpIsInf;
5578 break;
LoopDawg592860c2016-06-09 08:57:35 -06005579 case glslang::EOpIsFinite:
5580 unaryOp = spv::OpIsFinite;
5581 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005582
Rex Xucbc426e2015-12-15 16:03:10 +08005583 case glslang::EOpFloatBitsToInt:
5584 case glslang::EOpFloatBitsToUint:
5585 case glslang::EOpIntBitsToFloat:
5586 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005587 case glslang::EOpDoubleBitsToInt64:
5588 case glslang::EOpDoubleBitsToUint64:
5589 case glslang::EOpInt64BitsToDouble:
5590 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005591 case glslang::EOpFloat16BitsToInt16:
5592 case glslang::EOpFloat16BitsToUint16:
5593 case glslang::EOpInt16BitsToFloat16:
5594 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005595 unaryOp = spv::OpBitcast;
5596 break;
5597
John Kessenich140f3df2015-06-26 16:58:36 -06005598 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005599 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005600 break;
5601 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005602 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005603 break;
5604 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005605 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005606 break;
5607 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005608 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005609 break;
5610 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005611 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005612 break;
5613 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005614 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005615 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005616#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005617 case glslang::EOpPackSnorm4x8:
5618 libCall = spv::GLSLstd450PackSnorm4x8;
5619 break;
5620 case glslang::EOpUnpackSnorm4x8:
5621 libCall = spv::GLSLstd450UnpackSnorm4x8;
5622 break;
5623 case glslang::EOpPackUnorm4x8:
5624 libCall = spv::GLSLstd450PackUnorm4x8;
5625 break;
5626 case glslang::EOpUnpackUnorm4x8:
5627 libCall = spv::GLSLstd450UnpackUnorm4x8;
5628 break;
5629 case glslang::EOpPackDouble2x32:
5630 libCall = spv::GLSLstd450PackDouble2x32;
5631 break;
5632 case glslang::EOpUnpackDouble2x32:
5633 libCall = spv::GLSLstd450UnpackDouble2x32;
5634 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005635#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005636
Rex Xu8ff43de2016-04-22 16:51:45 +08005637 case glslang::EOpPackInt2x32:
5638 case glslang::EOpUnpackInt2x32:
5639 case glslang::EOpPackUint2x32:
5640 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005641 case glslang::EOpPack16:
5642 case glslang::EOpPack32:
5643 case glslang::EOpPack64:
5644 case glslang::EOpUnpack32:
5645 case glslang::EOpUnpack16:
5646 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005647 case glslang::EOpPackInt2x16:
5648 case glslang::EOpUnpackInt2x16:
5649 case glslang::EOpPackUint2x16:
5650 case glslang::EOpUnpackUint2x16:
5651 case glslang::EOpPackInt4x16:
5652 case glslang::EOpUnpackInt4x16:
5653 case glslang::EOpPackUint4x16:
5654 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005655 case glslang::EOpPackFloat2x16:
5656 case glslang::EOpUnpackFloat2x16:
5657 unaryOp = spv::OpBitcast;
5658 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005659
John Kessenich140f3df2015-06-26 16:58:36 -06005660 case glslang::EOpDPdx:
5661 unaryOp = spv::OpDPdx;
5662 break;
5663 case glslang::EOpDPdy:
5664 unaryOp = spv::OpDPdy;
5665 break;
5666 case glslang::EOpFwidth:
5667 unaryOp = spv::OpFwidth;
5668 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005669
John Kessenich140f3df2015-06-26 16:58:36 -06005670 case glslang::EOpAny:
5671 unaryOp = spv::OpAny;
5672 break;
5673 case glslang::EOpAll:
5674 unaryOp = spv::OpAll;
5675 break;
5676
5677 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005678 if (isFloat)
5679 libCall = spv::GLSLstd450FAbs;
5680 else
5681 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005682 break;
5683 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005684 if (isFloat)
5685 libCall = spv::GLSLstd450FSign;
5686 else
5687 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005688 break;
5689
John Kessenicha28f7a72019-08-06 07:00:58 -06005690#ifndef GLSLANG_WEB
5691 case glslang::EOpDPdxFine:
5692 unaryOp = spv::OpDPdxFine;
5693 break;
5694 case glslang::EOpDPdyFine:
5695 unaryOp = spv::OpDPdyFine;
5696 break;
5697 case glslang::EOpFwidthFine:
5698 unaryOp = spv::OpFwidthFine;
5699 break;
5700 case glslang::EOpDPdxCoarse:
5701 unaryOp = spv::OpDPdxCoarse;
5702 break;
5703 case glslang::EOpDPdyCoarse:
5704 unaryOp = spv::OpDPdyCoarse;
5705 break;
5706 case glslang::EOpFwidthCoarse:
5707 unaryOp = spv::OpFwidthCoarse;
5708 break;
5709 case glslang::EOpInterpolateAtCentroid:
5710 if (typeProxy == glslang::EbtFloat16)
5711 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5712 libCall = spv::GLSLstd450InterpolateAtCentroid;
5713 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005714 case glslang::EOpAtomicCounterIncrement:
5715 case glslang::EOpAtomicCounterDecrement:
5716 case glslang::EOpAtomicCounter:
5717 {
5718 // Handle all of the atomics in one place, in createAtomicOperation()
5719 std::vector<spv::Id> operands;
5720 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005721 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06005722 }
5723
John Kessenichfc51d282015-08-19 13:34:18 -06005724 case glslang::EOpBitFieldReverse:
5725 unaryOp = spv::OpBitReverse;
5726 break;
5727 case glslang::EOpBitCount:
5728 unaryOp = spv::OpBitCount;
5729 break;
5730 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005731 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005732 break;
5733 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005734 if (isUnsigned)
5735 libCall = spv::GLSLstd450FindUMsb;
5736 else
5737 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005738 break;
5739
Rex Xu574ab042016-04-14 16:53:07 +08005740 case glslang::EOpBallot:
5741 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005742 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005743 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005744 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005745 case glslang::EOpMinInvocations:
5746 case glslang::EOpMaxInvocations:
5747 case glslang::EOpAddInvocations:
5748 case glslang::EOpMinInvocationsNonUniform:
5749 case glslang::EOpMaxInvocationsNonUniform:
5750 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005751 case glslang::EOpMinInvocationsInclusiveScan:
5752 case glslang::EOpMaxInvocationsInclusiveScan:
5753 case glslang::EOpAddInvocationsInclusiveScan:
5754 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5755 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5756 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5757 case glslang::EOpMinInvocationsExclusiveScan:
5758 case glslang::EOpMaxInvocationsExclusiveScan:
5759 case glslang::EOpAddInvocationsExclusiveScan:
5760 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5761 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5762 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08005763 {
5764 std::vector<spv::Id> operands;
5765 operands.push_back(operand);
5766 return createInvocationsOperation(op, typeId, operands, typeProxy);
5767 }
John Kessenich66011cb2018-03-06 16:12:04 -07005768 case glslang::EOpSubgroupAll:
5769 case glslang::EOpSubgroupAny:
5770 case glslang::EOpSubgroupAllEqual:
5771 case glslang::EOpSubgroupBroadcastFirst:
5772 case glslang::EOpSubgroupBallot:
5773 case glslang::EOpSubgroupInverseBallot:
5774 case glslang::EOpSubgroupBallotBitCount:
5775 case glslang::EOpSubgroupBallotInclusiveBitCount:
5776 case glslang::EOpSubgroupBallotExclusiveBitCount:
5777 case glslang::EOpSubgroupBallotFindLSB:
5778 case glslang::EOpSubgroupBallotFindMSB:
5779 case glslang::EOpSubgroupAdd:
5780 case glslang::EOpSubgroupMul:
5781 case glslang::EOpSubgroupMin:
5782 case glslang::EOpSubgroupMax:
5783 case glslang::EOpSubgroupAnd:
5784 case glslang::EOpSubgroupOr:
5785 case glslang::EOpSubgroupXor:
5786 case glslang::EOpSubgroupInclusiveAdd:
5787 case glslang::EOpSubgroupInclusiveMul:
5788 case glslang::EOpSubgroupInclusiveMin:
5789 case glslang::EOpSubgroupInclusiveMax:
5790 case glslang::EOpSubgroupInclusiveAnd:
5791 case glslang::EOpSubgroupInclusiveOr:
5792 case glslang::EOpSubgroupInclusiveXor:
5793 case glslang::EOpSubgroupExclusiveAdd:
5794 case glslang::EOpSubgroupExclusiveMul:
5795 case glslang::EOpSubgroupExclusiveMin:
5796 case glslang::EOpSubgroupExclusiveMax:
5797 case glslang::EOpSubgroupExclusiveAnd:
5798 case glslang::EOpSubgroupExclusiveOr:
5799 case glslang::EOpSubgroupExclusiveXor:
5800 case glslang::EOpSubgroupQuadSwapHorizontal:
5801 case glslang::EOpSubgroupQuadSwapVertical:
5802 case glslang::EOpSubgroupQuadSwapDiagonal: {
5803 std::vector<spv::Id> operands;
5804 operands.push_back(operand);
5805 return createSubgroupOperation(op, typeId, operands, typeProxy);
5806 }
Rex Xu9d93a232016-05-05 12:30:44 +08005807 case glslang::EOpMbcnt:
5808 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5809 libCall = spv::MbcntAMD;
5810 break;
5811
5812 case glslang::EOpCubeFaceIndex:
5813 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5814 libCall = spv::CubeFaceIndexAMD;
5815 break;
5816
5817 case glslang::EOpCubeFaceCoord:
5818 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5819 libCall = spv::CubeFaceCoordAMD;
5820 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005821 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005822 unaryOp = spv::OpGroupNonUniformPartitionNV;
5823 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005824 case glslang::EOpConstructReference:
5825 unaryOp = spv::OpBitcast;
5826 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005827#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05005828
5829 case glslang::EOpCopyObject:
5830 unaryOp = spv::OpCopyObject;
5831 break;
5832
John Kessenich140f3df2015-06-26 16:58:36 -06005833 default:
5834 return 0;
5835 }
5836
5837 spv::Id id;
5838 if (libCall >= 0) {
5839 std::vector<spv::Id> args;
5840 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005841 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005842 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005843 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005844 }
John Kessenich140f3df2015-06-26 16:58:36 -06005845
John Kessenichb9197c82019-08-11 07:41:45 -06005846 decorations.addNoContraction(builder, id);
5847 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06005848 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005849}
5850
John Kessenich7a53f762016-01-20 11:19:27 -07005851// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005852spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5853 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005854{
5855 // Handle unary operations vector by vector.
5856 // The result type is the same type as the original type.
5857 // The algorithm is to:
5858 // - break the matrix into vectors
5859 // - apply the operation to each vector
5860 // - make a matrix out the vector results
5861
5862 // get the types sorted out
5863 int numCols = builder.getNumColumns(operand);
5864 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005865 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5866 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005867 std::vector<spv::Id> results;
5868
5869 // do each vector op
5870 for (int c = 0; c < numCols; ++c) {
5871 std::vector<unsigned int> indexes;
5872 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005873 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5874 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005875 decorations.addNoContraction(builder, destVec);
5876 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06005877 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005878 }
5879
5880 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005881 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005882 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005883 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005884}
5885
John Kessenichad7645f2018-06-04 19:11:25 -06005886// For converting integers where both the bitwidth and the signedness could
5887// change, but only do the width change here. The caller is still responsible
5888// for the signedness conversion.
5889spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005890{
John Kessenichad7645f2018-06-04 19:11:25 -06005891 // Get the result type width, based on the type to convert to.
5892 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005893 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005894 case glslang::EOpConvInt16ToUint8:
5895 case glslang::EOpConvIntToUint8:
5896 case glslang::EOpConvInt64ToUint8:
5897 case glslang::EOpConvUint16ToInt8:
5898 case glslang::EOpConvUintToInt8:
5899 case glslang::EOpConvUint64ToInt8:
5900 width = 8;
5901 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005902 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005903 case glslang::EOpConvIntToUint16:
5904 case glslang::EOpConvInt64ToUint16:
5905 case glslang::EOpConvUint8ToInt16:
5906 case glslang::EOpConvUintToInt16:
5907 case glslang::EOpConvUint64ToInt16:
5908 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005909 break;
5910 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005911 case glslang::EOpConvInt16ToUint:
5912 case glslang::EOpConvInt64ToUint:
5913 case glslang::EOpConvUint8ToInt:
5914 case glslang::EOpConvUint16ToInt:
5915 case glslang::EOpConvUint64ToInt:
5916 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005917 break;
5918 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005919 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005920 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005921 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005922 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005923 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005924 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005925 break;
5926
5927 default:
5928 assert(false && "Default missing");
5929 break;
5930 }
5931
John Kessenichad7645f2018-06-04 19:11:25 -06005932 // Get the conversion operation and result type,
5933 // based on the target width, but the source type.
5934 spv::Id type = spv::NoType;
5935 spv::Op convOp = spv::OpNop;
5936 switch(op) {
5937 case glslang::EOpConvInt8ToUint16:
5938 case glslang::EOpConvInt8ToUint:
5939 case glslang::EOpConvInt8ToUint64:
5940 case glslang::EOpConvInt16ToUint8:
5941 case glslang::EOpConvInt16ToUint:
5942 case glslang::EOpConvInt16ToUint64:
5943 case glslang::EOpConvIntToUint8:
5944 case glslang::EOpConvIntToUint16:
5945 case glslang::EOpConvIntToUint64:
5946 case glslang::EOpConvInt64ToUint8:
5947 case glslang::EOpConvInt64ToUint16:
5948 case glslang::EOpConvInt64ToUint:
5949 convOp = spv::OpSConvert;
5950 type = builder.makeIntType(width);
5951 break;
5952 default:
5953 convOp = spv::OpUConvert;
5954 type = builder.makeUintType(width);
5955 break;
5956 }
5957
John Kessenich66011cb2018-03-06 16:12:04 -07005958 if (vectorSize > 0)
5959 type = builder.makeVectorType(type, vectorSize);
5960
John Kessenichad7645f2018-06-04 19:11:25 -06005961 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005962}
5963
John Kessenichead86222018-03-28 18:01:20 -06005964spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5965 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005966{
5967 spv::Op convOp = spv::OpNop;
5968 spv::Id zero = 0;
5969 spv::Id one = 0;
5970
5971 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5972
5973 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005974 case glslang::EOpConvIntToBool:
5975 case glslang::EOpConvUintToBool:
5976 zero = builder.makeUintConstant(0);
5977 zero = makeSmearedConstant(zero, vectorSize);
5978 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06005979 case glslang::EOpConvFloatToBool:
5980 zero = builder.makeFloatConstant(0.0F);
5981 zero = makeSmearedConstant(zero, vectorSize);
5982 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06005983 case glslang::EOpConvBoolToFloat:
5984 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005985 zero = builder.makeFloatConstant(0.0F);
5986 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005987 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005988
John Kessenich140f3df2015-06-26 16:58:36 -06005989 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005990 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06005991#ifndef GLSLANG_WEB
5992 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08005993 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005994 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06005995 } else
5996#endif
5997 {
5998 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005999 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006000 }
Rex Xucabbb782017-03-24 13:41:14 +08006001
John Kessenich140f3df2015-06-26 16:58:36 -06006002 convOp = spv::OpSelect;
6003 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006004
John Kessenich140f3df2015-06-26 16:58:36 -06006005 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006006 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006007#ifndef GLSLANG_WEB
6008 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006009 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006010 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006011 } else
6012#endif
6013 {
6014 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006015 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006016 }
Rex Xucabbb782017-03-24 13:41:14 +08006017
John Kessenich140f3df2015-06-26 16:58:36 -06006018 convOp = spv::OpSelect;
6019 break;
6020
John Kessenich66011cb2018-03-06 16:12:04 -07006021 case glslang::EOpConvInt8ToFloat16:
6022 case glslang::EOpConvInt8ToFloat:
6023 case glslang::EOpConvInt8ToDouble:
6024 case glslang::EOpConvInt16ToFloat16:
6025 case glslang::EOpConvInt16ToFloat:
6026 case glslang::EOpConvInt16ToDouble:
6027 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006028 case glslang::EOpConvIntToFloat:
6029 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006030 case glslang::EOpConvInt64ToFloat:
6031 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006032 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006033 convOp = spv::OpConvertSToF;
6034 break;
6035
John Kessenich66011cb2018-03-06 16:12:04 -07006036 case glslang::EOpConvUint8ToFloat16:
6037 case glslang::EOpConvUint8ToFloat:
6038 case glslang::EOpConvUint8ToDouble:
6039 case glslang::EOpConvUint16ToFloat16:
6040 case glslang::EOpConvUint16ToFloat:
6041 case glslang::EOpConvUint16ToDouble:
6042 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006043 case glslang::EOpConvUintToFloat:
6044 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006045 case glslang::EOpConvUint64ToFloat:
6046 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006047 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006048 convOp = spv::OpConvertUToF;
6049 break;
6050
John Kessenich66011cb2018-03-06 16:12:04 -07006051 case glslang::EOpConvFloat16ToInt8:
6052 case glslang::EOpConvFloatToInt8:
6053 case glslang::EOpConvDoubleToInt8:
6054 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006055 case glslang::EOpConvFloatToInt16:
6056 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006057 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006058 case glslang::EOpConvFloatToInt:
6059 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006060 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006061 case glslang::EOpConvFloatToInt64:
6062 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006063 convOp = spv::OpConvertFToS;
6064 break;
6065
John Kessenich66011cb2018-03-06 16:12:04 -07006066 case glslang::EOpConvUint8ToInt8:
6067 case glslang::EOpConvInt8ToUint8:
6068 case glslang::EOpConvUint16ToInt16:
6069 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006070 case glslang::EOpConvUintToInt:
6071 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006072 case glslang::EOpConvUint64ToInt64:
6073 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006074 if (builder.isInSpecConstCodeGenMode()) {
6075 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006076#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006077 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6078 zero = builder.makeUint8Constant(0);
6079 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006080 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006081 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6082 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006083 } else
6084#endif
6085 {
Rex Xucabbb782017-03-24 13:41:14 +08006086 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006087 }
qining189b2032016-04-12 23:16:20 -04006088 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006089 // Use OpIAdd, instead of OpBitcast to do the conversion when
6090 // generating for OpSpecConstantOp instruction.
6091 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6092 }
6093 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006094 convOp = spv::OpBitcast;
6095 break;
6096
John Kessenich66011cb2018-03-06 16:12:04 -07006097 case glslang::EOpConvFloat16ToUint8:
6098 case glslang::EOpConvFloatToUint8:
6099 case glslang::EOpConvDoubleToUint8:
6100 case glslang::EOpConvFloat16ToUint16:
6101 case glslang::EOpConvFloatToUint16:
6102 case glslang::EOpConvDoubleToUint16:
6103 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006104 case glslang::EOpConvFloatToUint:
6105 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006106 case glslang::EOpConvFloatToUint64:
6107 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006108 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006109 convOp = spv::OpConvertFToU;
6110 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006111
John Kessenich39697cd2019-08-08 10:35:51 -06006112#ifndef GLSLANG_WEB
6113 case glslang::EOpConvInt8ToBool:
6114 case glslang::EOpConvUint8ToBool:
6115 zero = builder.makeUint8Constant(0);
6116 zero = makeSmearedConstant(zero, vectorSize);
6117 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6118 case glslang::EOpConvInt16ToBool:
6119 case glslang::EOpConvUint16ToBool:
6120 zero = builder.makeUint16Constant(0);
6121 zero = makeSmearedConstant(zero, vectorSize);
6122 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6123 case glslang::EOpConvInt64ToBool:
6124 case glslang::EOpConvUint64ToBool:
6125 zero = builder.makeUint64Constant(0);
6126 zero = makeSmearedConstant(zero, vectorSize);
6127 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6128 case glslang::EOpConvDoubleToBool:
6129 zero = builder.makeDoubleConstant(0.0);
6130 zero = makeSmearedConstant(zero, vectorSize);
6131 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6132 case glslang::EOpConvFloat16ToBool:
6133 zero = builder.makeFloat16Constant(0.0F);
6134 zero = makeSmearedConstant(zero, vectorSize);
6135 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6136 case glslang::EOpConvBoolToDouble:
6137 convOp = spv::OpSelect;
6138 zero = builder.makeDoubleConstant(0.0);
6139 one = builder.makeDoubleConstant(1.0);
6140 break;
6141 case glslang::EOpConvBoolToFloat16:
6142 convOp = spv::OpSelect;
6143 zero = builder.makeFloat16Constant(0.0F);
6144 one = builder.makeFloat16Constant(1.0F);
6145 break;
6146 case glslang::EOpConvBoolToInt8:
6147 zero = builder.makeInt8Constant(0);
6148 one = builder.makeInt8Constant(1);
6149 convOp = spv::OpSelect;
6150 break;
6151 case glslang::EOpConvBoolToUint8:
6152 zero = builder.makeUint8Constant(0);
6153 one = builder.makeUint8Constant(1);
6154 convOp = spv::OpSelect;
6155 break;
6156 case glslang::EOpConvBoolToInt16:
6157 zero = builder.makeInt16Constant(0);
6158 one = builder.makeInt16Constant(1);
6159 convOp = spv::OpSelect;
6160 break;
6161 case glslang::EOpConvBoolToUint16:
6162 zero = builder.makeUint16Constant(0);
6163 one = builder.makeUint16Constant(1);
6164 convOp = spv::OpSelect;
6165 break;
6166 case glslang::EOpConvDoubleToFloat:
6167 case glslang::EOpConvFloatToDouble:
6168 case glslang::EOpConvDoubleToFloat16:
6169 case glslang::EOpConvFloat16ToDouble:
6170 case glslang::EOpConvFloatToFloat16:
6171 case glslang::EOpConvFloat16ToFloat:
6172 convOp = spv::OpFConvert;
6173 if (builder.isMatrixType(destType))
6174 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6175 break;
6176
John Kessenich66011cb2018-03-06 16:12:04 -07006177 case glslang::EOpConvInt8ToInt16:
6178 case glslang::EOpConvInt8ToInt:
6179 case glslang::EOpConvInt8ToInt64:
6180 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006181 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006182 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006183 case glslang::EOpConvIntToInt8:
6184 case glslang::EOpConvIntToInt16:
6185 case glslang::EOpConvIntToInt64:
6186 case glslang::EOpConvInt64ToInt8:
6187 case glslang::EOpConvInt64ToInt16:
6188 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006189 convOp = spv::OpSConvert;
6190 break;
6191
John Kessenich66011cb2018-03-06 16:12:04 -07006192 case glslang::EOpConvUint8ToUint16:
6193 case glslang::EOpConvUint8ToUint:
6194 case glslang::EOpConvUint8ToUint64:
6195 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006196 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006197 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006198 case glslang::EOpConvUintToUint8:
6199 case glslang::EOpConvUintToUint16:
6200 case glslang::EOpConvUintToUint64:
6201 case glslang::EOpConvUint64ToUint8:
6202 case glslang::EOpConvUint64ToUint16:
6203 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006204 convOp = spv::OpUConvert;
6205 break;
6206
John Kessenich66011cb2018-03-06 16:12:04 -07006207 case glslang::EOpConvInt8ToUint16:
6208 case glslang::EOpConvInt8ToUint:
6209 case glslang::EOpConvInt8ToUint64:
6210 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006211 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006212 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006213 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006214 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006215 case glslang::EOpConvIntToUint64:
6216 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006217 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006218 case glslang::EOpConvInt64ToUint:
6219 case glslang::EOpConvUint8ToInt16:
6220 case glslang::EOpConvUint8ToInt:
6221 case glslang::EOpConvUint8ToInt64:
6222 case glslang::EOpConvUint16ToInt8:
6223 case glslang::EOpConvUint16ToInt:
6224 case glslang::EOpConvUint16ToInt64:
6225 case glslang::EOpConvUintToInt8:
6226 case glslang::EOpConvUintToInt16:
6227 case glslang::EOpConvUintToInt64:
6228 case glslang::EOpConvUint64ToInt8:
6229 case glslang::EOpConvUint64ToInt16:
6230 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006231 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006232 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006233
6234 if (builder.isInSpecConstCodeGenMode()) {
6235 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006236 switch(op) {
6237 case glslang::EOpConvInt16ToUint8:
6238 case glslang::EOpConvIntToUint8:
6239 case glslang::EOpConvInt64ToUint8:
6240 case glslang::EOpConvUint16ToInt8:
6241 case glslang::EOpConvUintToInt8:
6242 case glslang::EOpConvUint64ToInt8:
6243 zero = builder.makeUint8Constant(0);
6244 break;
6245 case glslang::EOpConvInt8ToUint16:
6246 case glslang::EOpConvIntToUint16:
6247 case glslang::EOpConvInt64ToUint16:
6248 case glslang::EOpConvUint8ToInt16:
6249 case glslang::EOpConvUintToInt16:
6250 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006251 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006252 break;
6253 case glslang::EOpConvInt8ToUint:
6254 case glslang::EOpConvInt16ToUint:
6255 case glslang::EOpConvInt64ToUint:
6256 case glslang::EOpConvUint8ToInt:
6257 case glslang::EOpConvUint16ToInt:
6258 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006259 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006260 break;
6261 case glslang::EOpConvInt8ToUint64:
6262 case glslang::EOpConvInt16ToUint64:
6263 case glslang::EOpConvIntToUint64:
6264 case glslang::EOpConvUint8ToInt64:
6265 case glslang::EOpConvUint16ToInt64:
6266 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006267 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006268 break;
6269 default:
6270 assert(false && "Default missing");
6271 break;
6272 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006273 zero = makeSmearedConstant(zero, vectorSize);
6274 // Use OpIAdd, instead of OpBitcast to do the conversion when
6275 // generating for OpSpecConstantOp instruction.
6276 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6277 }
6278 // For normal run-time conversion instruction, use OpBitcast.
6279 convOp = spv::OpBitcast;
6280 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006281 case glslang::EOpConvUint64ToPtr:
6282 convOp = spv::OpConvertUToPtr;
6283 break;
6284 case glslang::EOpConvPtrToUint64:
6285 convOp = spv::OpConvertPtrToU;
6286 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006287 case glslang::EOpConvPtrToUvec2:
6288 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006289 if (builder.isVector(operand))
6290 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6291 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006292 convOp = spv::OpBitcast;
6293 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006294#endif
6295
John Kessenich140f3df2015-06-26 16:58:36 -06006296 default:
6297 break;
6298 }
6299
6300 spv::Id result = 0;
6301 if (convOp == spv::OpNop)
6302 return result;
6303
6304 if (convOp == spv::OpSelect) {
6305 zero = makeSmearedConstant(zero, vectorSize);
6306 one = makeSmearedConstant(one, vectorSize);
6307 result = builder.createTriOp(convOp, destType, operand, one, zero);
6308 } else
6309 result = builder.createUnaryOp(convOp, destType, operand);
6310
John Kessenichead86222018-03-28 18:01:20 -06006311 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006312 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006313 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006314}
6315
6316spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6317{
6318 if (vectorSize == 0)
6319 return constant;
6320
6321 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6322 std::vector<spv::Id> components;
6323 for (int c = 0; c < vectorSize; ++c)
6324 components.push_back(constant);
6325 return builder.makeCompositeConstant(vectorTypeId, components);
6326}
6327
John Kessenich426394d2015-07-23 10:22:48 -06006328// For glslang ops that map to SPV atomic opCodes
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006329spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006330{
6331 spv::Op opCode = spv::OpNop;
6332
6333 switch (op) {
6334 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006335 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006336 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006337 opCode = spv::OpAtomicIAdd;
6338 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006339 case glslang::EOpAtomicCounterSubtract:
6340 opCode = spv::OpAtomicISub;
6341 break;
John Kessenich426394d2015-07-23 10:22:48 -06006342 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006343 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006344 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006345 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006346 break;
6347 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006348 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006349 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006350 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006351 break;
6352 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006353 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006354 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006355 opCode = spv::OpAtomicAnd;
6356 break;
6357 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006358 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006359 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006360 opCode = spv::OpAtomicOr;
6361 break;
6362 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006363 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006364 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006365 opCode = spv::OpAtomicXor;
6366 break;
6367 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006368 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006369 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006370 opCode = spv::OpAtomicExchange;
6371 break;
6372 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006373 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006374 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006375 opCode = spv::OpAtomicCompareExchange;
6376 break;
6377 case glslang::EOpAtomicCounterIncrement:
6378 opCode = spv::OpAtomicIIncrement;
6379 break;
6380 case glslang::EOpAtomicCounterDecrement:
6381 opCode = spv::OpAtomicIDecrement;
6382 break;
6383 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006384 case glslang::EOpImageAtomicLoad:
6385 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006386 opCode = spv::OpAtomicLoad;
6387 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006388 case glslang::EOpAtomicStore:
6389 case glslang::EOpImageAtomicStore:
6390 opCode = spv::OpAtomicStore;
6391 break;
John Kessenich426394d2015-07-23 10:22:48 -06006392 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006393 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006394 break;
6395 }
6396
Rex Xue8fe8b02017-09-26 15:42:56 +08006397 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6398 builder.addCapability(spv::CapabilityInt64Atomics);
6399
John Kessenich426394d2015-07-23 10:22:48 -06006400 // Sort out the operands
6401 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006402 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006403 // - compare-exchange swaps the value and comparator
6404 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006405 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006406 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6407 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6408 spv::Id scopeId;
6409 if (glslangIntermediate->usingVulkanMemoryModel()) {
6410 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6411 } else {
6412 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6413 }
6414 // semantics default to relaxed
Jeff Bolz016ddee2019-10-17 11:22:57 -05006415 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() && glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006416 spv::MemorySemanticsVolatileMask :
6417 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006418 spv::Id semanticsId2 = semanticsId;
6419
6420 pointerId = operands[0];
6421 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6422 // no additional operands
6423 } else if (opCode == spv::OpAtomicCompareExchange) {
6424 compareId = operands[1];
6425 valueId = operands[2];
6426 if (operands.size() > 3) {
6427 scopeId = operands[3];
6428 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6429 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6430 }
6431 } else if (opCode == spv::OpAtomicLoad) {
6432 if (operands.size() > 1) {
6433 scopeId = operands[1];
6434 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6435 }
6436 } else {
6437 // atomic store or RMW
6438 valueId = operands[1];
6439 if (operands.size() > 2) {
6440 scopeId = operands[2];
6441 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6442 }
Rex Xu04db3f52015-09-16 11:44:02 +08006443 }
John Kessenich426394d2015-07-23 10:22:48 -06006444
Jeff Bolz36831c92018-09-05 10:11:41 -05006445 // Check for capabilities
6446 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006447 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6448 spv::MemorySemanticsMakeVisibleKHRMask |
6449 spv::MemorySemanticsOutputMemoryKHRMask |
6450 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006451 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6452 }
John Kessenich426394d2015-07-23 10:22:48 -06006453
Jeff Bolz36831c92018-09-05 10:11:41 -05006454 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6455 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6456 }
John Kessenich48d6e792017-10-06 21:21:48 -06006457
Jeff Bolz36831c92018-09-05 10:11:41 -05006458 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6459 spvAtomicOperands.push_back(pointerId);
6460 spvAtomicOperands.push_back(scopeId);
6461 spvAtomicOperands.push_back(semanticsId);
6462 if (opCode == spv::OpAtomicCompareExchange) {
6463 spvAtomicOperands.push_back(semanticsId2);
6464 spvAtomicOperands.push_back(valueId);
6465 spvAtomicOperands.push_back(compareId);
6466 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6467 spvAtomicOperands.push_back(valueId);
6468 }
John Kessenich48d6e792017-10-06 21:21:48 -06006469
Jeff Bolz36831c92018-09-05 10:11:41 -05006470 if (opCode == spv::OpAtomicStore) {
6471 builder.createNoResultOp(opCode, spvAtomicOperands);
6472 return 0;
6473 } else {
6474 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6475
6476 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6477 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6478 if (op == glslang::EOpAtomicCounterDecrement)
6479 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6480
6481 return resultId;
6482 }
John Kessenich426394d2015-07-23 10:22:48 -06006483}
6484
John Kessenich91cef522016-05-05 16:45:40 -06006485// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006486spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006487{
John Kessenich66011cb2018-03-06 16:12:04 -07006488 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6489 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006490
Rex Xu51596642016-09-21 18:56:12 +08006491 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006492 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006493 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6494
chaocf200da82016-12-20 12:44:35 -08006495 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6496 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006497 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6498 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006499 } else if (op == glslang::EOpAnyInvocation ||
6500 op == glslang::EOpAllInvocations ||
6501 op == glslang::EOpAllInvocationsEqual) {
6502 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6503 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006504 } else {
6505 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006506 if (op == glslang::EOpMinInvocationsNonUniform ||
6507 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006508 op == glslang::EOpAddInvocationsNonUniform ||
6509 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6510 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6511 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6512 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6513 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6514 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006515 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006516
Rex Xu430ef402016-10-14 17:22:23 +08006517 switch (op) {
6518 case glslang::EOpMinInvocations:
6519 case glslang::EOpMaxInvocations:
6520 case glslang::EOpAddInvocations:
6521 case glslang::EOpMinInvocationsNonUniform:
6522 case glslang::EOpMaxInvocationsNonUniform:
6523 case glslang::EOpAddInvocationsNonUniform:
6524 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006525 break;
6526 case glslang::EOpMinInvocationsInclusiveScan:
6527 case glslang::EOpMaxInvocationsInclusiveScan:
6528 case glslang::EOpAddInvocationsInclusiveScan:
6529 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6530 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6531 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6532 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006533 break;
6534 case glslang::EOpMinInvocationsExclusiveScan:
6535 case glslang::EOpMaxInvocationsExclusiveScan:
6536 case glslang::EOpAddInvocationsExclusiveScan:
6537 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6538 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6539 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6540 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006541 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006542 default:
6543 break;
Rex Xu430ef402016-10-14 17:22:23 +08006544 }
John Kessenich149afc32018-08-14 13:31:43 -06006545 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6546 spvGroupOperands.push_back(scope);
6547 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006548 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006549 spvGroupOperands.push_back(groupOp);
6550 }
Rex Xu51596642016-09-21 18:56:12 +08006551 }
6552
John Kessenich149afc32018-08-14 13:31:43 -06006553 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6554 spv::IdImmediate op = { true, *opIt };
6555 spvGroupOperands.push_back(op);
6556 }
John Kessenich91cef522016-05-05 16:45:40 -06006557
6558 switch (op) {
6559 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006560 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006561 break;
John Kessenich91cef522016-05-05 16:45:40 -06006562 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006563 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006564 break;
John Kessenich91cef522016-05-05 16:45:40 -06006565 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006566 opCode = spv::OpSubgroupAllEqualKHR;
6567 break;
Rex Xu51596642016-09-21 18:56:12 +08006568 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006569 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006570 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006571 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006572 break;
6573 case glslang::EOpReadFirstInvocation:
6574 opCode = spv::OpSubgroupFirstInvocationKHR;
6575 break;
6576 case glslang::EOpBallot:
6577 {
6578 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6579 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6580 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6581 //
6582 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6583 //
6584 spv::Id uintType = builder.makeUintType(32);
6585 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6586 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6587
6588 std::vector<spv::Id> components;
6589 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6590 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6591
6592 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6593 return builder.createUnaryOp(spv::OpBitcast, typeId,
6594 builder.createCompositeConstruct(uvec2Type, components));
6595 }
6596
Rex Xu9d93a232016-05-05 12:30:44 +08006597 case glslang::EOpMinInvocations:
6598 case glslang::EOpMaxInvocations:
6599 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006600 case glslang::EOpMinInvocationsInclusiveScan:
6601 case glslang::EOpMaxInvocationsInclusiveScan:
6602 case glslang::EOpAddInvocationsInclusiveScan:
6603 case glslang::EOpMinInvocationsExclusiveScan:
6604 case glslang::EOpMaxInvocationsExclusiveScan:
6605 case glslang::EOpAddInvocationsExclusiveScan:
6606 if (op == glslang::EOpMinInvocations ||
6607 op == glslang::EOpMinInvocationsInclusiveScan ||
6608 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006609 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006610 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006611 else {
6612 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006613 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006614 else
Rex Xu51596642016-09-21 18:56:12 +08006615 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006616 }
Rex Xu430ef402016-10-14 17:22:23 +08006617 } else if (op == glslang::EOpMaxInvocations ||
6618 op == glslang::EOpMaxInvocationsInclusiveScan ||
6619 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006620 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006621 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006622 else {
6623 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006624 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006625 else
Rex Xu51596642016-09-21 18:56:12 +08006626 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006627 }
6628 } else {
6629 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006630 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006631 else
Rex Xu51596642016-09-21 18:56:12 +08006632 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006633 }
6634
Rex Xu2bbbe062016-08-23 15:41:05 +08006635 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006636 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006637
6638 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006639 case glslang::EOpMinInvocationsNonUniform:
6640 case glslang::EOpMaxInvocationsNonUniform:
6641 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006642 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6643 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6644 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6645 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6646 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6647 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6648 if (op == glslang::EOpMinInvocationsNonUniform ||
6649 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6650 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006651 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006652 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006653 else {
6654 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006655 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006656 else
Rex Xu51596642016-09-21 18:56:12 +08006657 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006658 }
6659 }
Rex Xu430ef402016-10-14 17:22:23 +08006660 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6661 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6662 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006663 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006664 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006665 else {
6666 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006667 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006668 else
Rex Xu51596642016-09-21 18:56:12 +08006669 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006670 }
6671 }
6672 else {
6673 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006674 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006675 else
Rex Xu51596642016-09-21 18:56:12 +08006676 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006677 }
6678
Rex Xu2bbbe062016-08-23 15:41:05 +08006679 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006680 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006681
6682 break;
John Kessenich91cef522016-05-05 16:45:40 -06006683 default:
6684 logger->missingFunctionality("invocation operation");
6685 return spv::NoResult;
6686 }
Rex Xu51596642016-09-21 18:56:12 +08006687
6688 assert(opCode != spv::OpNop);
6689 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006690}
6691
Rex Xu2bbbe062016-08-23 15:41:05 +08006692// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006693spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6694 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006695{
6696 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6697 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006698 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006699 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006700 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6701 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6702 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
6703
6704 // Handle group invocation operations scalar by scalar.
6705 // The result type is the same type as the original type.
6706 // The algorithm is to:
6707 // - break the vector into scalars
6708 // - apply the operation to each scalar
6709 // - make a vector out the scalar results
6710
6711 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006712 int numComponents = builder.getNumComponents(operands[0]);
6713 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006714 std::vector<spv::Id> results;
6715
6716 // do each scalar op
6717 for (int comp = 0; comp < numComponents; ++comp) {
6718 std::vector<unsigned int> indexes;
6719 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006720 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6721 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006722 if (op == spv::OpSubgroupReadInvocationKHR) {
6723 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006724 spv::IdImmediate operand = { true, operands[1] };
6725 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006726 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006727 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6728 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006729 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006730 spv::IdImmediate operand = { true, operands[1] };
6731 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006732 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006733 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6734 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006735 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006736 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006737 spvGroupOperands.push_back(scalar);
6738 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006739
Rex Xub7072052016-09-26 15:53:40 +08006740 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006741 }
6742
6743 // put the pieces together
6744 return builder.createCompositeConstruct(typeId, results);
6745}
Rex Xu2bbbe062016-08-23 15:41:05 +08006746
John Kessenich66011cb2018-03-06 16:12:04 -07006747// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006748spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6749 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006750{
6751 // Add the required capabilities.
6752 switch (op) {
6753 case glslang::EOpSubgroupElect:
6754 builder.addCapability(spv::CapabilityGroupNonUniform);
6755 break;
6756 case glslang::EOpSubgroupAll:
6757 case glslang::EOpSubgroupAny:
6758 case glslang::EOpSubgroupAllEqual:
6759 builder.addCapability(spv::CapabilityGroupNonUniform);
6760 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6761 break;
6762 case glslang::EOpSubgroupBroadcast:
6763 case glslang::EOpSubgroupBroadcastFirst:
6764 case glslang::EOpSubgroupBallot:
6765 case glslang::EOpSubgroupInverseBallot:
6766 case glslang::EOpSubgroupBallotBitExtract:
6767 case glslang::EOpSubgroupBallotBitCount:
6768 case glslang::EOpSubgroupBallotInclusiveBitCount:
6769 case glslang::EOpSubgroupBallotExclusiveBitCount:
6770 case glslang::EOpSubgroupBallotFindLSB:
6771 case glslang::EOpSubgroupBallotFindMSB:
6772 builder.addCapability(spv::CapabilityGroupNonUniform);
6773 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6774 break;
6775 case glslang::EOpSubgroupShuffle:
6776 case glslang::EOpSubgroupShuffleXor:
6777 builder.addCapability(spv::CapabilityGroupNonUniform);
6778 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6779 break;
6780 case glslang::EOpSubgroupShuffleUp:
6781 case glslang::EOpSubgroupShuffleDown:
6782 builder.addCapability(spv::CapabilityGroupNonUniform);
6783 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6784 break;
6785 case glslang::EOpSubgroupAdd:
6786 case glslang::EOpSubgroupMul:
6787 case glslang::EOpSubgroupMin:
6788 case glslang::EOpSubgroupMax:
6789 case glslang::EOpSubgroupAnd:
6790 case glslang::EOpSubgroupOr:
6791 case glslang::EOpSubgroupXor:
6792 case glslang::EOpSubgroupInclusiveAdd:
6793 case glslang::EOpSubgroupInclusiveMul:
6794 case glslang::EOpSubgroupInclusiveMin:
6795 case glslang::EOpSubgroupInclusiveMax:
6796 case glslang::EOpSubgroupInclusiveAnd:
6797 case glslang::EOpSubgroupInclusiveOr:
6798 case glslang::EOpSubgroupInclusiveXor:
6799 case glslang::EOpSubgroupExclusiveAdd:
6800 case glslang::EOpSubgroupExclusiveMul:
6801 case glslang::EOpSubgroupExclusiveMin:
6802 case glslang::EOpSubgroupExclusiveMax:
6803 case glslang::EOpSubgroupExclusiveAnd:
6804 case glslang::EOpSubgroupExclusiveOr:
6805 case glslang::EOpSubgroupExclusiveXor:
6806 builder.addCapability(spv::CapabilityGroupNonUniform);
6807 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6808 break;
6809 case glslang::EOpSubgroupClusteredAdd:
6810 case glslang::EOpSubgroupClusteredMul:
6811 case glslang::EOpSubgroupClusteredMin:
6812 case glslang::EOpSubgroupClusteredMax:
6813 case glslang::EOpSubgroupClusteredAnd:
6814 case glslang::EOpSubgroupClusteredOr:
6815 case glslang::EOpSubgroupClusteredXor:
6816 builder.addCapability(spv::CapabilityGroupNonUniform);
6817 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6818 break;
6819 case glslang::EOpSubgroupQuadBroadcast:
6820 case glslang::EOpSubgroupQuadSwapHorizontal:
6821 case glslang::EOpSubgroupQuadSwapVertical:
6822 case glslang::EOpSubgroupQuadSwapDiagonal:
6823 builder.addCapability(spv::CapabilityGroupNonUniform);
6824 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6825 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006826 case glslang::EOpSubgroupPartitionedAdd:
6827 case glslang::EOpSubgroupPartitionedMul:
6828 case glslang::EOpSubgroupPartitionedMin:
6829 case glslang::EOpSubgroupPartitionedMax:
6830 case glslang::EOpSubgroupPartitionedAnd:
6831 case glslang::EOpSubgroupPartitionedOr:
6832 case glslang::EOpSubgroupPartitionedXor:
6833 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6834 case glslang::EOpSubgroupPartitionedInclusiveMul:
6835 case glslang::EOpSubgroupPartitionedInclusiveMin:
6836 case glslang::EOpSubgroupPartitionedInclusiveMax:
6837 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6838 case glslang::EOpSubgroupPartitionedInclusiveOr:
6839 case glslang::EOpSubgroupPartitionedInclusiveXor:
6840 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6841 case glslang::EOpSubgroupPartitionedExclusiveMul:
6842 case glslang::EOpSubgroupPartitionedExclusiveMin:
6843 case glslang::EOpSubgroupPartitionedExclusiveMax:
6844 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6845 case glslang::EOpSubgroupPartitionedExclusiveOr:
6846 case glslang::EOpSubgroupPartitionedExclusiveXor:
6847 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6848 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6849 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006850 default: assert(0 && "Unhandled subgroup operation!");
6851 }
6852
Jeff Bolzc5b669e2019-09-08 08:49:18 -05006853
6854 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
6855 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07006856 const bool isBool = typeProxy == glslang::EbtBool;
6857
6858 spv::Op opCode = spv::OpNop;
6859
6860 // Figure out which opcode to use.
6861 switch (op) {
6862 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6863 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6864 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6865 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6866 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6867 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6868 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6869 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6870 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6871 case glslang::EOpSubgroupBallotBitCount:
6872 case glslang::EOpSubgroupBallotInclusiveBitCount:
6873 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6874 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6875 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6876 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6877 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6878 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6879 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6880 case glslang::EOpSubgroupAdd:
6881 case glslang::EOpSubgroupInclusiveAdd:
6882 case glslang::EOpSubgroupExclusiveAdd:
6883 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006884 case glslang::EOpSubgroupPartitionedAdd:
6885 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6886 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07006887 if (isFloat) {
6888 opCode = spv::OpGroupNonUniformFAdd;
6889 } else {
6890 opCode = spv::OpGroupNonUniformIAdd;
6891 }
6892 break;
6893 case glslang::EOpSubgroupMul:
6894 case glslang::EOpSubgroupInclusiveMul:
6895 case glslang::EOpSubgroupExclusiveMul:
6896 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006897 case glslang::EOpSubgroupPartitionedMul:
6898 case glslang::EOpSubgroupPartitionedInclusiveMul:
6899 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07006900 if (isFloat) {
6901 opCode = spv::OpGroupNonUniformFMul;
6902 } else {
6903 opCode = spv::OpGroupNonUniformIMul;
6904 }
6905 break;
6906 case glslang::EOpSubgroupMin:
6907 case glslang::EOpSubgroupInclusiveMin:
6908 case glslang::EOpSubgroupExclusiveMin:
6909 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006910 case glslang::EOpSubgroupPartitionedMin:
6911 case glslang::EOpSubgroupPartitionedInclusiveMin:
6912 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07006913 if (isFloat) {
6914 opCode = spv::OpGroupNonUniformFMin;
6915 } else if (isUnsigned) {
6916 opCode = spv::OpGroupNonUniformUMin;
6917 } else {
6918 opCode = spv::OpGroupNonUniformSMin;
6919 }
6920 break;
6921 case glslang::EOpSubgroupMax:
6922 case glslang::EOpSubgroupInclusiveMax:
6923 case glslang::EOpSubgroupExclusiveMax:
6924 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006925 case glslang::EOpSubgroupPartitionedMax:
6926 case glslang::EOpSubgroupPartitionedInclusiveMax:
6927 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07006928 if (isFloat) {
6929 opCode = spv::OpGroupNonUniformFMax;
6930 } else if (isUnsigned) {
6931 opCode = spv::OpGroupNonUniformUMax;
6932 } else {
6933 opCode = spv::OpGroupNonUniformSMax;
6934 }
6935 break;
6936 case glslang::EOpSubgroupAnd:
6937 case glslang::EOpSubgroupInclusiveAnd:
6938 case glslang::EOpSubgroupExclusiveAnd:
6939 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006940 case glslang::EOpSubgroupPartitionedAnd:
6941 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6942 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07006943 if (isBool) {
6944 opCode = spv::OpGroupNonUniformLogicalAnd;
6945 } else {
6946 opCode = spv::OpGroupNonUniformBitwiseAnd;
6947 }
6948 break;
6949 case glslang::EOpSubgroupOr:
6950 case glslang::EOpSubgroupInclusiveOr:
6951 case glslang::EOpSubgroupExclusiveOr:
6952 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006953 case glslang::EOpSubgroupPartitionedOr:
6954 case glslang::EOpSubgroupPartitionedInclusiveOr:
6955 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07006956 if (isBool) {
6957 opCode = spv::OpGroupNonUniformLogicalOr;
6958 } else {
6959 opCode = spv::OpGroupNonUniformBitwiseOr;
6960 }
6961 break;
6962 case glslang::EOpSubgroupXor:
6963 case glslang::EOpSubgroupInclusiveXor:
6964 case glslang::EOpSubgroupExclusiveXor:
6965 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006966 case glslang::EOpSubgroupPartitionedXor:
6967 case glslang::EOpSubgroupPartitionedInclusiveXor:
6968 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07006969 if (isBool) {
6970 opCode = spv::OpGroupNonUniformLogicalXor;
6971 } else {
6972 opCode = spv::OpGroupNonUniformBitwiseXor;
6973 }
6974 break;
6975 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6976 case glslang::EOpSubgroupQuadSwapHorizontal:
6977 case glslang::EOpSubgroupQuadSwapVertical:
6978 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6979 default: assert(0 && "Unhandled subgroup operation!");
6980 }
6981
John Kessenich149afc32018-08-14 13:31:43 -06006982 // get the right Group Operation
6983 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006984 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006985 default:
6986 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006987 case glslang::EOpSubgroupBallotBitCount:
6988 case glslang::EOpSubgroupAdd:
6989 case glslang::EOpSubgroupMul:
6990 case glslang::EOpSubgroupMin:
6991 case glslang::EOpSubgroupMax:
6992 case glslang::EOpSubgroupAnd:
6993 case glslang::EOpSubgroupOr:
6994 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006995 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006996 break;
6997 case glslang::EOpSubgroupBallotInclusiveBitCount:
6998 case glslang::EOpSubgroupInclusiveAdd:
6999 case glslang::EOpSubgroupInclusiveMul:
7000 case glslang::EOpSubgroupInclusiveMin:
7001 case glslang::EOpSubgroupInclusiveMax:
7002 case glslang::EOpSubgroupInclusiveAnd:
7003 case glslang::EOpSubgroupInclusiveOr:
7004 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007005 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007006 break;
7007 case glslang::EOpSubgroupBallotExclusiveBitCount:
7008 case glslang::EOpSubgroupExclusiveAdd:
7009 case glslang::EOpSubgroupExclusiveMul:
7010 case glslang::EOpSubgroupExclusiveMin:
7011 case glslang::EOpSubgroupExclusiveMax:
7012 case glslang::EOpSubgroupExclusiveAnd:
7013 case glslang::EOpSubgroupExclusiveOr:
7014 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007015 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007016 break;
7017 case glslang::EOpSubgroupClusteredAdd:
7018 case glslang::EOpSubgroupClusteredMul:
7019 case glslang::EOpSubgroupClusteredMin:
7020 case glslang::EOpSubgroupClusteredMax:
7021 case glslang::EOpSubgroupClusteredAnd:
7022 case glslang::EOpSubgroupClusteredOr:
7023 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007024 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007025 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007026 case glslang::EOpSubgroupPartitionedAdd:
7027 case glslang::EOpSubgroupPartitionedMul:
7028 case glslang::EOpSubgroupPartitionedMin:
7029 case glslang::EOpSubgroupPartitionedMax:
7030 case glslang::EOpSubgroupPartitionedAnd:
7031 case glslang::EOpSubgroupPartitionedOr:
7032 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007033 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007034 break;
7035 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7036 case glslang::EOpSubgroupPartitionedInclusiveMul:
7037 case glslang::EOpSubgroupPartitionedInclusiveMin:
7038 case glslang::EOpSubgroupPartitionedInclusiveMax:
7039 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7040 case glslang::EOpSubgroupPartitionedInclusiveOr:
7041 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007042 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007043 break;
7044 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7045 case glslang::EOpSubgroupPartitionedExclusiveMul:
7046 case glslang::EOpSubgroupPartitionedExclusiveMin:
7047 case glslang::EOpSubgroupPartitionedExclusiveMax:
7048 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7049 case glslang::EOpSubgroupPartitionedExclusiveOr:
7050 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007051 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007052 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007053 }
7054
John Kessenich149afc32018-08-14 13:31:43 -06007055 // build the instruction
7056 std::vector<spv::IdImmediate> spvGroupOperands;
7057
7058 // Every operation begins with the Execution Scope operand.
7059 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7060 spvGroupOperands.push_back(executionScope);
7061
7062 // Next, for all operations that use a Group Operation, push that as an operand.
7063 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007064 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007065 spvGroupOperands.push_back(groupOperand);
7066 }
7067
John Kessenich66011cb2018-03-06 16:12:04 -07007068 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007069 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7070 spv::IdImmediate operand = { true, *opIt };
7071 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007072 }
7073
7074 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007075 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007076 switch (op) {
7077 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007078 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7079 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7080 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7081 }
7082 if (directionId != spv::NoResult) {
7083 spv::IdImmediate direction = { true, directionId };
7084 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007085 }
7086
7087 return builder.createOp(opCode, typeId, spvGroupOperands);
7088}
7089
John Kessenich5e4b1242015-08-06 22:53:06 -06007090spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007091{
John Kessenich66011cb2018-03-06 16:12:04 -07007092 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7093 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007094
John Kessenich140f3df2015-06-26 16:58:36 -06007095 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007096 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007097 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007098 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007099 spv::Id typeId0 = 0;
7100 if (consumedOperands > 0)
7101 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007102 spv::Id typeId1 = 0;
7103 if (consumedOperands > 1)
7104 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007105 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007106
7107 switch (op) {
7108 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007109 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007110 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007111 else if (isUnsigned)
7112 libCall = spv::GLSLstd450UMin;
7113 else
7114 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007115 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007116 break;
7117 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007118 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007119 break;
7120 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007121 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007122 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007123 else if (isUnsigned)
7124 libCall = spv::GLSLstd450UMax;
7125 else
7126 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007127 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007128 break;
7129 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007130 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007131 break;
7132 case glslang::EOpDot:
7133 opCode = spv::OpDot;
7134 break;
7135 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007136 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007137 break;
7138
7139 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007140 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007141 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007142 else if (isUnsigned)
7143 libCall = spv::GLSLstd450UClamp;
7144 else
7145 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007146 builder.promoteScalar(precision, operands.front(), operands[1]);
7147 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007148 break;
7149 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007150 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7151 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007152 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007153 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007154 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007155 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007156 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007157 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007158 break;
7159 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007160 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007161 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007162 break;
7163 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007164 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007165 builder.promoteScalar(precision, operands[0], operands[2]);
7166 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007167 break;
7168
7169 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007170 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007171 break;
7172 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007173 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007174 break;
7175 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007176 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007177 break;
7178 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007179 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007180 break;
7181 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007182 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007183 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007184 case glslang::EOpBarrier:
7185 {
7186 // This is for the extended controlBarrier function, with four operands.
7187 // The unextended barrier() goes through createNoArgOperation.
7188 assert(operands.size() == 4);
7189 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7190 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7191 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7192 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7193 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7194 spv::MemorySemanticsMakeVisibleKHRMask |
7195 spv::MemorySemanticsOutputMemoryKHRMask |
7196 spv::MemorySemanticsVolatileMask)) {
7197 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7198 }
7199 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7200 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7201 }
7202 return 0;
7203 }
7204 break;
7205 case glslang::EOpMemoryBarrier:
7206 {
7207 // This is for the extended memoryBarrier function, with three operands.
7208 // The unextended memoryBarrier() goes through createNoArgOperation.
7209 assert(operands.size() == 3);
7210 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7211 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7212 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7213 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7214 spv::MemorySemanticsMakeVisibleKHRMask |
7215 spv::MemorySemanticsOutputMemoryKHRMask |
7216 spv::MemorySemanticsVolatileMask)) {
7217 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7218 }
7219 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7220 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7221 }
7222 return 0;
7223 }
7224 break;
7225
John Kessenicha28f7a72019-08-06 07:00:58 -06007226#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007227 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007228 if (typeProxy == glslang::EbtFloat16)
7229 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007230 libCall = spv::GLSLstd450InterpolateAtSample;
7231 break;
7232 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007233 if (typeProxy == glslang::EbtFloat16)
7234 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007235 libCall = spv::GLSLstd450InterpolateAtOffset;
7236 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007237 case glslang::EOpAddCarry:
7238 opCode = spv::OpIAddCarry;
7239 typeId = builder.makeStructResultType(typeId0, typeId0);
7240 consumedOperands = 2;
7241 break;
7242 case glslang::EOpSubBorrow:
7243 opCode = spv::OpISubBorrow;
7244 typeId = builder.makeStructResultType(typeId0, typeId0);
7245 consumedOperands = 2;
7246 break;
7247 case glslang::EOpUMulExtended:
7248 opCode = spv::OpUMulExtended;
7249 typeId = builder.makeStructResultType(typeId0, typeId0);
7250 consumedOperands = 2;
7251 break;
7252 case glslang::EOpIMulExtended:
7253 opCode = spv::OpSMulExtended;
7254 typeId = builder.makeStructResultType(typeId0, typeId0);
7255 consumedOperands = 2;
7256 break;
7257 case glslang::EOpBitfieldExtract:
7258 if (isUnsigned)
7259 opCode = spv::OpBitFieldUExtract;
7260 else
7261 opCode = spv::OpBitFieldSExtract;
7262 break;
7263 case glslang::EOpBitfieldInsert:
7264 opCode = spv::OpBitFieldInsert;
7265 break;
7266
7267 case glslang::EOpFma:
7268 libCall = spv::GLSLstd450Fma;
7269 break;
7270 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007271 {
7272 libCall = spv::GLSLstd450FrexpStruct;
7273 assert(builder.isPointerType(typeId1));
7274 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007275 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007276 if (width == 16)
7277 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7278 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007279 if (builder.getNumComponents(operands[0]) == 1)
7280 frexpIntType = builder.makeIntegerType(width, true);
7281 else
7282 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7283 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7284 consumedOperands = 1;
7285 }
John Kessenich55e7d112015-11-15 21:33:39 -07007286 break;
7287 case glslang::EOpLdexp:
7288 libCall = spv::GLSLstd450Ldexp;
7289 break;
7290
Rex Xu574ab042016-04-14 16:53:07 +08007291 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007292 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007293
John Kessenich66011cb2018-03-06 16:12:04 -07007294 case glslang::EOpSubgroupBroadcast:
7295 case glslang::EOpSubgroupBallotBitExtract:
7296 case glslang::EOpSubgroupShuffle:
7297 case glslang::EOpSubgroupShuffleXor:
7298 case glslang::EOpSubgroupShuffleUp:
7299 case glslang::EOpSubgroupShuffleDown:
7300 case glslang::EOpSubgroupClusteredAdd:
7301 case glslang::EOpSubgroupClusteredMul:
7302 case glslang::EOpSubgroupClusteredMin:
7303 case glslang::EOpSubgroupClusteredMax:
7304 case glslang::EOpSubgroupClusteredAnd:
7305 case glslang::EOpSubgroupClusteredOr:
7306 case glslang::EOpSubgroupClusteredXor:
7307 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007308 case glslang::EOpSubgroupPartitionedAdd:
7309 case glslang::EOpSubgroupPartitionedMul:
7310 case glslang::EOpSubgroupPartitionedMin:
7311 case glslang::EOpSubgroupPartitionedMax:
7312 case glslang::EOpSubgroupPartitionedAnd:
7313 case glslang::EOpSubgroupPartitionedOr:
7314 case glslang::EOpSubgroupPartitionedXor:
7315 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7316 case glslang::EOpSubgroupPartitionedInclusiveMul:
7317 case glslang::EOpSubgroupPartitionedInclusiveMin:
7318 case glslang::EOpSubgroupPartitionedInclusiveMax:
7319 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7320 case glslang::EOpSubgroupPartitionedInclusiveOr:
7321 case glslang::EOpSubgroupPartitionedInclusiveXor:
7322 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7323 case glslang::EOpSubgroupPartitionedExclusiveMul:
7324 case glslang::EOpSubgroupPartitionedExclusiveMin:
7325 case glslang::EOpSubgroupPartitionedExclusiveMax:
7326 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7327 case glslang::EOpSubgroupPartitionedExclusiveOr:
7328 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007329 return createSubgroupOperation(op, typeId, operands, typeProxy);
7330
Rex Xu9d93a232016-05-05 12:30:44 +08007331 case glslang::EOpSwizzleInvocations:
7332 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7333 libCall = spv::SwizzleInvocationsAMD;
7334 break;
7335 case glslang::EOpSwizzleInvocationsMasked:
7336 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7337 libCall = spv::SwizzleInvocationsMaskedAMD;
7338 break;
7339 case glslang::EOpWriteInvocation:
7340 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7341 libCall = spv::WriteInvocationAMD;
7342 break;
7343
7344 case glslang::EOpMin3:
7345 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7346 if (isFloat)
7347 libCall = spv::FMin3AMD;
7348 else {
7349 if (isUnsigned)
7350 libCall = spv::UMin3AMD;
7351 else
7352 libCall = spv::SMin3AMD;
7353 }
7354 break;
7355 case glslang::EOpMax3:
7356 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7357 if (isFloat)
7358 libCall = spv::FMax3AMD;
7359 else {
7360 if (isUnsigned)
7361 libCall = spv::UMax3AMD;
7362 else
7363 libCall = spv::SMax3AMD;
7364 }
7365 break;
7366 case glslang::EOpMid3:
7367 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7368 if (isFloat)
7369 libCall = spv::FMid3AMD;
7370 else {
7371 if (isUnsigned)
7372 libCall = spv::UMid3AMD;
7373 else
7374 libCall = spv::SMid3AMD;
7375 }
7376 break;
7377
7378 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007379 if (typeProxy == glslang::EbtFloat16)
7380 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007381 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7382 libCall = spv::InterpolateAtVertexAMD;
7383 break;
Chao Chen3c366992018-09-19 11:41:59 -07007384
Chao Chenb50c02e2018-09-19 11:42:24 -07007385 case glslang::EOpReportIntersectionNV:
7386 {
7387 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007388 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007389 }
7390 break;
7391 case glslang::EOpTraceNV:
7392 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007393 builder.createNoResultOp(spv::OpTraceNV, operands);
7394 return 0;
7395 }
7396 break;
7397 case glslang::EOpExecuteCallableNV:
7398 {
7399 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007400 return 0;
7401 }
7402 break;
Chao Chen3c366992018-09-19 11:41:59 -07007403 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7404 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7405 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007406 case glslang::EOpCooperativeMatrixMulAdd:
7407 opCode = spv::OpCooperativeMatrixMulAddNV;
7408 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007409#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007410 default:
7411 return 0;
7412 }
7413
7414 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007415 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007416 // Use an extended instruction from the standard library.
7417 // Construct the call arguments, without modifying the original operands vector.
7418 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7419 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007420 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007421 } else if (opCode == spv::OpDot && !isFloat) {
7422 // int dot(int, int)
7423 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7424 const int componentCount = builder.getNumComponents(operands[0]);
7425 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7426 builder.setPrecision(mulOp, precision);
7427 id = builder.createCompositeExtract(mulOp, typeId, 0);
7428 for (int i = 1; i < componentCount; ++i) {
7429 builder.setPrecision(id, precision);
7430 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7431 }
John Kessenich2359bd02015-12-06 19:29:11 -07007432 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007433 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007434 case 0:
7435 // should all be handled by visitAggregate and createNoArgOperation
7436 assert(0);
7437 return 0;
7438 case 1:
7439 // should all be handled by createUnaryOperation
7440 assert(0);
7441 return 0;
7442 case 2:
7443 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7444 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007445 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007446 // anything 3 or over doesn't have l-value operands, so all should be consumed
7447 assert(consumedOperands == operands.size());
7448 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007449 break;
7450 }
7451 }
7452
John Kessenichb9197c82019-08-11 07:41:45 -06007453#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007454 // Decode the return types that were structures
7455 switch (op) {
7456 case glslang::EOpAddCarry:
7457 case glslang::EOpSubBorrow:
7458 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7459 id = builder.createCompositeExtract(id, typeId0, 0);
7460 break;
7461 case glslang::EOpUMulExtended:
7462 case glslang::EOpIMulExtended:
7463 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7464 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7465 break;
7466 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007467 {
7468 assert(operands.size() == 2);
7469 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7470 // "exp" is floating-point type (from HLSL intrinsic)
7471 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7472 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7473 builder.createStore(member1, operands[1]);
7474 } else
7475 // "exp" is integer type (from GLSL built-in function)
7476 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7477 id = builder.createCompositeExtract(id, typeId0, 0);
7478 }
John Kessenich55e7d112015-11-15 21:33:39 -07007479 break;
7480 default:
7481 break;
7482 }
John Kessenichb9197c82019-08-11 07:41:45 -06007483#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007484
John Kessenich32cfd492016-02-02 12:37:46 -07007485 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007486}
7487
Rex Xu9d93a232016-05-05 12:30:44 +08007488// Intrinsics with no arguments (or no return value, and no precision).
7489spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007490{
Jeff Bolz36831c92018-09-05 10:11:41 -05007491 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7492 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007493
7494 switch (op) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007495#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007496 case glslang::EOpEmitVertex:
7497 builder.createNoResultOp(spv::OpEmitVertex);
7498 return 0;
7499 case glslang::EOpEndPrimitive:
7500 builder.createNoResultOp(spv::OpEndPrimitive);
7501 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007502#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007503 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007504 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007505 if (glslangIntermediate->usingVulkanMemoryModel()) {
7506 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7507 spv::MemorySemanticsOutputMemoryKHRMask |
7508 spv::MemorySemanticsAcquireReleaseMask);
7509 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7510 } else {
7511 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7512 }
John Kessenich82979362017-12-11 04:02:24 -07007513 } else {
7514 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7515 spv::MemorySemanticsWorkgroupMemoryMask |
7516 spv::MemorySemanticsAcquireReleaseMask);
7517 }
John Kessenich140f3df2015-06-26 16:58:36 -06007518 return 0;
7519 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007520 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7521 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007522 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007523 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007524 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7525 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007526 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007527 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007528 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7529 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007530 return 0;
7531 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007532 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7533 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007534 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007535#ifndef GLSLANG_WEB
7536 case glslang::EOpMemoryBarrierAtomicCounter:
7537 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7538 spv::MemorySemanticsAcquireReleaseMask);
7539 return 0;
7540 case glslang::EOpMemoryBarrierImage:
7541 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7542 spv::MemorySemanticsAcquireReleaseMask);
7543 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007544 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007545 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007546 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007547 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007548 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007549 case glslang::EOpDeviceMemoryBarrier:
7550 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7551 spv::MemorySemanticsImageMemoryMask |
7552 spv::MemorySemanticsAcquireReleaseMask);
7553 return 0;
7554 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7555 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7556 spv::MemorySemanticsImageMemoryMask |
7557 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007558 return 0;
7559 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007560 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7561 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007562 return 0;
7563 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007564 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7565 spv::MemorySemanticsWorkgroupMemoryMask |
7566 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007567 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007568 case glslang::EOpSubgroupBarrier:
7569 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7570 spv::MemorySemanticsAcquireReleaseMask);
7571 return spv::NoResult;
7572 case glslang::EOpSubgroupMemoryBarrier:
7573 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7574 spv::MemorySemanticsAcquireReleaseMask);
7575 return spv::NoResult;
7576 case glslang::EOpSubgroupMemoryBarrierBuffer:
7577 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7578 spv::MemorySemanticsAcquireReleaseMask);
7579 return spv::NoResult;
7580 case glslang::EOpSubgroupMemoryBarrierImage:
7581 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7582 spv::MemorySemanticsAcquireReleaseMask);
7583 return spv::NoResult;
7584 case glslang::EOpSubgroupMemoryBarrierShared:
7585 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7586 spv::MemorySemanticsAcquireReleaseMask);
7587 return spv::NoResult;
7588 case glslang::EOpSubgroupElect: {
7589 std::vector<spv::Id> operands;
7590 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7591 }
Rex Xu9d93a232016-05-05 12:30:44 +08007592 case glslang::EOpTime:
7593 {
7594 std::vector<spv::Id> args; // Dummy arguments
7595 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7596 return builder.setPrecision(id, precision);
7597 }
Chao Chenb50c02e2018-09-19 11:42:24 -07007598 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007599 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007600 return 0;
7601 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007602 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007603 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05007604
7605 case glslang::EOpBeginInvocationInterlock:
7606 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
7607 return 0;
7608 case glslang::EOpEndInvocationInterlock:
7609 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
7610 return 0;
7611
Jeff Bolzba6170b2019-07-01 09:23:23 -05007612 case glslang::EOpIsHelperInvocation:
7613 {
7614 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08007615 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
7616 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
7617 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05007618 }
7619
amhagan91fb0092019-07-10 21:14:38 -04007620 case glslang::EOpReadClockSubgroupKHR: {
7621 std::vector<spv::Id> args;
7622 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
7623 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7624 builder.addCapability(spv::CapabilityShaderClockKHR);
7625 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7626 }
7627
7628 case glslang::EOpReadClockDeviceKHR: {
7629 std::vector<spv::Id> args;
7630 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
7631 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7632 builder.addCapability(spv::CapabilityShaderClockKHR);
7633 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7634 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06007635#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007636 default:
John Kessenich155d3512019-08-08 23:29:20 -06007637 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007638 }
John Kessenich155d3512019-08-08 23:29:20 -06007639
7640 logger->missingFunctionality("unknown operation with no arguments");
7641
7642 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007643}
7644
7645spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7646{
John Kessenich2f273362015-07-18 22:34:27 -06007647 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007648 spv::Id id;
7649 if (symbolValues.end() != iter) {
7650 id = iter->second;
7651 return id;
7652 }
7653
7654 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06007655 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
7656 auto forcedType = getForcedType(builtIn, symbol->getType());
7657 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06007658 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06007659 if (forcedType.second != spv::NoType)
7660 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06007661
Rex Xuc884b4a2016-06-29 15:03:44 +08007662 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007663 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7664 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7665 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06007666#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007667 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06007668 if (symbol->getQualifier().hasComponent())
7669 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
7670 if (symbol->getQualifier().hasIndex())
7671 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07007672#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007673 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007674 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06007675 // atomic counters use this:
7676 if (symbol->getQualifier().hasOffset())
7677 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007678 }
7679
scygan2c864272016-05-18 18:09:17 +02007680 if (symbol->getQualifier().hasLocation())
7681 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007682 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007683 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007684 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007685 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007686 }
John Kessenich140f3df2015-06-26 16:58:36 -06007687 if (symbol->getQualifier().hasSet())
7688 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007689 else if (IsDescriptorResource(symbol->getType())) {
7690 // default to 0
7691 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7692 }
John Kessenich140f3df2015-06-26 16:58:36 -06007693 if (symbol->getQualifier().hasBinding())
7694 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007695 else if (IsDescriptorResource(symbol->getType())) {
7696 // default to 0
7697 builder.addDecoration(id, spv::DecorationBinding, 0);
7698 }
John Kessenich6c292d32016-02-15 20:58:50 -07007699 if (symbol->getQualifier().hasAttachment())
7700 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007701 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007702 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007703 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007704 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007705 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7706 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7707 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7708 }
7709 if (symbol->getQualifier().hasXfbOffset())
7710 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007711 }
7712
John Kessenichb9197c82019-08-11 07:41:45 -06007713 // add built-in variable decoration
7714 if (builtIn != spv::BuiltInMax) {
7715 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
7716 }
7717
7718#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08007719 if (symbol->getType().isImage()) {
7720 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007721 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007722 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007723 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007724 }
7725
John Kessenich5611c6d2018-04-05 11:25:02 -06007726 // nonuniform
7727 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7728
chaoc0ad6a4e2016-12-19 16:29:34 -08007729 if (builtIn == spv::BuiltInSampleMask) {
7730 spv::Decoration decoration;
7731 // GL_NV_sample_mask_override_coverage extension
7732 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007733 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007734 else
7735 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007736 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007737 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07007738 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08007739 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7740 }
7741 }
chaoc771d89f2017-01-13 01:10:53 -08007742 else if (builtIn == spv::BuiltInLayer) {
7743 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007744 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007745 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007746 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7747 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7748 }
John Kessenichb41bff62017-08-11 13:07:17 -06007749 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007750 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7751 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007752 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7753 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7754 }
7755 }
7756
chaoc6e5acae2016-12-20 13:28:52 -08007757 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007758 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007759 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007760 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7761 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007762 if (symbol->getQualifier().pervertexNV) {
7763 builder.addDecoration(id, spv::DecorationPerVertexNV);
7764 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7765 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7766 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007767
John Kessenich5d610ee2018-03-07 18:05:55 -07007768 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7769 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7770 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7771 symbol->getType().getQualifier().semanticName);
7772 }
7773
John Kessenich7015bd62019-08-01 03:28:08 -06007774 if (symbol->isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007775 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7776 }
John Kessenichb9197c82019-08-11 07:41:45 -06007777#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007778
John Kessenich140f3df2015-06-26 16:58:36 -06007779 return id;
7780}
7781
John Kessenicha28f7a72019-08-06 07:00:58 -06007782#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007783// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7784void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7785{
7786 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007787 if (qualifier.perPrimitiveNV) {
7788 // Need to add capability/extension for fragment shader.
7789 // Mesh shader already adds this by default.
7790 if (glslangIntermediate->getStage() == EShLangFragment) {
7791 builder.addCapability(spv::CapabilityMeshShadingNV);
7792 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7793 }
Chao Chen3c366992018-09-19 11:41:59 -07007794 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007795 }
Chao Chen3c366992018-09-19 11:41:59 -07007796 if (qualifier.perViewNV)
7797 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7798 if (qualifier.perTaskNV)
7799 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7800 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007801 if (qualifier.perPrimitiveNV) {
7802 // Need to add capability/extension for fragment shader.
7803 // Mesh shader already adds this by default.
7804 if (glslangIntermediate->getStage() == EShLangFragment) {
7805 builder.addCapability(spv::CapabilityMeshShadingNV);
7806 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7807 }
Chao Chen3c366992018-09-19 11:41:59 -07007808 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007809 }
Chao Chen3c366992018-09-19 11:41:59 -07007810 if (qualifier.perViewNV)
7811 builder.addDecoration(id, spv::DecorationPerViewNV);
7812 if (qualifier.perTaskNV)
7813 builder.addDecoration(id, spv::DecorationPerTaskNV);
7814 }
7815}
7816#endif
7817
John Kessenich55e7d112015-11-15 21:33:39 -07007818// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007819// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007820//
7821// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7822//
7823// Recursively walk the nodes. The nodes form a tree whose leaves are
7824// regular constants, which themselves are trees that createSpvConstant()
7825// recursively walks. So, this function walks the "top" of the tree:
7826// - emit specialization constant-building instructions for specConstant
7827// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007828spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007829{
John Kessenich7cc0e282016-03-20 00:46:02 -06007830 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007831
qining4f4bb812016-04-03 23:55:17 -04007832 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007833 if (! node.getQualifier().specConstant) {
7834 // hand off to the non-spec-constant path
7835 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7836 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007837 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007838 nextConst, false);
7839 }
7840
7841 // We now know we have a specialization constant to build
7842
John Kessenichd94c0032016-05-30 19:29:40 -06007843 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007844 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7845 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7846 std::vector<spv::Id> dimConstId;
7847 for (int dim = 0; dim < 3; ++dim) {
7848 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7849 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007850 if (specConst) {
7851 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7852 glslangIntermediate->getLocalSizeSpecId(dim));
7853 }
qining4f4bb812016-04-03 23:55:17 -04007854 }
7855 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7856 }
7857
7858 // An AST node labelled as specialization constant should be a symbol node.
7859 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7860 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007861 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007862 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007863 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7864 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7865 // will set the builder into spec constant op instruction generating mode.
7866 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007867 result = accessChainLoad(sub_tree->getType());
7868 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007869 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007870 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007871 } else {
7872 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007873 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007874 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007875 builder.addName(result, sn->getName().c_str());
7876 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007877 }
qining4f4bb812016-04-03 23:55:17 -04007878
7879 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7880 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007881 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007882 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007883}
7884
John Kessenich140f3df2015-06-26 16:58:36 -06007885// Use 'consts' as the flattened glslang source of scalar constants to recursively
7886// build the aggregate SPIR-V constant.
7887//
7888// If there are not enough elements present in 'consts', 0 will be substituted;
7889// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7890//
qining08408382016-03-21 09:51:37 -04007891spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007892{
7893 // vector of constants for SPIR-V
7894 std::vector<spv::Id> spvConsts;
7895
7896 // Type is used for struct and array constants
7897 spv::Id typeId = convertGlslangToSpvType(glslangType);
7898
7899 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007900 glslang::TType elementType(glslangType, 0);
7901 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007902 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007903 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007904 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007905 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007906 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007907 } else if (glslangType.isCoopMat()) {
7908 glslang::TType componentType(glslangType.getBasicType());
7909 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007910 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007911 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7912 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007913 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007914 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007915 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7916 bool zero = nextConst >= consts.size();
7917 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06007918 case glslang::EbtInt:
7919 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7920 break;
7921 case glslang::EbtUint:
7922 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7923 break;
7924 case glslang::EbtFloat:
7925 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7926 break;
7927 case glslang::EbtBool:
7928 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7929 break;
7930#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07007931 case glslang::EbtInt8:
7932 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7933 break;
7934 case glslang::EbtUint8:
7935 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7936 break;
7937 case glslang::EbtInt16:
7938 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7939 break;
7940 case glslang::EbtUint16:
7941 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7942 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007943 case glslang::EbtInt64:
7944 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7945 break;
7946 case glslang::EbtUint64:
7947 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7948 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007949 case glslang::EbtDouble:
7950 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7951 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007952 case glslang::EbtFloat16:
7953 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7954 break;
John Kessenich39697cd2019-08-08 10:35:51 -06007955#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007956 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007957 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007958 break;
7959 }
7960 ++nextConst;
7961 }
7962 } else {
7963 // we have a non-aggregate (scalar) constant
7964 bool zero = nextConst >= consts.size();
7965 spv::Id scalar = 0;
7966 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06007967 case glslang::EbtInt:
7968 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
7969 break;
7970 case glslang::EbtUint:
7971 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
7972 break;
7973 case glslang::EbtFloat:
7974 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7975 break;
7976 case glslang::EbtBool:
7977 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
7978 break;
7979#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07007980 case glslang::EbtInt8:
7981 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7982 break;
7983 case glslang::EbtUint8:
7984 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7985 break;
7986 case glslang::EbtInt16:
7987 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7988 break;
7989 case glslang::EbtUint16:
7990 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7991 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007992 case glslang::EbtInt64:
7993 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7994 break;
7995 case glslang::EbtUint64:
7996 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7997 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007998 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007999 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008000 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008001 case glslang::EbtFloat16:
8002 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8003 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008004 case glslang::EbtReference:
8005 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8006 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8007 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008008#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008009 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008010 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008011 break;
8012 }
8013 ++nextConst;
8014 return scalar;
8015 }
8016
8017 return builder.makeCompositeConstant(typeId, spvConsts);
8018}
8019
John Kessenich7c1aa102015-10-15 13:29:11 -06008020// Return true if the node is a constant or symbol whose reading has no
8021// non-trivial observable cost or effect.
8022bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8023{
8024 // don't know what this is
8025 if (node == nullptr)
8026 return false;
8027
8028 // a constant is safe
8029 if (node->getAsConstantUnion() != nullptr)
8030 return true;
8031
8032 // not a symbol means non-trivial
8033 if (node->getAsSymbolNode() == nullptr)
8034 return false;
8035
8036 // a symbol, depends on what's being read
8037 switch (node->getType().getQualifier().storage) {
8038 case glslang::EvqTemporary:
8039 case glslang::EvqGlobal:
8040 case glslang::EvqIn:
8041 case glslang::EvqInOut:
8042 case glslang::EvqConst:
8043 case glslang::EvqConstReadOnly:
8044 case glslang::EvqUniform:
8045 return true;
8046 default:
8047 return false;
8048 }
qining25262b32016-05-06 17:25:16 -04008049}
John Kessenich7c1aa102015-10-15 13:29:11 -06008050
8051// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008052// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008053// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008054// Return true if trivial.
8055bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8056{
8057 if (node == nullptr)
8058 return false;
8059
John Kessenich84cc15f2017-05-24 16:44:47 -06008060 // count non scalars as trivial, as well as anything coming from HLSL
8061 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008062 return true;
8063
John Kessenich7c1aa102015-10-15 13:29:11 -06008064 // symbols and constants are trivial
8065 if (isTrivialLeaf(node))
8066 return true;
8067
8068 // otherwise, it needs to be a simple operation or one or two leaf nodes
8069
8070 // not a simple operation
8071 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8072 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8073 if (binaryNode == nullptr && unaryNode == nullptr)
8074 return false;
8075
8076 // not on leaf nodes
8077 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8078 return false;
8079
8080 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8081 return false;
8082 }
8083
8084 switch (node->getAsOperator()->getOp()) {
8085 case glslang::EOpLogicalNot:
8086 case glslang::EOpConvIntToBool:
8087 case glslang::EOpConvUintToBool:
8088 case glslang::EOpConvFloatToBool:
8089 case glslang::EOpConvDoubleToBool:
8090 case glslang::EOpEqual:
8091 case glslang::EOpNotEqual:
8092 case glslang::EOpLessThan:
8093 case glslang::EOpGreaterThan:
8094 case glslang::EOpLessThanEqual:
8095 case glslang::EOpGreaterThanEqual:
8096 case glslang::EOpIndexDirect:
8097 case glslang::EOpIndexDirectStruct:
8098 case glslang::EOpLogicalXor:
8099 case glslang::EOpAny:
8100 case glslang::EOpAll:
8101 return true;
8102 default:
8103 return false;
8104 }
8105}
8106
8107// Emit short-circuiting code, where 'right' is never evaluated unless
8108// the left side is true (for &&) or false (for ||).
8109spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
8110{
8111 spv::Id boolTypeId = builder.makeBoolType();
8112
8113 // emit left operand
8114 builder.clearAccessChain();
8115 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008116 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008117
8118 // Operands to accumulate OpPhi operands
8119 std::vector<spv::Id> phiOperands;
8120 // accumulate left operand's phi information
8121 phiOperands.push_back(leftId);
8122 phiOperands.push_back(builder.getBuildPoint()->getId());
8123
8124 // Make the two kinds of operation symmetric with a "!"
8125 // || => emit "if (! left) result = right"
8126 // && => emit "if ( left) result = right"
8127 //
8128 // TODO: this runtime "not" for || could be avoided by adding functionality
8129 // to 'builder' to have an "else" without an "then"
8130 if (op == glslang::EOpLogicalOr)
8131 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8132
8133 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008134 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008135
8136 // emit right operand as the "then" part of the "if"
8137 builder.clearAccessChain();
8138 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008139 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008140
8141 // accumulate left operand's phi information
8142 phiOperands.push_back(rightId);
8143 phiOperands.push_back(builder.getBuildPoint()->getId());
8144
8145 // finish the "if"
8146 ifBuilder.makeEndIf();
8147
8148 // phi together the two results
8149 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8150}
8151
John Kessenicha28f7a72019-08-06 07:00:58 -06008152#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008153// Return type Id of the imported set of extended instructions corresponds to the name.
8154// Import this set if it has not been imported yet.
8155spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8156{
8157 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8158 return extBuiltinMap[name];
8159 else {
Rex Xu51596642016-09-21 18:56:12 +08008160 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008161 spv::Id extBuiltins = builder.import(name);
8162 extBuiltinMap[name] = extBuiltins;
8163 return extBuiltins;
8164 }
8165}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008166#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008167
John Kessenich140f3df2015-06-26 16:58:36 -06008168}; // end anonymous namespace
8169
8170namespace glslang {
8171
John Kessenich68d78fd2015-07-12 19:28:10 -06008172void GetSpirvVersion(std::string& version)
8173{
John Kessenich9e55f632015-07-15 10:03:39 -06008174 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008175 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008176 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008177 version = buf;
8178}
8179
John Kessenicha372a3e2017-11-02 22:32:14 -06008180// For low-order part of the generator's magic number. Bump up
8181// when there is a change in the style (e.g., if SSA form changes,
8182// or a different instruction sequence to do something gets used).
8183int GetSpirvGeneratorVersion()
8184{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008185 // return 1; // start
8186 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008187 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008188 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008189 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008190 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8191 // versions 4 and 6 each generate OpArrayLength as it has long been done
8192 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06008193}
8194
John Kessenich140f3df2015-06-26 16:58:36 -06008195// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008196void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008197{
8198 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008199 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008200 if (out.fail())
8201 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008202 for (int i = 0; i < (int)spirv.size(); ++i) {
8203 unsigned int word = spirv[i];
8204 out.write((const char*)&word, 4);
8205 }
8206 out.close();
8207}
8208
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008209// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008210void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008211{
John Kessenich155d3512019-08-08 23:29:20 -06008212#ifndef GLSLANG_WEB
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008213 std::ofstream out;
8214 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008215 if (out.fail())
8216 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008217 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008218 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008219 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008220 if (varName != nullptr) {
8221 out << "\t #pragma once" << std::endl;
8222 out << "const uint32_t " << varName << "[] = {" << std::endl;
8223 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008224 const int WORDS_PER_LINE = 8;
8225 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8226 out << "\t";
8227 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8228 const unsigned int word = spirv[i + j];
8229 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8230 if (i + j + 1 < (int)spirv.size()) {
8231 out << ",";
8232 }
8233 }
8234 out << std::endl;
8235 }
Flavio15017db2017-02-15 14:29:33 -08008236 if (varName != nullptr) {
8237 out << "};";
8238 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008239 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008240#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008241}
8242
John Kessenich140f3df2015-06-26 16:58:36 -06008243//
8244// Set up the glslang traversal
8245//
John Kessenich4e11b612018-08-30 16:56:59 -06008246void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008247{
Lei Zhang17535f72016-05-04 15:55:59 -04008248 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008249 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008250}
8251
John Kessenich4e11b612018-08-30 16:56:59 -06008252void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008253 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008254{
John Kessenich140f3df2015-06-26 16:58:36 -06008255 TIntermNode* root = intermediate.getTreeRoot();
8256
8257 if (root == 0)
8258 return;
8259
John Kessenich4e11b612018-08-30 16:56:59 -06008260 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008261 if (options == nullptr)
8262 options = &defaultOptions;
8263
John Kessenich4e11b612018-08-30 16:56:59 -06008264 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008265
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008266 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008267 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008268 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008269 it.dumpSpv(spirv);
8270
GregFfb03a552018-03-29 11:49:14 -06008271#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008272 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8273 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008274 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8275 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008276 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008277 prelegalization = false;
8278 }
John Kessenich717c80a2018-08-23 15:17:10 -06008279
John Kessenich4e11b612018-08-30 16:56:59 -06008280 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008281 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008282
John Kessenich717c80a2018-08-23 15:17:10 -06008283 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008284 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008285
GregFcd1f1692017-09-21 18:40:22 -06008286#endif
8287
John Kessenich4e11b612018-08-30 16:56:59 -06008288 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008289}
8290
8291}; // end namespace glslang