Merge remote-tracking branch 'aosp/upstream-master'
Pulls in the following:
e1cd410 Merge pull request #232 from Qining/fix-spec-const-bool-to-int-conversion
189b203 Refine the code and address comments
e24aa5e SpecOp bool->uint/int and uint<->int conversion
cec24c9 Merge pull request #231 from dneto0/gtests-link-to-hlsl
6f29a1b SPV for OpenGL: Issue #229: don't allow gl_VertexIndex or gl_InstanceIndex under -G.
c079210 Unit test executable should link to libHLSL
d995241 Merge pull request #226 from baldurk/warning-fixes
4028916 Fix warning about function parameter shadowing class member variable
3cb57d3 Fix warning about losing information, use size_t instead of int
6e620c4 Nonfunctional: Remove stray ';' and fix Google Test sentence in README.
7e3e486 Memory: Don't use pool memory to store the entry point name in the intermediate representation.
78a6b78 Front-end: Get the right set of nodes marked as spec-const.
a8d9fab Merge pull request #216 from Qining/fix-non-const-array-size-from-spec-const
75d1d80 add SpecConstantOpModeGuard to GlslangToSpvTraverser::visitSymbol()
4088766 Turn on SpecConstantOpMode based on node qualifier
4c91261 fix the wrong generated code when a non-constant array is declared with its size derived from spec constant operations
aa0298b Merge pull request #220 from Qining/fix-built-in-spec-constants
4f4bb81 Built-in values declared as specialization constant
1c7e707 Merge branch 'master' into hlsl-frontend
9c2f1c7 Merge branch 'master' of github.com:KhronosGroup/glslang
79845ad Merge pull request #217 from baldurk/vs2010-compile-fixes
bb5743e Merge pull request #219 from 1ace/master
6a6d6dd fix spelling mistakes
f0bcb0a Comment: fix comment from gtest check in.
bd9f835 Specify explicit return type on lambda function
0dfbe3f Change {parameter} lists into explicit std::vector temporaries
a42533e Merge pull request #190 from antiagainst/gtest
af59197 Merge pull request #214 from amdrexu/bugfix
3dad506 Merge pull request #215 from Qining/spec-constants-operations
5c61d8e fix format; remove unnecessary parameters; rename some spec op mode guard class; remove support of float point comparison and composite type comparison; update the tests.
414eb60 Link in Google Test framework.
1354520 Spec Constant Operations
cb0e471 Parser: Update array size of gl_ClipDistance/gl_CullDistance in gl_in[].
c3869fe Merge pull request #211 from Qining/spec-constants-composite
0840838 Support specialization composite constants
28001b1 Merge pull request #212 from amdrexu/bugfix
4e8bf59 Parser: Fix a build issue (VS2012).
5ace09a Merge pull request #210 from AWoloszyn/fix-compilation
272afd2 Fixed compilation issue introduced by my last commit
56368b6 Merge pull request #198 from AWoloszyn/update-includer
ddb65a4 Front-end: Propagate spec-constness up through aggregate constructors.
a132af5 Updated the includer interface to allow relative includes.
aecd497 HLSL: Abstract accepting an identifier.
078d7f2 HLSL: Simplify appearances a bit to make easier to read.
5f934b0 HLSL: Accept basic funtion definitions. (Not yet mapping input/output for entry point.)
48882ef HLSL: Get correct set of reserved words.
d016be1 HLSL: Hook up constructor expressions through the AST.
87142c7 HLSL: Add basic declaration syntax and AST generation.
e01a9bc HLSL: Plumb in HLSL parse context and keywords, and most basic HLSL parser and test.
b3dc3ac Refactor TParseContext into 3 level inheritance.
66e2faf Support multiple source languages, adding HLSL as an option.
4d65ee3 Generalize "main" to a settable entry point name.
diff --git a/.gitignore b/.gitignore
index d93c202..66cbff9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,3 +7,4 @@
Test/localResults/
Test/multiThread.out
Test/singleThread.out
+External/googletest
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 1d723d8..1027e7e 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,5 +1,7 @@
cmake_minimum_required(VERSION 2.8)
+enable_testing()
+
set(CMAKE_INSTALL_PREFIX "install" CACHE STRING "prefix")
project(glslang)
@@ -11,7 +13,7 @@
add_definitions(-fPIC)
add_definitions(-DGLSLANG_OSINCLUDE_UNIX)
else(WIN32)
- message("unkown platform")
+ message("unknown platform")
endif(WIN32)
if(CMAKE_COMPILER_IS_GNUCXX)
@@ -20,7 +22,12 @@
add_definitions(-std=c++11)
endif()
+# We depend on these for later projects, so they should come first.
+add_subdirectory(External)
+
add_subdirectory(glslang)
add_subdirectory(OGLCompilersDLL)
add_subdirectory(StandAlone)
add_subdirectory(SPIRV)
+add_subdirectory(hlsl)
+add_subdirectory(gtests)
diff --git a/External/CMakeLists.txt b/External/CMakeLists.txt
new file mode 100644
index 0000000..d43cf9d
--- /dev/null
+++ b/External/CMakeLists.txt
@@ -0,0 +1,16 @@
+# Suppress all warnings from external projects.
+set_property(DIRECTORY APPEND PROPERTY COMPILE_OPTIONS -w)
+
+if (TARGET gmock)
+ message(STATUS "Google Mock already configured - use it")
+elseif(IS_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/googletest)
+ # We need to make sure Google Test does not mess up with the
+ # global CRT settings on Windows.
+ if(WIN32)
+ set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
+ endif(WIN32)
+ add_subdirectory(googletest)
+else()
+ message(STATUS
+ "Google Mock was not found - tests based on that will not build")
+endif()
diff --git a/README.md b/README.md
index 7a60e28..d669e50 100644
--- a/README.md
+++ b/README.md
@@ -61,6 +61,12 @@
-o MachineIndependent/glslang_tab.cpp
```
+Glslang is adding the ability to test with
+[Google Test](https://github.com/google/googletest) framework. If you want to
+build and run those tests, please make sure you have a copy of Google Tests
+checked out in the `External/` directory:
+`git clone https://github.com/google/googletest.git`.
+
Programmatic Interfaces
-----------------------
@@ -97,7 +103,7 @@
See `ShaderLang.h` and the usage of it in `StandAlone/StandAlone.cpp` for more
details.
-### C Functional Interface (orginal)
+### C Functional Interface (orignal)
This interface is in roughly the first 2/3 of `ShaderLang.h`, and referred to
as the `Sh*()` interface, as all the entry points start `Sh`.
@@ -112,13 +118,17 @@
```
In practice, `ShCompile()` takes shader strings, default version, and
-warning/error and other options for controling compilation.
+warning/error and other options for controlling compilation.
Testing
-------
Test results should always be included with a pull request that modifies
-functionality. There is a simple process for doing this, described here:
+functionality. And since glslang added the ability to test with
+[Google Test](https://github.com/google/googletest) framework,
+please write your new tests using Google Test.
+
+The old (deprecated) testing process is:
`Test` is an active test directory that contains test input and a
subdirectory `baseResults` that contains the expected results of the
diff --git a/SPIRV/GlslangToSpv.cpp b/SPIRV/GlslangToSpv.cpp
index 6f5697e..39f3b8b 100755
--- a/SPIRV/GlslangToSpv.cpp
+++ b/SPIRV/GlslangToSpv.cpp
@@ -66,6 +66,27 @@
// or a different instruction sequence to do something gets used).
const int GeneratorVersion = 1;
+namespace {
+class SpecConstantOpModeGuard {
+public:
+ SpecConstantOpModeGuard(spv::Builder* builder)
+ : builder_(builder) {
+ previous_flag_ = builder->isInSpecConstCodeGenMode();
+ }
+ ~SpecConstantOpModeGuard() {
+ previous_flag_ ? builder_->setToSpecConstCodeGenMode()
+ : builder_->setToNormalCodeGenMode();
+ }
+ void turnOnSpecConstantOpMode() {
+ builder_->setToSpecConstCodeGenMode();
+ }
+
+private:
+ spv::Builder* builder_;
+ bool previous_flag_;
+};
+}
+
//
// The main holder of information for translating glslang to SPIR-V.
//
@@ -128,8 +149,9 @@
void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
- spv::Id createSpvSpecConstant(const glslang::TIntermTyped&);
- spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
+ spv::Id createSpvConstant(const glslang::TIntermTyped&);
+ spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
+ spv::Id createSpvConstantFromConstSubTree(glslang::TIntermTyped* subTree);
bool isTrivialLeaf(const glslang::TIntermTyped* node);
bool isTrivial(const glslang::TIntermTyped* node);
spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
@@ -160,15 +182,22 @@
//
// Translate glslang profile to SPIR-V source language.
-spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
+spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
{
- switch (profile) {
- case ENoProfile:
- case ECoreProfile:
- case ECompatibilityProfile:
- return spv::SourceLanguageGLSL;
- case EEsProfile:
- return spv::SourceLanguageESSL;
+ switch (source) {
+ case glslang::EShSourceGlsl:
+ switch (profile) {
+ case ENoProfile:
+ case ECoreProfile:
+ case ECompatibilityProfile:
+ return spv::SourceLanguageGLSL;
+ case EEsProfile:
+ return spv::SourceLanguageESSL;
+ default:
+ return spv::SourceLanguageUnknown;
+ }
+ case glslang::EShSourceHlsl:
+ return spv::SourceLanguageHLSL;
default:
return spv::SourceLanguageUnknown;
}
@@ -587,11 +616,11 @@
spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
builder.clearAccessChain();
- builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
+ builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
stdBuiltins = builder.import("GLSL.std.450");
builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
- shaderEntry = builder.makeMain();
- entryPoint = builder.addEntryPoint(executionModel, shaderEntry, "main");
+ shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
+ entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
// Add the source extensions
const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
@@ -749,6 +778,10 @@
//
void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
{
+ SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
+ if (symbol->getType().getQualifier().isSpecConstant())
+ spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
+
// getSymbolId() will set up all the IO decorations on the first call.
// Formal function parameters were mapped during makeFunctions().
spv::Id id = getSymbolId(symbol);
@@ -786,6 +819,10 @@
bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
{
+ SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
+ if (node->getType().getQualifier().isSpecConstant())
+ spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
+
// First, handle special cases
switch (node->getOp()) {
case glslang::EOpAssign:
@@ -958,6 +995,10 @@
bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
{
+ SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
+ if (node->getType().getQualifier().isSpecConstant())
+ spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
+
spv::Id result = spv::NoResult;
// try texturing first
@@ -1520,7 +1561,7 @@
void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
{
int nextConst = 0;
- spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst, false);
+ spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
builder.clearAccessChain();
builder.setAccessChainRValue(constant);
@@ -1630,7 +1671,7 @@
// can still have a mapping to a SPIR-V Id.
// This includes specialization constants.
if (node->getQualifier().isConstant()) {
- return createSpvSpecConstant(*node);
+ return createSpvConstant(*node);
}
// Now, handle actual variables
@@ -2082,7 +2123,9 @@
bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
{
- return node->getName() == "main(";
+ // have to ignore mangling and just look at the base name
+ size_t firstOpen = node->getName().find('(');
+ return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
}
// Make all the functions, skeletally, without actually visiting their bodies.
@@ -3264,6 +3307,15 @@
case glslang::EOpConvUintToInt:
case glslang::EOpConvIntToUint:
+ if (builder.isInSpecConstCodeGenMode()) {
+ // Build zero scalar or vector for OpIAdd.
+ zero = builder.makeUintConstant(0);
+ zero = makeSmearedConstant(zero, vectorSize);
+ // Use OpIAdd, instead of OpBitcast to do the conversion when
+ // generating for OpSpecConstantOp instruction.
+ return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
+ }
+ // For normal run-time conversion instruction, use OpBitcast.
convOp = spv::OpBitcast;
break;
@@ -3730,43 +3782,50 @@
// recursively walks. So, this function walks the "top" of the tree:
// - emit specialization constant-building instructions for specConstant
// - when running into a non-spec-constant, switch to createSpvConstant()
-spv::Id TGlslangToSpvTraverser::createSpvSpecConstant(const glslang::TIntermTyped& node)
+spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
{
assert(node.getQualifier().isConstant());
+ // Handle front-end constants first (non-specialization constants).
if (! node.getQualifier().specConstant) {
// hand off to the non-spec-constant path
assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
int nextConst = 0;
- return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
+ return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
nextConst, false);
}
// We now know we have a specialization constant to build
- if (node.getAsSymbolNode() && node.getQualifier().hasSpecConstantId()) {
- // this is a direct literal assigned to a layout(constant_id=) declaration
- int nextConst = 0;
- return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
- nextConst, true);
- } else {
- // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
- // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
- if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
- std::vector<spv::Id> dimConstId;
- for (int dim = 0; dim < 3; ++dim) {
- bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
- dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
- if (specConst)
- addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
- }
- return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
- } else {
- spv::MissingFunctionality("specialization-constant expression trees");
- exit(1);
- return spv::NoResult;
+ // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
+ // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
+ if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
+ std::vector<spv::Id> dimConstId;
+ for (int dim = 0; dim < 3; ++dim) {
+ bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
+ dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
+ if (specConst)
+ addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
+ }
+ return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
+ }
+
+ // An AST node labelled as specialization constant should be a symbol node.
+ // Its initializer should either be a sub tree with constant nodes, or a constant union array.
+ if (auto* sn = node.getAsSymbolNode()) {
+ if (auto* sub_tree = sn->getConstSubtree()) {
+ return createSpvConstantFromConstSubTree(sub_tree);
+ } else if (auto* const_union_array = &sn->getConstArray()){
+ int nextConst = 0;
+ return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
}
}
+
+ // Neither a front-end constant node, nor a specialization constant node with constant union array or
+ // constant sub tree as initializer.
+ spv::MissingFunctionality("Neither a front-end constant nor a spec constant.");
+ exit(1);
+ return spv::NoResult;
}
// Use 'consts' as the flattened glslang source of scalar constants to recursively
@@ -3775,7 +3834,7 @@
// If there are not enough elements present in 'consts', 0 will be substituted;
// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
//
-spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
+spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
{
// vector of constants for SPIR-V
std::vector<spv::Id> spvConsts;
@@ -3786,15 +3845,15 @@
if (glslangType.isArray()) {
glslang::TType elementType(glslangType, 0);
for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
- spvConsts.push_back(createSpvConstant(elementType, consts, nextConst, false));
+ spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
} else if (glslangType.isMatrix()) {
glslang::TType vectorType(glslangType, 0);
for (int col = 0; col < glslangType.getMatrixCols(); ++col)
- spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst, false));
+ spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
} else if (glslangType.getStruct()) {
glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
- spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst, false));
+ spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
} else if (glslangType.isVector()) {
for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
bool zero = nextConst >= consts.size();
@@ -3851,6 +3910,68 @@
return builder.makeCompositeConstant(typeId, spvConsts);
}
+// Create constant ID from const initializer sub tree.
+spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstSubTree(
+ glslang::TIntermTyped* subTree)
+{
+ const glslang::TType& glslangType = subTree->getType();
+ spv::Id typeId = convertGlslangToSpvType(glslangType);
+ bool is_spec_const = subTree->getType().getQualifier().isSpecConstant();
+ if (const glslang::TIntermAggregate* an = subTree->getAsAggregate()) {
+ // Aggregate node, we should generate OpConstantComposite or
+ // OpSpecConstantComposite instruction.
+
+ std::vector<spv::Id> const_constituents;
+ for (auto NI = an->getSequence().begin(); NI != an->getSequence().end();
+ NI++) {
+ const_constituents.push_back(
+ createSpvConstantFromConstSubTree((*NI)->getAsTyped()));
+ }
+ // Note that constructors are aggregate nodes, so expressions like:
+ // float x = float(y) will become an aggregate node. If 'x' is declared
+ // as a constant, the aggregate node representing 'float(y)' will be
+ // processed here.
+ if (builder.isVectorType(typeId) || builder.isMatrixType(typeId) ||
+ builder.isAggregateType(typeId)) {
+ return builder.makeCompositeConstant(typeId, const_constituents, is_spec_const);
+ } else {
+ assert(builder.isScalarType(typeId) && const_constituents.size() == 1);
+ return const_constituents.front();
+ }
+
+ } else if (glslang::TIntermBinary* bn = subTree->getAsBinaryNode()) {
+ // Binary operation node, we should generate OpSpecConstantOp <binary op>
+ // This case should only happen when Specialization Constants are involved.
+ bn->traverse(this);
+ return accessChainLoad(bn->getType());
+
+ } else if (glslang::TIntermUnary* un = subTree->getAsUnaryNode()) {
+ // Unary operation node, similar to binary operation node, should only
+ // happen when specialization constants are involved.
+ un->traverse(this);
+ return accessChainLoad(un->getType());
+
+ } else if (const glslang::TIntermConstantUnion* cn = subTree->getAsConstantUnion()) {
+ // ConstantUnion node, should redirect to
+ // createSpvConstantFromConstUnionArray
+ int nextConst = 0;
+ return createSpvConstantFromConstUnionArray(
+ glslangType, cn->getConstArray(), nextConst, is_spec_const);
+
+ } else if (const glslang::TIntermSymbol* sn = subTree->getAsSymbolNode()) {
+ // Symbol node. Call getSymbolId(). This should cover both cases 1) the
+ // symbol has already been assigned an ID, 2) need a new ID for this
+ // symbol.
+ return getSymbolId(sn);
+
+ } else {
+ spv::MissingFunctionality(
+ "createSpvConstantFromConstSubTree() not covered TIntermTyped* const "
+ "initializer subtree.");
+ return spv::NoResult;
+ }
+}
+
// Return true if the node is a constant or symbol whose reading has no
// non-trivial observable cost or effect.
bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
diff --git a/SPIRV/GlslangToSpv.h b/SPIRV/GlslangToSpv.h
index d8a1889..ea75340 100644
--- a/SPIRV/GlslangToSpv.h
+++ b/SPIRV/GlslangToSpv.h
@@ -40,4 +40,4 @@
void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv);
void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName);
-};
+}
diff --git a/SPIRV/SPVRemapper.cpp b/SPIRV/SPVRemapper.cpp
index 965867e..35dda17 100755
--- a/SPIRV/SPVRemapper.cpp
+++ b/SPIRV/SPVRemapper.cpp
@@ -573,7 +573,7 @@
op_fn_nop);
// Window size for context-sensitive canonicalization values
- // Emperical best size from a single data set. TODO: Would be a good tunable.
+ // Empirical best size from a single data set. TODO: Would be a good tunable.
// We essentially perform a little convolution around each instruction,
// to capture the flavor of nearby code, to hopefully match to similar
// code in other modules.
diff --git a/SPIRV/SpvBuilder.cpp b/SPIRV/SpvBuilder.cpp
index 336d3de..7896deb 100644
--- a/SPIRV/SpvBuilder.cpp
+++ b/SPIRV/SpvBuilder.cpp
@@ -64,7 +64,8 @@
builderNumber(magicNumber),
buildPoint(0),
uniqueId(0),
- mainFunction(0)
+ mainFunction(0),
+ generatingOpCodeForSpecConst(false)
{
clearAccessChain();
}
@@ -893,7 +894,7 @@
}
// Comments in header
-Function* Builder::makeMain()
+Function* Builder::makeEntrypoint(const char* entryPoint)
{
assert(! mainFunction);
@@ -901,7 +902,7 @@
std::vector<Id> params;
std::vector<Decoration> precisions;
- mainFunction = makeFunctionEntry(NoPrecision, makeVoidType(), "main", params, precisions, &entry);
+ mainFunction = makeFunctionEntry(NoPrecision, makeVoidType(), entryPoint, params, precisions, &entry);
return mainFunction;
}
@@ -1063,6 +1064,11 @@
Id Builder::createCompositeExtract(Id composite, Id typeId, unsigned index)
{
+ // Generate code for spec constants if in spec constant operation
+ // generation mode.
+ if (generatingOpCodeForSpecConst) {
+ return createSpecConstantOp(OpCompositeExtract, typeId, std::vector<Id>(1, composite), std::vector<Id>(1, index));
+ }
Instruction* extract = new Instruction(getUniqueId(), typeId, OpCompositeExtract);
extract->addIdOperand(composite);
extract->addImmediateOperand(index);
@@ -1073,6 +1079,11 @@
Id Builder::createCompositeExtract(Id composite, Id typeId, std::vector<unsigned>& indexes)
{
+ // Generate code for spec constants if in spec constant operation
+ // generation mode.
+ if (generatingOpCodeForSpecConst) {
+ return createSpecConstantOp(OpCompositeExtract, typeId, std::vector<Id>(1, composite), indexes);
+ }
Instruction* extract = new Instruction(getUniqueId(), typeId, OpCompositeExtract);
extract->addIdOperand(composite);
for (int i = 0; i < (int)indexes.size(); ++i)
@@ -1170,6 +1181,11 @@
// An opcode that has one operands, a result id, and a type
Id Builder::createUnaryOp(Op opCode, Id typeId, Id operand)
{
+ // Generate code for spec constants if in spec constant operation
+ // generation mode.
+ if (generatingOpCodeForSpecConst) {
+ return createSpecConstantOp(opCode, typeId, std::vector<Id>(1, operand), std::vector<Id>());
+ }
Instruction* op = new Instruction(getUniqueId(), typeId, opCode);
op->addIdOperand(operand);
buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
@@ -1179,6 +1195,13 @@
Id Builder::createBinOp(Op opCode, Id typeId, Id left, Id right)
{
+ // Generate code for spec constants if in spec constant operation
+ // generation mode.
+ if (generatingOpCodeForSpecConst) {
+ std::vector<Id> operands(2);
+ operands[0] = left; operands[1] = right;
+ return createSpecConstantOp(opCode, typeId, operands, std::vector<Id>());
+ }
Instruction* op = new Instruction(getUniqueId(), typeId, opCode);
op->addIdOperand(left);
op->addIdOperand(right);
@@ -1189,6 +1212,16 @@
Id Builder::createTriOp(Op opCode, Id typeId, Id op1, Id op2, Id op3)
{
+ // Generate code for spec constants if in spec constant operation
+ // generation mode.
+ if (generatingOpCodeForSpecConst) {
+ std::vector<Id> operands(3);
+ operands[0] = op1;
+ operands[1] = op2;
+ operands[2] = op3;
+ return createSpecConstantOp(
+ opCode, typeId, operands, std::vector<Id>());
+ }
Instruction* op = new Instruction(getUniqueId(), typeId, opCode);
op->addIdOperand(op1);
op->addIdOperand(op2);
@@ -1208,6 +1241,20 @@
return op->getResultId();
}
+Id Builder::createSpecConstantOp(Op opCode, Id typeId, const std::vector<Id>& operands, const std::vector<unsigned>& literals)
+{
+ Instruction* op = new Instruction(getUniqueId(), typeId, OpSpecConstantOp);
+ op->addImmediateOperand((unsigned) opCode);
+ for (auto it = operands.cbegin(); it != operands.cend(); ++it)
+ op->addIdOperand(*it);
+ for (auto it = literals.cbegin(); it != literals.cend(); ++it)
+ op->addImmediateOperand(*it);
+ module.mapInstruction(op);
+ constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(op));
+
+ return op->getResultId();
+}
+
Id Builder::createFunctionCall(spv::Function* function, std::vector<spv::Id>& args)
{
Instruction* op = new Instruction(getUniqueId(), function->getReturnType(), OpFunctionCall);
@@ -1225,6 +1272,11 @@
if (channels.size() == 1)
return setPrecision(createCompositeExtract(source, typeId, channels.front()), precision);
+ if (generatingOpCodeForSpecConst) {
+ std::vector<Id> operands(2);
+ operands[0] = operands[1] = source;
+ return setPrecision(createSpecConstantOp(OpVectorShuffle, typeId, operands, channels), precision);
+ }
Instruction* swizzle = new Instruction(getUniqueId(), typeId, OpVectorShuffle);
assert(isVector(source));
swizzle->addIdOperand(source);
@@ -1290,10 +1342,23 @@
if (numComponents == 1)
return scalar;
- Instruction* smear = new Instruction(getUniqueId(), vectorType, OpCompositeConstruct);
- for (int c = 0; c < numComponents; ++c)
- smear->addIdOperand(scalar);
- buildPoint->addInstruction(std::unique_ptr<Instruction>(smear));
+ Instruction* smear = nullptr;
+ if (generatingOpCodeForSpecConst) {
+ auto members = std::vector<spv::Id>(numComponents, scalar);
+ // 'scalar' can not be spec constant here. All spec constant involved
+ // promotion is done in createSpvConstantFromConstUnionArray(). This
+ // 'if' branch is only accessed when 'scalar' is used in the def-chain
+ // of other vector type spec constants. In such cases, all the
+ // instructions needed to promote 'scalar' to a vector type constants
+ // should be added at module level.
+ auto result_id = makeCompositeConstant(vectorType, members, false);
+ smear = module.getInstruction(result_id);
+ } else {
+ smear = new Instruction(getUniqueId(), vectorType, OpCompositeConstruct);
+ for (int c = 0; c < numComponents; ++c)
+ smear->addIdOperand(scalar);
+ buildPoint->addInstruction(std::unique_ptr<Instruction>(smear));
+ }
return setPrecision(smear->getResultId(), precision);
}
@@ -2158,7 +2223,7 @@
}
}
decorations.erase(std::remove_if(decorations.begin(), decorations.end(),
- [&unreachable_definitions](std::unique_ptr<Instruction>& I) {
+ [&unreachable_definitions](std::unique_ptr<Instruction>& I) -> bool {
Instruction* inst = I.get();
Id decoration_id = inst->getIdOperand(0);
return unreachable_definitions.count(decoration_id) != 0;
@@ -2268,7 +2333,7 @@
// To the extent any swizzling can become part of the chain
// of accesses instead of a post operation, make it so.
-// If 'dynamic' is true, include transfering a non-static component index,
+// If 'dynamic' is true, include transferring a non-static component index,
// otherwise, only transfer static indexes.
//
// Also, Boolean vectors are likely to be special. While
diff --git a/SPIRV/SpvBuilder.h b/SPIRV/SpvBuilder.h
index e16ba38..62f6775 100755
--- a/SPIRV/SpvBuilder.h
+++ b/SPIRV/SpvBuilder.h
@@ -205,9 +205,9 @@
void setBuildPoint(Block* bp) { buildPoint = bp; }
Block* getBuildPoint() const { return buildPoint; }
- // Make the main function. The returned pointer is only valid
+ // Make the entry-point function. The returned pointer is only valid
// for the lifetime of this builder.
- Function* makeMain();
+ Function* makeEntrypoint(const char*);
// Make a shader-style function, and create its entry block if entry is non-zero.
// Return the function, pass back the entry.
@@ -262,6 +262,7 @@
Id createTriOp(Op, Id typeId, Id operand1, Id operand2, Id operand3);
Id createOp(Op, Id typeId, const std::vector<Id>& operands);
Id createFunctionCall(spv::Function*, std::vector<spv::Id>&);
+ Id createSpecConstantOp(Op, Id typeId, const std::vector<spv::Id>& operands, const std::vector<unsigned>& literals);
// Take an rvalue (source) and a set of channels to extract from it to
// make a new rvalue, which is returned.
@@ -521,6 +522,13 @@
void createConditionalBranch(Id condition, Block* thenBlock, Block* elseBlock);
void createLoopMerge(Block* mergeBlock, Block* continueBlock, unsigned int control);
+ // Sets to generate opcode for specialization constants.
+ void setToSpecConstCodeGenMode() { generatingOpCodeForSpecConst = true; }
+ // Sets to generate opcode for non-specialization constants (normal mode).
+ void setToNormalCodeGenMode() { generatingOpCodeForSpecConst = false; }
+ // Check if the builder is generating code for spec constants.
+ bool isInSpecConstCodeGenMode() { return generatingOpCodeForSpecConst; }
+
protected:
Id makeIntConstant(Id typeId, unsigned value, bool specConstant);
Id findScalarConstant(Op typeClass, Op opcode, Id typeId, unsigned value) const;
@@ -544,6 +552,7 @@
Block* buildPoint;
Id uniqueId;
Function* mainFunction;
+ bool generatingOpCodeForSpecConst;
AccessChain accessChain;
// special blocks of instructions for output
diff --git a/SPIRV/doc.cpp b/SPIRV/doc.cpp
index 7cf1c87..7ee86b5 100755
--- a/SPIRV/doc.cpp
+++ b/SPIRV/doc.cpp
@@ -64,7 +64,7 @@
// (for non-sparse mask enums, this is the number of enumurants)
//
-const int SourceLanguageCeiling = 5;
+const int SourceLanguageCeiling = 6; // HLSL todo: need official enumerant
const char* SourceString(int source)
{
@@ -74,6 +74,7 @@
case 2: return "GLSL";
case 3: return "OpenCL_C";
case 4: return "OpenCL_CPP";
+ case 5: return "HLSL";
case SourceLanguageCeiling:
default: return "Bad";
diff --git a/SPIRV/spirv.hpp b/SPIRV/spirv.hpp
index 5620aba..7447fcf 100755
--- a/SPIRV/spirv.hpp
+++ b/SPIRV/spirv.hpp
@@ -61,6 +61,7 @@
SourceLanguageGLSL = 2,
SourceLanguageOpenCL_C = 3,
SourceLanguageOpenCL_CPP = 4,
+ SourceLanguageHLSL = 5,
};
enum ExecutionModel {
diff --git a/StandAlone/CMakeLists.txt b/StandAlone/CMakeLists.txt
index 38cb2bd..e9d7211 100644
--- a/StandAlone/CMakeLists.txt
+++ b/StandAlone/CMakeLists.txt
@@ -1,5 +1,13 @@
cmake_minimum_required(VERSION 2.8)
+add_library(glslang-default-resource-limits
+ ${CMAKE_CURRENT_SOURCE_DIR}/DefaultResourceLimits.cpp
+)
+target_include_directories(glslang-default-resource-limits
+ PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}
+ PUBLIC ${PROJECT_SOURCE_DIR}
+)
+
set(SOURCES StandAlone.cpp)
set(REMAPPER_SOURCES spirv-remap.cpp)
@@ -10,7 +18,9 @@
glslang
OGLCompiler
OSDependent
- SPIRV)
+ HLSL
+ SPIRV
+ glslang-default-resource-limits)
if(WIN32)
set(LIBRARIES ${LIBRARIES} psapi)
diff --git a/StandAlone/DefaultResourceLimits.cpp b/StandAlone/DefaultResourceLimits.cpp
new file mode 100644
index 0000000..66032de
--- /dev/null
+++ b/StandAlone/DefaultResourceLimits.cpp
@@ -0,0 +1,239 @@
+//
+// Copyright (C) 2016 Google, Inc.
+//
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+//
+// Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//
+// Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+//
+// Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+
+#include <sstream>
+
+#include "DefaultResourceLimits.h"
+
+namespace glslang {
+
+const TBuiltInResource DefaultTBuiltInResource = {
+ /* .MaxLights = */ 32,
+ /* .MaxClipPlanes = */ 6,
+ /* .MaxTextureUnits = */ 32,
+ /* .MaxTextureCoords = */ 32,
+ /* .MaxVertexAttribs = */ 64,
+ /* .MaxVertexUniformComponents = */ 4096,
+ /* .MaxVaryingFloats = */ 64,
+ /* .MaxVertexTextureImageUnits = */ 32,
+ /* .MaxCombinedTextureImageUnits = */ 80,
+ /* .MaxTextureImageUnits = */ 32,
+ /* .MaxFragmentUniformComponents = */ 4096,
+ /* .MaxDrawBuffers = */ 32,
+ /* .MaxVertexUniformVectors = */ 128,
+ /* .MaxVaryingVectors = */ 8,
+ /* .MaxFragmentUniformVectors = */ 16,
+ /* .MaxVertexOutputVectors = */ 16,
+ /* .MaxFragmentInputVectors = */ 15,
+ /* .MinProgramTexelOffset = */ -8,
+ /* .MaxProgramTexelOffset = */ 7,
+ /* .MaxClipDistances = */ 8,
+ /* .MaxComputeWorkGroupCountX = */ 65535,
+ /* .MaxComputeWorkGroupCountY = */ 65535,
+ /* .MaxComputeWorkGroupCountZ = */ 65535,
+ /* .MaxComputeWorkGroupSizeX = */ 1024,
+ /* .MaxComputeWorkGroupSizeY = */ 1024,
+ /* .MaxComputeWorkGroupSizeZ = */ 64,
+ /* .MaxComputeUniformComponents = */ 1024,
+ /* .MaxComputeTextureImageUnits = */ 16,
+ /* .MaxComputeImageUniforms = */ 8,
+ /* .MaxComputeAtomicCounters = */ 8,
+ /* .MaxComputeAtomicCounterBuffers = */ 1,
+ /* .MaxVaryingComponents = */ 60,
+ /* .MaxVertexOutputComponents = */ 64,
+ /* .MaxGeometryInputComponents = */ 64,
+ /* .MaxGeometryOutputComponents = */ 128,
+ /* .MaxFragmentInputComponents = */ 128,
+ /* .MaxImageUnits = */ 8,
+ /* .MaxCombinedImageUnitsAndFragmentOutputs = */ 8,
+ /* .MaxCombinedShaderOutputResources = */ 8,
+ /* .MaxImageSamples = */ 0,
+ /* .MaxVertexImageUniforms = */ 0,
+ /* .MaxTessControlImageUniforms = */ 0,
+ /* .MaxTessEvaluationImageUniforms = */ 0,
+ /* .MaxGeometryImageUniforms = */ 0,
+ /* .MaxFragmentImageUniforms = */ 8,
+ /* .MaxCombinedImageUniforms = */ 8,
+ /* .MaxGeometryTextureImageUnits = */ 16,
+ /* .MaxGeometryOutputVertices = */ 256,
+ /* .MaxGeometryTotalOutputComponents = */ 1024,
+ /* .MaxGeometryUniformComponents = */ 1024,
+ /* .MaxGeometryVaryingComponents = */ 64,
+ /* .MaxTessControlInputComponents = */ 128,
+ /* .MaxTessControlOutputComponents = */ 128,
+ /* .MaxTessControlTextureImageUnits = */ 16,
+ /* .MaxTessControlUniformComponents = */ 1024,
+ /* .MaxTessControlTotalOutputComponents = */ 4096,
+ /* .MaxTessEvaluationInputComponents = */ 128,
+ /* .MaxTessEvaluationOutputComponents = */ 128,
+ /* .MaxTessEvaluationTextureImageUnits = */ 16,
+ /* .MaxTessEvaluationUniformComponents = */ 1024,
+ /* .MaxTessPatchComponents = */ 120,
+ /* .MaxPatchVertices = */ 32,
+ /* .MaxTessGenLevel = */ 64,
+ /* .MaxViewports = */ 16,
+ /* .MaxVertexAtomicCounters = */ 0,
+ /* .MaxTessControlAtomicCounters = */ 0,
+ /* .MaxTessEvaluationAtomicCounters = */ 0,
+ /* .MaxGeometryAtomicCounters = */ 0,
+ /* .MaxFragmentAtomicCounters = */ 8,
+ /* .MaxCombinedAtomicCounters = */ 8,
+ /* .MaxAtomicCounterBindings = */ 1,
+ /* .MaxVertexAtomicCounterBuffers = */ 0,
+ /* .MaxTessControlAtomicCounterBuffers = */ 0,
+ /* .MaxTessEvaluationAtomicCounterBuffers = */ 0,
+ /* .MaxGeometryAtomicCounterBuffers = */ 0,
+ /* .MaxFragmentAtomicCounterBuffers = */ 1,
+ /* .MaxCombinedAtomicCounterBuffers = */ 1,
+ /* .MaxAtomicCounterBufferSize = */ 16384,
+ /* .MaxTransformFeedbackBuffers = */ 4,
+ /* .MaxTransformFeedbackInterleavedComponents = */ 64,
+ /* .MaxCullDistances = */ 8,
+ /* .MaxCombinedClipAndCullDistances = */ 8,
+ /* .MaxSamples = */ 4,
+ /* .limits = */ {
+ /* .nonInductiveForLoops = */ 1,
+ /* .whileLoops = */ 1,
+ /* .doWhileLoops = */ 1,
+ /* .generalUniformIndexing = */ 1,
+ /* .generalAttributeMatrixVectorIndexing = */ 1,
+ /* .generalVaryingIndexing = */ 1,
+ /* .generalSamplerIndexing = */ 1,
+ /* .generalVariableIndexing = */ 1,
+ /* .generalConstantMatrixVectorIndexing = */ 1,
+ }};
+
+std::string GetDefaultTBuiltInResourceString()
+{
+ std::ostringstream ostream;
+
+ ostream << "MaxLights " << DefaultTBuiltInResource.maxLights << "\n"
+ << "MaxClipPlanes " << DefaultTBuiltInResource.maxClipPlanes << "\n"
+ << "MaxTextureUnits " << DefaultTBuiltInResource.maxTextureUnits << "\n"
+ << "MaxTextureCoords " << DefaultTBuiltInResource.maxTextureCoords << "\n"
+ << "MaxVertexAttribs " << DefaultTBuiltInResource.maxVertexAttribs << "\n"
+ << "MaxVertexUniformComponents " << DefaultTBuiltInResource.maxVertexUniformComponents << "\n"
+ << "MaxVaryingFloats " << DefaultTBuiltInResource.maxVaryingFloats << "\n"
+ << "MaxVertexTextureImageUnits " << DefaultTBuiltInResource.maxVertexTextureImageUnits << "\n"
+ << "MaxCombinedTextureImageUnits " << DefaultTBuiltInResource.maxCombinedTextureImageUnits << "\n"
+ << "MaxTextureImageUnits " << DefaultTBuiltInResource.maxTextureImageUnits << "\n"
+ << "MaxFragmentUniformComponents " << DefaultTBuiltInResource.maxFragmentUniformComponents << "\n"
+ << "MaxDrawBuffers " << DefaultTBuiltInResource.maxDrawBuffers << "\n"
+ << "MaxVertexUniformVectors " << DefaultTBuiltInResource.maxVertexUniformVectors << "\n"
+ << "MaxVaryingVectors " << DefaultTBuiltInResource.maxVaryingVectors << "\n"
+ << "MaxFragmentUniformVectors " << DefaultTBuiltInResource.maxFragmentUniformVectors << "\n"
+ << "MaxVertexOutputVectors " << DefaultTBuiltInResource.maxVertexOutputVectors << "\n"
+ << "MaxFragmentInputVectors " << DefaultTBuiltInResource.maxFragmentInputVectors << "\n"
+ << "MinProgramTexelOffset " << DefaultTBuiltInResource.minProgramTexelOffset << "\n"
+ << "MaxProgramTexelOffset " << DefaultTBuiltInResource.maxProgramTexelOffset << "\n"
+ << "MaxClipDistances " << DefaultTBuiltInResource.maxClipDistances << "\n"
+ << "MaxComputeWorkGroupCountX " << DefaultTBuiltInResource.maxComputeWorkGroupCountX << "\n"
+ << "MaxComputeWorkGroupCountY " << DefaultTBuiltInResource.maxComputeWorkGroupCountY << "\n"
+ << "MaxComputeWorkGroupCountZ " << DefaultTBuiltInResource.maxComputeWorkGroupCountZ << "\n"
+ << "MaxComputeWorkGroupSizeX " << DefaultTBuiltInResource.maxComputeWorkGroupSizeX << "\n"
+ << "MaxComputeWorkGroupSizeY " << DefaultTBuiltInResource.maxComputeWorkGroupSizeY << "\n"
+ << "MaxComputeWorkGroupSizeZ " << DefaultTBuiltInResource.maxComputeWorkGroupSizeZ << "\n"
+ << "MaxComputeUniformComponents " << DefaultTBuiltInResource.maxComputeUniformComponents << "\n"
+ << "MaxComputeTextureImageUnits " << DefaultTBuiltInResource.maxComputeTextureImageUnits << "\n"
+ << "MaxComputeImageUniforms " << DefaultTBuiltInResource.maxComputeImageUniforms << "\n"
+ << "MaxComputeAtomicCounters " << DefaultTBuiltInResource.maxComputeAtomicCounters << "\n"
+ << "MaxComputeAtomicCounterBuffers " << DefaultTBuiltInResource.maxComputeAtomicCounterBuffers << "\n"
+ << "MaxVaryingComponents " << DefaultTBuiltInResource.maxVaryingComponents << "\n"
+ << "MaxVertexOutputComponents " << DefaultTBuiltInResource.maxVertexOutputComponents << "\n"
+ << "MaxGeometryInputComponents " << DefaultTBuiltInResource.maxGeometryInputComponents << "\n"
+ << "MaxGeometryOutputComponents " << DefaultTBuiltInResource.maxGeometryOutputComponents << "\n"
+ << "MaxFragmentInputComponents " << DefaultTBuiltInResource.maxFragmentInputComponents << "\n"
+ << "MaxImageUnits " << DefaultTBuiltInResource.maxImageUnits << "\n"
+ << "MaxCombinedImageUnitsAndFragmentOutputs " << DefaultTBuiltInResource.maxCombinedImageUnitsAndFragmentOutputs << "\n"
+ << "MaxCombinedShaderOutputResources " << DefaultTBuiltInResource.maxCombinedShaderOutputResources << "\n"
+ << "MaxImageSamples " << DefaultTBuiltInResource.maxImageSamples << "\n"
+ << "MaxVertexImageUniforms " << DefaultTBuiltInResource.maxVertexImageUniforms << "\n"
+ << "MaxTessControlImageUniforms " << DefaultTBuiltInResource.maxTessControlImageUniforms << "\n"
+ << "MaxTessEvaluationImageUniforms " << DefaultTBuiltInResource.maxTessEvaluationImageUniforms << "\n"
+ << "MaxGeometryImageUniforms " << DefaultTBuiltInResource.maxGeometryImageUniforms << "\n"
+ << "MaxFragmentImageUniforms " << DefaultTBuiltInResource.maxFragmentImageUniforms << "\n"
+ << "MaxCombinedImageUniforms " << DefaultTBuiltInResource.maxCombinedImageUniforms << "\n"
+ << "MaxGeometryTextureImageUnits " << DefaultTBuiltInResource.maxGeometryTextureImageUnits << "\n"
+ << "MaxGeometryOutputVertices " << DefaultTBuiltInResource.maxGeometryOutputVertices << "\n"
+ << "MaxGeometryTotalOutputComponents " << DefaultTBuiltInResource.maxGeometryTotalOutputComponents << "\n"
+ << "MaxGeometryUniformComponents " << DefaultTBuiltInResource.maxGeometryUniformComponents << "\n"
+ << "MaxGeometryVaryingComponents " << DefaultTBuiltInResource.maxGeometryVaryingComponents << "\n"
+ << "MaxTessControlInputComponents " << DefaultTBuiltInResource.maxTessControlInputComponents << "\n"
+ << "MaxTessControlOutputComponents " << DefaultTBuiltInResource.maxTessControlOutputComponents << "\n"
+ << "MaxTessControlTextureImageUnits " << DefaultTBuiltInResource.maxTessControlTextureImageUnits << "\n"
+ << "MaxTessControlUniformComponents " << DefaultTBuiltInResource.maxTessControlUniformComponents << "\n"
+ << "MaxTessControlTotalOutputComponents " << DefaultTBuiltInResource.maxTessControlTotalOutputComponents << "\n"
+ << "MaxTessEvaluationInputComponents " << DefaultTBuiltInResource.maxTessEvaluationInputComponents << "\n"
+ << "MaxTessEvaluationOutputComponents " << DefaultTBuiltInResource.maxTessEvaluationOutputComponents << "\n"
+ << "MaxTessEvaluationTextureImageUnits " << DefaultTBuiltInResource.maxTessEvaluationTextureImageUnits << "\n"
+ << "MaxTessEvaluationUniformComponents " << DefaultTBuiltInResource.maxTessEvaluationUniformComponents << "\n"
+ << "MaxTessPatchComponents " << DefaultTBuiltInResource.maxTessPatchComponents << "\n"
+ << "MaxPatchVertices " << DefaultTBuiltInResource.maxPatchVertices << "\n"
+ << "MaxTessGenLevel " << DefaultTBuiltInResource.maxTessGenLevel << "\n"
+ << "MaxViewports " << DefaultTBuiltInResource.maxViewports << "\n"
+ << "MaxVertexAtomicCounters " << DefaultTBuiltInResource.maxVertexAtomicCounters << "\n"
+ << "MaxTessControlAtomicCounters " << DefaultTBuiltInResource.maxTessControlAtomicCounters << "\n"
+ << "MaxTessEvaluationAtomicCounters " << DefaultTBuiltInResource.maxTessEvaluationAtomicCounters << "\n"
+ << "MaxGeometryAtomicCounters " << DefaultTBuiltInResource.maxGeometryAtomicCounters << "\n"
+ << "MaxFragmentAtomicCounters " << DefaultTBuiltInResource.maxFragmentAtomicCounters << "\n"
+ << "MaxCombinedAtomicCounters " << DefaultTBuiltInResource.maxCombinedAtomicCounters << "\n"
+ << "MaxAtomicCounterBindings " << DefaultTBuiltInResource.maxAtomicCounterBindings << "\n"
+ << "MaxVertexAtomicCounterBuffers " << DefaultTBuiltInResource.maxVertexAtomicCounterBuffers << "\n"
+ << "MaxTessControlAtomicCounterBuffers " << DefaultTBuiltInResource.maxTessControlAtomicCounterBuffers << "\n"
+ << "MaxTessEvaluationAtomicCounterBuffers " << DefaultTBuiltInResource.maxTessEvaluationAtomicCounterBuffers << "\n"
+ << "MaxGeometryAtomicCounterBuffers " << DefaultTBuiltInResource.maxGeometryAtomicCounterBuffers << "\n"
+ << "MaxFragmentAtomicCounterBuffers " << DefaultTBuiltInResource.maxFragmentAtomicCounterBuffers << "\n"
+ << "MaxCombinedAtomicCounterBuffers " << DefaultTBuiltInResource.maxCombinedAtomicCounterBuffers << "\n"
+ << "MaxAtomicCounterBufferSize " << DefaultTBuiltInResource.maxAtomicCounterBufferSize << "\n"
+ << "MaxTransformFeedbackBuffers " << DefaultTBuiltInResource.maxTransformFeedbackBuffers << "\n"
+ << "MaxTransformFeedbackInterleavedComponents " << DefaultTBuiltInResource.maxTransformFeedbackInterleavedComponents << "\n"
+ << "MaxCullDistances " << DefaultTBuiltInResource.maxCullDistances << "\n"
+ << "MaxCombinedClipAndCullDistances " << DefaultTBuiltInResource.maxCombinedClipAndCullDistances << "\n"
+ << "MaxSamples " << DefaultTBuiltInResource.maxSamples << "\n"
+
+ << "nonInductiveForLoops " << DefaultTBuiltInResource.limits.nonInductiveForLoops << "\n"
+ << "whileLoops " << DefaultTBuiltInResource.limits.whileLoops << "\n"
+ << "doWhileLoops " << DefaultTBuiltInResource.limits.doWhileLoops << "\n"
+ << "generalUniformIndexing " << DefaultTBuiltInResource.limits.generalUniformIndexing << "\n"
+ << "generalAttributeMatrixVectorIndexing " << DefaultTBuiltInResource.limits.generalAttributeMatrixVectorIndexing << "\n"
+ << "generalVaryingIndexing " << DefaultTBuiltInResource.limits.generalVaryingIndexing << "\n"
+ << "generalSamplerIndexing " << DefaultTBuiltInResource.limits.generalSamplerIndexing << "\n"
+ << "generalVariableIndexing " << DefaultTBuiltInResource.limits.generalVariableIndexing << "\n"
+ << "generalConstantMatrixVectorIndexing " << DefaultTBuiltInResource.limits.generalConstantMatrixVectorIndexing << "\n"
+ ;
+
+ return ostream.str();
+}
+
+} // end namespace glslang
diff --git a/StandAlone/DefaultResourceLimits.h b/StandAlone/DefaultResourceLimits.h
new file mode 100644
index 0000000..fa52a2a
--- /dev/null
+++ b/StandAlone/DefaultResourceLimits.h
@@ -0,0 +1,54 @@
+//
+// Copyright (C) 2016 Google, Inc.
+//
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+//
+// Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//
+// Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+//
+// Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+
+#ifndef _DEFAULT_RESOURCE_LIMITS_INCLUDED_
+#define _DEFAULT_RESOURCE_LIMITS_INCLUDED_
+
+#include <string>
+
+#include "glslang/Include/ResourceLimits.h"
+
+namespace glslang {
+
+// These are the default resources for TBuiltInResources, used for both
+// - parsing this string for the case where the user didn't supply one,
+// - dumping out a template for user construction of a config file.
+extern const TBuiltInResource DefaultTBuiltInResource;
+
+// Returns the DefaultTBuiltInResource as a human-readable string.
+std::string GetDefaultTBuiltInResourceString();
+
+} // end namespace glslang
+
+#endif // _DEFAULT_RESOURCE_LIMITS_INCLUDED_
diff --git a/StandAlone/StandAlone.cpp b/StandAlone/StandAlone.cpp
index cc59d38..2f5a718 100644
--- a/StandAlone/StandAlone.cpp
+++ b/StandAlone/StandAlone.cpp
@@ -37,6 +37,7 @@
// this only applies to the standalone wrapper, not the front end in general
#define _CRT_SECURE_NO_WARNINGS
+#include "DefaultResourceLimits.h"
#include "Worklist.h"
#include "./../glslang/Include/ShHandle.h"
#include "./../glslang/Include/revision.h"
@@ -74,6 +75,7 @@
EOptionVulkanRules = 0x2000,
EOptionDefaultDesktop = 0x4000,
EOptionOutputPreprocessed = 0x8000,
+ EOptionReadHlsl = 0x10000,
};
//
@@ -111,108 +113,7 @@
std::string ConfigFile;
//
-// These are the default resources for TBuiltInResources, used for both
-// - parsing this string for the case where the user didn't supply one
-// - dumping out a template for user construction of a config file
-//
-const char* DefaultConfig =
- "MaxLights 32\n"
- "MaxClipPlanes 6\n"
- "MaxTextureUnits 32\n"
- "MaxTextureCoords 32\n"
- "MaxVertexAttribs 64\n"
- "MaxVertexUniformComponents 4096\n"
- "MaxVaryingFloats 64\n"
- "MaxVertexTextureImageUnits 32\n"
- "MaxCombinedTextureImageUnits 80\n"
- "MaxTextureImageUnits 32\n"
- "MaxFragmentUniformComponents 4096\n"
- "MaxDrawBuffers 32\n"
- "MaxVertexUniformVectors 128\n"
- "MaxVaryingVectors 8\n"
- "MaxFragmentUniformVectors 16\n"
- "MaxVertexOutputVectors 16\n"
- "MaxFragmentInputVectors 15\n"
- "MinProgramTexelOffset -8\n"
- "MaxProgramTexelOffset 7\n"
- "MaxClipDistances 8\n"
- "MaxComputeWorkGroupCountX 65535\n"
- "MaxComputeWorkGroupCountY 65535\n"
- "MaxComputeWorkGroupCountZ 65535\n"
- "MaxComputeWorkGroupSizeX 1024\n"
- "MaxComputeWorkGroupSizeY 1024\n"
- "MaxComputeWorkGroupSizeZ 64\n"
- "MaxComputeUniformComponents 1024\n"
- "MaxComputeTextureImageUnits 16\n"
- "MaxComputeImageUniforms 8\n"
- "MaxComputeAtomicCounters 8\n"
- "MaxComputeAtomicCounterBuffers 1\n"
- "MaxVaryingComponents 60\n"
- "MaxVertexOutputComponents 64\n"
- "MaxGeometryInputComponents 64\n"
- "MaxGeometryOutputComponents 128\n"
- "MaxFragmentInputComponents 128\n"
- "MaxImageUnits 8\n"
- "MaxCombinedImageUnitsAndFragmentOutputs 8\n"
- "MaxCombinedShaderOutputResources 8\n"
- "MaxImageSamples 0\n"
- "MaxVertexImageUniforms 0\n"
- "MaxTessControlImageUniforms 0\n"
- "MaxTessEvaluationImageUniforms 0\n"
- "MaxGeometryImageUniforms 0\n"
- "MaxFragmentImageUniforms 8\n"
- "MaxCombinedImageUniforms 8\n"
- "MaxGeometryTextureImageUnits 16\n"
- "MaxGeometryOutputVertices 256\n"
- "MaxGeometryTotalOutputComponents 1024\n"
- "MaxGeometryUniformComponents 1024\n"
- "MaxGeometryVaryingComponents 64\n"
- "MaxTessControlInputComponents 128\n"
- "MaxTessControlOutputComponents 128\n"
- "MaxTessControlTextureImageUnits 16\n"
- "MaxTessControlUniformComponents 1024\n"
- "MaxTessControlTotalOutputComponents 4096\n"
- "MaxTessEvaluationInputComponents 128\n"
- "MaxTessEvaluationOutputComponents 128\n"
- "MaxTessEvaluationTextureImageUnits 16\n"
- "MaxTessEvaluationUniformComponents 1024\n"
- "MaxTessPatchComponents 120\n"
- "MaxPatchVertices 32\n"
- "MaxTessGenLevel 64\n"
- "MaxViewports 16\n"
- "MaxVertexAtomicCounters 0\n"
- "MaxTessControlAtomicCounters 0\n"
- "MaxTessEvaluationAtomicCounters 0\n"
- "MaxGeometryAtomicCounters 0\n"
- "MaxFragmentAtomicCounters 8\n"
- "MaxCombinedAtomicCounters 8\n"
- "MaxAtomicCounterBindings 1\n"
- "MaxVertexAtomicCounterBuffers 0\n"
- "MaxTessControlAtomicCounterBuffers 0\n"
- "MaxTessEvaluationAtomicCounterBuffers 0\n"
- "MaxGeometryAtomicCounterBuffers 0\n"
- "MaxFragmentAtomicCounterBuffers 1\n"
- "MaxCombinedAtomicCounterBuffers 1\n"
- "MaxAtomicCounterBufferSize 16384\n"
- "MaxTransformFeedbackBuffers 4\n"
- "MaxTransformFeedbackInterleavedComponents 64\n"
- "MaxCullDistances 8\n"
- "MaxCombinedClipAndCullDistances 8\n"
- "MaxSamples 4\n"
-
- "nonInductiveForLoops 1\n"
- "whileLoops 1\n"
- "doWhileLoops 1\n"
- "generalUniformIndexing 1\n"
- "generalAttributeMatrixVectorIndexing 1\n"
- "generalVaryingIndexing 1\n"
- "generalSamplerIndexing 1\n"
- "generalVariableIndexing 1\n"
- "generalConstantMatrixVectorIndexing 1\n"
- ;
-
-//
-// Parse either a .conf file provided by the user or the default string above.
+// Parse either a .conf file provided by the user or the default from glslang::DefaultTBuiltInResource
//
void ProcessConfigFile()
{
@@ -229,8 +130,8 @@
}
if (config == 0) {
- config = new char[strlen(DefaultConfig) + 1];
- strcpy(config, DefaultConfig);
+ Resources = glslang::DefaultTBuiltInResource;
+ return;
}
const char* delims = " \t\n\r";
@@ -449,6 +350,7 @@
int Options = 0;
const char* ExecutableName = nullptr;
const char* binaryFileName = nullptr;
+const char* entryPointName = nullptr;
//
// Create the default name for saving a binary if -o is not provided.
@@ -537,6 +439,19 @@
case 'd':
Options |= EOptionDefaultDesktop;
break;
+ case 'D':
+ Options |= EOptionReadHlsl;
+ break;
+ case 'e':
+ // HLSL todo: entry point handle needs much more sophistication.
+ // This is okay for one compilation unit with one entry point.
+ entryPointName = argv[1];
+ if (argc > 0) {
+ argc--;
+ argv++;
+ } else
+ Error("no <entry-point> provided for -e");
+ break;
case 'h':
usage();
break;
@@ -616,6 +531,8 @@
messages = (EShMessages)(messages | EShMsgVulkanRules);
if (Options & EOptionOutputPreprocessed)
messages = (EShMessages)(messages | EShMsgOnlyPreprocessor);
+ if (Options & EOptionReadHlsl)
+ messages = (EShMessages)(messages | EShMsgReadHlsl);
}
//
@@ -693,14 +610,17 @@
const auto &compUnit = *it;
glslang::TShader* shader = new glslang::TShader(compUnit.stage);
shader->setStrings(compUnit.text, 1);
+ if (entryPointName) // HLSL todo: this needs to be tracked per compUnits
+ shader->setEntryPoint(entryPointName);
shaders.push_back(shader);
const int defaultVersion = Options & EOptionDefaultDesktop? 110: 100;
if (Options & EOptionOutputPreprocessed) {
std::string str;
+ glslang::TShader::ForbidInclude includer;
if (shader->preprocess(&Resources, defaultVersion, ENoProfile, false, false,
- messages, &str, glslang::TShader::ForbidInclude())) {
+ messages, &str, includer)) {
PutsIfNonEmpty(str.c_str());
} else {
CompileFailed = true;
@@ -726,20 +646,24 @@
// Program-level processing...
//
+ // Link
if (! (Options & EOptionOutputPreprocessed) && ! program.link(messages))
LinkFailed = true;
+ // Report
if (! (Options & EOptionSuppressInfolog) &&
! (Options & EOptionMemoryLeakMode)) {
PutsIfNonEmpty(program.getInfoLog());
PutsIfNonEmpty(program.getInfoDebugLog());
}
+ // Reflect
if (Options & EOptionDumpReflection) {
program.buildReflection();
program.dumpReflection();
}
+ // Dump SPIR-V
if (Options & EOptionSpv) {
if (CompileFailed || LinkFailed)
printf("SPIR-V is not generated for failed compile or link\n");
@@ -831,7 +755,7 @@
ProcessArguments(argc, argv);
if (Options & EOptionDumpConfig) {
- printf("%s", DefaultConfig);
+ printf("%s", glslang::GetDefaultTBuiltInResourceString().c_str());
if (Worklist.empty())
return ESuccess;
}
@@ -1030,6 +954,8 @@
" creates the default configuration file (redirect to a .conf file)\n"
" -d default to desktop (#version 110) when there is no shader #version\n"
" (default is ES version 100)\n"
+ " -D input is HLSL\n"
+ " -e specify entry-point name\n"
" -h print this usage message\n"
" -i intermediate tree (glslang AST) is printed out\n"
" -l link all input files together to form a single module\n"
diff --git a/Test/baseResults/150.geom.out b/Test/baseResults/150.geom.out
index aa00868..48b7925 100644
--- a/Test/baseResults/150.geom.out
+++ b/Test/baseResults/150.geom.out
@@ -215,9 +215,9 @@
0:33 Constant:
0:33 3 (const int)
0:33 direct index (temp float ClipDistance)
-0:33 gl_ClipDistance: direct index for structure (in 1-element array of float ClipDistance)
-0:33 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
-0:33 'gl_in' (in 4-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
+0:33 gl_ClipDistance: direct index for structure (in 3-element array of float ClipDistance)
+0:33 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
+0:33 'gl_in' (in 4-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
0:33 Constant:
0:33 1 (const int)
0:33 Constant:
@@ -230,8 +230,8 @@
0:34 Constant:
0:34 0 (const uint)
0:34 gl_Position: direct index for structure (in 4-component vector of float Position)
-0:34 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
-0:34 'gl_in' (in 4-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
+0:34 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
+0:34 'gl_in' (in 4-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
0:34 Constant:
0:34 0 (const int)
0:34 Constant:
@@ -242,8 +242,8 @@
0:35 Constant:
0:35 1 (const uint)
0:35 gl_PointSize: direct index for structure (in float PointSize)
-0:35 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
-0:35 'gl_in' (in 4-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
+0:35 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
+0:35 'gl_in' (in 4-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
0:35 Constant:
0:35 3 (const int)
0:35 Constant:
@@ -293,7 +293,7 @@
0:? 'toF' (layout(stream=0 ) out block{layout(stream=0 ) out 3-component vector of float color})
0:? 'anon@0' (layout(stream=0 ) out block{layout(stream=0 ) out 3-component vector of float color})
0:? 'anon@1' (layout(stream=0 ) out block{layout(stream=0 ) gl_Position 4-component vector of float Position gl_Position, layout(stream=0 ) gl_PointSize float PointSize gl_PointSize, layout(stream=0 ) out 4-element array of float ClipDistance gl_ClipDistance})
-0:? 'gl_in' (in 4-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
+0:? 'gl_in' (in 4-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
0:? 'ov0' (layout(stream=0 ) out 4-component vector of float)
0:? 'ov4' (layout(stream=4 ) out 4-component vector of float)
0:? 'o1v0' (layout(stream=0 ) out 4-component vector of float)
diff --git a/Test/baseResults/150.tesc.out b/Test/baseResults/150.tesc.out
index a5289c9..8b7ab7d 100644
--- a/Test/baseResults/150.tesc.out
+++ b/Test/baseResults/150.tesc.out
@@ -932,8 +932,8 @@
0:20 move second child to first child (temp 4-component vector of float)
0:20 'p' (temp 4-component vector of float)
0:20 gl_Position: direct index for structure (in 4-component vector of float Position)
-0:20 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
-0:20 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
+0:20 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
+0:20 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
0:20 Constant:
0:20 1 (const int)
0:20 Constant:
@@ -942,8 +942,8 @@
0:21 move second child to first child (temp float)
0:21 'ps' (temp float)
0:21 gl_PointSize: direct index for structure (in float PointSize)
-0:21 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
-0:21 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
+0:21 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
+0:21 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
0:21 Constant:
0:21 1 (const int)
0:21 Constant:
@@ -952,9 +952,9 @@
0:22 move second child to first child (temp float)
0:22 'cd' (temp float)
0:22 direct index (temp float ClipDistance)
-0:22 gl_ClipDistance: direct index for structure (in 1-element array of float ClipDistance)
-0:22 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
-0:22 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
+0:22 gl_ClipDistance: direct index for structure (in 3-element array of float ClipDistance)
+0:22 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
+0:22 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
0:22 Constant:
0:22 1 (const int)
0:22 Constant:
@@ -975,25 +975,25 @@
0:26 'gl_InvocationID' (in int InvocationID)
0:28 move second child to first child (temp 4-component vector of float)
0:28 gl_Position: direct index for structure (out 4-component vector of float Position)
-0:28 indirect index (temp block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 1-element array of float ClipDistance gl_ClipDistance})
-0:28 'gl_out' (out 4-element array of block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 1-element array of float ClipDistance gl_ClipDistance})
+0:28 indirect index (temp block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 2-element array of float ClipDistance gl_ClipDistance})
+0:28 'gl_out' (out 4-element array of block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 2-element array of float ClipDistance gl_ClipDistance})
0:28 'gl_InvocationID' (in int InvocationID)
0:28 Constant:
0:28 0 (const int)
0:28 'p' (temp 4-component vector of float)
0:29 move second child to first child (temp float)
0:29 gl_PointSize: direct index for structure (out float PointSize)
-0:29 indirect index (temp block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 1-element array of float ClipDistance gl_ClipDistance})
-0:29 'gl_out' (out 4-element array of block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 1-element array of float ClipDistance gl_ClipDistance})
+0:29 indirect index (temp block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 2-element array of float ClipDistance gl_ClipDistance})
+0:29 'gl_out' (out 4-element array of block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 2-element array of float ClipDistance gl_ClipDistance})
0:29 'gl_InvocationID' (in int InvocationID)
0:29 Constant:
0:29 1 (const int)
0:29 'ps' (temp float)
0:30 move second child to first child (temp float)
0:30 direct index (temp float ClipDistance)
-0:30 gl_ClipDistance: direct index for structure (out 1-element array of float ClipDistance)
-0:30 indirect index (temp block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 1-element array of float ClipDistance gl_ClipDistance})
-0:30 'gl_out' (out 4-element array of block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 1-element array of float ClipDistance gl_ClipDistance})
+0:30 gl_ClipDistance: direct index for structure (out 2-element array of float ClipDistance)
+0:30 indirect index (temp block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 2-element array of float ClipDistance gl_ClipDistance})
+0:30 'gl_out' (out 4-element array of block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 2-element array of float ClipDistance gl_ClipDistance})
0:30 'gl_InvocationID' (in int InvocationID)
0:30 Constant:
0:30 2 (const int)
@@ -1027,8 +1027,8 @@
0:23 move second child to first child (temp 4-component vector of float)
0:23 'p' (temp 4-component vector of float)
0:23 gl_Position: direct index for structure (in 4-component vector of float Position)
-0:23 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
-0:23 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
+0:23 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
+0:23 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
0:23 Constant:
0:23 1 (const int)
0:23 Constant:
@@ -1037,8 +1037,8 @@
0:24 move second child to first child (temp float)
0:24 'ps' (temp float)
0:24 gl_PointSize: direct index for structure (in float PointSize)
-0:24 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
-0:24 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
+0:24 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
+0:24 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
0:24 Constant:
0:24 1 (const int)
0:24 Constant:
@@ -1047,9 +1047,9 @@
0:25 move second child to first child (temp float)
0:25 'cd' (temp float)
0:25 direct index (temp float ClipDistance)
-0:25 gl_ClipDistance: direct index for structure (in 1-element array of float ClipDistance)
-0:25 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
-0:25 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
+0:25 gl_ClipDistance: direct index for structure (in 3-element array of float ClipDistance)
+0:25 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
+0:25 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
0:25 Constant:
0:25 1 (const int)
0:25 Constant:
@@ -1070,25 +1070,25 @@
0:29 'gl_InvocationID' (in int InvocationID)
0:31 move second child to first child (temp 4-component vector of float)
0:31 gl_Position: direct index for structure (out 4-component vector of float Position)
-0:31 indirect index (temp block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 1-element array of float ClipDistance gl_ClipDistance})
-0:31 'gl_out' (out 4-element array of block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 1-element array of float ClipDistance gl_ClipDistance})
+0:31 indirect index (temp block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 2-element array of float ClipDistance gl_ClipDistance})
+0:31 'gl_out' (out 4-element array of block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 2-element array of float ClipDistance gl_ClipDistance})
0:31 'gl_InvocationID' (in int InvocationID)
0:31 Constant:
0:31 0 (const int)
0:31 'p' (temp 4-component vector of float)
0:32 move second child to first child (temp float)
0:32 gl_PointSize: direct index for structure (out float PointSize)
-0:32 indirect index (temp block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 1-element array of float ClipDistance gl_ClipDistance})
-0:32 'gl_out' (out 4-element array of block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 1-element array of float ClipDistance gl_ClipDistance})
+0:32 indirect index (temp block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 2-element array of float ClipDistance gl_ClipDistance})
+0:32 'gl_out' (out 4-element array of block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 2-element array of float ClipDistance gl_ClipDistance})
0:32 'gl_InvocationID' (in int InvocationID)
0:32 Constant:
0:32 1 (const int)
0:32 'ps' (temp float)
0:33 move second child to first child (temp float)
0:33 direct index (temp float ClipDistance)
-0:33 gl_ClipDistance: direct index for structure (out 1-element array of float ClipDistance)
-0:33 indirect index (temp block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 1-element array of float ClipDistance gl_ClipDistance})
-0:33 'gl_out' (out 4-element array of block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 1-element array of float ClipDistance gl_ClipDistance})
+0:33 gl_ClipDistance: direct index for structure (out 2-element array of float ClipDistance)
+0:33 indirect index (temp block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 2-element array of float ClipDistance gl_ClipDistance})
+0:33 'gl_out' (out 4-element array of block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 2-element array of float ClipDistance gl_ClipDistance})
0:33 'gl_InvocationID' (in int InvocationID)
0:33 Constant:
0:33 2 (const int)
@@ -1158,8 +1158,8 @@
0:67 Function Parameters:
0:69 Sequence
0:69 gl_PointSize: direct index for structure (out float PointSize)
-0:69 direct index (temp block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 1-element array of float ClipDistance gl_ClipDistance})
-0:69 'gl_out' (out 4-element array of block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 1-element array of float ClipDistance gl_ClipDistance})
+0:69 direct index (temp block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 2-element array of float ClipDistance gl_ClipDistance})
+0:69 'gl_out' (out 4-element array of block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 2-element array of float ClipDistance gl_ClipDistance})
0:69 Constant:
0:69 4 (const int)
0:69 Constant:
@@ -1192,8 +1192,8 @@
0:17 move second child to first child (temp 4-component vector of float)
0:17 'p' (temp 4-component vector of float)
0:17 gl_Position: direct index for structure (in 4-component vector of float Position)
-0:17 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
-0:17 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
+0:17 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
+0:17 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
0:17 Constant:
0:17 1 (const int)
0:17 Constant:
@@ -1202,8 +1202,8 @@
0:18 move second child to first child (temp float)
0:18 'ps' (temp float)
0:18 gl_PointSize: direct index for structure (in float PointSize)
-0:18 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
-0:18 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
+0:18 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
+0:18 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
0:18 Constant:
0:18 1 (const int)
0:18 Constant:
@@ -1212,9 +1212,9 @@
0:19 move second child to first child (temp float)
0:19 'cd' (temp float)
0:19 direct index (temp float ClipDistance)
-0:19 gl_ClipDistance: direct index for structure (in 1-element array of float ClipDistance)
-0:19 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
-0:19 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
+0:19 gl_ClipDistance: direct index for structure (in 3-element array of float ClipDistance)
+0:19 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
+0:19 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
0:19 Constant:
0:19 1 (const int)
0:19 Constant:
@@ -1280,7 +1280,7 @@
0:37 0 (const int)
0:36 true case is null
0:? Linker Objects
-0:? 'gl_out' (out 4-element array of block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 1-element array of float ClipDistance gl_ClipDistance})
+0:? 'gl_out' (out 4-element array of block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 2-element array of float ClipDistance gl_ClipDistance})
0:? 'outa' (global 4-element array of int)
0:? 'patchOut' (patch out 4-component vector of float)
0:? 'patchIn' (patch in 4-component vector of float)
@@ -1324,8 +1324,8 @@
0:22 move second child to first child (temp 4-component vector of float)
0:22 'p' (temp 4-component vector of float)
0:22 gl_Position: direct index for structure (in 4-component vector of float Position)
-0:22 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
-0:22 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
+0:22 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
+0:22 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
0:22 Constant:
0:22 1 (const int)
0:22 Constant:
@@ -1334,8 +1334,8 @@
0:23 move second child to first child (temp float)
0:23 'ps' (temp float)
0:23 gl_PointSize: direct index for structure (in float PointSize)
-0:23 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
-0:23 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
+0:23 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
+0:23 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
0:23 Constant:
0:23 1 (const int)
0:23 Constant:
@@ -1344,9 +1344,9 @@
0:24 move second child to first child (temp float)
0:24 'cd' (temp float)
0:24 direct index (temp float ClipDistance)
-0:24 gl_ClipDistance: direct index for structure (in 1-element array of float ClipDistance)
-0:24 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
-0:24 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
+0:24 gl_ClipDistance: direct index for structure (in 3-element array of float ClipDistance)
+0:24 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
+0:24 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
0:24 Constant:
0:24 1 (const int)
0:24 Constant:
@@ -1414,8 +1414,8 @@
0:32 move second child to first child (temp 4-component vector of float)
0:32 'p' (temp 4-component vector of float)
0:32 gl_Position: direct index for structure (in 4-component vector of float Position)
-0:32 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
-0:32 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
+0:32 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
+0:32 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
0:32 Constant:
0:32 1 (const int)
0:32 Constant:
@@ -1424,8 +1424,8 @@
0:33 move second child to first child (temp float)
0:33 'ps' (temp float)
0:33 gl_PointSize: direct index for structure (in float PointSize)
-0:33 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
-0:33 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
+0:33 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
+0:33 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
0:33 Constant:
0:33 1 (const int)
0:33 Constant:
@@ -1434,9 +1434,9 @@
0:34 move second child to first child (temp float)
0:34 'cd' (temp float)
0:34 direct index (temp float ClipDistance)
-0:34 gl_ClipDistance: direct index for structure (in 1-element array of float ClipDistance)
-0:34 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
-0:34 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
+0:34 gl_ClipDistance: direct index for structure (in 3-element array of float ClipDistance)
+0:34 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
+0:34 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
0:34 Constant:
0:34 1 (const int)
0:34 Constant:
@@ -1572,7 +1572,7 @@
0:? 'badp2' (flat patch in 4-component vector of float)
0:? 'badp3' (noperspective patch in 4-component vector of float)
0:? 'badp4' (patch sample in 3-component vector of float)
-0:? 'gl_in' (in 32-element array of block{in 1-element array of float ClipDistance gl_ClipDistance})
+0:? 'gl_in' (in 32-element array of block{in 3-element array of float ClipDistance gl_ClipDistance})
0:? 'ina' (in 2-component vector of float)
0:? 'inb' (in 32-element array of 2-component vector of float)
0:? 'inc' (in 32-element array of 2-component vector of float)
diff --git a/Test/baseResults/400.tesc.out b/Test/baseResults/400.tesc.out
index 6a0b895..99867ca 100644
--- a/Test/baseResults/400.tesc.out
+++ b/Test/baseResults/400.tesc.out
@@ -233,8 +233,8 @@
0:23 move second child to first child (temp 4-component vector of float)
0:23 'p' (temp 4-component vector of float)
0:23 gl_Position: direct index for structure (in 4-component vector of float Position)
-0:23 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
-0:23 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
+0:23 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
+0:23 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
0:23 Constant:
0:23 1 (const int)
0:23 Constant:
@@ -243,8 +243,8 @@
0:24 move second child to first child (temp float)
0:24 'ps' (temp float)
0:24 gl_PointSize: direct index for structure (in float PointSize)
-0:24 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
-0:24 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
+0:24 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
+0:24 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
0:24 Constant:
0:24 1 (const int)
0:24 Constant:
@@ -253,9 +253,9 @@
0:25 move second child to first child (temp float)
0:25 'cd' (temp float)
0:25 direct index (temp float ClipDistance)
-0:25 gl_ClipDistance: direct index for structure (in 1-element array of float ClipDistance)
-0:25 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
-0:25 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
+0:25 gl_ClipDistance: direct index for structure (in 3-element array of float ClipDistance)
+0:25 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
+0:25 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
0:25 Constant:
0:25 1 (const int)
0:25 Constant:
@@ -276,25 +276,25 @@
0:29 'gl_InvocationID' (in int InvocationID)
0:31 move second child to first child (temp 4-component vector of float)
0:31 gl_Position: direct index for structure (out 4-component vector of float Position)
-0:31 indirect index (temp block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 1-element array of float ClipDistance gl_ClipDistance})
-0:31 'gl_out' (out 4-element array of block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 1-element array of float ClipDistance gl_ClipDistance})
+0:31 indirect index (temp block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 2-element array of float ClipDistance gl_ClipDistance})
+0:31 'gl_out' (out 4-element array of block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 2-element array of float ClipDistance gl_ClipDistance})
0:31 'gl_InvocationID' (in int InvocationID)
0:31 Constant:
0:31 0 (const int)
0:31 'p' (temp 4-component vector of float)
0:32 move second child to first child (temp float)
0:32 gl_PointSize: direct index for structure (out float PointSize)
-0:32 indirect index (temp block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 1-element array of float ClipDistance gl_ClipDistance})
-0:32 'gl_out' (out 4-element array of block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 1-element array of float ClipDistance gl_ClipDistance})
+0:32 indirect index (temp block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 2-element array of float ClipDistance gl_ClipDistance})
+0:32 'gl_out' (out 4-element array of block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 2-element array of float ClipDistance gl_ClipDistance})
0:32 'gl_InvocationID' (in int InvocationID)
0:32 Constant:
0:32 1 (const int)
0:32 'ps' (temp float)
0:33 move second child to first child (temp float)
0:33 direct index (temp float ClipDistance)
-0:33 gl_ClipDistance: direct index for structure (out 1-element array of float ClipDistance)
-0:33 indirect index (temp block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 1-element array of float ClipDistance gl_ClipDistance})
-0:33 'gl_out' (out 4-element array of block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 1-element array of float ClipDistance gl_ClipDistance})
+0:33 gl_ClipDistance: direct index for structure (out 2-element array of float ClipDistance)
+0:33 indirect index (temp block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 2-element array of float ClipDistance gl_ClipDistance})
+0:33 'gl_out' (out 4-element array of block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 2-element array of float ClipDistance gl_ClipDistance})
0:33 'gl_InvocationID' (in int InvocationID)
0:33 Constant:
0:33 2 (const int)
@@ -364,8 +364,8 @@
0:67 Function Parameters:
0:69 Sequence
0:69 gl_PointSize: direct index for structure (out float PointSize)
-0:69 direct index (temp block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 1-element array of float ClipDistance gl_ClipDistance})
-0:69 'gl_out' (out 4-element array of block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 1-element array of float ClipDistance gl_ClipDistance})
+0:69 direct index (temp block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 2-element array of float ClipDistance gl_ClipDistance})
+0:69 'gl_out' (out 4-element array of block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 2-element array of float ClipDistance gl_ClipDistance})
0:69 Constant:
0:69 4 (const int)
0:69 Constant:
@@ -390,7 +390,7 @@
0:97 'd' (temp double)
0:97 'd' (temp double)
0:? Linker Objects
-0:? 'gl_out' (out 4-element array of block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 1-element array of float ClipDistance gl_ClipDistance})
+0:? 'gl_out' (out 4-element array of block{out 4-component vector of float Position gl_Position, out float PointSize gl_PointSize, out 2-element array of float ClipDistance gl_ClipDistance})
0:? 'outa' (global 4-element array of int)
0:? 'patchIn' (patch in 4-component vector of float)
0:? 'patchOut' (patch out 4-component vector of float)
diff --git a/Test/baseResults/400.tese.out b/Test/baseResults/400.tese.out
index 55670f8..76883aa 100644
--- a/Test/baseResults/400.tese.out
+++ b/Test/baseResults/400.tese.out
@@ -179,8 +179,8 @@
0:32 move second child to first child (temp 4-component vector of float)
0:32 'p' (temp 4-component vector of float)
0:32 gl_Position: direct index for structure (in 4-component vector of float Position)
-0:32 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
-0:32 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
+0:32 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
+0:32 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
0:32 Constant:
0:32 1 (const int)
0:32 Constant:
@@ -189,8 +189,8 @@
0:33 move second child to first child (temp float)
0:33 'ps' (temp float)
0:33 gl_PointSize: direct index for structure (in float PointSize)
-0:33 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
-0:33 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
+0:33 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
+0:33 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
0:33 Constant:
0:33 1 (const int)
0:33 Constant:
@@ -199,9 +199,9 @@
0:34 move second child to first child (temp float)
0:34 'cd' (temp float)
0:34 direct index (temp float ClipDistance)
-0:34 gl_ClipDistance: direct index for structure (in 1-element array of float ClipDistance)
-0:34 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
-0:34 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
+0:34 gl_ClipDistance: direct index for structure (in 3-element array of float ClipDistance)
+0:34 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
+0:34 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
0:34 Constant:
0:34 1 (const int)
0:34 Constant:
@@ -263,7 +263,7 @@
0:? 'badp2' (flat patch in 4-component vector of float)
0:? 'badp3' (noperspective patch in 4-component vector of float)
0:? 'badp4' (patch sample in 3-component vector of float)
-0:? 'gl_in' (in 32-element array of block{in 1-element array of float ClipDistance gl_ClipDistance})
+0:? 'gl_in' (in 32-element array of block{in 3-element array of float ClipDistance gl_ClipDistance})
0:? 'ina' (in 2-component vector of float)
0:? 'inb' (in 32-element array of 2-component vector of float)
0:? 'inc' (in 32-element array of 2-component vector of float)
diff --git a/Test/baseResults/420.tesc.out b/Test/baseResults/420.tesc.out
index db65fd9..594e130 100644
--- a/Test/baseResults/420.tesc.out
+++ b/Test/baseResults/420.tesc.out
@@ -132,8 +132,8 @@
0:17 move second child to first child (temp 4-component vector of float)
0:17 'p' (temp 4-component vector of float)
0:17 gl_Position: direct index for structure (in 4-component vector of float Position)
-0:17 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
-0:17 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
+0:17 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
+0:17 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
0:17 Constant:
0:17 1 (const int)
0:17 Constant:
@@ -142,8 +142,8 @@
0:18 move second child to first child (temp float)
0:18 'ps' (temp float)
0:18 gl_PointSize: direct index for structure (in float PointSize)
-0:18 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
-0:18 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
+0:18 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
+0:18 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
0:18 Constant:
0:18 1 (const int)
0:18 Constant:
@@ -152,9 +152,9 @@
0:19 move second child to first child (temp float)
0:19 'cd' (temp float)
0:19 direct index (temp float ClipDistance)
-0:19 gl_ClipDistance: direct index for structure (in 1-element array of float ClipDistance)
-0:19 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
-0:19 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 1-element array of float ClipDistance gl_ClipDistance})
+0:19 gl_ClipDistance: direct index for structure (in 3-element array of float ClipDistance)
+0:19 direct index (temp block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
+0:19 'gl_in' (in 32-element array of block{in 4-component vector of float Position gl_Position, in float PointSize gl_PointSize, in 3-element array of float ClipDistance gl_ClipDistance})
0:19 Constant:
0:19 1 (const int)
0:19 Constant:
diff --git a/Test/baseResults/450.geom.out b/Test/baseResults/450.geom.out
index fd98d08..1579e18 100644
--- a/Test/baseResults/450.geom.out
+++ b/Test/baseResults/450.geom.out
@@ -57,9 +57,9 @@
0:13 Constant:
0:13 2 (const int)
0:13 direct index (temp float CullDistance)
-0:13 gl_CullDistance: direct index for structure (in 1-element array of float CullDistance)
-0:13 direct index (temp block{in 1-element array of float CullDistance gl_CullDistance})
-0:13 'gl_in' (in 2-element array of block{in 1-element array of float CullDistance gl_CullDistance})
+0:13 gl_CullDistance: direct index for structure (in 3-element array of float CullDistance)
+0:13 direct index (temp block{in 3-element array of float CullDistance gl_CullDistance})
+0:13 'gl_in' (in 2-element array of block{in 3-element array of float CullDistance gl_CullDistance})
0:13 Constant:
0:13 1 (const int)
0:13 Constant:
@@ -67,6 +67,6 @@
0:13 Constant:
0:13 2 (const int)
0:? Linker Objects
-0:? 'gl_in' (in 2-element array of block{in 1-element array of float CullDistance gl_CullDistance})
+0:? 'gl_in' (in 2-element array of block{in 3-element array of float CullDistance gl_CullDistance})
0:? 'anon@0' (layout(stream=0 ) out block{layout(stream=0 ) out 3-element array of float CullDistance gl_CullDistance})
diff --git a/Test/baseResults/450.tesc.out b/Test/baseResults/450.tesc.out
index 8a8e9fb..66cd5c2 100644
--- a/Test/baseResults/450.tesc.out
+++ b/Test/baseResults/450.tesc.out
@@ -44,18 +44,18 @@
0:13 Sequence
0:13 move second child to first child (temp float)
0:13 direct index (temp float CullDistance)
-0:13 gl_CullDistance: direct index for structure (out 1-element array of float CullDistance)
-0:13 indirect index (temp block{out 1-element array of float CullDistance gl_CullDistance})
-0:13 'gl_out' (out 4-element array of block{out 1-element array of float CullDistance gl_CullDistance})
+0:13 gl_CullDistance: direct index for structure (out 3-element array of float CullDistance)
+0:13 indirect index (temp block{out 3-element array of float CullDistance gl_CullDistance})
+0:13 'gl_out' (out 4-element array of block{out 3-element array of float CullDistance gl_CullDistance})
0:13 'gl_InvocationID' (in int InvocationID)
0:13 Constant:
0:13 0 (const int)
0:13 Constant:
0:13 2 (const int)
0:13 direct index (temp float CullDistance)
-0:13 gl_CullDistance: direct index for structure (in 1-element array of float CullDistance)
-0:13 direct index (temp block{in 1-element array of float CullDistance gl_CullDistance})
-0:13 'gl_in' (in 32-element array of block{in 1-element array of float CullDistance gl_CullDistance})
+0:13 gl_CullDistance: direct index for structure (in 3-element array of float CullDistance)
+0:13 direct index (temp block{in 3-element array of float CullDistance gl_CullDistance})
+0:13 'gl_in' (in 32-element array of block{in 3-element array of float CullDistance gl_CullDistance})
0:13 Constant:
0:13 1 (const int)
0:13 Constant:
@@ -63,6 +63,6 @@
0:13 Constant:
0:13 2 (const int)
0:? Linker Objects
-0:? 'gl_in' (in 32-element array of block{in 1-element array of float CullDistance gl_CullDistance})
-0:? 'gl_out' (out 4-element array of block{out 1-element array of float CullDistance gl_CullDistance})
+0:? 'gl_in' (in 32-element array of block{in 3-element array of float CullDistance gl_CullDistance})
+0:? 'gl_out' (out 4-element array of block{out 3-element array of float CullDistance gl_CullDistance})
diff --git a/Test/baseResults/450.tese.out b/Test/baseResults/450.tese.out
index c6e97b8..a1116b4 100644
--- a/Test/baseResults/450.tese.out
+++ b/Test/baseResults/450.tese.out
@@ -53,9 +53,9 @@
0:13 Constant:
0:13 2 (const int)
0:13 direct index (temp float CullDistance)
-0:13 gl_CullDistance: direct index for structure (in 1-element array of float CullDistance)
-0:13 direct index (temp block{in 1-element array of float CullDistance gl_CullDistance})
-0:13 'gl_in' (in 32-element array of block{in 1-element array of float CullDistance gl_CullDistance})
+0:13 gl_CullDistance: direct index for structure (in 3-element array of float CullDistance)
+0:13 direct index (temp block{in 3-element array of float CullDistance gl_CullDistance})
+0:13 'gl_in' (in 32-element array of block{in 3-element array of float CullDistance gl_CullDistance})
0:13 Constant:
0:13 1 (const int)
0:13 Constant:
@@ -63,6 +63,6 @@
0:13 Constant:
0:13 2 (const int)
0:? Linker Objects
-0:? 'gl_in' (in 32-element array of block{in 1-element array of float CullDistance gl_CullDistance})
+0:? 'gl_in' (in 32-element array of block{in 3-element array of float CullDistance gl_CullDistance})
0:? 'anon@0' (out block{out 3-element array of float CullDistance gl_CullDistance})
diff --git a/Test/baseResults/hlsl.frag.out b/Test/baseResults/hlsl.frag.out
new file mode 100644
index 0000000..0fae4ae
--- /dev/null
+++ b/Test/baseResults/hlsl.frag.out
@@ -0,0 +1,74 @@
+hlsl.frag
+Shader version: 100
+gl_FragCoord origin is upper left
+0:? Sequence
+0:1 move second child to first child (temp 4-component vector of float)
+0:1 'AmbientColor' (temp 4-component vector of float)
+0:? Constant:
+0:? 1.000000
+0:? 0.500000
+0:? 0.000000
+0:? 1.000000
+0:8 Function Definition: PixelShaderFunction(vf4; (temp 4-component vector of float)
+0:5 Function Parameters:
+0:5 'input' (temp 4-component vector of float)
+0:? Sequence
+0:6 Branch: Return with expression
+0:6 add (temp 4-component vector of float)
+0:6 'input' (temp 4-component vector of float)
+0:6 'AmbientColor' (temp 4-component vector of float)
+0:? Linker Objects
+0:? 'AmbientColor' (temp 4-component vector of float)
+
+
+Linked fragment stage:
+
+
+Shader version: 100
+gl_FragCoord origin is upper left
+0:? Sequence
+0:1 move second child to first child (temp 4-component vector of float)
+0:1 'AmbientColor' (temp 4-component vector of float)
+0:? Constant:
+0:? 1.000000
+0:? 0.500000
+0:? 0.000000
+0:? 1.000000
+0:8 Function Definition: PixelShaderFunction(vf4; (temp 4-component vector of float)
+0:5 Function Parameters:
+0:5 'input' (temp 4-component vector of float)
+0:? Sequence
+0:6 Branch: Return with expression
+0:6 add (temp 4-component vector of float)
+0:6 'input' (temp 4-component vector of float)
+0:6 'AmbientColor' (temp 4-component vector of float)
+0:? Linker Objects
+0:? 'AmbientColor' (temp 4-component vector of float)
+
+// Module Version 10000
+// Generated by (magic number): 80001
+// Id's are bound by 15
+
+ Capability Shader
+ 1: ExtInstImport "GLSL.std.450"
+ MemoryModel Logical GLSL450
+ EntryPoint Fragment 4 "PixelShaderFunction"
+ ExecutionMode 4 OriginUpperLeft
+ Source HLSL 100
+ Name 4 "PixelShaderFunction"
+ Name 9 "input"
+ Name 11 "AmbientColor"
+ 2: TypeVoid
+ 3: TypeFunction 2
+ 6: TypeFloat 32
+ 7: TypeVector 6(float) 4
+ 8: TypePointer Function 7(fvec4)
+4(PixelShaderFunction): 2 Function None 3
+ 5: Label
+ 9(input): 8(ptr) Variable Function
+11(AmbientColor): 8(ptr) Variable Function
+ 10: 7(fvec4) Load 9(input)
+ 12: 7(fvec4) Load 11(AmbientColor)
+ 13: 7(fvec4) FAdd 10 12
+ ReturnValue 13
+ FunctionEnd
diff --git a/Test/baseResults/spv.330.geom.out b/Test/baseResults/spv.330.geom.out
old mode 100755
new mode 100644
diff --git a/Test/baseResults/spv.400.tesc.out b/Test/baseResults/spv.400.tesc.out
index eea07ce..290a19c 100755
--- a/Test/baseResults/spv.400.tesc.out
+++ b/Test/baseResults/spv.400.tesc.out
@@ -7,68 +7,68 @@
// Module Version 10000
// Generated by (magic number): 80001
-// Id's are bound by 93
+// Id's are bound by 94
Capability Tessellation
Capability TessellationPointSize
Capability ClipDistance
1: ExtInstImport "GLSL.std.450"
MemoryModel Logical GLSL450
- EntryPoint TessellationControl 4 "main" 23 40 43 46 52 66 73 79 83 84 87 88 91 92
+ EntryPoint TessellationControl 4 "main" 24 41 44 47 55 69 74 80 84 85 88 89 92 93
ExecutionMode 4 OutputVertices 4
Source GLSL 400
SourceExtension "GL_ARB_separate_shader_objects"
Name 4 "main"
Name 12 "a"
Name 17 "p"
- Name 19 "gl_PerVertex"
- MemberName 19(gl_PerVertex) 0 "gl_Position"
- MemberName 19(gl_PerVertex) 1 "gl_PointSize"
- MemberName 19(gl_PerVertex) 2 "gl_ClipDistance"
- Name 23 "gl_in"
- Name 30 "ps"
- Name 34 "cd"
- Name 38 "pvi"
- Name 40 "gl_PatchVerticesIn"
- Name 42 "pid"
- Name 43 "gl_PrimitiveID"
- Name 45 "iid"
- Name 46 "gl_InvocationID"
- Name 48 "gl_PerVertex"
- MemberName 48(gl_PerVertex) 0 "gl_Position"
- MemberName 48(gl_PerVertex) 1 "gl_PointSize"
- MemberName 48(gl_PerVertex) 2 "gl_ClipDistance"
- Name 52 "gl_out"
- Name 66 "gl_TessLevelOuter"
- Name 73 "gl_TessLevelInner"
- Name 78 "outa"
- Name 79 "patchOut"
- Name 83 "inb"
- Name 84 "ind"
- Name 87 "ivla"
- Name 88 "ivlb"
- Name 91 "ovla"
- Name 92 "ovlb"
- MemberDecorate 19(gl_PerVertex) 0 BuiltIn Position
- MemberDecorate 19(gl_PerVertex) 1 BuiltIn PointSize
- MemberDecorate 19(gl_PerVertex) 2 BuiltIn ClipDistance
- Decorate 19(gl_PerVertex) Block
- Decorate 40(gl_PatchVerticesIn) BuiltIn PatchVertices
- Decorate 43(gl_PrimitiveID) BuiltIn PrimitiveId
- Decorate 46(gl_InvocationID) BuiltIn InvocationId
- MemberDecorate 48(gl_PerVertex) 0 BuiltIn Position
- MemberDecorate 48(gl_PerVertex) 1 BuiltIn PointSize
- MemberDecorate 48(gl_PerVertex) 2 BuiltIn ClipDistance
- Decorate 48(gl_PerVertex) Block
- Decorate 66(gl_TessLevelOuter) Patch
- Decorate 66(gl_TessLevelOuter) BuiltIn TessLevelOuter
- Decorate 73(gl_TessLevelInner) Patch
- Decorate 73(gl_TessLevelInner) BuiltIn TessLevelInner
- Decorate 79(patchOut) Patch
- Decorate 87(ivla) Location 3
- Decorate 88(ivlb) Location 4
- Decorate 91(ovla) Location 3
- Decorate 92(ovlb) Location 4
+ Name 20 "gl_PerVertex"
+ MemberName 20(gl_PerVertex) 0 "gl_Position"
+ MemberName 20(gl_PerVertex) 1 "gl_PointSize"
+ MemberName 20(gl_PerVertex) 2 "gl_ClipDistance"
+ Name 24 "gl_in"
+ Name 31 "ps"
+ Name 35 "cd"
+ Name 39 "pvi"
+ Name 41 "gl_PatchVerticesIn"
+ Name 43 "pid"
+ Name 44 "gl_PrimitiveID"
+ Name 46 "iid"
+ Name 47 "gl_InvocationID"
+ Name 51 "gl_PerVertex"
+ MemberName 51(gl_PerVertex) 0 "gl_Position"
+ MemberName 51(gl_PerVertex) 1 "gl_PointSize"
+ MemberName 51(gl_PerVertex) 2 "gl_ClipDistance"
+ Name 55 "gl_out"
+ Name 69 "gl_TessLevelOuter"
+ Name 74 "gl_TessLevelInner"
+ Name 79 "outa"
+ Name 80 "patchOut"
+ Name 84 "inb"
+ Name 85 "ind"
+ Name 88 "ivla"
+ Name 89 "ivlb"
+ Name 92 "ovla"
+ Name 93 "ovlb"
+ MemberDecorate 20(gl_PerVertex) 0 BuiltIn Position
+ MemberDecorate 20(gl_PerVertex) 1 BuiltIn PointSize
+ MemberDecorate 20(gl_PerVertex) 2 BuiltIn ClipDistance
+ Decorate 20(gl_PerVertex) Block
+ Decorate 41(gl_PatchVerticesIn) BuiltIn PatchVertices
+ Decorate 44(gl_PrimitiveID) BuiltIn PrimitiveId
+ Decorate 47(gl_InvocationID) BuiltIn InvocationId
+ MemberDecorate 51(gl_PerVertex) 0 BuiltIn Position
+ MemberDecorate 51(gl_PerVertex) 1 BuiltIn PointSize
+ MemberDecorate 51(gl_PerVertex) 2 BuiltIn ClipDistance
+ Decorate 51(gl_PerVertex) Block
+ Decorate 69(gl_TessLevelOuter) Patch
+ Decorate 69(gl_TessLevelOuter) BuiltIn TessLevelOuter
+ Decorate 74(gl_TessLevelInner) Patch
+ Decorate 74(gl_TessLevelInner) BuiltIn TessLevelInner
+ Decorate 80(patchOut) Patch
+ Decorate 88(ivla) Location 3
+ Decorate 89(ivlb) Location 4
+ Decorate 92(ovla) Location 3
+ Decorate 93(ovlb) Location 4
2: TypeVoid
3: TypeFunction 2
6: TypeInt 32 0
@@ -81,98 +81,99 @@
14: TypeFloat 32
15: TypeVector 14(float) 4
16: TypePointer Function 15(fvec4)
- 18: TypeArray 14(float) 7
-19(gl_PerVertex): TypeStruct 15(fvec4) 14(float) 18
- 20: 6(int) Constant 32
- 21: TypeArray 19(gl_PerVertex) 20
- 22: TypePointer Input 21
- 23(gl_in): 22(ptr) Variable Input
- 24: 10(int) Constant 1
- 25: 10(int) Constant 0
- 26: TypePointer Input 15(fvec4)
- 29: TypePointer Function 14(float)
- 31: TypePointer Input 14(float)
- 35: 10(int) Constant 2
- 39: TypePointer Input 10(int)
-40(gl_PatchVerticesIn): 39(ptr) Variable Input
-43(gl_PrimitiveID): 39(ptr) Variable Input
-46(gl_InvocationID): 39(ptr) Variable Input
-48(gl_PerVertex): TypeStruct 15(fvec4) 14(float) 18
- 49: 6(int) Constant 4
- 50: TypeArray 48(gl_PerVertex) 49
- 51: TypePointer Output 50
- 52(gl_out): 51(ptr) Variable Output
- 55: TypePointer Output 15(fvec4)
- 59: TypePointer Output 14(float)
- 64: TypeArray 14(float) 49
- 65: TypePointer Output 64
-66(gl_TessLevelOuter): 65(ptr) Variable Output
- 67: 10(int) Constant 3
- 68: 14(float) Constant 1078774989
- 70: 6(int) Constant 2
- 71: TypeArray 14(float) 70
- 72: TypePointer Output 71
-73(gl_TessLevelInner): 72(ptr) Variable Output
- 74: 14(float) Constant 1067869798
- 76: TypeArray 10(int) 49
- 77: TypePointer Private 76
- 78(outa): 77(ptr) Variable Private
- 79(patchOut): 55(ptr) Variable Output
- 80: TypeVector 14(float) 2
- 81: TypeArray 80(fvec2) 20
- 82: TypePointer Input 81
- 83(inb): 82(ptr) Variable Input
- 84(ind): 82(ptr) Variable Input
- 85: TypeArray 15(fvec4) 20
- 86: TypePointer Input 85
- 87(ivla): 86(ptr) Variable Input
- 88(ivlb): 86(ptr) Variable Input
- 89: TypeArray 15(fvec4) 49
- 90: TypePointer Output 89
- 91(ovla): 90(ptr) Variable Output
- 92(ovlb): 90(ptr) Variable Output
+ 18: 6(int) Constant 3
+ 19: TypeArray 14(float) 18
+20(gl_PerVertex): TypeStruct 15(fvec4) 14(float) 19
+ 21: 6(int) Constant 32
+ 22: TypeArray 20(gl_PerVertex) 21
+ 23: TypePointer Input 22
+ 24(gl_in): 23(ptr) Variable Input
+ 25: 10(int) Constant 1
+ 26: 10(int) Constant 0
+ 27: TypePointer Input 15(fvec4)
+ 30: TypePointer Function 14(float)
+ 32: TypePointer Input 14(float)
+ 36: 10(int) Constant 2
+ 40: TypePointer Input 10(int)
+41(gl_PatchVerticesIn): 40(ptr) Variable Input
+44(gl_PrimitiveID): 40(ptr) Variable Input
+47(gl_InvocationID): 40(ptr) Variable Input
+ 49: 6(int) Constant 2
+ 50: TypeArray 14(float) 49
+51(gl_PerVertex): TypeStruct 15(fvec4) 14(float) 50
+ 52: 6(int) Constant 4
+ 53: TypeArray 51(gl_PerVertex) 52
+ 54: TypePointer Output 53
+ 55(gl_out): 54(ptr) Variable Output
+ 58: TypePointer Output 15(fvec4)
+ 62: TypePointer Output 14(float)
+ 67: TypeArray 14(float) 52
+ 68: TypePointer Output 67
+69(gl_TessLevelOuter): 68(ptr) Variable Output
+ 70: 10(int) Constant 3
+ 71: 14(float) Constant 1078774989
+ 73: TypePointer Output 50
+74(gl_TessLevelInner): 73(ptr) Variable Output
+ 75: 14(float) Constant 1067869798
+ 77: TypeArray 10(int) 52
+ 78: TypePointer Private 77
+ 79(outa): 78(ptr) Variable Private
+ 80(patchOut): 58(ptr) Variable Output
+ 81: TypeVector 14(float) 2
+ 82: TypeArray 81(fvec2) 21
+ 83: TypePointer Input 82
+ 84(inb): 83(ptr) Variable Input
+ 85(ind): 83(ptr) Variable Input
+ 86: TypeArray 15(fvec4) 21
+ 87: TypePointer Input 86
+ 88(ivla): 87(ptr) Variable Input
+ 89(ivlb): 87(ptr) Variable Input
+ 90: TypeArray 15(fvec4) 52
+ 91: TypePointer Output 90
+ 92(ovla): 91(ptr) Variable Output
+ 93(ovlb): 91(ptr) Variable Output
4(main): 2 Function None 3
5: Label
12(a): 11(ptr) Variable Function
17(p): 16(ptr) Variable Function
- 30(ps): 29(ptr) Variable Function
- 34(cd): 29(ptr) Variable Function
- 38(pvi): 11(ptr) Variable Function
- 42(pid): 11(ptr) Variable Function
- 45(iid): 11(ptr) Variable Function
+ 31(ps): 30(ptr) Variable Function
+ 35(cd): 30(ptr) Variable Function
+ 39(pvi): 11(ptr) Variable Function
+ 43(pid): 11(ptr) Variable Function
+ 46(iid): 11(ptr) Variable Function
MemoryBarrier 7 8
ControlBarrier 7 7 9
Store 12(a) 13
- 27: 26(ptr) AccessChain 23(gl_in) 24 25
- 28: 15(fvec4) Load 27
- Store 17(p) 28
- 32: 31(ptr) AccessChain 23(gl_in) 24 24
- 33: 14(float) Load 32
- Store 30(ps) 33
- 36: 31(ptr) AccessChain 23(gl_in) 24 35 35
- 37: 14(float) Load 36
- Store 34(cd) 37
- 41: 10(int) Load 40(gl_PatchVerticesIn)
- Store 38(pvi) 41
- 44: 10(int) Load 43(gl_PrimitiveID)
- Store 42(pid) 44
- 47: 10(int) Load 46(gl_InvocationID)
- Store 45(iid) 47
- 53: 10(int) Load 46(gl_InvocationID)
- 54: 15(fvec4) Load 17(p)
- 56: 55(ptr) AccessChain 52(gl_out) 53 25
- Store 56 54
- 57: 10(int) Load 46(gl_InvocationID)
- 58: 14(float) Load 30(ps)
- 60: 59(ptr) AccessChain 52(gl_out) 57 24
- Store 60 58
- 61: 10(int) Load 46(gl_InvocationID)
- 62: 14(float) Load 34(cd)
- 63: 59(ptr) AccessChain 52(gl_out) 61 35 24
- Store 63 62
- 69: 59(ptr) AccessChain 66(gl_TessLevelOuter) 67
- Store 69 68
- 75: 59(ptr) AccessChain 73(gl_TessLevelInner) 24
- Store 75 74
+ 28: 27(ptr) AccessChain 24(gl_in) 25 26
+ 29: 15(fvec4) Load 28
+ Store 17(p) 29
+ 33: 32(ptr) AccessChain 24(gl_in) 25 25
+ 34: 14(float) Load 33
+ Store 31(ps) 34
+ 37: 32(ptr) AccessChain 24(gl_in) 25 36 36
+ 38: 14(float) Load 37
+ Store 35(cd) 38
+ 42: 10(int) Load 41(gl_PatchVerticesIn)
+ Store 39(pvi) 42
+ 45: 10(int) Load 44(gl_PrimitiveID)
+ Store 43(pid) 45
+ 48: 10(int) Load 47(gl_InvocationID)
+ Store 46(iid) 48
+ 56: 10(int) Load 47(gl_InvocationID)
+ 57: 15(fvec4) Load 17(p)
+ 59: 58(ptr) AccessChain 55(gl_out) 56 26
+ Store 59 57
+ 60: 10(int) Load 47(gl_InvocationID)
+ 61: 14(float) Load 31(ps)
+ 63: 62(ptr) AccessChain 55(gl_out) 60 25
+ Store 63 61
+ 64: 10(int) Load 47(gl_InvocationID)
+ 65: 14(float) Load 35(cd)
+ 66: 62(ptr) AccessChain 55(gl_out) 64 36 25
+ Store 66 65
+ 72: 62(ptr) AccessChain 69(gl_TessLevelOuter) 70
+ Store 72 71
+ 76: 62(ptr) AccessChain 74(gl_TessLevelInner) 25
+ Store 76 75
Return
FunctionEnd
diff --git a/Test/baseResults/spv.400.tese.out b/Test/baseResults/spv.400.tese.out
index 03e181c..51534b1 100755
--- a/Test/baseResults/spv.400.tese.out
+++ b/Test/baseResults/spv.400.tese.out
@@ -7,14 +7,14 @@
// Module Version 10000
// Generated by (magic number): 80001
-// Id's are bound by 98
+// Id's are bound by 96
Capability Tessellation
Capability TessellationPointSize
Capability ClipDistance
1: ExtInstImport "GLSL.std.450"
MemoryModel Logical GLSL450
- EntryPoint TessellationEvaluation 4 "main" 21 38 41 47 53 61 68 77 81 82 86 90 93 94 97
+ EntryPoint TessellationEvaluation 4 "main" 21 38 41 47 53 61 66 75 79 80 84 88 91 92 95
ExecutionMode 4 Triangles
ExecutionMode 4 SpacingFractionalOdd
ExecutionMode 4 VertexOrderCcw
@@ -41,23 +41,23 @@
Name 53 "gl_TessLevelOuter"
Name 57 "tli"
Name 61 "gl_TessLevelInner"
- Name 66 "gl_PerVertex"
- MemberName 66(gl_PerVertex) 0 "gl_Position"
- MemberName 66(gl_PerVertex) 1 "gl_PointSize"
- MemberName 66(gl_PerVertex) 2 "gl_ClipDistance"
- Name 68 ""
- Name 77 "patchIn"
- Name 81 "inb"
- Name 82 "ind"
- Name 83 "testblb"
- MemberName 83(testblb) 0 "f"
- Name 86 "blb"
- Name 87 "testbld"
- MemberName 87(testbld) 0 "f"
- Name 90 "bld"
- Name 93 "ivla"
- Name 94 "ivlb"
- Name 97 "ovla"
+ Name 64 "gl_PerVertex"
+ MemberName 64(gl_PerVertex) 0 "gl_Position"
+ MemberName 64(gl_PerVertex) 1 "gl_PointSize"
+ MemberName 64(gl_PerVertex) 2 "gl_ClipDistance"
+ Name 66 ""
+ Name 75 "patchIn"
+ Name 79 "inb"
+ Name 80 "ind"
+ Name 81 "testblb"
+ MemberName 81(testblb) 0 "f"
+ Name 84 "blb"
+ Name 85 "testbld"
+ MemberName 85(testbld) 0 "f"
+ Name 88 "bld"
+ Name 91 "ivla"
+ Name 92 "ivlb"
+ Name 95 "ovla"
MemberDecorate 17(gl_PerVertex) 0 BuiltIn Position
MemberDecorate 17(gl_PerVertex) 1 BuiltIn PointSize
MemberDecorate 17(gl_PerVertex) 2 BuiltIn ClipDistance
@@ -69,16 +69,16 @@
Decorate 53(gl_TessLevelOuter) BuiltIn TessLevelOuter
Decorate 61(gl_TessLevelInner) Patch
Decorate 61(gl_TessLevelInner) BuiltIn TessLevelInner
- MemberDecorate 66(gl_PerVertex) 0 BuiltIn Position
- MemberDecorate 66(gl_PerVertex) 1 BuiltIn PointSize
- MemberDecorate 66(gl_PerVertex) 2 BuiltIn ClipDistance
- Decorate 66(gl_PerVertex) Block
- Decorate 77(patchIn) Patch
- Decorate 83(testblb) Block
- Decorate 87(testbld) Block
- Decorate 93(ivla) Location 23
- Decorate 94(ivlb) Location 24
- Decorate 97(ovla) Location 23
+ MemberDecorate 64(gl_PerVertex) 0 BuiltIn Position
+ MemberDecorate 64(gl_PerVertex) 1 BuiltIn PointSize
+ MemberDecorate 64(gl_PerVertex) 2 BuiltIn ClipDistance
+ Decorate 64(gl_PerVertex) Block
+ Decorate 75(patchIn) Patch
+ Decorate 81(testblb) Block
+ Decorate 85(testbld) Block
+ Decorate 91(ivla) Location 23
+ Decorate 92(ivlb) Location 24
+ Decorate 95(ovla) Location 23
2: TypeVoid
3: TypeFunction 2
6: TypeInt 32 1
@@ -88,7 +88,7 @@
11: TypeVector 10(float) 4
12: TypePointer Function 11(fvec4)
14: TypeInt 32 0
- 15: 14(int) Constant 1
+ 15: 14(int) Constant 3
16: TypeArray 10(float) 15
17(gl_PerVertex): TypeStruct 11(fvec4) 10(float) 16
18: 14(int) Constant 32
@@ -117,34 +117,32 @@
59: TypeArray 10(float) 58
60: TypePointer Input 59
61(gl_TessLevelInner): 60(ptr) Variable Input
- 64: 14(int) Constant 3
- 65: TypeArray 10(float) 64
-66(gl_PerVertex): TypeStruct 11(fvec4) 10(float) 65
- 67: TypePointer Output 66(gl_PerVertex)
- 68: 67(ptr) Variable Output
- 70: TypePointer Output 11(fvec4)
- 73: TypePointer Output 10(float)
- 77(patchIn): 24(ptr) Variable Input
- 78: TypeVector 10(float) 2
- 79: TypeArray 78(fvec2) 18
- 80: TypePointer Input 79
- 81(inb): 80(ptr) Variable Input
- 82(ind): 80(ptr) Variable Input
- 83(testblb): TypeStruct 6(int)
- 84: TypeArray 83(testblb) 18
- 85: TypePointer Input 84
- 86(blb): 85(ptr) Variable Input
- 87(testbld): TypeStruct 6(int)
- 88: TypeArray 87(testbld) 18
- 89: TypePointer Input 88
- 90(bld): 89(ptr) Variable Input
- 91: TypeArray 11(fvec4) 18
- 92: TypePointer Input 91
- 93(ivla): 92(ptr) Variable Input
- 94(ivlb): 92(ptr) Variable Input
- 95: TypeArray 11(fvec4) 58
- 96: TypePointer Output 95
- 97(ovla): 96(ptr) Variable Output
+64(gl_PerVertex): TypeStruct 11(fvec4) 10(float) 16
+ 65: TypePointer Output 64(gl_PerVertex)
+ 66: 65(ptr) Variable Output
+ 68: TypePointer Output 11(fvec4)
+ 71: TypePointer Output 10(float)
+ 75(patchIn): 24(ptr) Variable Input
+ 76: TypeVector 10(float) 2
+ 77: TypeArray 76(fvec2) 18
+ 78: TypePointer Input 77
+ 79(inb): 78(ptr) Variable Input
+ 80(ind): 78(ptr) Variable Input
+ 81(testblb): TypeStruct 6(int)
+ 82: TypeArray 81(testblb) 18
+ 83: TypePointer Input 82
+ 84(blb): 83(ptr) Variable Input
+ 85(testbld): TypeStruct 6(int)
+ 86: TypeArray 85(testbld) 18
+ 87: TypePointer Input 86
+ 88(bld): 87(ptr) Variable Input
+ 89: TypeArray 11(fvec4) 18
+ 90: TypePointer Input 89
+ 91(ivla): 90(ptr) Variable Input
+ 92(ivlb): 90(ptr) Variable Input
+ 93: TypeArray 11(fvec4) 58
+ 94: TypePointer Output 93
+ 95(ovla): 94(ptr) Variable Output
4(main): 2 Function None 3
5: Label
8(a): 7(ptr) Variable Function
@@ -178,14 +176,14 @@
62: 29(ptr) AccessChain 61(gl_TessLevelInner) 22
63: 10(float) Load 62
Store 57(tli) 63
- 69: 11(fvec4) Load 13(p)
- 71: 70(ptr) AccessChain 68 23
- Store 71 69
- 72: 10(float) Load 28(ps)
- 74: 73(ptr) AccessChain 68 22
- Store 74 72
- 75: 10(float) Load 32(cd)
- 76: 73(ptr) AccessChain 68 33 33
- Store 76 75
+ 67: 11(fvec4) Load 13(p)
+ 69: 68(ptr) AccessChain 66 23
+ Store 69 67
+ 70: 10(float) Load 28(ps)
+ 72: 71(ptr) AccessChain 66 22
+ Store 72 70
+ 73: 10(float) Load 32(cd)
+ 74: 71(ptr) AccessChain 66 33 33
+ Store 74 73
Return
FunctionEnd
diff --git a/Test/baseResults/spv.specConstant.comp.out b/Test/baseResults/spv.specConstant.comp.out
index d1c9b0a..2f16f04 100644
--- a/Test/baseResults/spv.specConstant.comp.out
+++ b/Test/baseResults/spv.specConstant.comp.out
@@ -39,16 +39,16 @@
15: TypeVector 6(int) 3
16: 15(ivec3) SpecConstantComposite 12 13 14
17: 6(int) Constant 0
+ 18: 6(int) SpecConstantOp 81 16 0
19: 6(int) Constant 1
+ 20: 6(int) SpecConstantOp 81 16 1(GLSL.std.450)
+ 21: 6(int) SpecConstantOp 132 18 20
22: 6(int) Constant 2
+ 23: 6(int) SpecConstantOp 81 16 2
+ 24: 6(int) SpecConstantOp 132 21 23
25: TypePointer Uniform 6(int)
4(main): 2 Function None 3
5: Label
- 18: 6(int) CompositeExtract 16 0
- 20: 6(int) CompositeExtract 16 1
- 21: 6(int) IMul 18 20
- 23: 6(int) CompositeExtract 16 2
- 24: 6(int) IMul 21 23
26: 25(ptr) AccessChain 9(bi) 11
Store 26 24
Return
diff --git a/Test/baseResults/spv.specConstant.vert.out b/Test/baseResults/spv.specConstant.vert.out
index 862dc19..dadab07 100644
--- a/Test/baseResults/spv.specConstant.vert.out
+++ b/Test/baseResults/spv.specConstant.vert.out
@@ -7,32 +7,35 @@
// Module Version 10000
// Generated by (magic number): 80001
-// Id's are bound by 72
+// Id's are bound by 81
Capability Shader
Capability Float64
1: ExtInstImport "GLSL.std.450"
MemoryModel Logical GLSL450
- EntryPoint Vertex 4 "main" 17 19 25 50
+ EntryPoint Vertex 4 "main" 20 22 28 53
Source GLSL 400
Name 4 "main"
Name 14 "foo(vf4[s1498];"
Name 13 "p"
- Name 17 "color"
- Name 19 "ucol"
- Name 25 "size"
- Name 44 "param"
- Name 50 "dupUcol"
+ Name 17 "builtin_spec_constant("
+ Name 20 "color"
+ Name 22 "ucol"
+ Name 28 "size"
+ Name 47 "param"
+ Name 53 "dupUcol"
+ Name 76 "result"
Decorate 9 SpecId 16
- Decorate 27 SpecId 17
- Decorate 31 SpecId 22
- Decorate 36 SpecId 19
- Decorate 37 SpecId 18
- Decorate 47 SpecId 116
- Decorate 57 SpecId 117
- Decorate 60 SpecId 122
- Decorate 64 SpecId 119
- Decorate 65 SpecId 118
+ Decorate 30 SpecId 17
+ Decorate 34 SpecId 22
+ Decorate 39 SpecId 19
+ Decorate 40 SpecId 18
+ Decorate 50 SpecId 116
+ Decorate 60 SpecId 117
+ Decorate 63 SpecId 122
+ Decorate 67 SpecId 119
+ Decorate 68 SpecId 118
+ Decorate 77 SpecId 24
2: TypeVoid
3: TypeFunction 2
6: TypeFloat 32
@@ -42,83 +45,93 @@
10: TypeArray 7(fvec4) 9
11: TypePointer Function 10
12: TypeFunction 2 11(ptr)
- 16: TypePointer Output 7(fvec4)
- 17(color): 16(ptr) Variable Output
- 18: TypePointer Input 10
- 19(ucol): 18(ptr) Variable Input
- 20: 8(int) Constant 2
- 21: TypePointer Input 7(fvec4)
- 24: TypePointer Output 8(int)
- 25(size): 24(ptr) Variable Output
- 26: TypeBool
- 27: 26(bool) SpecConstantTrue
- 30: TypeInt 32 0
- 31: 30(int) SpecConstant 2
- 35: TypeFloat 64
- 36: 35(float) SpecConstant 1413754136 1074340347
- 37: 6(float) SpecConstant 1078523331
- 47: 8(int) SpecConstant 12
- 48: TypeArray 7(fvec4) 47
- 49: TypePointer Input 48
- 50(dupUcol): 49(ptr) Variable Input
- 57: 26(bool) SpecConstantTrue
- 60: 30(int) SpecConstant 2
- 64: 35(float) SpecConstant 1413754136 1074340347
- 65: 6(float) SpecConstant 1078523331
+ 16: TypeFunction 8(int)
+ 19: TypePointer Output 7(fvec4)
+ 20(color): 19(ptr) Variable Output
+ 21: TypePointer Input 10
+ 22(ucol): 21(ptr) Variable Input
+ 23: 8(int) Constant 2
+ 24: TypePointer Input 7(fvec4)
+ 27: TypePointer Output 8(int)
+ 28(size): 27(ptr) Variable Output
+ 29: TypeBool
+ 30: 29(bool) SpecConstantTrue
+ 33: TypeInt 32 0
+ 34: 33(int) SpecConstant 2
+ 38: TypeFloat 64
+ 39: 38(float) SpecConstant 1413754136 1074340347
+ 40: 6(float) SpecConstant 1078523331
+ 50: 8(int) SpecConstant 12
+ 51: TypeArray 7(fvec4) 50
+ 52: TypePointer Input 51
+ 53(dupUcol): 52(ptr) Variable Input
+ 60: 29(bool) SpecConstantTrue
+ 63: 33(int) SpecConstant 2
+ 67: 38(float) SpecConstant 1413754136 1074340347
+ 68: 6(float) SpecConstant 1078523331
+ 75: TypePointer Function 8(int)
+ 77: 8(int) SpecConstant 8
4(main): 2 Function None 3
5: Label
- 44(param): 11(ptr) Variable Function
- 22: 21(ptr) AccessChain 19(ucol) 20
- 23: 7(fvec4) Load 22
- Store 17(color) 23
- Store 25(size) 9
- SelectionMerge 29 None
- BranchConditional 27 28 29
- 28: Label
- 32: 6(float) ConvertUToF 31
- 33: 7(fvec4) Load 17(color)
- 34: 7(fvec4) VectorTimesScalar 33 32
- Store 17(color) 34
- Branch 29
- 29: Label
- 38: 35(float) FConvert 37
- 39: 35(float) FDiv 36 38
- 40: 6(float) FConvert 39
- 41: 7(fvec4) Load 17(color)
- 42: 7(fvec4) CompositeConstruct 40 40 40 40
- 43: 7(fvec4) FAdd 41 42
- Store 17(color) 43
- 45: 10 Load 19(ucol)
- Store 44(param) 45
- 46: 2 FunctionCall 14(foo(vf4[s1498];) 44(param)
+ 47(param): 11(ptr) Variable Function
+ 25: 24(ptr) AccessChain 22(ucol) 23
+ 26: 7(fvec4) Load 25
+ Store 20(color) 26
+ Store 28(size) 9
+ SelectionMerge 32 None
+ BranchConditional 30 31 32
+ 31: Label
+ 35: 6(float) ConvertUToF 34
+ 36: 7(fvec4) Load 20(color)
+ 37: 7(fvec4) VectorTimesScalar 36 35
+ Store 20(color) 37
+ Branch 32
+ 32: Label
+ 41: 38(float) FConvert 40
+ 42: 38(float) FDiv 39 41
+ 43: 6(float) FConvert 42
+ 44: 7(fvec4) Load 20(color)
+ 45: 7(fvec4) CompositeConstruct 43 43 43 43
+ 46: 7(fvec4) FAdd 44 45
+ Store 20(color) 46
+ 48: 10 Load 22(ucol)
+ Store 47(param) 48
+ 49: 2 FunctionCall 14(foo(vf4[s1498];) 47(param)
Return
FunctionEnd
14(foo(vf4[s1498];): 2 Function None 12
13(p): 11(ptr) FunctionParameter
15: Label
- 51: 21(ptr) AccessChain 50(dupUcol) 20
- 52: 7(fvec4) Load 51
- 53: 7(fvec4) Load 17(color)
- 54: 7(fvec4) FAdd 53 52
- Store 17(color) 54
- 55: 8(int) Load 25(size)
- 56: 8(int) IAdd 55 47
- Store 25(size) 56
- SelectionMerge 59 None
- BranchConditional 57 58 59
- 58: Label
- 61: 6(float) ConvertUToF 60
- 62: 7(fvec4) Load 17(color)
- 63: 7(fvec4) VectorTimesScalar 62 61
- Store 17(color) 63
- Branch 59
- 59: Label
- 66: 35(float) FConvert 65
- 67: 35(float) FDiv 64 66
- 68: 6(float) FConvert 67
- 69: 7(fvec4) Load 17(color)
- 70: 7(fvec4) CompositeConstruct 68 68 68 68
- 71: 7(fvec4) FAdd 69 70
- Store 17(color) 71
+ 54: 24(ptr) AccessChain 53(dupUcol) 23
+ 55: 7(fvec4) Load 54
+ 56: 7(fvec4) Load 20(color)
+ 57: 7(fvec4) FAdd 56 55
+ Store 20(color) 57
+ 58: 8(int) Load 28(size)
+ 59: 8(int) IAdd 58 50
+ Store 28(size) 59
+ SelectionMerge 62 None
+ BranchConditional 60 61 62
+ 61: Label
+ 64: 6(float) ConvertUToF 63
+ 65: 7(fvec4) Load 20(color)
+ 66: 7(fvec4) VectorTimesScalar 65 64
+ Store 20(color) 66
+ Branch 62
+ 62: Label
+ 69: 38(float) FConvert 68
+ 70: 38(float) FDiv 67 69
+ 71: 6(float) FConvert 70
+ 72: 7(fvec4) Load 20(color)
+ 73: 7(fvec4) CompositeConstruct 71 71 71 71
+ 74: 7(fvec4) FAdd 72 73
+ Store 20(color) 74
Return
FunctionEnd
+17(builtin_spec_constant(): 8(int) Function None 16
+ 18: Label
+ 76(result): 75(ptr) Variable Function
+ Store 76(result) 77
+ 78: 8(int) Load 76(result)
+ ReturnValue 78
+ FunctionEnd
diff --git a/Test/baseResults/spv.specConstantComposite.vert.out b/Test/baseResults/spv.specConstantComposite.vert.out
new file mode 100644
index 0000000..5e2dfa4
--- /dev/null
+++ b/Test/baseResults/spv.specConstantComposite.vert.out
@@ -0,0 +1,172 @@
+spv.specConstantComposite.vert
+Warning, version 450 is not yet complete; most version-specific features are present, but some are missing.
+
+
+Linked vertex stage:
+
+
+// Module Version 10000
+// Generated by (magic number): 80001
+// Id's are bound by 106
+
+ Capability Shader
+ Capability Float64
+ 1: ExtInstImport "GLSL.std.450"
+ MemoryModel Logical GLSL450
+ EntryPoint Vertex 4 "main" 27 105
+ Source GLSL 450
+ Name 4 "main"
+ Name 6 "refer_primary_spec_const("
+ Name 8 "refer_composite_spec_const("
+ Name 10 "refer_copmosite_dot_dereference("
+ Name 12 "refer_composite_bracket_dereference("
+ Name 16 "refer_spec_const_array_length("
+ Name 18 "declare_spec_const_in_func("
+ Name 27 "color"
+ Name 41 "flat_struct"
+ MemberName 41(flat_struct) 0 "i"
+ MemberName 41(flat_struct) 1 "f"
+ MemberName 41(flat_struct) 2 "d"
+ MemberName 41(flat_struct) 3 "b"
+ Name 42 "nesting_struct"
+ MemberName 42(nesting_struct) 0 "nested"
+ MemberName 42(nesting_struct) 1 "v"
+ MemberName 42(nesting_struct) 2 "i"
+ Name 72 "indexable"
+ Name 76 "indexable"
+ Name 83 "len"
+ Name 105 "global_vec4_array_with_spec_length"
+ Decorate 21 SpecId 203
+ Decorate 28 SpecId 200
+ Decorate 32 SpecId 201
+ Decorate 43 SpecId 202
+ 2: TypeVoid
+ 3: TypeFunction 2
+ 14: TypeInt 32 1
+ 15: TypeFunction 14(int)
+ 20: TypeBool
+ 21: 20(bool) SpecConstantTrue
+ 24: TypeFloat 32
+ 25: TypeVector 24(float) 4
+ 26: TypePointer Output 25(fvec4)
+ 27(color): 26(ptr) Variable Output
+ 28: 14(int) SpecConstant 3
+ 32: 24(float) SpecConstant 1078523331
+ 33: 25(fvec4) SpecConstantComposite 32 32 32 32
+ 36: 24(float) Constant 1133908460
+ 37: 25(fvec4) SpecConstantComposite 32 32 36 36
+ 40: TypeFloat 64
+ 41(flat_struct): TypeStruct 14(int) 24(float) 40(float) 20(bool)
+42(nesting_struct): TypeStruct 41(flat_struct) 25(fvec4) 14(int)
+ 43: 40(float) SpecConstant 1413754136 1074340347
+ 44:41(flat_struct) SpecConstantComposite 28 32 43 21
+ 45:42(nesting_struct) SpecConstantComposite 44 33 28
+ 46: 14(int) Constant 2
+ 51: TypeInt 32 0
+ 52: 51(int) Constant 0
+ 57: 51(int) Constant 5
+ 58: TypeArray 24(float) 57
+ 59: 24(float) Constant 1065353216
+ 60: 24(float) Constant 1073741824
+ 61: 24(float) Constant 1077936128
+ 62: 58 SpecConstantComposite 32 32 59 60 61
+ 63: 14(int) Constant 1
+ 68: TypeArray 14(int) 57
+ 69: 14(int) Constant 30
+ 70: 68 SpecConstantComposite 28 28 63 46 69
+ 71: TypePointer Function 68
+ 73: TypePointer Function 14(int)
+ 87: 24(float) Constant 1106321080
+ 88:41(flat_struct) SpecConstantComposite 69 87 43 21
+ 89: 14(int) Constant 10
+ 90:42(nesting_struct) SpecConstantComposite 88 37 89
+ 96: 20(bool) ConstantFalse
+ 97:41(flat_struct) SpecConstantComposite 28 32 43 96
+ 98: 24(float) Constant 1036831949
+ 99: 25(fvec4) ConstantComposite 98 98 98 98
+ 100:42(nesting_struct) SpecConstantComposite 97 99 28
+ 101: 14(int) Constant 3000
+ 102:42(nesting_struct) SpecConstantComposite 88 37 101
+ 103: TypeArray 25(fvec4) 28
+ 104: TypePointer Input 103
+105(global_vec4_array_with_spec_length): 104(ptr) Variable Input
+ 4(main): 2 Function None 3
+ 5: Label
+ Return
+ FunctionEnd
+6(refer_primary_spec_const(): 2 Function None 3
+ 7: Label
+ SelectionMerge 23 None
+ BranchConditional 21 22 23
+ 22: Label
+ 29: 24(float) ConvertSToF 28
+ 30: 25(fvec4) Load 27(color)
+ 31: 25(fvec4) VectorTimesScalar 30 29
+ Store 27(color) 31
+ Branch 23
+ 23: Label
+ Return
+ FunctionEnd
+8(refer_composite_spec_const(): 2 Function None 3
+ 9: Label
+ 34: 25(fvec4) Load 27(color)
+ 35: 25(fvec4) FAdd 34 33
+ Store 27(color) 35
+ 38: 25(fvec4) Load 27(color)
+ 39: 25(fvec4) FSub 38 37
+ Store 27(color) 39
+ Return
+ FunctionEnd
+10(refer_copmosite_dot_dereference(): 2 Function None 3
+ 11: Label
+ 47: 14(int) CompositeExtract 45 2
+ 48: 24(float) ConvertSToF 47
+ 49: 25(fvec4) Load 27(color)
+ 50: 25(fvec4) VectorTimesScalar 49 48
+ Store 27(color) 50
+ 53: 24(float) CompositeExtract 33 0
+ 54: 25(fvec4) Load 27(color)
+ 55: 25(fvec4) CompositeConstruct 53 53 53 53
+ 56: 25(fvec4) FAdd 54 55
+ Store 27(color) 56
+ Return
+ FunctionEnd
+12(refer_composite_bracket_dereference(): 2 Function None 3
+ 13: Label
+ 72(indexable): 71(ptr) Variable Function
+ 76(indexable): 71(ptr) Variable Function
+ 64: 24(float) CompositeExtract 62 1
+ 65: 25(fvec4) Load 27(color)
+ 66: 25(fvec4) CompositeConstruct 64 64 64 64
+ 67: 25(fvec4) FSub 65 66
+ Store 27(color) 67
+ Store 72(indexable) 70
+ 74: 73(ptr) AccessChain 72(indexable) 28
+ 75: 14(int) Load 74
+ Store 76(indexable) 70
+ 77: 73(ptr) AccessChain 76(indexable) 75
+ 78: 14(int) Load 77
+ 79: 24(float) ConvertSToF 78
+ 80: 25(fvec4) Load 27(color)
+ 81: 25(fvec4) CompositeConstruct 79 79 79 79
+ 82: 25(fvec4) FDiv 80 81
+ Store 27(color) 82
+ Return
+ FunctionEnd
+16(refer_spec_const_array_length(): 14(int) Function None 15
+ 17: Label
+ 83(len): 73(ptr) Variable Function
+ Store 83(len) 28
+ 84: 14(int) Load 83(len)
+ ReturnValue 84
+ FunctionEnd
+18(declare_spec_const_in_func(): 2 Function None 3
+ 19: Label
+ 91: 14(int) CompositeExtract 90 2
+ 92: 24(float) ConvertSToF 91
+ 93: 25(fvec4) Load 27(color)
+ 94: 25(fvec4) CompositeConstruct 92 92 92 92
+ 95: 25(fvec4) FDiv 93 94
+ Store 27(color) 95
+ Return
+ FunctionEnd
diff --git a/Test/baseResults/spv.specConstantOperations.vert.out b/Test/baseResults/spv.specConstantOperations.vert.out
new file mode 100644
index 0000000..eedbea5
--- /dev/null
+++ b/Test/baseResults/spv.specConstantOperations.vert.out
@@ -0,0 +1,167 @@
+spv.specConstantOperations.vert
+Warning, version 450 is not yet complete; most version-specific features are present, but some are missing.
+
+
+Linked vertex stage:
+
+
+// Module Version 10000
+// Generated by (magic number): 80001
+// Id's are bound by 134
+
+ Capability Shader
+ 1: ExtInstImport "GLSL.std.450"
+ MemoryModel Logical GLSL450
+ EntryPoint Vertex 4 "main"
+ Source GLSL 450
+ Name 4 "main"
+ Name 8 "non_const_array_size_from_spec_const("
+ Name 11 "i"
+ Name 27 "array"
+ Decorate 19 SpecId 201
+ Decorate 40 SpecId 200
+ Decorate 42 SpecId 202
+ Decorate 43 SpecId 203
+ 2: TypeVoid
+ 3: TypeFunction 2
+ 6: TypeInt 32 1
+ 7: TypeFunction 6(int)
+ 10: TypePointer Function 6(int)
+ 12: 6(int) Constant 0
+ 19: 6(int) SpecConstant 10
+ 20: 6(int) Constant 2
+ 21: 6(int) SpecConstantOp 128 19 20
+ 22: TypeBool
+ 24: 6(int) SpecConstantOp 128 19 20
+ 25: TypeArray 6(int) 24
+ 26: TypePointer Function 25
+ 29: 6(int) Constant 1023
+ 32: 6(int) Constant 1
+ 34: 6(int) SpecConstantOp 128 19 32
+ 39: TypeFloat 32
+ 40: 39(float) SpecConstant 1078530010
+ 41: TypeInt 32 0
+ 42: 41(int) SpecConstant 100
+ 43: 6(int) SpecConstant 4294967286
+ 44: 41(int) Constant 0
+ 45: 22(bool) SpecConstantOp 171 19 44
+ 46: 22(bool) SpecConstantOp 171 42 44
+ 47: 6(int) SpecConstantOp 169 45 32 12
+ 48: 41(int) Constant 1
+ 49: 41(int) SpecConstantOp 169 45 48 44
+ 50: 41(int) SpecConstantOp 128 43 44
+ 51: 6(int) SpecConstantOp 128 42 44
+ 52: 6(int) SpecConstantOp 126 19
+ 53: 6(int) SpecConstantOp 200 19
+ 54: 6(int) SpecConstantOp 128 19 20
+ 55: 6(int) SpecConstantOp 128 19 20
+ 56: 6(int) Constant 3
+ 57: 6(int) SpecConstantOp 130 55 56
+ 58: 6(int) Constant 4
+ 59: 6(int) SpecConstantOp 130 54 58
+ 60: 6(int) SpecConstantOp 132 43 20
+ 61: 41(int) Constant 2
+ 62: 41(int) SpecConstantOp 132 42 61
+ 63: 6(int) Constant 5
+ 64: 6(int) SpecConstantOp 135 60 63
+ 65: 41(int) Constant 5
+ 66: 41(int) SpecConstantOp 134 62 65
+ 67: 6(int) SpecConstantOp 139 43 58
+ 68: 41(int) Constant 4
+ 69: 41(int) SpecConstantOp 137 42 68
+ 70: 6(int) SpecConstantOp 132 43 56
+ 71: 6(int) SpecConstantOp 135 70 63
+ 72: 6(int) Constant 10
+ 73: 6(int) SpecConstantOp 195 43 72
+ 74: 6(int) Constant 20
+ 75: 41(int) SpecConstantOp 194 42 74
+ 76: 6(int) SpecConstantOp 196 43 32
+ 77: 41(int) SpecConstantOp 196 42 20
+ 78: 6(int) Constant 256
+ 79: 6(int) SpecConstantOp 197 43 78
+ 80: 41(int) Constant 512
+ 81: 41(int) SpecConstantOp 198 42 80
+ 82: 22(bool) SpecConstantOp 177 19 43
+ 83: 22(bool) SpecConstantOp 170 42 42
+ 84: 22(bool) SpecConstantOp 173 19 43
+ 85: TypeVector 6(int) 4
+ 86: 6(int) Constant 30
+ 87: 85(ivec4) SpecConstantComposite 74 86 19 19
+ 88: TypeVector 41(int) 4
+ 89: 41(int) Constant 4294967295
+ 90: 41(int) Constant 4294967294
+ 91: 88(ivec4) SpecConstantComposite 42 42 89 90
+ 92: TypeVector 39(float) 4
+ 93: 39(float) Constant 1067450368
+ 94: 92(fvec4) SpecConstantComposite 40 93 40 93
+ 95: TypeVector 22(bool) 4
+ 96: 88(ivec4) ConstantComposite 44 44 44 44
+ 97: 95(bvec4) SpecConstantOp 171 87 96
+ 98: 95(bvec4) SpecConstantOp 171 91 96
+ 99: 85(ivec4) ConstantComposite 12 12 12 12
+ 100: 85(ivec4) ConstantComposite 32 32 32 32
+ 101: 85(ivec4) SpecConstantOp 169 97 100 99
+ 102: 88(ivec4) ConstantComposite 48 48 48 48
+ 103: 88(ivec4) SpecConstantOp 169 97 102 96
+ 104: 88(ivec4) SpecConstantOp 128 87 96
+ 105: 85(ivec4) SpecConstantOp 128 91 96
+ 106: 85(ivec4) SpecConstantOp 200 87
+ 107: 85(ivec4) SpecConstantOp 126 87
+ 108: 85(ivec4) ConstantComposite 20 20 20 20
+ 109: 85(ivec4) SpecConstantOp 128 87 108
+ 110: 85(ivec4) SpecConstantOp 128 87 108
+ 111: 85(ivec4) ConstantComposite 56 56 56 56
+ 112: 85(ivec4) SpecConstantOp 130 110 111
+ 113: 85(ivec4) ConstantComposite 58 58 58 58
+ 114: 85(ivec4) SpecConstantOp 130 112 113
+ 115: 85(ivec4) SpecConstantOp 132 87 108
+ 116: 85(ivec4) ConstantComposite 63 63 63 63
+ 117: 85(ivec4) SpecConstantOp 135 115 116
+ 118: 85(ivec4) SpecConstantOp 139 87 113
+ 119: 85(ivec4) ConstantComposite 72 72 72 72
+ 120: 85(ivec4) SpecConstantOp 195 87 119
+ 121: 85(ivec4) SpecConstantOp 196 87 108
+ 122: 6(int) Constant 1024
+ 123: 85(ivec4) ConstantComposite 122 122 122 122
+ 124: 85(ivec4) SpecConstantOp 197 87 123
+ 125: 41(int) Constant 2048
+ 126: 88(ivec4) ConstantComposite 125 125 125 125
+ 127: 88(ivec4) SpecConstantOp 198 91 126
+ 128: 6(int) SpecConstantOp 81 87 0
+ 129: TypeVector 6(int) 2
+ 130: 129(ivec2) SpecConstantOp 79 87 87 1(GLSL.std.450) 0
+ 131: TypeVector 6(int) 3
+ 132: 131(ivec3) SpecConstantOp 79 87 87 2 1(GLSL.std.450) 0
+ 133: 85(ivec4) SpecConstantOp 79 87 87 1(GLSL.std.450) 2 0 3
+ 4(main): 2 Function None 3
+ 5: Label
+ Return
+ FunctionEnd
+8(non_const_array_size_from_spec_const(): 6(int) Function None 7
+ 9: Label
+ 11(i): 10(ptr) Variable Function
+ 27(array): 26(ptr) Variable Function
+ Store 11(i) 12
+ Branch 13
+ 13: Label
+ LoopMerge 15 16 None
+ Branch 17
+ 17: Label
+ 18: 6(int) Load 11(i)
+ 23: 22(bool) SLessThan 18 21
+ BranchConditional 23 14 15
+ 14: Label
+ 28: 6(int) Load 11(i)
+ 30: 10(ptr) AccessChain 27(array) 28
+ Store 30 29
+ Branch 16
+ 16: Label
+ 31: 6(int) Load 11(i)
+ 33: 6(int) IAdd 31 32
+ Store 11(i) 33
+ Branch 13
+ 15: Label
+ 35: 10(ptr) AccessChain 27(array) 34
+ 36: 6(int) Load 35
+ ReturnValue 36
+ FunctionEnd
diff --git a/Test/baseResults/spv.test.frag.out b/Test/baseResults/spv.test.frag.out
old mode 100755
new mode 100644
diff --git a/Test/baseResults/spv.test.vert.out b/Test/baseResults/spv.test.vert.out
old mode 100755
new mode 100644
diff --git a/Test/hlsl.frag b/Test/hlsl.frag
new file mode 100644
index 0000000..7ee5849
--- /dev/null
+++ b/Test/hlsl.frag
@@ -0,0 +1,7 @@
+float4 AmbientColor = float4(1, 0.5, 0, 1);
+//float AmbientIntensity = 0.1;
+
+float4 PixelShaderFunction(float4 input) : COLOR0
+{
+ return input /* * AmbientIntensity */ + AmbientColor;
+}
diff --git a/Test/runtests b/Test/runtests
index c324911..d5099a9 100755
--- a/Test/runtests
+++ b/Test/runtests
@@ -56,6 +56,24 @@
rm -f comp.spv frag.spv geom.spv tesc.spv tese.spv vert.spv
#
+# HLSL -> SPIR-V code generation tests
+#
+while read t; do
+ case $t in
+ \#*)
+ # Skip comment lines in the test list file.
+ ;;
+ *)
+ echo Running HLSL-to-SPIR-V $t...
+ b=`basename $t`
+ $EXE -D -e PixelShaderFunction -H -i $t > $TARGETDIR/$b.out
+ diff -b $BASEDIR/$b.out $TARGETDIR/$b.out || HASERROR=1
+ ;;
+ esac
+done < test-hlsl-spirv-list
+rm -f comp.spv frag.spv geom.spv tesc.spv tese.spv vert.spv
+
+#
# Preprocessor tests
#
while read t; do
diff --git a/Test/spv.specConstant.vert b/Test/spv.specConstant.vert
index 0f9764d..9813bf5 100644
--- a/Test/spv.specConstant.vert
+++ b/Test/spv.specConstant.vert
@@ -8,6 +8,8 @@
layout(constant_id = 19) const double spDouble = 3.1415926535897932384626433832795;
layout(constant_id = 22) const uint scale = 2;
+layout(constant_id = 24) gl_MaxImageUnits;
+
out vec4 color;
out int size;
@@ -41,3 +43,9 @@
color *= dupScale;
color += float(spDupDouble / spDupFloat);
}
+
+int builtin_spec_constant()
+{
+ int result = gl_MaxImageUnits;
+ return result;
+}
diff --git a/Test/spv.specConstantComposite.vert b/Test/spv.specConstantComposite.vert
new file mode 100644
index 0000000..4450ddd
--- /dev/null
+++ b/Test/spv.specConstantComposite.vert
@@ -0,0 +1,93 @@
+#version 450
+
+// constant_id specified scalar spec constants
+layout(constant_id = 200) const int spec_int = 3;
+layout(constant_id = 201) const float spec_float = 3.14;
+layout(constant_id = 202) const
+ double spec_double = 3.1415926535897932384626433832795;
+layout(constant_id = 203) const bool spec_bool = true;
+
+const float cast_spec_float = float(spec_float);
+
+// Flat struct
+struct flat_struct {
+ int i;
+ float f;
+ double d;
+ bool b;
+};
+
+// Nesting struct
+struct nesting_struct {
+ flat_struct nested;
+ vec4 v;
+ int i;
+};
+
+// Expect OpSpecConstantComposite
+// Flat struct initializer
+const flat_struct spec_flat_struct_all_spec = {spec_int, spec_float,
+ spec_double, spec_bool};
+const flat_struct spec_flat_struct_partial_spec = {30, 30.14, spec_double,
+ spec_bool};
+
+// Nesting struct initializer
+const nesting_struct nesting_struct_ctor = {
+ {spec_int, spec_float, spec_double, false},
+ vec4(0.1, 0.1, 0.1, 0.1),
+ spec_int};
+
+// Vector constructor
+const vec4 spec_vec4_all_spec =
+ vec4(spec_float, spec_float, spec_float, spec_float);
+const vec4 spec_vec4_partial_spec =
+ vec4(spec_float, spec_float, 300.14, 300.14);
+
+// Struct nesting constructor
+const nesting_struct spec_nesting_struct_all_spec = {
+ spec_flat_struct_all_spec, spec_vec4_all_spec, spec_int};
+const nesting_struct spec_nesting_struct_partial_spec = {
+ spec_flat_struct_partial_spec, spec_vec4_partial_spec, 3000};
+
+const float spec_float_array[5] = {spec_float, spec_float, 1.0, 2.0, 3.0};
+const int spec_int_array[5] = {spec_int, spec_int, 1, 2, 30};
+
+// global_vec4_array_with_spec_length is not a spec constant, but its array
+// size is. When calling global_vec4_array_with_spec_length.length(), A
+// TIntermSymbol Node shoule be returned, instead of a TIntermConstantUnion
+// node which represents a known constant value.
+in vec4 global_vec4_array_with_spec_length[spec_int];
+
+out vec4 color;
+
+void refer_primary_spec_const() {
+ if (spec_bool) color *= spec_int;
+}
+
+void refer_composite_spec_const() {
+ color += spec_vec4_all_spec;
+ color -= spec_vec4_partial_spec;
+}
+
+void refer_copmosite_dot_dereference() {
+ color *= spec_nesting_struct_all_spec.i;
+ color += spec_vec4_all_spec.x;
+}
+
+void refer_composite_bracket_dereference() {
+ color -= spec_float_array[1];
+ color /= spec_int_array[spec_int_array[spec_int]];
+}
+
+int refer_spec_const_array_length() {
+ int len = global_vec4_array_with_spec_length.length();
+ return len;
+}
+
+void declare_spec_const_in_func() {
+ const nesting_struct spec_const_declared_in_func = {
+ spec_flat_struct_partial_spec, spec_vec4_partial_spec, 10};
+ color /= spec_const_declared_in_func.i;
+}
+
+void main() {}
diff --git a/Test/spv.specConstantOperations.vert b/Test/spv.specConstantOperations.vert
new file mode 100644
index 0000000..f2d57bf
--- /dev/null
+++ b/Test/spv.specConstantOperations.vert
@@ -0,0 +1,110 @@
+#version 450
+
+layout(constant_id = 200) const float sp_float = 3.1415926;
+layout(constant_id = 201) const int sp_int = 10;
+layout(constant_id = 202) const uint sp_uint = 100;
+layout(constant_id = 203) const int sp_sint = -10;
+
+
+//
+// Scalars
+//
+
+// uint/int <-> bool conversion
+const bool bool_from_int = bool(sp_int);
+const bool bool_from_uint = bool(sp_uint);
+const int int_from_bool = int(bool_from_int);
+const uint uint_from_bool = uint(bool_from_int);
+
+// uint <-> int
+const uint sp_uint_from_sint = uint(sp_sint);
+const int sp_sint_from_uint = int(sp_uint);
+
+// Negate and Not
+const int negate_int = -sp_int;
+const int not_int = ~sp_int;
+
+// Add and Subtract
+const int sp_int_add_two = sp_int + 2;
+const int sp_int_add_two_sub_three = sp_int + 2 - 3;
+const int sp_int_add_two_sub_four = sp_int_add_two - 4;
+
+// Mul, Div and Rem
+const int sp_sint_mul_two = sp_sint * 2;
+const uint sp_uint_mul_two = sp_uint * 2;
+const int sp_sint_mul_two_div_five = sp_sint_mul_two / 5;
+const uint sp_uint_mul_two_div_five = sp_uint_mul_two / 5;
+const int sp_sint_rem_four = sp_sint % 4;
+const uint sp_uint_rem_four = sp_uint % 4;
+const int sp_sint_mul_three_div_five = sp_sint * 3 / 5;
+
+// Shift
+const int sp_sint_shift_right_arithmetic = sp_sint >> 10;
+const uint sp_uint_shift_right_arithmetic = sp_uint >> 20;
+const int sp_sint_shift_left = sp_sint << 1;
+const uint sp_uint_shift_left = sp_uint << 2;
+
+// Bitwise And, Or, Xor
+const int sp_sint_or_256 = sp_sint | 0x100;
+const uint sp_uint_xor_512 = sp_uint ^ 0x200;
+
+/* // Scalar comparison */
+const bool sp_int_lt_sp_sint = sp_int < sp_sint;
+const bool sp_uint_equal_sp_uint = sp_uint == sp_uint;
+const bool sp_int_gt_sp_sint = sp_int > sp_sint;
+
+//
+// Vectors
+//
+const ivec4 iv = ivec4(20, 30, sp_int, sp_int);
+const uvec4 uv = uvec4(sp_uint, sp_uint, -1, -2);
+const vec4 fv = vec4(sp_float, 1.25, sp_float, 1.25);
+
+// uint/int <-> bool conversion
+const bvec4 bv_from_iv = bvec4(iv);
+const bvec4 bv_from_uv = bvec4(uv);
+const ivec4 iv_from_bv = ivec4(bv_from_iv);
+const uvec4 uv_from_bv = uvec4(bv_from_iv);
+
+// uint <-> int
+const uvec4 uv_from_iv = uvec4(iv);
+const ivec4 iv_from_uv = ivec4(uv);
+
+// Negate and Not
+const ivec4 not_iv = ~iv;
+const ivec4 negate_iv = -iv;
+
+// Add and Subtract
+const ivec4 iv_add_two = iv + 2;
+const ivec4 iv_add_two_sub_three = iv + 2 - 3;
+const ivec4 iv_add_two_sub_four = iv_add_two_sub_three - 4;
+
+// Mul, Div and Rem
+const ivec4 iv_mul_two = iv * 2;
+const ivec4 iv_mul_two_div_five = iv_mul_two / 5;
+const ivec4 iv_rem_four = iv % 4;
+
+// Shift
+const ivec4 iv_shift_right_arithmetic = iv >> 10;
+const ivec4 iv_shift_left = iv << 2;
+
+// Bitwise And, Or, Xor
+const ivec4 iv_or_1024 = iv | 0x400;
+const uvec4 uv_xor_2048 = uv ^ 0x800;
+
+// Swizzles
+const int iv_x = iv.x;
+const ivec2 iv_yx = iv.yx;
+const ivec3 iv_zyx = iv.zyx;
+const ivec4 iv_yzxw = iv.yzxw;
+
+int non_const_array_size_from_spec_const() {
+ int array[sp_int + 2];
+ for (int i = 0; i < sp_int + 2; i++) {
+ array[i] = 1023;
+ }
+ return array[sp_int + 1];
+}
+
+void main() {}
+
diff --git a/Test/test-hlsl-spirv-list b/Test/test-hlsl-spirv-list
new file mode 100644
index 0000000..d98a3cb
--- /dev/null
+++ b/Test/test-hlsl-spirv-list
@@ -0,0 +1,4 @@
+# Test looping constructs.
+# No tests yet for making sure break and continue from a nested loop
+# goes to the innermost target.
+hlsl.frag
diff --git a/Test/test-spirv-list b/Test/test-spirv-list
index 0e22367..b7dfd53 100644
--- a/Test/test-spirv-list
+++ b/Test/test-spirv-list
@@ -102,6 +102,8 @@
spv.subpass.frag
spv.specConstant.vert
spv.specConstant.comp
+spv.specConstantComposite.vert
+spv.specConstantOperations.vert
# GLSL-level semantics
vulkan.frag
vulkan.vert
diff --git a/glslang/CMakeLists.txt b/glslang/CMakeLists.txt
index 28f4742..b6c70c4 100644
--- a/glslang/CMakeLists.txt
+++ b/glslang/CMakeLists.txt
@@ -63,6 +63,7 @@
MachineIndependent/ScanContext.h
MachineIndependent/SymbolTable.h
MachineIndependent/Versions.h
+ MachineIndependent/parseVersions.h
MachineIndependent/preprocessor/PpContext.h
MachineIndependent/preprocessor/PpTokens.h)
diff --git a/glslang/Include/InfoSink.h b/glslang/Include/InfoSink.h
index a321ebc..5862e5d 100644
--- a/glslang/Include/InfoSink.h
+++ b/glslang/Include/InfoSink.h
@@ -92,7 +92,7 @@
case EPrefixInternalError: append("INTERNAL ERROR: "); break;
case EPrefixUnimplemented: append("UNIMPLEMENTED: "); break;
case EPrefixNote: append("NOTE: "); break;
- default: append("UNKOWN ERROR: "); break;
+ default: append("UNKNOWN ERROR: "); break;
}
}
void location(const TSourceLoc& loc) {
diff --git a/glslang/Include/PoolAlloc.h b/glslang/Include/PoolAlloc.h
index de41053..c3bebc6 100644
--- a/glslang/Include/PoolAlloc.h
+++ b/glslang/Include/PoolAlloc.h
@@ -95,7 +95,7 @@
void checkAllocList() const;
- // Return total size needed to accomodate user buffer of 'size',
+ // Return total size needed to accommodate user buffer of 'size',
// plus our tracking data.
inline static size_t allocationSize(size_t size) {
return size + 2 * guardBlockSize + headerSize();
@@ -241,8 +241,8 @@
int numCalls; // just an interesting statistic
size_t totalBytes; // just an interesting statistic
private:
- TPoolAllocator& operator=(const TPoolAllocator&); // dont allow assignment operator
- TPoolAllocator(const TPoolAllocator&); // dont allow default copy constructor
+ TPoolAllocator& operator=(const TPoolAllocator&); // don't allow assignment operator
+ TPoolAllocator(const TPoolAllocator&); // don't allow default copy constructor
};
diff --git a/glslang/Include/Types.h b/glslang/Include/Types.h
index 05681c9..e28e5b2 100644
--- a/glslang/Include/Types.h
+++ b/glslang/Include/Types.h
@@ -999,9 +999,9 @@
qualifier.storage = EvqGlobal;
}
- void init(const TSourceLoc& loc, bool global = false)
+ void init(const TSourceLoc& l, bool global = false)
{
- initType(loc);
+ initType(l);
sampler.clear();
initQualifiers(global);
shaderQualifiers.init();
@@ -1223,6 +1223,7 @@
virtual int getMatrixCols() const { return matrixCols; }
virtual int getMatrixRows() const { return matrixRows; }
virtual int getOuterArraySize() const { return arraySizes->getOuterSize(); }
+ virtual TIntermTyped* getOuterArrayNode() const { return arraySizes->getOuterNode(); }
virtual int getCumulativeArraySize() const { return arraySizes->getCumulativeSize(); }
virtual bool isArrayOfArrays() const { return arraySizes != nullptr && arraySizes->getNumDims() > 1; }
virtual int getImplicitArraySize() const { return arraySizes->getImplicitSize(); }
diff --git a/glslang/MachineIndependent/Initialize.cpp b/glslang/MachineIndependent/Initialize.cpp
index 2e094f0..446c51c 100644
--- a/glslang/MachineIndependent/Initialize.cpp
+++ b/glslang/MachineIndependent/Initialize.cpp
@@ -1708,7 +1708,7 @@
stageBuiltins[EShLangVertex].append(
"int gl_InstanceID;" // needs qualifier fixed later
);
- if (spv > 0 && version >= 140)
+ if (vulkan > 0 && version >= 140)
stageBuiltins[EShLangVertex].append(
"in int gl_VertexIndex;"
"in int gl_InstanceIndex;"
@@ -1733,7 +1733,7 @@
"in highp int gl_VertexID;" // needs qualifier fixed later
"in highp int gl_InstanceID;" // needs qualifier fixed later
);
- if (spv > 0)
+ if (vulkan > 0)
stageBuiltins[EShLangVertex].append(
"in highp int gl_VertexIndex;"
"in highp int gl_InstanceIndex;"
diff --git a/glslang/MachineIndependent/Intermediate.cpp b/glslang/MachineIndependent/Intermediate.cpp
index 777de2d..d0fa74e 100644
--- a/glslang/MachineIndependent/Intermediate.cpp
+++ b/glslang/MachineIndependent/Intermediate.cpp
@@ -145,10 +145,12 @@
// If either is a specialization constant, while the other is
// a constant (or specialization constant), the result is still
- // a specialization constant.
+ // a specialization constant, if the operation is an allowed
+ // specialization-constant operation.
if (( left->getType().getQualifier().isSpecConstant() && right->getType().getQualifier().isConstant()) ||
(right->getType().getQualifier().isSpecConstant() && left->getType().getQualifier().isConstant()))
- node->getWritableType().getQualifier().makeSpecConstant();
+ if (isSpecializationOperation(*node))
+ node->getWritableType().getQualifier().makeSpecConstant();
return node;
}
@@ -292,8 +294,9 @@
if (child->getAsConstantUnion())
return child->getAsConstantUnion()->fold(op, node->getType());
- // If it's a specialization constant, the result is too.
- if (child->getType().getQualifier().isSpecConstant())
+ // If it's a specialization constant, the result is too,
+ // if the operation is allowed for specialization constants.
+ if (child->getType().getQualifier().isSpecConstant() && isSpecializationOperation(*node))
node->getWritableType().getQualifier().makeSpecConstant();
return node;
@@ -619,8 +622,8 @@
// TODO: it seems that some unary folding operations should occur here, but are not
- // Propagate specialization-constant-ness.
- if (node->getType().getQualifier().isSpecConstant())
+ // Propagate specialization-constant-ness, if allowed
+ if (node->getType().getQualifier().isSpecConstant() && isSpecializationOperation(*newNode))
newNode->getWritableType().getQualifier().makeSpecConstant();
return newNode;
@@ -1065,6 +1068,87 @@
RemoveAllTreeNodes(treeRoot);
}
+//
+// Implement the part of KHR_vulkan_glsl that lists the set of operations
+// that can result in a specialization constant operation.
+//
+// "5.x Specialization Constant Operations"
+//
+// ...
+//
+// It also needs to allow basic construction, swizzling, and indexing
+// operations.
+//
+bool TIntermediate::isSpecializationOperation(const TIntermOperator& node) const
+{
+ // allow construction
+ if (node.isConstructor())
+ return true;
+
+ // The set for floating point is quite limited
+ if (node.getBasicType() == EbtFloat ||
+ node.getBasicType() == EbtDouble) {
+ switch (node.getOp()) {
+ case EOpIndexDirect:
+ case EOpIndexIndirect:
+ case EOpIndexDirectStruct:
+ case EOpVectorSwizzle:
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ // Floating-point is out of the way.
+ // Now check for integer/bool-based operations
+ switch (node.getOp()) {
+
+ // dereference/swizzle
+ case EOpIndexDirect:
+ case EOpIndexIndirect:
+ case EOpIndexDirectStruct:
+ case EOpVectorSwizzle:
+
+ // conversion constructors
+ case EOpConvIntToBool:
+ case EOpConvUintToBool:
+ case EOpConvUintToInt:
+ case EOpConvBoolToInt:
+ case EOpConvIntToUint:
+ case EOpConvBoolToUint:
+
+ // unary operations
+ case EOpNegative:
+ case EOpLogicalNot:
+ case EOpBitwiseNot:
+
+ // binary operations
+ case EOpAdd:
+ case EOpSub:
+ case EOpMul:
+ case EOpVectorTimesScalar:
+ case EOpDiv:
+ case EOpMod:
+ case EOpRightShift:
+ case EOpLeftShift:
+ case EOpAnd:
+ case EOpInclusiveOr:
+ case EOpExclusiveOr:
+ case EOpLogicalOr:
+ case EOpLogicalXor:
+ case EOpLogicalAnd:
+ case EOpEqual:
+ case EOpNotEqual:
+ case EOpLessThan:
+ case EOpGreaterThan:
+ case EOpLessThanEqual:
+ case EOpGreaterThanEqual:
+ return true;
+ default:
+ return false;
+ }
+}
+
////////////////////////////////////////////////////////////////
//
// Member functions of the nodes used for building the tree.
diff --git a/glslang/MachineIndependent/ParseHelper.cpp b/glslang/MachineIndependent/ParseHelper.cpp
index d6f4115..4c1b7a0 100644
--- a/glslang/MachineIndependent/ParseHelper.cpp
+++ b/glslang/MachineIndependent/ParseHelper.cpp
@@ -48,14 +48,14 @@
namespace glslang {
-TParseContext::TParseContext(TSymbolTable& symt, TIntermediate& interm, bool pb, int v, EProfile p, int spv, int vulkan, EShLanguage L, TInfoSink& is,
- bool fc, EShMessages m) :
- intermediate(interm), symbolTable(symt), infoSink(is), language(L),
- version(v), profile(p), spv(spv), vulkan(vulkan), forwardCompatible(fc),
+TParseContext::TParseContext(TSymbolTable& symbolTable, TIntermediate& interm, bool parsingBuiltins,
+ int version, EProfile profile, int spv, int vulkan, EShLanguage language,
+ TInfoSink& infoSink, bool forwardCompatible, EShMessages messages) :
+ TParseContextBase(symbolTable, interm, version, profile, spv, vulkan, language, infoSink, forwardCompatible, messages),
contextPragma(true, false), loopNestingLevel(0), structNestingLevel(0), controlFlowNestingLevel(0), statementNestingLevel(0),
- postMainReturn(false),
- tokensBeforeEOF(false), limits(resources.limits), messages(m), currentScanner(nullptr),
- numErrors(0), parsingBuiltins(pb), afterEOF(false),
+ inMain(false), postMainReturn(false), currentFunctionType(nullptr), blockName(nullptr),
+ limits(resources.limits), parsingBuiltins(parsingBuiltins),
+ afterEOF(false),
atomicUintOffsets(nullptr), anyIndexLimits(false)
{
// ensure we always have a linkage node, even if empty, to simplify tree topology algorithms
@@ -484,7 +484,7 @@
TIntermTyped* result = nullptr;
int indexValue = 0;
- if (index->getQualifier().isConstant()) {
+ if (index->getQualifier().isFrontEndConstant()) {
indexValue = index->getAsConstantUnion()->getConstArray()[0].getIConst();
checkIndex(loc, base->getType(), indexValue);
}
@@ -503,7 +503,7 @@
if (base->getAsSymbolNode() && isIoResizeArray(base->getType()))
handleIoResizeArrayAccess(loc, base);
- if (index->getQualifier().isConstant()) {
+ if (index->getQualifier().isFrontEndConstant()) {
if (base->getType().isImplicitlySizedArray())
updateImplicitArraySize(loc, base, indexValue);
result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
@@ -541,10 +541,15 @@
} else {
// Insert valid dereferenced result
TType newType(base->getType(), 0); // dereferenced type
- if (base->getType().getQualifier().isFrontEndConstant() && index->getQualifier().isFrontEndConstant())
+ if (base->getType().getQualifier().isConstant() && index->getQualifier().isConstant()) {
newType.getQualifier().storage = EvqConst;
- else
+ // If base or index is a specialization constant, the result should also be a specialization constant.
+ if (base->getType().getQualifier().isSpecConstant() || index->getQualifier().isSpecConstant()) {
+ newType.getQualifier().makeSpecConstant();
+ }
+ } else {
newType.getQualifier().makePartialTemporary();
+ }
result->setType(newType);
if (anyIndexLimits)
@@ -981,7 +986,7 @@
//
// Raise error message if main function takes any parameters or returns anything other than void
//
- if (function.getName() == "main") {
+ if (function.getName() == intermediate.getEntryPoint().c_str()) {
if (function.getParamCount() > 0)
error(loc, "function cannot take any parameter(s)", function.getName().c_str(), "");
if (function.getType().getBasicType() != EbtVoid)
@@ -1226,6 +1231,11 @@
else
error(loc, "", function->getName().c_str(), "array must be declared with a size before using this method");
}
+ } else if (type.getOuterArrayNode()) {
+ // If the array's outer size is specified by an intermediate node, it means the array's length
+ // was specified by a specialization constant. In such a case, we should return the node of the
+ // specialization constants to represent the length.
+ return type.getOuterArrayNode();
} else
length = type.getOuterArraySize();
} else if (type.isMatrix())
@@ -2210,7 +2220,7 @@
int size = 0;
bool constType = true;
- bool specConstType = true;
+ bool specConstType = false; // value is only valid if constType is true
bool full = false;
bool overFull = false;
bool matrixInMatrix = false;
@@ -2241,14 +2251,15 @@
if (! function[arg].type->getQualifier().isConstant())
constType = false;
- if (! function[arg].type->getQualifier().isSpecConstant())
- specConstType = false;
+ if (function[arg].type->getQualifier().isSpecConstant())
+ specConstType = true;
}
if (constType) {
- type.getQualifier().storage = EvqConst;
if (specConstType)
- type.getQualifier().specConstant = true;
+ type.getQualifier().makeSpecConstant();
+ else
+ type.getQualifier().storage = EvqConst;
}
if (type.isArray()) {
@@ -3111,16 +3122,27 @@
// This has to be the result of a block dereference, unless it's bad shader code
// If it's a uniform block, then an error will be issued elsewhere, but
// return early now to avoid crashing later in this function.
- if (! deref->getLeft()->getAsSymbolNode() || deref->getLeft()->getBasicType() != EbtBlock ||
+ if (deref->getLeft()->getBasicType() != EbtBlock ||
deref->getLeft()->getType().getQualifier().storage == EvqUniform ||
deref->getRight()->getAsConstantUnion() == nullptr)
return;
- blockIndex = deref->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
+ const TIntermTyped* left = deref->getLeft();
+ const TIntermTyped* right = deref->getRight();
- lookupName = &deref->getLeft()->getAsSymbolNode()->getName();
+ if (left->getAsBinaryNode()) {
+ left = left->getAsBinaryNode()->getLeft(); // Block array access
+ assert(left->isArray());
+ }
+
+ if (! left->getAsSymbolNode())
+ return;
+
+ blockIndex = right->getAsConstantUnion()->getConstArray()[0].getIConst();
+
+ lookupName = &left->getAsSymbolNode()->getName();
if (IsAnonymous(*lookupName))
- lookupName = &(*deref->getLeft()->getType().getStruct())[blockIndex].type->getFieldName();
+ lookupName = &(*left->getType().getStruct())[blockIndex].type->getFieldName();
}
// Lookup the symbol, should only fail if shader code is incorrect
@@ -3133,7 +3155,10 @@
return;
}
- symbol->getWritableType().setImplicitArraySize(index + 1);
+ if (symbol->getType().isStruct() && blockIndex != -1)
+ (*symbol->getWritableType().getStruct())[blockIndex].type->setImplicitArraySize(index + 1);
+ else
+ symbol->getWritableType().setImplicitArraySize(index + 1);
}
// Returns true if the first argument to the #line directive is the line number for the next line.
@@ -3145,7 +3170,8 @@
// Desktop, version 3.30 and later, and ES: "After processing this directive
// (including its new-line), the implementation will behave as if it is compiling at line number line and
// source string number source-string-number.
-bool TParseContext::lineDirectiveShouldSetNextLine() const {
+bool TParseContext::lineDirectiveShouldSetNextLine() const
+{
return profile == EEsProfile || version >= 330;
}
@@ -5101,12 +5127,17 @@
// if the structure constructor contains more than one parameter, then construct
// each parameter
- int paramCount = 0; // keeps a track of the constructor parameter number being checked
+ int paramCount = 0; // keeps track of the constructor parameter number being checked
// for each parameter to the constructor call, check to see if the right type is passed or convert them
// to the right type if possible (and allowed).
// for structure constructors, just check if the right type is passed, no conversion is allowed.
+ // We don't know "top down" whether type is a specialization constant,
+ // but a const becomes a specialization constant if any of its children are.
+ bool hasSpecConst = false;
+ bool isConstConstrutor = true;
+
for (TIntermSequence::iterator p = sequenceVector.begin();
p != sequenceVector.end(); p++, paramCount++) {
if (type.isArray())
@@ -5116,13 +5147,19 @@
else
newNode = constructBuiltIn(type, op, (*p)->getAsTyped(), node->getLoc(), true);
- if (newNode)
+ if (newNode) {
*p = newNode;
- else
+ if (! newNode->getType().getQualifier().isConstant())
+ isConstConstrutor = false;
+ if (newNode->getType().getQualifier().isSpecConstant())
+ hasSpecConst = true;
+ } else
return nullptr;
}
TIntermTyped* constructor = intermediate.setAggregateOperator(aggrNode, op, type, loc);
+ if (isConstConstrutor && hasSpecConst)
+ constructor->getWritableType().getQualifier().makeSpecConstant();
return constructor;
}
@@ -5677,6 +5714,10 @@
error(loc, "cannot change qualification after use", "invariant", "");
symbol->getWritableType().getQualifier().invariant = true;
invariantCheck(loc, symbol->getType().getQualifier());
+ } else if (qualifier.specConstant) {
+ symbol->getWritableType().getQualifier().makeSpecConstant();
+ if (qualifier.hasSpecConstantId())
+ symbol->getWritableType().getQualifier().layoutSpecConstantId = qualifier.layoutSpecConstantId;
} else
warn(loc, "unknown requalification", "", "");
}
@@ -5967,32 +6008,4 @@
return switchNode;
}
-void TParseContext::notifyVersion(int line, int version, const char* type_string)
-{
- if (versionCallback) {
- versionCallback(line, version, type_string);
- }
-}
-
-void TParseContext::notifyErrorDirective(int line, const char* error_message)
-{
- if (errorCallback) {
- errorCallback(line, error_message);
- }
-}
-
-void TParseContext::notifyLineDirective(int curLineNo, int newLineNo, bool hasSource, int sourceNum, const char* sourceName)
-{
- if (lineCallback) {
- lineCallback(curLineNo, newLineNo, hasSource, sourceNum, sourceName);
- }
-}
-
-void TParseContext::notifyExtensionDirective(int line, const char* extension, const char* behavior)
-{
- if (extensionCallback) {
- extensionCallback(line, extension, behavior);
- }
-}
-
} // end namespace glslang
diff --git a/glslang/MachineIndependent/ParseHelper.h b/glslang/MachineIndependent/ParseHelper.h
index ac1932d..ea5d0ba 100644
--- a/glslang/MachineIndependent/ParseHelper.h
+++ b/glslang/MachineIndependent/ParseHelper.h
@@ -33,10 +33,18 @@
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
+
+//
+// This header defines a two-level parse-helper hierarchy, derived from
+// TParseVersions:
+// - TParseContextBase: sharable across multiple parsers
+// - TParseContext: GLSL specific helper
+//
+
#ifndef _PARSER_HELPER_INCLUDED_
#define _PARSER_HELPER_INCLUDED_
-#include "Versions.h"
+#include "parseVersions.h"
#include "../Include/ShHandle.h"
#include "SymbolTable.h"
#include "localintermediate.h"
@@ -60,10 +68,88 @@
typedef std::set<int> TIdSetType;
//
-// The following are extra variables needed during parsing, grouped together so
-// they can be passed to the parser without needing a global.
+// Sharable code (as well as what's in TParseVersions) across
+// parse helpers.
//
-class TParseContext {
+class TParseContextBase : public TParseVersions {
+public:
+ TParseContextBase(TSymbolTable& symbolTable, TIntermediate& interm, int version,
+ EProfile profile, int spv, int vulkan, EShLanguage language,
+ TInfoSink& infoSink, bool forwardCompatible, EShMessages messages)
+ : TParseVersions(interm, version, profile, spv, vulkan, language, infoSink, forwardCompatible, messages),
+ symbolTable(symbolTable), tokensBeforeEOF(false),
+ linkage(nullptr), scanContext(nullptr), ppContext(nullptr) { }
+ virtual ~TParseContextBase() { }
+
+ virtual void setLimits(const TBuiltInResource&) = 0;
+
+ EShLanguage getLanguage() const { return language; }
+ TIntermAggregate*& getLinkage() { return linkage; }
+ void setScanContext(TScanContext* c) { scanContext = c; }
+ TScanContext* getScanContext() const { return scanContext; }
+ void setPpContext(TPpContext* c) { ppContext = c; }
+ TPpContext* getPpContext() const { return ppContext; }
+
+ virtual void setLineCallback(const std::function<void(int, int, bool, int, const char*)>& func) { lineCallback = func; }
+ virtual void setExtensionCallback(const std::function<void(int, const char*, const char*)>& func) { extensionCallback = func; }
+ virtual void setVersionCallback(const std::function<void(int, int, const char*)>& func) { versionCallback = func; }
+ virtual void setPragmaCallback(const std::function<void(int, const TVector<TString>&)>& func) { pragmaCallback = func; }
+ virtual void setErrorCallback(const std::function<void(int, const char*)>& func) { errorCallback = func; }
+
+ virtual void reservedPpErrorCheck(const TSourceLoc&, const char* name, const char* op) = 0;
+ virtual bool lineContinuationCheck(const TSourceLoc&, bool endOfComment) = 0;
+ virtual bool lineDirectiveShouldSetNextLine() const = 0;
+ virtual void handlePragma(const TSourceLoc&, const TVector<TString>&) = 0;
+
+ virtual bool parseShaderStrings(TPpContext&, TInputScanner& input, bool versionWillBeError = false) = 0;
+
+ virtual void notifyVersion(int line, int version, const char* type_string)
+ {
+ if (versionCallback)
+ versionCallback(line, version, type_string);
+ }
+ virtual void notifyErrorDirective(int line, const char* error_message)
+ {
+ if (errorCallback)
+ errorCallback(line, error_message);
+ }
+ virtual void notifyLineDirective(int curLineNo, int newLineNo, bool hasSource, int sourceNum, const char* sourceName)
+ {
+ if (lineCallback)
+ lineCallback(curLineNo, newLineNo, hasSource, sourceNum, sourceName);
+ }
+ virtual void notifyExtensionDirective(int line, const char* extension, const char* behavior)
+ {
+ if (extensionCallback)
+ extensionCallback(line, extension, behavior);
+ }
+
+ TSymbolTable& symbolTable; // symbol table that goes with the current language, version, and profile
+ bool tokensBeforeEOF;
+
+protected:
+ TParseContextBase(TParseContextBase&);
+ TParseContextBase& operator=(TParseContextBase&);
+
+ TIntermAggregate* linkage; // aggregate node of objects the linker may need, if not referenced by the rest of the AST
+ TScanContext* scanContext;
+ TPpContext* ppContext;
+
+ // These, if set, will be called when a line, pragma ... is preprocessed.
+ // They will be called with any parameters to the original directive.
+ std::function<void(int, int, bool, int, const char*)> lineCallback;
+ std::function<void(int, const TVector<TString>&)> pragmaCallback;
+ std::function<void(int, int, const char*)> versionCallback;
+ std::function<void(int, const char*, const char*)> extensionCallback;
+ std::function<void(int, const char*)> errorCallback;
+};
+
+//
+// GLSL-specific parse helper. Should have GLSL in the name, but that's
+// too big of a change for comparing branches at the moment, and perhaps
+// impacts downstream consumers as well.
+//
+class TParseContext : public TParseContextBase {
public:
TParseContext(TSymbolTable&, TIntermediate&, bool parsingBuiltins, int version, EProfile, int spv, int vulkan, EShLanguage, TInfoSink&,
bool forwardCompatible = false, EShMessages messages = EShMsgDefault);
@@ -72,7 +158,6 @@
void setLimits(const TBuiltInResource&);
bool parseShaderStrings(TPpContext&, TInputScanner& input, bool versionWillBeError = false);
void parserError(const char* s); // for bison's yyerror
- const char* getPreamble();
void C_DECL error(const TSourceLoc&, const char* szReason, const char* szToken,
const char* szExtraInfoFormat, ...);
@@ -83,12 +168,10 @@
void C_DECL ppWarn(const TSourceLoc&, const char* szReason, const char* szToken,
const char* szExtraInfoFormat, ...);
- bool relaxedErrors() const { return (messages & EShMsgRelaxedErrors) != 0; }
- bool suppressWarnings() const { return (messages & EShMsgSuppressWarnings) != 0; }
-
void reservedErrorCheck(const TSourceLoc&, const TString&);
void reservedPpErrorCheck(const TSourceLoc&, const char* name, const char* op);
bool lineContinuationCheck(const TSourceLoc&, bool endOfComment);
+ bool lineDirectiveShouldSetNextLine() const;
bool builtInName(const TString&);
void handlePragma(const TSourceLoc&, const TVector<TString>&);
@@ -210,55 +293,6 @@
void updateImplicitArraySize(const TSourceLoc&, TIntermNode*, int index);
- void setScanContext(TScanContext* c) { scanContext = c; }
- TScanContext* getScanContext() const { return scanContext; }
- void setPpContext(TPpContext* c) { ppContext = c; }
- TPpContext* getPpContext() const { return ppContext; }
- void addError() { ++numErrors; }
- int getNumErrors() const { return numErrors; }
- const TSourceLoc& getCurrentLoc() const { return currentScanner->getSourceLoc(); }
- void setCurrentLine(int line) { currentScanner->setLine(line); }
- void setCurrentColumn(int col) { currentScanner->setColumn(col); }
- void setCurrentSourceName(const char* name) { currentScanner->setFile(name); }
- void setCurrentString(int string) { currentScanner->setString(string); }
- void setScanner(TInputScanner* scanner) { currentScanner = scanner; }
- TInputScanner* getScanner() const { return currentScanner; }
-
- bool lineDirectiveShouldSetNextLine() const;
-
- void notifyVersion(int line, int version, const char* type_string);
- void notifyErrorDirective(int line, const char* error_message);
- void notifyLineDirective(int curLineNo, int newLineNo, bool hasSource, int sourceNum, const char* sourceName);
- void notifyExtensionDirective(int line, const char* extension, const char* behavior);
-
- // The following are implemented in Versions.cpp to localize version/profile/stage/extensions control
- void initializeExtensionBehavior();
- void requireProfile(const TSourceLoc&, int queryProfiles, const char* featureDesc);
- void profileRequires(const TSourceLoc&, int queryProfiles, int minVersion, int numExtensions, const char* const extensions[], const char* featureDesc);
- void profileRequires(const TSourceLoc&, int queryProfiles, int minVersion, const char* const extension, const char* featureDesc);
- void requireStage(const TSourceLoc&, EShLanguageMask, const char* featureDesc);
- void requireStage(const TSourceLoc&, EShLanguage, const char* featureDesc);
- void checkDeprecated(const TSourceLoc&, int queryProfiles, int depVersion, const char* featureDesc);
- void requireNotRemoved(const TSourceLoc&, int queryProfiles, int removedVersion, const char* featureDesc);
- void requireExtensions(const TSourceLoc&, int numExtensions, const char* const extensions[], const char* featureDesc);
- void ppRequireExtensions(const TSourceLoc&, int numExtensions, const char* const extensions[], const char* featureDesc);
- TExtensionBehavior getExtensionBehavior(const char*);
- bool extensionTurnedOn(const char* const extension);
- bool extensionsTurnedOn(int numExtensions, const char* const extensions[]);
- void updateExtensionBehavior(int line, const char* const extension, const char* behavior);
- void fullIntegerCheck(const TSourceLoc&, const char* op);
- void doubleCheck(const TSourceLoc&, const char* op);
- void spvRemoved(const TSourceLoc&, const char* op);
- void vulkanRemoved(const TSourceLoc&, const char* op);
- void requireVulkan(const TSourceLoc&, const char* op);
- void requireSpv(const TSourceLoc&, const char* op);
-
- void setVersionCallback(const std::function<void(int, int, const char*)>& func) { versionCallback = func; }
- void setPragmaCallback(const std::function<void(int, const TVector<TString>&)>& func) { pragmaCallback = func; }
- void setLineCallback(const std::function<void(int, int, bool, int, const char*)>& func) { lineCallback = func; }
- void setExtensionCallback(const std::function<void(int, const char*, const char*)>& func) { extensionCallback = func; }
- void setErrorCallback(const std::function<void(int, const char*)>& func) { errorCallback = func; }
-
protected:
void nonInitConstCheck(const TSourceLoc&, TString& identifier, TType& type);
void inheritGlobalDefaults(TQualifier& dst) const;
@@ -268,8 +302,6 @@
TIntermNode* executeInitializer(const TSourceLoc&, TIntermTyped* initializer, TVariable* variable);
TIntermTyped* convertInitializerList(const TSourceLoc&, const TType&, TIntermTyped* initializer);
TOperator mapTypeToConstructorOp(const TType&) const;
- bool checkExtensionsRequested(const TSourceLoc&, int numExtensions, const char* const extensions[], const char* featureDesc);
- void updateExtensionBehavior(const char* const extension, TExtensionBehavior);
void finalErrorCheck();
void outputMessage(const TSourceLoc&, const char* szReason, const char* szToken,
const char* szExtraInfoFormat, TPrefixType prefix,
@@ -280,18 +312,6 @@
// Generally, bison productions, the scanner, and the PP need read/write access to these; just give them direct access
//
- TIntermediate& intermediate; // helper for making and hooking up pieces of the parse tree
- TSymbolTable& symbolTable; // symbol table that goes with the current language, version, and profile
- TInfoSink& infoSink;
-
- // compilation mode
- EShLanguage language; // vertex or fragment language
- int version; // version, updated by #version in the shader
- EProfile profile; // the declared profile in the shader (core by default)
- int spv; // SPIR-V version; 0 means not SPIR-V
- int vulkan; // Vulkan version; 0 means not vulkan
- bool forwardCompatible; // true if errors are to be given for use of deprecated features
-
// Current state of parsing
struct TPragma contextPragma;
int loopNestingLevel; // 0 if outside all loops
@@ -306,9 +326,7 @@
bool functionReturnsValue; // true if a non-void function has a return
const TString* blockName;
TQualifier currentBlockQualifier;
- TIntermAggregate *linkage; // aggregate node of objects the linker may need, if not referenced by the rest of the AST
TPrecisionQualifier defaultPrecision[EbtNumTypes];
- bool tokensBeforeEOF;
TBuiltInResource resources;
TLimits& limits;
@@ -316,13 +334,7 @@
TParseContext(TParseContext&);
TParseContext& operator=(TParseContext&);
- EShMessages messages; // errors/warnings/rule-sets
- TScanContext* scanContext;
- TPpContext* ppContext;
- TInputScanner* currentScanner;
- int numErrors; // number of compile-time errors encountered
bool parsingBuiltins; // true if parsing built-in symbols/functions
- TMap<TString, TExtensionBehavior> extensionBehavior; // for each extension string, what its current behavior is set to
static const int maxSamplerIndex = EsdNumDims * (EbtNumTypes * (2 * 2 * 2)); // see computeSamplerTypeIndex()
TPrecisionQualifier defaultSamplerPrecision[maxSamplerIndex];
bool afterEOF;
@@ -369,14 +381,6 @@
// array-sizing declarations
//
TVector<TSymbol*> ioArraySymbolResizeList;
-
- // These, if set, will be called when a line, pragma ... is preprocessed.
- // They will be called with any parameters to the original directive.
- std::function<void(int, int, bool, int, const char*)> lineCallback;
- std::function<void(int, const TVector<TString>&)> pragmaCallback;
- std::function<void(int, int, const char*)> versionCallback;
- std::function<void(int, const char*, const char*)> extensionCallback;
- std::function<void(int, const char*)> errorCallback;
};
} // end namespace glslang
diff --git a/glslang/MachineIndependent/Scan.h b/glslang/MachineIndependent/Scan.h
index 936b99f..219049b 100644
--- a/glslang/MachineIndependent/Scan.h
+++ b/glslang/MachineIndependent/Scan.h
@@ -51,10 +51,10 @@
//
class TInputScanner {
public:
- TInputScanner(int n, const char* const s[], size_t L[], const char* const* names = nullptr, int b = 0, int f = 0) :
+ TInputScanner(int n, const char* const s[], size_t L[], const char* const* names = nullptr, int b = 0, int f = 0, bool single = false) :
numSources(n),
sources(reinterpret_cast<const unsigned char* const *>(s)), // up to this point, common usage is "char*", but now we need positive 8-bit characters
- lengths(L), currentSource(0), currentChar(0), stringBias(b), finale(f)
+ lengths(L), currentSource(0), currentChar(0), stringBias(b), finale(f), singleLogical(single)
{
loc = new TSourceLoc[numSources];
for (int i = 0; i < numSources; ++i) {
@@ -67,6 +67,10 @@
loc[currentSource].string = -stringBias;
loc[currentSource].line = 1;
loc[currentSource].column = 0;
+ logicalSourceLoc.string = 0;
+ logicalSourceLoc.line = 1;
+ logicalSourceLoc.column = 0;
+ logicalSourceLoc.name = loc[0].name;
}
virtual ~TInputScanner()
@@ -82,8 +86,11 @@
int ret = peek();
++loc[currentSource].column;
+ ++logicalSourceLoc.column;
if (ret == '\n') {
++loc[currentSource].line;
+ ++logicalSourceLoc.line;
+ logicalSourceLoc.column = 0;
loc[currentSource].column = 0;
}
advance();
@@ -118,6 +125,7 @@
if (currentChar > 0) {
--currentChar;
--loc[currentSource].column;
+ --logicalSourceLoc.column;
if (loc[currentSource].column < 0) {
// We've moved back past a new line. Find the
// previous newline (or start of the file) to compute
@@ -129,6 +137,7 @@
}
--chIndex;
}
+ logicalSourceLoc.column = (int)(currentChar - chIndex);
loc[currentSource].column = (int)(currentChar - chIndex);
}
} else {
@@ -141,23 +150,57 @@
} else
currentChar = lengths[currentSource] - 1;
}
- if (peek() == '\n')
+ if (peek() == '\n') {
--loc[currentSource].line;
+ --logicalSourceLoc.line;
+ }
}
// for #line override
- void setLine(int newLine) { loc[getLastValidSourceIndex()].line = newLine; }
- void setFile(const char* filename) { loc[getLastValidSourceIndex()].name = filename; }
+ void setLine(int newLine)
+ {
+ logicalSourceLoc.line = newLine;
+ loc[getLastValidSourceIndex()].line = newLine;
+ }
+
+ // for #line override in filename based parsing
+ void setFile(const char* filename)
+ {
+ logicalSourceLoc.name = filename;
+ loc[getLastValidSourceIndex()].name = filename;
+ }
+
+ void setFile(const char* filename, size_t i)
+ {
+ if (i == getLastValidSourceIndex()) {
+ logicalSourceLoc.name = filename;
+ }
+ loc[i].name = filename;
+ }
+
void setString(int newString)
{
+ logicalSourceLoc.string = newString;
loc[getLastValidSourceIndex()].string = newString;
+ logicalSourceLoc.name = nullptr;
loc[getLastValidSourceIndex()].name = nullptr;
}
// for #include content indentation
- void setColumn(int col) { loc[getLastValidSourceIndex()].column = col; }
+ void setColumn(int col)
+ {
+ logicalSourceLoc.column = col;
+ loc[getLastValidSourceIndex()].column = col;
+ }
- const TSourceLoc& getSourceLoc() const { return loc[std::max(0, std::min(currentSource, numSources - finale - 1))]; }
+ const TSourceLoc& getSourceLoc() const
+ {
+ if (singleLogical) {
+ return logicalSourceLoc;
+ } else {
+ return loc[std::max(0, std::min(currentSource, numSources - finale - 1))];
+ }
+ }
// Returns the index (starting from 0) of the most recent valid source string we are reading from.
int getLastValidSourceIndex() const { return std::min(currentSource, numSources - 1); }
@@ -204,6 +247,10 @@
int stringBias; // the first string that is the user's string number 0
int finale; // number of internal strings after user's last string
+
+ TSourceLoc logicalSourceLoc;
+ bool singleLogical; // treats the strings as a single logical string.
+ // locations will be reported from the first string.
};
} // end namespace glslang
diff --git a/glslang/MachineIndependent/ScanContext.h b/glslang/MachineIndependent/ScanContext.h
index 5f1ffb5..f237bee 100644
--- a/glslang/MachineIndependent/ScanContext.h
+++ b/glslang/MachineIndependent/ScanContext.h
@@ -48,7 +48,7 @@
class TScanContext {
public:
- explicit TScanContext(TParseContext& pc) : parseContext(pc), afterType(false), field(false) { }
+ explicit TScanContext(TParseContextBase& pc) : parseContext(pc), afterType(false), field(false) { }
virtual ~TScanContext() { }
static void fillInKeywordMap();
@@ -72,7 +72,7 @@
int firstGenerationImage(bool inEs310);
int secondGenerationImage();
- TParseContext& parseContext;
+ TParseContextBase& parseContext;
bool afterType; // true if we've recognized a type, so can only be looking for an identifier
bool field; // true if we're on a field, right after a '.'
TSourceLoc loc;
diff --git a/glslang/MachineIndependent/ShaderLang.cpp b/glslang/MachineIndependent/ShaderLang.cpp
index 1f83553..6034f1a 100644
--- a/glslang/MachineIndependent/ShaderLang.cpp
+++ b/glslang/MachineIndependent/ShaderLang.cpp
@@ -46,6 +46,7 @@
#include <sstream>
#include "SymbolTable.h"
#include "ParseHelper.h"
+#include "../../hlsl/hlslParseHelper.h"
#include "Scan.h"
#include "ScanContext.h"
@@ -131,7 +132,8 @@
TIntermediate intermediate(language, version, profile);
TParseContext parseContext(symbolTable, intermediate, true, version, profile, spv, vulkan, language, infoSink);
- TPpContext ppContext(parseContext, TShader::ForbidInclude());
+ TShader::ForbidInclude includer;
+ TPpContext ppContext(parseContext, "", includer);
TScanContext scanContext(parseContext);
parseContext.setScanContext(&scanContext);
parseContext.setPpContext(&ppContext);
@@ -307,11 +309,19 @@
glslang::ReleaseGlobalLock();
}
-bool DeduceVersionProfile(TInfoSink& infoSink, EShLanguage stage, bool versionNotFirst, int defaultVersion, int& version, EProfile& profile, int spv)
+// Return true if the shader was correctly specified for version/profile/stage.
+bool DeduceVersionProfile(TInfoSink& infoSink, EShLanguage stage, bool versionNotFirst, int defaultVersion,
+ EShSource source, int& version, EProfile& profile, int spv)
{
const int FirstProfileVersion = 150;
bool correct = true;
+ if (source == EShSourceHlsl) {
+ version = defaultVersion;
+ profile = ENoProfile;
+ return correct;
+ }
+
// Get a good version...
if (version == 0) {
version = defaultVersion;
@@ -456,7 +466,7 @@
// This is the common setup and cleanup code for PreprocessDeferred and
// CompileDeferred.
// It takes any callable with a signature of
-// bool (TParseContext& parseContext, TPpContext& ppContext,
+// bool (TParseContextBase& parseContext, TPpContext& ppContext,
// TInputScanner& input, bool versionWillBeError,
// TSymbolTable& , TIntermediate& ,
// EShOptimizationLevel , EShMessages );
@@ -482,7 +492,7 @@
TIntermediate& intermediate, // returned tree, etc.
ProcessingContext& processingContext,
bool requireNonempty,
- const TShader::Includer& includer
+ TShader::Includer& includer
)
{
if (! InitThread())
@@ -550,9 +560,9 @@
version = defaultVersion;
profile = defaultProfile;
}
-
int spv = (messages & EShMsgSpvRules) ? 100 : 0; // TODO find path to get real version number here, for now non-0 is what matters
- bool goodVersion = DeduceVersionProfile(compiler->infoSink, compiler->getLanguage(), versionNotFirst, defaultVersion, version, profile, spv);
+ EShSource source = (messages & EShMsgReadHlsl) ? EShSourceHlsl : EShSourceGlsl;
+ bool goodVersion = DeduceVersionProfile(compiler->infoSink, compiler->getLanguage(), versionNotFirst, defaultVersion, source, version, profile, spv);
bool versionWillBeError = (versionNotFound || (profile == EEsProfile && version >= 300 && versionNotFirst));
bool warnVersionNotFirst = false;
if (! versionWillBeError && versionNotFirstToken) {
@@ -563,6 +573,7 @@
}
int vulkan = (messages & EShMsgVulkanRules) ? 100 : 0; // TODO find path to get real version number here, for now non-0 is what matters
+ intermediate.setSource(source);
intermediate.setVersion(version);
intermediate.setProfile(profile);
intermediate.setSpv(spv);
@@ -588,25 +599,37 @@
// Now we can process the full shader under proper symbols and rules.
//
- TParseContext parseContext(symbolTable, intermediate, false, version, profile, spv, vulkan, compiler->getLanguage(), compiler->infoSink, forwardCompatible, messages);
- glslang::TScanContext scanContext(parseContext);
- TPpContext ppContext(parseContext, includer);
- parseContext.setScanContext(&scanContext);
- parseContext.setPpContext(&ppContext);
- parseContext.setLimits(*resources);
+ TParseContextBase* parseContext;
+ if (source == EShSourceHlsl) {
+ parseContext = new HlslParseContext(symbolTable, intermediate, false, version, profile, spv, vulkan,
+ compiler->getLanguage(), compiler->infoSink, forwardCompatible, messages);
+ }
+ else {
+ intermediate.setEntryPoint("main");
+ parseContext = new TParseContext(symbolTable, intermediate, false, version, profile, spv, vulkan,
+ compiler->getLanguage(), compiler->infoSink, forwardCompatible, messages);
+ }
+ TPpContext ppContext(*parseContext, names[numPre]? names[numPre]: "", includer);
+
+ // only GLSL (bison triggered, really) needs an externally set scan context
+ glslang::TScanContext scanContext(*parseContext);
+ if ((messages & EShMsgReadHlsl) == 0)
+ parseContext->setScanContext(&scanContext);
+
+ parseContext->setPpContext(&ppContext);
+ parseContext->setLimits(*resources);
if (! goodVersion)
- parseContext.addError();
+ parseContext->addError();
if (warnVersionNotFirst) {
TSourceLoc loc;
loc.init();
- parseContext.warn(loc, "Illegal to have non-comment, non-whitespace tokens before #version", "#version", "");
+ parseContext->warn(loc, "Illegal to have non-comment, non-whitespace tokens before #version", "#version", "");
}
- parseContext.initializeExtensionBehavior();
-
+ parseContext->initializeExtensionBehavior();
// Fill in the strings as outlined above.
- strings[0] = parseContext.getPreamble();
+ strings[0] = parseContext->getPreamble();
lengths[0] = strlen(strings[0]);
names[0] = nullptr;
strings[1] = customPreamble;
@@ -624,14 +647,14 @@
// Push a new symbol allocation scope that will get used for the shader's globals.
symbolTable.push();
- bool success = processingContext(parseContext, ppContext, fullInput,
+ bool success = processingContext(*parseContext, ppContext, fullInput,
versionWillBeError, symbolTable,
intermediate, optLevel, messages);
// Clean up the symbol table. The AST is self-sufficient now.
delete symbolTableMemory;
-
+ delete parseContext;
delete [] lengths;
delete [] strings;
delete [] names;
@@ -706,7 +729,7 @@
// It places the result in the "string" argument to its constructor.
struct DoPreprocessing {
explicit DoPreprocessing(std::string* string): outputString(string) {}
- bool operator()(TParseContext& parseContext, TPpContext& ppContext,
+ bool operator()(TParseContextBase& parseContext, TPpContext& ppContext,
TInputScanner& input, bool versionWillBeError,
TSymbolTable& , TIntermediate& ,
EShOptimizationLevel , EShMessages )
@@ -817,7 +840,7 @@
// DoFullParse is a valid ProcessingConext template argument for fully
// parsing the shader. It populates the "intermediate" with the AST.
struct DoFullParse{
- bool operator()(TParseContext& parseContext, TPpContext& ppContext,
+ bool operator()(TParseContextBase& parseContext, TPpContext& ppContext,
TInputScanner& fullInput, bool versionWillBeError,
TSymbolTable& symbolTable, TIntermediate& intermediate,
EShOptimizationLevel optLevel, EShMessages messages)
@@ -826,13 +849,13 @@
// Parse the full shader.
if (! parseContext.parseShaderStrings(ppContext, fullInput, versionWillBeError))
success = false;
- intermediate.addSymbolLinkageNodes(parseContext.linkage, parseContext.language, symbolTable);
+ intermediate.addSymbolLinkageNodes(parseContext.getLinkage(), parseContext.getLanguage(), symbolTable);
if (success && intermediate.getTreeRoot()) {
if (optLevel == EShOptNoGeneration)
parseContext.infoSink.info.message(EPrefixNone, "No errors. No code generation or linking was requested.");
else
- success = intermediate.postProcess(intermediate.getTreeRoot(), parseContext.language);
+ success = intermediate.postProcess(intermediate.getTreeRoot(), parseContext.getLanguage());
} else if (! success) {
parseContext.infoSink.info.prefix(EPrefixError);
parseContext.infoSink.info << parseContext.getNumErrors() << " compilation errors. No code generated.\n\n";
@@ -863,7 +886,7 @@
bool forceDefaultVersionAndProfile,
bool forwardCompatible, // give errors for use of deprecated features
EShMessages messages, // warnings/errors/AST; things to print out
- const TShader::Includer& includer,
+ TShader::Includer& includer,
TIntermediate& intermediate, // returned tree, etc.
std::string* outputString)
{
@@ -902,7 +925,7 @@
bool forwardCompatible, // give errors for use of deprecated features
EShMessages messages, // warnings/errors/AST; things to print out
TIntermediate& intermediate,// returned tree, etc.
- const TShader::Includer& includer)
+ TShader::Includer& includer)
{
DoFullParse parser;
return ProcessDeferred(compiler, shaderStrings, numStrings, inputLengths, stringNames,
@@ -1051,9 +1074,10 @@
compiler->infoSink.debug.erase();
TIntermediate intermediate(compiler->getLanguage());
+ TShader::ForbidInclude includer;
bool success = CompileDeferred(compiler, shaderStrings, numStrings, inputLengths, nullptr,
"", optLevel, resources, defaultVersion, ENoProfile, false,
- forwardCompatible, messages, intermediate, TShader::ForbidInclude());
+ forwardCompatible, messages, intermediate, includer);
//
// Call the machine dependent compiler
@@ -1355,13 +1379,18 @@
stringNames = names;
}
+void TShader::setEntryPoint(const char* entryPoint)
+{
+ intermediate->setEntryPoint(entryPoint);
+}
+
//
// Turn the shader strings into a parse tree in the TIntermediate.
//
// Returns true for success.
//
bool TShader::parse(const TBuiltInResource* builtInResources, int defaultVersion, EProfile defaultProfile, bool forceDefaultVersionAndProfile,
- bool forwardCompatible, EShMessages messages, const Includer& includer)
+ bool forwardCompatible, EShMessages messages, Includer& includer)
{
if (! InitThread())
return false;
@@ -1389,7 +1418,7 @@
bool forceDefaultVersionAndProfile,
bool forwardCompatible, EShMessages message,
std::string* output_string,
- const TShader::Includer& includer)
+ Includer& includer)
{
if (! InitThread())
return false;
diff --git a/glslang/MachineIndependent/Versions.cpp b/glslang/MachineIndependent/Versions.cpp
index 676f4fd..af2f7f2 100644
--- a/glslang/MachineIndependent/Versions.cpp
+++ b/glslang/MachineIndependent/Versions.cpp
@@ -74,12 +74,12 @@
//
// const char* const XXX_extension_X = "XXX_extension_X";
//
-// 2) Add extension initialization to TParseContext::initializeExtensionBehavior(),
+// 2) Add extension initialization to TParseVersions::initializeExtensionBehavior(),
// the first function below:
//
// extensionBehavior[XXX_extension_X] = EBhDisable;
//
-// 3) Add any preprocessor directives etc. in the next function, TParseContext::getPreamble():
+// 3) Add any preprocessor directives etc. in the next function, TParseVersions::getPreamble():
//
// "#define XXX_extension_X 1\n"
//
@@ -138,7 +138,8 @@
// table. (There is a different symbol table for each version.)
//
-#include "ParseHelper.h"
+#include "parseVersions.h"
+#include "localintermediate.h"
namespace glslang {
@@ -147,7 +148,7 @@
// are incorporated into a core version, their features are supported through allowing that
// core version, not through a pseudo-enablement of the extension.
//
-void TParseContext::initializeExtensionBehavior()
+void TParseVersions::initializeExtensionBehavior()
{
extensionBehavior[E_GL_OES_texture_3D] = EBhDisable;
extensionBehavior[E_GL_OES_standard_derivatives] = EBhDisable;
@@ -213,7 +214,7 @@
// Get code that is not part of a shared symbol table, is specific to this shader,
// or needed by the preprocessor (which does not use a shared symbol table).
-const char* TParseContext::getPreamble()
+const char* TParseVersions::getPreamble()
{
if (profile == EEsProfile) {
return
@@ -297,7 +298,7 @@
// Operation: If the current profile is not one of the profileMask,
// give an error message.
//
-void TParseContext::requireProfile(const TSourceLoc& loc, int profileMask, const char* featureDesc)
+void TParseVersions::requireProfile(const TSourceLoc& loc, int profileMask, const char* featureDesc)
{
if (! (profile & profileMask))
error(loc, "not supported with this profile:", featureDesc, ProfileName(profile));
@@ -336,7 +337,7 @@
//
// entry point that takes multiple extensions
-void TParseContext::profileRequires(const TSourceLoc& loc, int profileMask, int minVersion, int numExtensions, const char* const extensions[], const char* featureDesc)
+void TParseVersions::profileRequires(const TSourceLoc& loc, int profileMask, int minVersion, int numExtensions, const char* const extensions[], const char* featureDesc)
{
if (profile & profileMask) {
bool okay = false;
@@ -361,7 +362,7 @@
}
// entry point for the above that takes a single extension
-void TParseContext::profileRequires(const TSourceLoc& loc, int profileMask, int minVersion, const char* extension, const char* featureDesc)
+void TParseVersions::profileRequires(const TSourceLoc& loc, int profileMask, int minVersion, const char* extension, const char* featureDesc)
{
profileRequires(loc, profileMask, minVersion, extension ? 1 : 0, &extension, featureDesc);
}
@@ -373,7 +374,7 @@
//
// Operation: If the current stage is not present, give an error message.
//
-void TParseContext::requireStage(const TSourceLoc& loc, EShLanguageMask languageMask, const char* featureDesc)
+void TParseVersions::requireStage(const TSourceLoc& loc, EShLanguageMask languageMask, const char* featureDesc)
{
if (((1 << language) & languageMask) == 0)
error(loc, "not supported in this stage:", featureDesc, StageName(language));
@@ -381,7 +382,7 @@
// If only one stage supports a feature, this can be called. But, all supporting stages
// must be specified with one call.
-void TParseContext::requireStage(const TSourceLoc& loc, EShLanguage stage, const char* featureDesc)
+void TParseVersions::requireStage(const TSourceLoc& loc, EShLanguage stage, const char* featureDesc)
{
requireStage(loc, static_cast<EShLanguageMask>(1 << stage), featureDesc);
}
@@ -390,7 +391,7 @@
// Within a set of profiles, see if a feature is deprecated and give an error or warning based on whether
// a future compatibility context is being use.
//
-void TParseContext::checkDeprecated(const TSourceLoc& loc, int profileMask, int depVersion, const char* featureDesc)
+void TParseVersions::checkDeprecated(const TSourceLoc& loc, int profileMask, int depVersion, const char* featureDesc)
{
if (profile & profileMask) {
if (version >= depVersion) {
@@ -407,7 +408,7 @@
// Within a set of profiles, see if a feature has now been removed and if so, give an error.
// The version argument is the first version no longer having the feature.
//
-void TParseContext::requireNotRemoved(const TSourceLoc& loc, int profileMask, int removedVersion, const char* featureDesc)
+void TParseVersions::requireNotRemoved(const TSourceLoc& loc, int profileMask, int removedVersion, const char* featureDesc)
{
if (profile & profileMask) {
if (version >= removedVersion) {
@@ -421,7 +422,7 @@
// Returns true if at least one of the extensions in the extensions parameter is requested. Otherwise, returns false.
// Warns appropriately if the requested behavior of an extension is "warn".
-bool TParseContext::checkExtensionsRequested(const TSourceLoc& loc, int numExtensions, const char* const extensions[], const char* featureDesc)
+bool TParseVersions::checkExtensionsRequested(const TSourceLoc& loc, int numExtensions, const char* const extensions[], const char* featureDesc)
{
// First, see if any of the extensions are enabled
for (int i = 0; i < numExtensions; ++i) {
@@ -452,7 +453,7 @@
// Use when there are no profile/version to check, it's just an error if one of the
// extensions is not present.
//
-void TParseContext::requireExtensions(const TSourceLoc& loc, int numExtensions, const char* const extensions[], const char* featureDesc)
+void TParseVersions::requireExtensions(const TSourceLoc& loc, int numExtensions, const char* const extensions[], const char* featureDesc)
{
if (checkExtensionsRequested(loc, numExtensions, extensions, featureDesc)) return;
@@ -470,7 +471,7 @@
// Use by preprocessor when there are no profile/version to check, it's just an error if one of the
// extensions is not present.
//
-void TParseContext::ppRequireExtensions(const TSourceLoc& loc, int numExtensions, const char* const extensions[], const char* featureDesc)
+void TParseVersions::ppRequireExtensions(const TSourceLoc& loc, int numExtensions, const char* const extensions[], const char* featureDesc)
{
if (checkExtensionsRequested(loc, numExtensions, extensions, featureDesc)) return;
@@ -484,7 +485,7 @@
}
}
-TExtensionBehavior TParseContext::getExtensionBehavior(const char* extension)
+TExtensionBehavior TParseVersions::getExtensionBehavior(const char* extension)
{
auto iter = extensionBehavior.find(TString(extension));
if (iter == extensionBehavior.end())
@@ -494,7 +495,7 @@
}
// Returns true if the given extension is set to enable, require, or warn.
-bool TParseContext::extensionTurnedOn(const char* const extension)
+bool TParseVersions::extensionTurnedOn(const char* const extension)
{
switch (getExtensionBehavior(extension)) {
case EBhEnable:
@@ -507,7 +508,7 @@
return false;
}
// See if any of the extensions are set to enable, require, or warn.
-bool TParseContext::extensionsTurnedOn(int numExtensions, const char* const extensions[])
+bool TParseVersions::extensionsTurnedOn(int numExtensions, const char* const extensions[])
{
for (int i = 0; i < numExtensions; ++i) {
if (extensionTurnedOn(extensions[i])) return true;
@@ -518,7 +519,7 @@
//
// Change the current state of an extension's behavior.
//
-void TParseContext::updateExtensionBehavior(int line, const char* extension, const char* behaviorString)
+void TParseVersions::updateExtensionBehavior(int line, const char* extension, const char* behaviorString)
{
// Translate from text string of extension's behavior to an enum.
TExtensionBehavior behavior = EBhDisable;
@@ -571,7 +572,7 @@
spv = 100;
}
-void TParseContext::updateExtensionBehavior(const char* extension, TExtensionBehavior behavior)
+void TParseVersions::updateExtensionBehavior(const char* extension, TExtensionBehavior behavior)
{
// Update the current behavior
if (strcmp(extension, "all") == 0) {
@@ -612,14 +613,14 @@
}
// Call for any operation needing full GLSL integer data-type support.
-void TParseContext::fullIntegerCheck(const TSourceLoc& loc, const char* op)
+void TParseVersions::fullIntegerCheck(const TSourceLoc& loc, const char* op)
{
profileRequires(loc, ENoProfile, 130, nullptr, op);
profileRequires(loc, EEsProfile, 300, nullptr, op);
}
// Call for any operation needing GLSL double data-type support.
-void TParseContext::doubleCheck(const TSourceLoc& loc, const char* op)
+void TParseVersions::doubleCheck(const TSourceLoc& loc, const char* op)
{
requireProfile(loc, ECoreProfile | ECompatibilityProfile, op);
profileRequires(loc, ECoreProfile, 400, nullptr, op);
@@ -627,28 +628,28 @@
}
// Call for any operation removed because SPIR-V is in use.
-void TParseContext::spvRemoved(const TSourceLoc& loc, const char* op)
+void TParseVersions::spvRemoved(const TSourceLoc& loc, const char* op)
{
if (spv > 0)
error(loc, "not allowed when generating SPIR-V", op, "");
}
// Call for any operation removed because Vulkan SPIR-V is being generated.
-void TParseContext::vulkanRemoved(const TSourceLoc& loc, const char* op)
+void TParseVersions::vulkanRemoved(const TSourceLoc& loc, const char* op)
{
if (vulkan > 0)
error(loc, "not allowed when using GLSL for Vulkan", op, "");
}
// Call for any operation that requires Vulkan.
-void TParseContext::requireVulkan(const TSourceLoc& loc, const char* op)
+void TParseVersions::requireVulkan(const TSourceLoc& loc, const char* op)
{
if (vulkan == 0)
error(loc, "only allowed when using GLSL for Vulkan", op, "");
}
// Call for any operation that requires SPIR-V.
-void TParseContext::requireSpv(const TSourceLoc& loc, const char* op)
+void TParseVersions::requireSpv(const TSourceLoc& loc, const char* op)
{
if (spv == 0)
error(loc, "only allowed when generating SPIR-V", op, "");
diff --git a/glslang/MachineIndependent/linkValidate.cpp b/glslang/MachineIndependent/linkValidate.cpp
index 6fef4fb..ef9daa8 100644
--- a/glslang/MachineIndependent/linkValidate.cpp
+++ b/glslang/MachineIndependent/linkValidate.cpp
@@ -69,6 +69,18 @@
//
void TIntermediate::merge(TInfoSink& infoSink, TIntermediate& unit)
{
+ if (source == EShSourceNone)
+ source = unit.source;
+
+ if (source != unit.source)
+ error(infoSink, "can't link compilation units from different source languages");
+
+ if (source == EShSourceHlsl && unit.entryPoint.size() > 0) {
+ if (entryPoint.size() > 0)
+ error(infoSink, "can't handle multiple entry points per stage");
+ else
+ entryPoint = unit.entryPoint;
+ }
numMains += unit.numMains;
numErrors += unit.numErrors;
numPushConstants += unit.numPushConstants;
@@ -355,8 +367,8 @@
// Also, lock in defaults of things not set, including array sizes.
//
void TIntermediate::finalCheck(TInfoSink& infoSink)
-{
- if (numMains < 1)
+{
+ if (source == EShSourceGlsl && numMains < 1)
error(infoSink, "Missing entry point: Each stage requires one \"void main()\" entry point");
if (numPushConstants > 1)
diff --git a/glslang/MachineIndependent/localintermediate.h b/glslang/MachineIndependent/localintermediate.h
index 5e5a2e7..c2d0c74 100644
--- a/glslang/MachineIndependent/localintermediate.h
+++ b/glslang/MachineIndependent/localintermediate.h
@@ -124,7 +124,8 @@
//
class TIntermediate {
public:
- explicit TIntermediate(EShLanguage l, int v = 0, EProfile p = ENoProfile) : language(l), treeRoot(0), profile(p), version(v), spv(0),
+ explicit TIntermediate(EShLanguage l, int v = 0, EProfile p = ENoProfile) :
+ source(EShSourceNone), language(l), profile(p), version(v), spv(0), treeRoot(0),
numMains(0), numErrors(0), numPushConstants(0), recursive(false),
invocations(TQualifier::layoutNotSet), vertices(TQualifier::layoutNotSet), inputPrimitive(ElgNone), outputPrimitive(ElgNone),
pixelCenterInteger(false), originUpperLeft(false),
@@ -143,8 +144,12 @@
bool postProcess(TIntermNode*, EShLanguage);
void output(TInfoSink&, bool tree);
- void removeTree();
+ void removeTree();
+ void setSource(EShSource s) { source = s; }
+ EShSource getSource() const { return source; }
+ void setEntryPoint(const char* ep) { entryPoint = ep; }
+ const std::string& getEntryPoint() const { return entryPoint; }
void setVersion(int v) { version = v; }
int getVersion() const { return version; }
void setProfile(EProfile p) { profile = p; }
@@ -337,12 +342,16 @@
TIntermSequence& findLinkerObjects() const;
bool userOutputUsed() const;
static int getBaseAlignmentScalar(const TType&, int& size);
+ bool isSpecializationOperation(const TIntermOperator&) const;
- const EShLanguage language;
- TIntermNode* treeRoot;
+
+ const EShLanguage language; // stage, known at construction time
+ EShSource source; // source language, known a bit later
+ std::string entryPoint;
EProfile profile;
int version;
int spv;
+ TIntermNode* treeRoot;
std::set<std::string> requestedExtensions; // cumulation of all enabled or required extensions; not connected to what subset of the shader used them
TBuiltInResource resources;
int numMains;
diff --git a/glslang/MachineIndependent/parseVersions.h b/glslang/MachineIndependent/parseVersions.h
new file mode 100755
index 0000000..c9dfdc9
--- /dev/null
+++ b/glslang/MachineIndependent/parseVersions.h
@@ -0,0 +1,134 @@
+//
+//Copyright (C) 2016 Google, Inc.
+//
+//All rights reserved.
+//
+//Redistribution and use in source and binary forms, with or without
+//modification, are permitted provided that the following conditions
+//are met:
+//
+// Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//
+// Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+//
+// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+//POSSIBILITY OF SUCH DAMAGE.
+//
+
+// This is implemented in Versions.cpp
+
+#ifndef _PARSE_VERSIONS_INCLUDED_
+#define _PARSE_VERSIONS_INCLUDED_
+
+#include "../Public/ShaderLang.h"
+#include "../Include/InfoSink.h"
+#include "Scan.h"
+
+#include <map>
+
+namespace glslang {
+
+//
+// Base class for parse helpers.
+// This just has version-related information and checking.
+// This class should be sufficient for preprocessing.
+//
+class TParseVersions {
+public:
+ TParseVersions(TIntermediate& interm, int version, EProfile profile,
+ int spv, int vulkan, EShLanguage language, TInfoSink& infoSink,
+ bool forwardCompatible, EShMessages messages)
+ : infoSink(infoSink), version(version), profile(profile), language(language),
+ spv(spv), vulkan(vulkan), forwardCompatible(forwardCompatible),
+ intermediate(interm), messages(messages), numErrors(0), currentScanner(0) { }
+ virtual ~TParseVersions() { }
+ virtual void initializeExtensionBehavior();
+ virtual void requireProfile(const TSourceLoc&, int queryProfiles, const char* featureDesc);
+ virtual void profileRequires(const TSourceLoc&, int queryProfiles, int minVersion, int numExtensions, const char* const extensions[], const char* featureDesc);
+ virtual void profileRequires(const TSourceLoc&, int queryProfiles, int minVersion, const char* const extension, const char* featureDesc);
+ virtual void requireStage(const TSourceLoc&, EShLanguageMask, const char* featureDesc);
+ virtual void requireStage(const TSourceLoc&, EShLanguage, const char* featureDesc);
+ virtual void checkDeprecated(const TSourceLoc&, int queryProfiles, int depVersion, const char* featureDesc);
+ virtual void requireNotRemoved(const TSourceLoc&, int queryProfiles, int removedVersion, const char* featureDesc);
+ virtual void requireExtensions(const TSourceLoc&, int numExtensions, const char* const extensions[], const char* featureDesc);
+ virtual void ppRequireExtensions(const TSourceLoc&, int numExtensions, const char* const extensions[], const char* featureDesc);
+ virtual TExtensionBehavior getExtensionBehavior(const char*);
+ virtual bool extensionTurnedOn(const char* const extension);
+ virtual bool extensionsTurnedOn(int numExtensions, const char* const extensions[]);
+ virtual void updateExtensionBehavior(int line, const char* const extension, const char* behavior);
+ virtual void fullIntegerCheck(const TSourceLoc&, const char* op);
+ virtual void doubleCheck(const TSourceLoc&, const char* op);
+ virtual void spvRemoved(const TSourceLoc&, const char* op);
+ virtual void vulkanRemoved(const TSourceLoc&, const char* op);
+ virtual void requireVulkan(const TSourceLoc&, const char* op);
+ virtual void requireSpv(const TSourceLoc&, const char* op);
+ virtual bool checkExtensionsRequested(const TSourceLoc&, int numExtensions, const char* const extensions[], const char* featureDesc);
+ virtual void updateExtensionBehavior(const char* const extension, TExtensionBehavior);
+
+ virtual void C_DECL error(const TSourceLoc&, const char* szReason, const char* szToken,
+ const char* szExtraInfoFormat, ...) = 0;
+ virtual void C_DECL warn(const TSourceLoc&, const char* szReason, const char* szToken,
+ const char* szExtraInfoFormat, ...) = 0;
+ virtual void C_DECL ppError(const TSourceLoc&, const char* szReason, const char* szToken,
+ const char* szExtraInfoFormat, ...) = 0;
+ virtual void C_DECL ppWarn(const TSourceLoc&, const char* szReason, const char* szToken,
+ const char* szExtraInfoFormat, ...) = 0;
+
+ void addError() { ++numErrors; }
+ int getNumErrors() const { return numErrors; }
+
+ void setScanner(TInputScanner* scanner) { currentScanner = scanner; }
+ TInputScanner* getScanner() const { return currentScanner; }
+ const TSourceLoc& getCurrentLoc() const { return currentScanner->getSourceLoc(); }
+ void setCurrentLine(int line) { currentScanner->setLine(line); }
+ void setCurrentColumn(int col) { currentScanner->setColumn(col); }
+ void setCurrentSourceName(const char* name) { currentScanner->setFile(name); }
+ void setCurrentString(int string) { currentScanner->setString(string); }
+
+ const char* getPreamble();
+ bool relaxedErrors() const { return (messages & EShMsgRelaxedErrors) != 0; }
+ bool suppressWarnings() const { return (messages & EShMsgSuppressWarnings) != 0; }
+
+ TInfoSink& infoSink;
+
+ // compilation mode
+ int version; // version, updated by #version in the shader
+ EProfile profile; // the declared profile in the shader (core by default)
+ EShLanguage language; // really the stage
+ int spv; // SPIR-V version; 0 means not SPIR-V
+ int vulkan; // Vulkan version; 0 means not vulkan
+ bool forwardCompatible; // true if errors are to be given for use of deprecated features
+ TIntermediate& intermediate; // helper for making and hooking up pieces of the parse tree
+
+protected:
+ EShMessages messages; // errors/warnings/rule-sets
+ int numErrors; // number of compile-time errors encountered
+ TInputScanner* currentScanner;
+
+private:
+ TMap<TString, TExtensionBehavior> extensionBehavior; // for each extension string, what its current behavior is set to
+ explicit TParseVersions(const TParseVersions&);
+ TParseVersions& operator=(const TParseVersions&);
+};
+
+} // end namespace glslang
+
+#endif // _PARSE_VERSIONS_INCLUDED_
diff --git a/glslang/MachineIndependent/preprocessor/Pp.cpp b/glslang/MachineIndependent/preprocessor/Pp.cpp
index da70942..b9d00c8 100644
--- a/glslang/MachineIndependent/preprocessor/Pp.cpp
+++ b/glslang/MachineIndependent/preprocessor/Pp.cpp
@@ -611,24 +611,28 @@
if (token != '\n' && token != EndOfInput) {
parseContext.ppError(ppToken->loc, "extra content after file designation", "#include", "");
} else {
- auto include = includer.include(filename.c_str());
- std::string sourceName = include.first;
- std::string replacement = include.second;
- if (!sourceName.empty()) {
- if (!replacement.empty()) {
+ TShader::Includer::IncludeResult* res = includer.include(filename.c_str(), TShader::Includer::EIncludeRelative, currentSourceFile.c_str(), includeStack.size() + 1);
+ if (res && !res->file_name.empty()) {
+ if (res->file_data && res->file_length) {
const bool forNextLine = parseContext.lineDirectiveShouldSetNextLine();
- std::ostringstream content;
- content << "#line " << forNextLine << " " << "\"" << sourceName << "\"\n";
- content << replacement << (replacement.back() == '\n' ? "" : "\n");
- content << "#line " << directiveLoc.line + forNextLine << " " << directiveLoc.getStringNameOrNum() << "\n";
- pushInput(new TokenizableString(directiveLoc, content.str(), this));
+ std::ostringstream prologue;
+ std::ostringstream epilogue;
+ prologue << "#line " << forNextLine << " " << "\"" << res->file_name << "\"\n";
+ epilogue << (res->file_data[res->file_length - 1] == '\n'? "" : "\n") << "#line " << directiveLoc.line + forNextLine << " " << directiveLoc.getStringNameOrNum() << "\n";
+ pushInput(new TokenizableIncludeFile(directiveLoc, prologue.str(), res, epilogue.str(), this));
}
// At EOF, there's no "current" location anymore.
if (token != EndOfInput) parseContext.setCurrentColumn(0);
// Don't accidentally return EndOfInput, which will end all preprocessing.
return '\n';
} else {
- parseContext.ppError(directiveLoc, replacement.c_str(), "#include", "");
+ std::string message =
+ res ? std::string(res->file_data, res->file_length)
+ : std::string("Could not process include directive");
+ parseContext.ppError(directiveLoc, message.c_str(), "#include", "");
+ if (res) {
+ includer.releaseInclude(res);
+ }
}
}
}
diff --git a/glslang/MachineIndependent/preprocessor/PpContext.cpp b/glslang/MachineIndependent/preprocessor/PpContext.cpp
index b8d2c73..6f0b8a9 100644
--- a/glslang/MachineIndependent/preprocessor/PpContext.cpp
+++ b/glslang/MachineIndependent/preprocessor/PpContext.cpp
@@ -83,8 +83,10 @@
namespace glslang {
-TPpContext::TPpContext(TParseContext& pc, const TShader::Includer& inclr) :
- preamble(0), strings(0), parseContext(pc), includer(inclr), inComment(false)
+TPpContext::TPpContext(TParseContextBase& pc, const std::string& rootFileName, TShader::Includer& inclr) :
+ preamble(0), strings(0), parseContext(pc), includer(inclr), inComment(false),
+ rootFileName(rootFileName),
+ currentSourceFile(rootFileName)
{
InitAtomTable();
InitScanner();
diff --git a/glslang/MachineIndependent/preprocessor/PpContext.h b/glslang/MachineIndependent/preprocessor/PpContext.h
index f1d5469..f65eb60 100644
--- a/glslang/MachineIndependent/preprocessor/PpContext.h
+++ b/glslang/MachineIndependent/preprocessor/PpContext.h
@@ -78,6 +78,7 @@
#ifndef PPCONTEXT_H
#define PPCONTEXT_H
+#include <stack>
#include <unordered_map>
#include "../ParseHelper.h"
@@ -121,7 +122,7 @@
// Don't expect too much in terms of OO design.
class TPpContext {
public:
- TPpContext(TParseContext&, const TShader::Includer&);
+ TPpContext(TParseContextBase&, const std::string& rootFileName, TShader::Includer&);
virtual ~TPpContext();
void setPreamble(const char* preamble, size_t length);
@@ -213,7 +214,7 @@
// Scanner data:
int previous_token;
- TParseContext& parseContext;
+ TParseContextBase& parseContext;
// Get the next token from *stack* of input sources, popping input sources
// that are out of tokens, down until an input sources is found that has a token.
@@ -290,7 +291,7 @@
//
// Used to obtain #include content.
- const TShader::Includer& includer;
+ TShader::Includer& includer;
int InitCPP();
int CPPdefine(TPpToken * ppToken);
@@ -430,21 +431,40 @@
TInputScanner* input;
};
- // Holds a string that can be tokenized via the tInput interface.
- class TokenizableString : public tInput {
+ // Holds a reference to included file data, as well as a
+ // prologue and an epilogue string. This can be scanned using the tInput
+ // interface and acts as a single source string.
+ class TokenizableIncludeFile : public tInput {
public:
- // Copies str, which must be non-empty.
- TokenizableString(const TSourceLoc& startLoc, const std::string& str, TPpContext* pp)
+ // Copies prologue and epilogue. The includedFile must remain valid
+ // until this TokenizableIncludeFile is no longer used.
+ TokenizableIncludeFile(const TSourceLoc& startLoc,
+ const std::string& prologue,
+ TShader::Includer::IncludeResult* includedFile,
+ const std::string& epilogue,
+ TPpContext* pp)
: tInput(pp),
- str_(str),
- strings(str_.data()),
- length(str_.size()),
- scanner(1, &strings, &length),
+ prologue_(prologue),
+ includedFile_(includedFile),
+ epilogue_(epilogue),
+ scanner(3, strings, lengths, names, 0, 0, true),
prevScanner(nullptr),
- stringInput(pp, scanner) {
- scanner.setLine(startLoc.line);
- scanner.setString(startLoc.string);
- scanner.setFile(startLoc.name);
+ stringInput(pp, scanner)
+ {
+ strings[0] = prologue_.data();
+ strings[1] = includedFile_->file_data;
+ strings[2] = epilogue_.data();
+
+ lengths[0] = prologue_.size();
+ lengths[1] = includedFile_->file_length;
+ lengths[2] = epilogue_.size();
+
+ scanner.setLine(startLoc.line);
+ scanner.setString(startLoc.string);
+
+ scanner.setFile(startLoc.name, 0);
+ scanner.setFile(startLoc.name, 1);
+ scanner.setFile(startLoc.name, 2);
}
// tInput methods:
@@ -456,16 +476,34 @@
{
prevScanner = pp->parseContext.getScanner();
pp->parseContext.setScanner(&scanner);
+ pp->push_include(includedFile_);
}
- void notifyDeleted() override { pp->parseContext.setScanner(prevScanner); }
+
+ void notifyDeleted() override
+ {
+ pp->parseContext.setScanner(prevScanner);
+ pp->pop_include();
+ }
private:
- // Stores the titular string.
- const std::string str_;
- // Will point to str_[0] and be passed to scanner constructor.
- const char* const strings;
+ // Stores the prologue for this string.
+ const std::string prologue_;
+
+ // Stores the epilogue for this string.
+ const std::string epilogue_;
+
+ // Points to the IncludeResult that this TokenizableIncludeFile represents.
+ TShader::Includer::IncludeResult* includedFile_;
+
+ // Will point to prologue_, includedFile_->file_data and epilogue_
+ // This is passed to scanner constructor.
+ // These do not own the storage and it must remain valid until this
+ // object has been destroyed.
+ const char* strings[3];
// Length of str_, passed to scanner constructor.
- size_t length;
+ size_t lengths[3];
+ // String names
+ const char* names[3];
// Scans over str_.
TInputScanner scanner;
// The previous effective scanner before the scanner in this instance
@@ -480,6 +518,24 @@
void missingEndifCheck();
int lFloatConst(int len, int ch, TPpToken* ppToken);
+ void push_include(TShader::Includer::IncludeResult* result)
+ {
+ currentSourceFile = result->file_name;
+ includeStack.push(result);
+ }
+
+ void pop_include()
+ {
+ TShader::Includer::IncludeResult* include = includeStack.top();
+ includeStack.pop();
+ includer.releaseInclude(include);
+ if (includeStack.empty()) {
+ currentSourceFile = rootFileName;
+ } else {
+ currentSourceFile = includeStack.top()->file_name;
+ }
+ }
+
bool inComment;
//
@@ -487,8 +543,12 @@
//
typedef TUnorderedMap<TString, int> TAtomMap;
typedef TVector<const TString*> TStringMap;
+
TAtomMap atomMap;
TStringMap stringMap;
+ std::stack<TShader::Includer::IncludeResult*> includeStack;
+ std::string currentSourceFile;
+ std::string rootFileName;
int nextAtom;
void InitAtomTable();
void AddAtomFixed(const char* s, int atom);
diff --git a/glslang/OSDependent/Unix/ossource.cpp b/glslang/OSDependent/Unix/ossource.cpp
index 5ce882a..3bd725e 100644
--- a/glslang/OSDependent/Unix/ossource.cpp
+++ b/glslang/OSDependent/Unix/ossource.cpp
@@ -61,7 +61,7 @@
//
-// Registers cleanup handler, sets cancel type and state, and excecutes the thread specific
+// Registers cleanup handler, sets cancel type and state, and executes the thread specific
// cleanup handler. This function will be called in the Standalone.cpp for regression
// testing. When OpenGL applications are run with the driver code, Linux OS does the
// thread cleanup.
diff --git a/glslang/Public/ShaderLang.h b/glslang/Public/ShaderLang.h
index 702b66f..856af26 100644
--- a/glslang/Public/ShaderLang.h
+++ b/glslang/Public/ShaderLang.h
@@ -86,7 +86,7 @@
EShLangFragment,
EShLangCompute,
EShLangCount,
-} EShLanguage;
+} EShLanguage; // would be better as stage, but this is ancient now
typedef enum {
EShLangVertexMask = (1 << EShLangVertex),
@@ -99,6 +99,12 @@
namespace glslang {
+typedef enum {
+ EShSourceNone,
+ EShSourceGlsl,
+ EShSourceHlsl,
+} EShSource; // if EShLanguage were EShStage, this could be EShLanguage instead
+
const char* StageName(EShLanguage);
} // end namespace glslang
@@ -132,6 +138,7 @@
EShMsgSpvRules = (1 << 3), // issue messages for SPIR-V generation
EShMsgVulkanRules = (1 << 4), // issue messages for Vulkan-requirements of GLSL for SPIR-V
EShMsgOnlyPreprocessor = (1 << 5), // only print out errors produced by the preprocessor
+ EShMsgReadHlsl = (1 << 6), // use HLSL parsing rules and semantics
};
//
@@ -290,27 +297,93 @@
void setStringsWithLengthsAndNames(
const char* const* s, const int* l, const char* const* names, int n);
void setPreamble(const char* s) { preamble = s; }
+ void setEntryPoint(const char* entryPoint);
// Interface to #include handlers.
+ //
+ // To support #include, a client of Glslang does the following:
+ // 1. Call setStringsWithNames to set the source strings and associated
+ // names. For example, the names could be the names of the files
+ // containing the shader sources.
+ // 2. Call parse with an Includer.
+ //
+ // When the Glslang parser encounters an #include directive, it calls
+ // the Includer's include method with the the requested include name
+ // together with the current string name. The returned IncludeResult
+ // contains the fully resolved name of the included source, together
+ // with the source text that should replace the #include directive
+ // in the source stream. After parsing that source, Glslang will
+ // release the IncludeResult object.
class Includer {
public:
- // On success, returns the full path and content of the file with the given
- // filename that replaces "#include filename". On failure, returns an empty
- // string and an error message.
- virtual std::pair<std::string, std::string> include(const char* filename) const = 0;
+ typedef enum {
+ EIncludeRelative, // For #include "something"
+ EIncludeStandard // Reserved. For #include <something>
+ } IncludeType;
+
+ // An IncludeResult contains the resolved name and content of a source
+ // inclusion.
+ struct IncludeResult {
+ // For a successful inclusion, the fully resolved name of the requested
+ // include. For example, in a filesystem-based includer, full resolution
+ // should convert a relative path name into an absolute path name.
+ // For a failed inclusion, this is an empty string.
+ std::string file_name;
+ // The content and byte length of the requested inclusion. The
+ // Includer producing this IncludeResult retains ownership of the
+ // storage.
+ // For a failed inclusion, the file_data
+ // field points to a string containing error details.
+ const char* file_data;
+ const size_t file_length;
+ // Include resolver's context.
+ void* user_data;
+ };
+
+ // Resolves an inclusion request by name, type, current source name,
+ // and include depth.
+ // On success, returns an IncludeResult containing the resolved name
+ // and content of the include. On failure, returns an IncludeResult
+ // with an empty string for the file_name and error details in the
+ // file_data field. The Includer retains ownership of the contents
+ // of the returned IncludeResult value, and those contents must
+ // remain valid until the releaseInclude method is called on that
+ // IncludeResult object.
+ virtual IncludeResult* include(const char* requested_source,
+ IncludeType type,
+ const char* requesting_source,
+ size_t inclusion_depth) = 0;
+ // Signals that the parser will no longer use the contents of the
+ // specified IncludeResult.
+ virtual void releaseInclude(IncludeResult* result) = 0;
};
// Returns an error message for any #include directive.
class ForbidInclude : public Includer {
public:
- std::pair<std::string, std::string> include(const char* /*filename*/) const override
+ IncludeResult* include(const char*, IncludeType, const char*, size_t) override
{
- return std::make_pair<std::string, std::string>("", "unexpected include directive");
+ static const char unexpected_include[] =
+ "unexpected include directive";
+ static const IncludeResult unexpectedIncludeResult =
+ {"", unexpected_include, sizeof(unexpected_include) - 1, nullptr};
+ return new IncludeResult(unexpectedIncludeResult);
+ }
+ virtual void releaseInclude(IncludeResult* result) override
+ {
+ delete result;
}
};
+ bool parse(const TBuiltInResource* res, int defaultVersion, EProfile defaultProfile, bool forceDefaultVersionAndProfile,
+ bool forwardCompatible, EShMessages messages)
+ {
+ TShader::ForbidInclude includer;
+ return parse(res, defaultVersion, defaultProfile, forceDefaultVersionAndProfile, forwardCompatible, messages, includer);
+ }
+
bool parse(const TBuiltInResource*, int defaultVersion, EProfile defaultProfile, bool forceDefaultVersionAndProfile,
- bool forwardCompatible, EShMessages, const Includer& = ForbidInclude());
+ bool forwardCompatible, EShMessages, Includer&);
// Equivalent to parse() without a default profile and without forcing defaults.
// Provided for backwards compatibility.
@@ -318,7 +391,7 @@
bool preprocess(const TBuiltInResource* builtInResources,
int defaultVersion, EProfile defaultProfile, bool forceDefaultVersionAndProfile,
bool forwardCompatible, EShMessages message, std::string* outputString,
- const TShader::Includer& includer);
+ Includer& includer);
const char* getInfoLog();
const char* getInfoDebugLog();
diff --git a/gtests/AST.FromFile.cpp b/gtests/AST.FromFile.cpp
new file mode 100644
index 0000000..5e0b31e
--- /dev/null
+++ b/gtests/AST.FromFile.cpp
@@ -0,0 +1,191 @@
+//
+// Copyright (C) 2016 Google, Inc.
+//
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+//
+// Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//
+// Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+//
+// Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+
+#include <gtest/gtest.h>
+
+#include "TestFixture.h"
+
+namespace glslangtest {
+namespace {
+
+using CompileToAstTest = GlslangTest<::testing::TestWithParam<std::string>>;
+
+TEST_P(CompileToAstTest, FromFile)
+{
+ loadFileCompileAndCheck(GLSLANG_TEST_DIRECTORY, GetParam(),
+ Semantics::OpenGL, Target::AST);
+}
+
+// clang-format off
+INSTANTIATE_TEST_CASE_P(
+ Glsl, CompileToAstTest,
+ ::testing::ValuesIn(std::vector<std::string>({
+ "sample.frag",
+ "sample.vert",
+ "decls.frag",
+ "specExamples.frag",
+ "specExamples.vert",
+ "versionsClean.frag",
+ "versionsClean.vert",
+ "versionsErrors.frag",
+ "versionsErrors.vert",
+ "100.frag",
+ "120.vert",
+ "120.frag",
+ "130.vert",
+ "130.frag",
+ "140.vert",
+ "140.frag",
+ "150.vert",
+ "150.geom",
+ "150.frag",
+ "precision.frag",
+ "precision.vert",
+ "nonSquare.vert",
+ "matrixError.vert",
+ "cppSimple.vert",
+ "cppIndent.vert",
+ "cppNest.vert",
+ "cppComplexExpr.vert",
+ "badChars.frag",
+ "pointCoord.frag",
+ "array.frag",
+ "array100.frag",
+ "comment.frag",
+ "300.vert",
+ "300.frag",
+ "300BuiltIns.frag",
+ "300layout.vert",
+ "300layout.frag",
+ "300operations.frag",
+ "300block.frag",
+ "310.comp",
+ "310.vert",
+ "310.geom",
+ "310.frag",
+ "310.tesc",
+ "310.tese",
+ "310implicitSizeArrayError.vert",
+ "310AofA.vert",
+ "330.frag",
+ "330comp.frag",
+ "constErrors.frag",
+ "constFold.frag",
+ "errors.frag",
+ "forwardRef.frag",
+ "uint.frag",
+ "switch.frag",
+ "tokenLength.vert",
+ "100Limits.vert",
+ "100scope.vert",
+ "110scope.vert",
+ "300scope.vert",
+ "400.frag",
+ "420.frag",
+ "420.vert",
+ "420.geom",
+ "420_size_gl_in.geom",
+ "430scope.vert",
+ "lineContinuation100.vert",
+ "lineContinuation.vert",
+ "numeral.frag",
+ "400.geom",
+ "400.tesc",
+ "400.tese",
+ "410.tesc",
+ "420.tesc",
+ "420.tese",
+ "410.geom",
+ "430.vert",
+ "430.comp",
+ "430AofA.frag",
+ "440.vert",
+ "440.frag",
+ "450.vert",
+ "450.geom",
+ "450.tesc",
+ "450.tese",
+ "450.frag",
+ "450.comp",
+ "dce.frag",
+ "atomic_uint.frag",
+ "aggOps.frag",
+ "always-discard.frag",
+ "always-discard2.frag",
+ "conditionalDiscard.frag",
+ "conversion.frag",
+ "dataOut.frag",
+ "dataOutIndirect.frag",
+ "deepRvalue.frag",
+ "depthOut.frag",
+ "discard-dce.frag",
+ "doWhileLoop.frag",
+ "earlyReturnDiscard.frag",
+ "flowControl.frag",
+ "forLoop.frag",
+ "functionCall.frag",
+ "functionSemantics.frag",
+ "length.frag",
+ "localAggregates.frag",
+ "loops.frag",
+ "loopsArtificial.frag",
+ "matrix.frag",
+ "matrix2.frag",
+ "newTexture.frag",
+ "Operations.frag",
+ "prepost.frag",
+ "simpleFunctionCall.frag",
+ "structAssignment.frag",
+ "structDeref.frag",
+ "structure.frag",
+ "swizzle.frag",
+ "syntaxError.frag",
+ "test.frag",
+ "texture.frag",
+ "types.frag",
+ "uniformArray.frag",
+ "variableArrayIndex.frag",
+ "varyingArray.frag",
+ "varyingArrayIndirect.frag",
+ "voidFunction.frag",
+ "whileLoop.frag",
+ "nonVulkan.frag",
+ "spv.atomic.comp",
+ })),
+ FileNameAsCustomTestName
+);
+// clang-format on
+
+} // anonymous namespace
+} // namespace glslangtest
diff --git a/gtests/BuiltInResource.FromFile.cpp b/gtests/BuiltInResource.FromFile.cpp
new file mode 100644
index 0000000..c2d2b8b
--- /dev/null
+++ b/gtests/BuiltInResource.FromFile.cpp
@@ -0,0 +1,57 @@
+//
+// Copyright (C) 2016 Google, Inc.
+//
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+//
+// Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//
+// Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+//
+// Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+
+#include <algorithm>
+
+#include <gtest/gtest.h>
+
+#include "StandAlone/DefaultResourceLimits.h"
+#include "TestFixture.h"
+
+namespace glslangtest {
+namespace {
+
+using DefaultResourceTest = GlslangTest<::testing::Test>;
+
+TEST_F(DefaultResourceTest, FromFile)
+{
+ const std::string path = GLSLANG_TEST_DIRECTORY "/baseResults/test.conf";
+ std::string expectedConfig;
+ tryLoadFile(path, "expected resource limit", &expectedConfig);
+ const std::string realConfig = glslang::GetDefaultTBuiltInResourceString();
+ ASSERT_EQ(expectedConfig, realConfig);
+}
+
+} // anonymous namespace
+} // namespace glslangtest
diff --git a/gtests/CMakeLists.txt b/gtests/CMakeLists.txt
new file mode 100644
index 0000000..7f477d6
--- /dev/null
+++ b/gtests/CMakeLists.txt
@@ -0,0 +1,32 @@
+if (TARGET gmock)
+ message(STATUS "Google Mock found - building tests")
+
+ set(TEST_SOURCES
+ # Framework related source files
+ ${CMAKE_CURRENT_SOURCE_DIR}/Initializer.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/Settings.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/Settings.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/TestFixture.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/TestFixture.h
+
+ # Test related source files
+ ${CMAKE_CURRENT_SOURCE_DIR}/AST.FromFile.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/BuiltInResource.FromFile.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/Pp.FromFile.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/Spv.FromFile.cpp
+ )
+
+ add_executable(glslangtests ${TEST_SOURCES})
+ target_compile_definitions(glslangtests
+ PRIVATE GLSLANG_TEST_DIRECTORY="${CMAKE_CURRENT_SOURCE_DIR}/../Test")
+ target_include_directories(glslangtests PRIVATE
+ ${CMAKE_CURRENT_SOURCE_DIR}
+ ${PROJECT_SOURCE_DIR}
+ ${gmock_SOURCE_DIR}/include
+ ${gtest_SOURCE_DIR}/include)
+ target_link_libraries(glslangtests PRIVATE
+ glslang OSDependent OGLCompiler HLSL glslang
+ SPIRV glslang-default-resource-limits gmock)
+ add_test(NAME glslang-gtests COMMAND glslangtests)
+endif()
diff --git a/gtests/Initializer.h b/gtests/Initializer.h
new file mode 100644
index 0000000..e8fa30d
--- /dev/null
+++ b/gtests/Initializer.h
@@ -0,0 +1,119 @@
+//
+// Copyright (C) 2016 Google, Inc.
+//
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+//
+// Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//
+// Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+//
+// Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+
+#ifndef GLSLANG_GTESTS_INITIALIZER_H
+#define GLSLANG_GTESTS_INITIALIZER_H
+
+#include <mutex>
+
+#include "glslang/Public/ShaderLang.h"
+
+namespace glslangtest {
+
+// Initializes glslang on creation, and destroys it on completion.
+// And provides .Acquire() as a way to reinitialize glslang if semantics change.
+// This object is expected to be a singleton, so that internal glslang state
+// can be correctly handled.
+//
+// TODO(antiagainst): It's a known bug that some of the internal states need to
+// be reset if semantics change:
+// https://github.com/KhronosGroup/glslang/issues/166
+// Therefore, the following mechanism is needed. Remove this once the above bug
+// gets fixed.
+class GlslangInitializer {
+public:
+ GlslangInitializer() : lastMessages(EShMsgDefault)
+ {
+ glslang::InitializeProcess();
+ }
+
+ ~GlslangInitializer() { glslang::FinalizeProcess(); }
+
+ // A token indicates that the glslang is reinitialized (if necessary) to the
+ // required semantics. And that won't change until the token is destroyed.
+ class InitializationToken {
+ public:
+ InitializationToken() : initializer(nullptr) {}
+ ~InitializationToken()
+ {
+ if (initializer) {
+ initializer->release();
+ }
+ }
+
+ InitializationToken(InitializationToken&& other)
+ : initializer(other.initializer)
+ {
+ other.initializer = nullptr;
+ }
+
+ InitializationToken(const InitializationToken&) = delete;
+
+ private:
+ InitializationToken(GlslangInitializer* initializer)
+ : initializer(initializer) {}
+
+ friend class GlslangInitializer;
+ GlslangInitializer* initializer;
+ };
+
+ // Obtains exclusive access to the glslang state. The state remains
+ // exclusive until the Initialization Token has been destroyed.
+ // Re-initializes glsl state iff the previous messages and the current
+ // messages are incompatible.
+ InitializationToken acquire(EShMessages new_messages)
+ {
+ stateLock.lock();
+
+ if ((lastMessages ^ new_messages) &
+ (EShMsgVulkanRules | EShMsgSpvRules)) {
+ glslang::FinalizeProcess();
+ glslang::InitializeProcess();
+ }
+ lastMessages = new_messages;
+ return InitializationToken(this);
+ }
+
+private:
+ void release() { stateLock.unlock(); }
+
+ friend class InitializationToken;
+
+ EShMessages lastMessages;
+ std::mutex stateLock;
+};
+
+} // namespace glslangtest
+
+#endif // GLSLANG_GTESTS_INITIALIZER_H
diff --git a/gtests/Pp.FromFile.cpp b/gtests/Pp.FromFile.cpp
new file mode 100644
index 0000000..cfd987b
--- /dev/null
+++ b/gtests/Pp.FromFile.cpp
@@ -0,0 +1,74 @@
+//
+// Copyright (C) 2016 Google, Inc.
+//
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+//
+// Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//
+// Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+//
+// Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+
+#include <gtest/gtest.h>
+
+#include "TestFixture.h"
+
+namespace glslangtest {
+namespace {
+
+using PreprocessingTest = GlslangTest<::testing::TestWithParam<std::string>>;
+
+TEST_P(PreprocessingTest, FromFile)
+{
+ loadFilePreprocessAndCheck(GLSLANG_TEST_DIRECTORY, GetParam());
+}
+
+// clang-format off
+INSTANTIATE_TEST_CASE_P(
+ Glsl, PreprocessingTest,
+ ::testing::ValuesIn(std::vector<std::string>({
+ "preprocessor.cpp_style_line_directive.vert",
+ "preprocessor.cpp_style___FILE__.vert",
+ "preprocessor.edge_cases.vert",
+ "preprocessor.errors.vert",
+ "preprocessor.extensions.vert",
+ "preprocessor.function_macro.vert",
+ "preprocessor.include.enabled.vert",
+ "preprocessor.include.disabled.vert",
+ "preprocessor.line.vert",
+ "preprocessor.line.frag",
+ "preprocessor.pragma.vert",
+ "preprocessor.simple.vert",
+ "preprocessor.success_if_parse_would_fail.vert",
+ "preprocessor.defined.vert",
+ "preprocessor.many.endif.vert",
+ })),
+ FileNameAsCustomTestName
+);
+// clang-format on
+
+} // anonymous namespace
+} // namespace glslangtest
diff --git a/gtests/README.md b/gtests/README.md
new file mode 100644
index 0000000..c8261cc
--- /dev/null
+++ b/gtests/README.md
@@ -0,0 +1,26 @@
+Glslang Tests based on the Google Test Framework
+================================================
+
+This directory contains [Google Test][gtest] based test fixture and test
+cases for glslang.
+
+Apart from typical unit tests, necessary utility methods are added into
+the [`GlslangTests`](TestFixture.h) fixture to provide the ability to do
+file-based integration tests. Various `*.FromFile.cpp` files lists names
+of files containing input shader code in the `Test/` directory. Utility
+methods will load the input shader source, compile them, and compare with
+the corresponding expected output in the `Test/baseResults/` directory.
+
+How to run the tests
+--------------------
+
+Please make sure you have a copy of [Google Test][gtest] checked out under
+the `External` directory before building. After building, just run the
+`ctest` command or the `gtests/glslangtests` binary in your build directory.
+
+The `gtests/glslangtests` binary also provides an `--update-mode` command
+line option, which, if supplied, will overwrite the golden files under
+the `Test/baseResults/` directory with real output from that invocation.
+This serves as an easy way to update golden files.
+
+[gtest]: https://github.com/google/googletest
diff --git a/gtests/Settings.cpp b/gtests/Settings.cpp
new file mode 100644
index 0000000..4ba7989
--- /dev/null
+++ b/gtests/Settings.cpp
@@ -0,0 +1,41 @@
+//
+// Copyright (C) 2016 Google, Inc.
+//
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+//
+// Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//
+// Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+//
+// Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+
+#include "Settings.h"
+
+namespace glslangtest {
+
+GTestSettings GlobalTestSettings = {nullptr, false};
+
+} // namespace glslangtest
diff --git a/gtests/Settings.h b/gtests/Settings.h
new file mode 100644
index 0000000..30056a7
--- /dev/null
+++ b/gtests/Settings.h
@@ -0,0 +1,54 @@
+//
+// Copyright (C) 2016 Google, Inc.
+//
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+//
+// Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//
+// Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+//
+// Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+
+#ifndef GLSLANG_GTESTS_SETTINGS_H
+#define GLSLANG_GTESTS_SETTINGS_H
+
+namespace glslangtest {
+
+class GlslangInitializer;
+
+struct GTestSettings {
+ // A handle to GlslangInitializer instance.
+ GlslangInitializer* initializer;
+ // An indicator of whether GTest should write real output to the file for
+ // the expected output.
+ bool updateMode;
+};
+
+extern GTestSettings GlobalTestSettings;
+
+} // namespace glslangtest
+
+#endif // GLSLANG_GTESTS_SETTINGS_H
diff --git a/gtests/Spv.FromFile.cpp b/gtests/Spv.FromFile.cpp
new file mode 100644
index 0000000..9cd0787
--- /dev/null
+++ b/gtests/Spv.FromFile.cpp
@@ -0,0 +1,188 @@
+//
+// Copyright (C) 2016 Google, Inc.
+//
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+//
+// Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//
+// Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+//
+// Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+
+#include <algorithm>
+
+#include <gtest/gtest.h>
+
+#include "TestFixture.h"
+
+namespace glslangtest {
+namespace {
+
+using CompileToSpirvTest = GlslangTest<::testing::TestWithParam<std::string>>;
+using VulkanSemantics = GlslangTest<::testing::TestWithParam<std::string>>;
+
+// Compiling GLSL to SPIR-V under Vulkan semantics. Expected to successfully
+// generate SPIR-V.
+TEST_P(CompileToSpirvTest, FromFile)
+{
+ loadFileCompileAndCheck(GLSLANG_TEST_DIRECTORY, GetParam(),
+ Semantics::Vulkan, Target::Spirv);
+}
+
+// GLSL-level Vulkan semantics test. Expected to error out before generating
+// SPIR-V.
+TEST_P(VulkanSemantics, FromFile)
+{
+ loadFileCompileAndCheck(GLSLANG_TEST_DIRECTORY, GetParam(),
+ Semantics::Vulkan, Target::Spirv);
+}
+
+// clang-format off
+INSTANTIATE_TEST_CASE_P(
+ Glsl, CompileToSpirvTest,
+ ::testing::ValuesIn(std::vector<std::string>({
+ // Test looping constructs.
+ // No tests yet for making sure break and continue from a nested loop
+ // goes to the innermost target.
+ "spv.do-simple.vert",
+ "spv.do-while-continue-break.vert",
+ "spv.for-complex-condition.vert",
+ "spv.for-continue-break.vert",
+ "spv.for-simple.vert",
+ "spv.for-notest.vert",
+ "spv.for-nobody.vert",
+ "spv.while-continue-break.vert",
+ "spv.while-simple.vert",
+ // vulkan-specific tests
+ "spv.set.vert",
+ "spv.double.comp",
+ "spv.100ops.frag",
+ "spv.130.frag",
+ "spv.140.frag",
+ "spv.150.geom",
+ "spv.150.vert",
+ "spv.300BuiltIns.vert",
+ "spv.300layout.frag",
+ "spv.300layout.vert",
+ "spv.300layoutp.vert",
+ "spv.310.comp",
+ "spv.330.geom",
+ "spv.400.frag",
+ "spv.400.tesc",
+ "spv.400.tese",
+ "spv.420.geom",
+ "spv.430.vert",
+ "spv.accessChain.frag",
+ "spv.aggOps.frag",
+ "spv.always-discard.frag",
+ "spv.always-discard2.frag",
+ "spv.bitCast.frag",
+ "spv.bool.vert",
+ "spv.boolInBlock.frag",
+ "spv.branch-return.vert",
+ "spv.conditionalDiscard.frag",
+ "spv.conversion.frag",
+ "spv.dataOut.frag",
+ "spv.dataOutIndirect.frag",
+ "spv.dataOutIndirect.vert",
+ "spv.deepRvalue.frag",
+ "spv.depthOut.frag",
+ "spv.discard-dce.frag",
+ "spv.doWhileLoop.frag",
+ "spv.earlyReturnDiscard.frag",
+ "spv.flowControl.frag",
+ "spv.forLoop.frag",
+ "spv.forwardFun.frag",
+ "spv.functionCall.frag",
+ "spv.functionSemantics.frag",
+ "spv.interpOps.frag",
+ "spv.layoutNested.vert",
+ "spv.length.frag",
+ "spv.localAggregates.frag",
+ "spv.loops.frag",
+ "spv.loopsArtificial.frag",
+ "spv.matFun.vert",
+ "spv.matrix.frag",
+ "spv.matrix2.frag",
+ "spv.memoryQualifier.frag",
+ "spv.merge-unreachable.frag",
+ "spv.newTexture.frag",
+ "spv.noDeadDecorations.vert",
+ "spv.nonSquare.vert",
+ "spv.Operations.frag",
+ "spv.intOps.vert",
+ "spv.precision.frag",
+ "spv.prepost.frag",
+ "spv.qualifiers.vert",
+ "spv.shiftOps.frag",
+ "spv.simpleFunctionCall.frag",
+ "spv.simpleMat.vert",
+ "spv.sparseTexture.frag",
+ "spv.sparseTextureClamp.frag",
+ "spv.structAssignment.frag",
+ "spv.structDeref.frag",
+ "spv.structure.frag",
+ "spv.switch.frag",
+ "spv.swizzle.frag",
+ "spv.test.frag",
+ "spv.test.vert",
+ "spv.texture.frag",
+ "spv.texture.vert",
+ "spv.image.frag",
+ "spv.types.frag",
+ "spv.uint.frag",
+ "spv.uniformArray.frag",
+ "spv.variableArrayIndex.frag",
+ "spv.varyingArray.frag",
+ "spv.varyingArrayIndirect.frag",
+ "spv.voidFunction.frag",
+ "spv.whileLoop.frag",
+ "spv.AofA.frag",
+ "spv.queryL.frag",
+ "spv.separate.frag",
+ "spv.shortCircuit.frag",
+ "spv.pushConstant.vert",
+ "spv.subpass.frag",
+ "spv.specConstant.vert",
+ "spv.specConstant.comp",
+ "spv.specConstantComposite.vert",
+ })),
+ FileNameAsCustomTestName
+);
+
+INSTANTIATE_TEST_CASE_P(
+ Glsl, VulkanSemantics,
+ ::testing::ValuesIn(std::vector<std::string>({
+ "vulkan.frag",
+ "vulkan.vert",
+ "vulkan.comp",
+ })),
+ FileNameAsCustomTestName
+);
+// clang-format on
+
+} // anonymous namespace
+} // namespace glslangtest
diff --git a/gtests/TestFixture.cpp b/gtests/TestFixture.cpp
new file mode 100644
index 0000000..744fa55
--- /dev/null
+++ b/gtests/TestFixture.cpp
@@ -0,0 +1,124 @@
+//
+// Copyright (C) 2016 Google, Inc.
+//
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+//
+// Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//
+// Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+//
+// Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+
+#include "TestFixture.h"
+
+namespace glslangtest {
+
+std::string FileNameAsCustomTestName(
+ const ::testing::TestParamInfo<std::string>& info)
+{
+ std::string name = info.param;
+ // A valid test case suffix cannot have '.' and '-' inside.
+ std::replace(name.begin(), name.end(), '.', '_');
+ std::replace(name.begin(), name.end(), '-', '_');
+ return name;
+}
+
+EShLanguage GetGlslLanguageForStage(const std::string& stage)
+{
+ if (stage == "vert") {
+ return EShLangVertex;
+ } else if (stage == "tesc") {
+ return EShLangTessControl;
+ } else if (stage == "tese") {
+ return EShLangTessEvaluation;
+ } else if (stage == "geom") {
+ return EShLangGeometry;
+ } else if (stage == "frag") {
+ return EShLangFragment;
+ } else if (stage == "comp") {
+ return EShLangCompute;
+ } else {
+ assert(0 && "Unknown shader stage");
+ return EShLangCount;
+ }
+}
+
+EShMessages GetSpirvMessageOptionsForSemanticsAndTarget(Semantics semantics,
+ Target target)
+{
+ EShMessages result = EShMsgDefault;
+
+ switch (target) {
+ case Target::AST:
+ result = EShMsgAST;
+ break;
+ case Target::Spirv:
+ result = EShMsgSpvRules;
+ break;
+ };
+
+ switch (semantics) {
+ case Semantics::OpenGL:
+ break;
+ case Semantics::Vulkan:
+ result = static_cast<EShMessages>(result | EShMsgVulkanRules);
+ break;
+ }
+
+ return result;
+}
+
+std::pair<bool, std::string> ReadFile(const std::string& path)
+{
+ std::ifstream fstream(path, std::ios::in);
+ if (fstream) {
+ std::string contents;
+ fstream.seekg(0, std::ios::end);
+ contents.reserve(fstream.tellg());
+ fstream.seekg(0, std::ios::beg);
+ contents.assign((std::istreambuf_iterator<char>(fstream)),
+ std::istreambuf_iterator<char>());
+ return std::make_pair(true, contents);
+ }
+ return std::make_pair(false, "");
+}
+
+bool WriteFile(const std::string& path, const std::string& contents)
+{
+ std::ofstream fstream(path, std::ios::out);
+ if (!fstream) return false;
+ fstream << contents;
+ fstream.flush();
+ return true;
+}
+
+std::string GetSuffix(const std::string& name)
+{
+ const size_t pos = name.rfind('.');
+ return (pos == std::string::npos) ? "" : name.substr(name.rfind('.') + 1);
+}
+
+} // namespace glslangtest
diff --git a/gtests/TestFixture.h b/gtests/TestFixture.h
new file mode 100644
index 0000000..87a365b
--- /dev/null
+++ b/gtests/TestFixture.h
@@ -0,0 +1,307 @@
+//
+// Copyright (C) 2016 Google, Inc.
+//
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+//
+// Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//
+// Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+//
+// Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+
+#ifndef GLSLANG_GTESTS_TEST_FIXTURE_H
+#define GLSLANG_GTESTS_TEST_FIXTURE_H
+
+#include <stdint.h>
+#include <fstream>
+#include <sstream>
+#include <streambuf>
+#include <tuple>
+
+#include <gtest/gtest.h>
+
+#include "SPIRV/GlslangToSpv.h"
+#include "SPIRV/disassemble.h"
+#include "SPIRV/doc.h"
+#include "StandAlone/DefaultResourceLimits.h"
+#include "glslang/Public/ShaderLang.h"
+
+#include "Initializer.h"
+#include "Settings.h"
+
+// We need CMake to provide us the absolute path to the directory containing
+// test files, so we are certain to find those files no matter where the test
+// harness binary is generated. This provides out-of-source build capability.
+#ifndef GLSLANG_TEST_DIRECTORY
+#error \
+ "GLSLANG_TEST_DIRECTORY needs to be defined for gtest to locate test files."
+#endif
+
+namespace glslangtest {
+
+// This function is used to provide custom test name suffixes based on the
+// shader source file names. Otherwise, the test name suffixes will just be
+// numbers, which are not quite obvious.
+std::string FileNameAsCustomTestName(
+ const ::testing::TestParamInfo<std::string>& info);
+
+// Enum for shader compilation semantics.
+enum class Semantics {
+ OpenGL,
+ Vulkan,
+};
+
+// Enum for compilation target.
+enum class Target {
+ AST,
+ Spirv,
+};
+
+EShLanguage GetGlslLanguageForStage(const std::string& stage);
+
+EShMessages GetSpirvMessageOptionsForSemanticsAndTarget(Semantics semantics,
+ Target target);
+
+// Reads the content of the file at the given |path|. On success, returns true
+// and the contents; otherwise, returns false and an empty string.
+std::pair<bool, std::string> ReadFile(const std::string& path);
+
+// Writes the given |contents| into the file at the given |path|. Returns true
+// on successful output.
+bool WriteFile(const std::string& path, const std::string& contents);
+
+// Returns the suffix of the given |name|.
+std::string GetSuffix(const std::string& name);
+
+// Base class for glslang integration tests. It contains many handy utility-like
+// methods such as reading shader source files, compiling into AST/SPIR-V, and
+// comparing with expected outputs.
+//
+// To write value-Parameterized tests:
+// using ValueParamTest = GlslangTest<::testing::TestWithParam<std::string>>;
+// To use as normal fixture:
+// using FixtureTest = GlslangTest<::testing::Test>;
+template <typename GT>
+class GlslangTest : public GT {
+public:
+ GlslangTest()
+ : defaultVersion(100),
+ defaultProfile(ENoProfile),
+ forceVersionProfile(false),
+ isForwardCompatible(false) {}
+
+ // Tries to load the contents from the file at the given |path|. On success,
+ // writes the contents into |contents|. On failure, errors out.
+ void tryLoadFile(const std::string& path, const std::string& tag,
+ std::string* contents)
+ {
+ bool fileReadOk;
+ std::tie(fileReadOk, *contents) = ReadFile(path);
+ ASSERT_TRUE(fileReadOk) << "Cannot open " << tag << " file: " << path;
+ }
+
+ // Checks the equality of |expected| and |real|. If they are not equal,
+ // write
+ // |real| to the given file named as |fname| if update mode is on.
+ void checkEqAndUpdateIfRequested(const std::string& expected,
+ const std::string& real,
+ const std::string& fname)
+ {
+ // In order to output the message we want under proper circumstances, we
+ // need the following operator<< stuff.
+ EXPECT_EQ(expected, real)
+ << (GlobalTestSettings.updateMode
+ ? ("Mismatch found and update mode turned on - "
+ "flushing expected result output.")
+ : "");
+
+ // Update the expected output file if requested.
+ // It looks weird to duplicate the comparison between expected_output
+ // and
+ // stream.str(). However, if creating a variable for the comparison
+ // result,
+ // we cannot have pretty print of the string diff in the above.
+ if (GlobalTestSettings.updateMode && expected != real) {
+ EXPECT_TRUE(WriteFile(fname, real)) << "Flushing failed";
+ }
+ }
+
+ // A struct for holding all the information returned by glslang compilation
+ // and linking.
+ struct GlslangResult {
+ const std::string compilationOutput;
+ const std::string compilationError;
+ const std::string linkingOutput;
+ const std::string linkingError;
+ const std::string spirv; // Optional SPIR-V disassembly text.
+ };
+
+ // Compiles and linkes the given GLSL |source| code of the given shader
+ // |stage| into the given |target| under the given |semantics|. Returns
+ // a GlslangResult instance containing all the information generated
+ // during the process. If |target| is Target::Spirv, also disassembles
+ // the result and returns disassembly text.
+ GlslangResult compileGlsl(const std::string& source,
+ const std::string& stage, Semantics semantics,
+ Target target)
+ {
+ const char* shaderStrings = source.data();
+ const int shaderLengths = static_cast<int>(source.size());
+ const EShLanguage language = GetGlslLanguageForStage(stage);
+
+ glslang::TShader shader(language);
+ shader.setStringsWithLengths(&shaderStrings, &shaderLengths, 1);
+ const EShMessages messages =
+ GetSpirvMessageOptionsForSemanticsAndTarget(semantics, target);
+ // Reinitialize glslang if the semantics change.
+ GlslangInitializer::InitializationToken token =
+ GlobalTestSettings.initializer->acquire(messages);
+ bool success =
+ shader.parse(&glslang::DefaultTBuiltInResource, defaultVersion,
+ isForwardCompatible, messages);
+
+ glslang::TProgram program;
+ program.addShader(&shader);
+ success &= program.link(messages);
+
+ if (success && target == Target::Spirv) {
+ std::vector<uint32_t> spirv_binary;
+ glslang::GlslangToSpv(*program.getIntermediate(language),
+ spirv_binary);
+
+ std::ostringstream disassembly_stream;
+ spv::Parameterize();
+ spv::Disassemble(disassembly_stream, spirv_binary);
+ return {shader.getInfoLog(), shader.getInfoDebugLog(),
+ program.getInfoLog(), program.getInfoDebugLog(),
+ disassembly_stream.str()};
+ } else {
+ return {shader.getInfoLog(), shader.getInfoDebugLog(),
+ program.getInfoLog(), program.getInfoDebugLog(), ""};
+ }
+ }
+
+ void loadFileCompileAndCheck(const std::string& testDir,
+ const std::string& testName,
+ Semantics semantics, Target target)
+ {
+ const std::string inputFname = testDir + "/" + testName;
+ const std::string expectedOutputFname =
+ testDir + "/baseResults/" + testName + ".out";
+ std::string input, expectedOutput;
+
+ tryLoadFile(inputFname, "input", &input);
+ tryLoadFile(expectedOutputFname, "expected output", &expectedOutput);
+
+ GlslangResult result =
+ compileGlsl(input, GetSuffix(testName), semantics, target);
+
+ // Generate the hybrid output in the way of glslangValidator.
+ std::ostringstream stream;
+
+ const auto outputIfNotEmpty = [&stream](const std::string& str) {
+ if (!str.empty()) stream << str << "\n";
+ };
+
+ stream << testName << "\n";
+ outputIfNotEmpty(result.compilationOutput);
+ outputIfNotEmpty(result.compilationError);
+ outputIfNotEmpty(result.linkingOutput);
+ outputIfNotEmpty(result.linkingError);
+ if (target == Target::Spirv) {
+ stream
+ << (result.spirv.empty()
+ ? "SPIR-V is not generated for failed compile or link\n"
+ : result.spirv);
+ }
+
+ checkEqAndUpdateIfRequested(expectedOutput, stream.str(),
+ expectedOutputFname);
+ }
+
+ // Preprocesses the given GLSL |source| code. On success, returns true, the
+ // preprocessed shader, and warning messages. Otherwise, returns false, an
+ // empty string, and error messages.
+ std::tuple<bool, std::string, std::string> preprocessGlsl(
+ const std::string& source)
+ {
+ const char* shaderStrings = source.data();
+ const int shaderLengths = static_cast<int>(source.size());
+
+ glslang::TShader shader(EShLangVertex);
+ shader.setStringsWithLengths(&shaderStrings, &shaderLengths, 1);
+ std::string ppShader;
+ glslang::TShader::ForbidInclude includer;
+ const bool success = shader.preprocess(
+ &glslang::DefaultTBuiltInResource, defaultVersion, defaultProfile,
+ forceVersionProfile, isForwardCompatible, EShMsgOnlyPreprocessor,
+ &ppShader, includer);
+
+ std::string log = shader.getInfoLog();
+ log += shader.getInfoDebugLog();
+ if (success) {
+ return std::make_tuple(true, ppShader, log);
+ } else {
+ return std::make_tuple(false, "", log);
+ }
+ }
+
+ void loadFilePreprocessAndCheck(const std::string& testDir,
+ const std::string& testName)
+ {
+ const std::string inputFname = testDir + "/" + testName;
+ const std::string expectedOutputFname =
+ testDir + "/baseResults/" + testName + ".out";
+ const std::string expectedErrorFname =
+ testDir + "/baseResults/" + testName + ".err";
+ std::string input, expectedOutput, expectedError;
+
+ tryLoadFile(inputFname, "input", &input);
+ tryLoadFile(expectedOutputFname, "expected output", &expectedOutput);
+ tryLoadFile(expectedErrorFname, "expected error", &expectedError);
+
+ bool ppOk;
+ std::string output, error;
+ std::tie(ppOk, output, error) = preprocessGlsl(input);
+ if (!output.empty()) output += '\n';
+ if (!error.empty()) error += '\n';
+
+ checkEqAndUpdateIfRequested(expectedOutput, output,
+ expectedOutputFname);
+ checkEqAndUpdateIfRequested(expectedError, error,
+ expectedErrorFname);
+ }
+
+private:
+ const int defaultVersion;
+ const EProfile defaultProfile;
+ const bool forceVersionProfile;
+ const bool isForwardCompatible;
+};
+
+} // namespace glslangtest
+
+#endif // GLSLANG_GTESTS_TEST_FIXTURE_H
diff --git a/gtests/main.cpp b/gtests/main.cpp
new file mode 100644
index 0000000..b9806aa
--- /dev/null
+++ b/gtests/main.cpp
@@ -0,0 +1,63 @@
+//
+// Copyright (C) 2016 Google, Inc.
+//
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+//
+// Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//
+// Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+//
+// Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+
+#include <memory>
+
+#include <gtest/gtest.h>
+
+#include "Initializer.h"
+#include "Settings.h"
+
+int main(int argc, char** argv)
+{
+ ::testing::InitGoogleTest(&argc, argv);
+
+ std::unique_ptr<glslangtest::GlslangInitializer> initializer(
+ new glslangtest::GlslangInitializer);
+
+ glslangtest::GlobalTestSettings.initializer = initializer.get();
+
+ for (int i = 1; i < argc; ++i) {
+ if (!strncmp("--update-mode", argv[i], 13)) {
+ glslangtest::GlobalTestSettings.updateMode = true;
+ break;
+ }
+ }
+
+ const int result = RUN_ALL_TESTS();
+
+ glslangtest::GlobalTestSettings.initializer = nullptr;
+
+ return result;
+}
diff --git a/hlsl/CMakeLists.txt b/hlsl/CMakeLists.txt
new file mode 100755
index 0000000..acc69f0
--- /dev/null
+++ b/hlsl/CMakeLists.txt
@@ -0,0 +1,21 @@
+cmake_minimum_required(VERSION 2.8)
+
+set(SOURCES
+ hlslParseHelper.cpp
+ hlslScanContext.cpp
+ hlslGrammar.cpp)
+
+set(HEADERS
+ hlslParseHelper.h
+ hlslTokens.h
+ hlslScanContext.h
+ hlslGrammar.h)
+
+add_library(HLSL STATIC ${SOURCES} ${HEADERS})
+
+if(WIN32)
+ source_group("Source" FILES ${SOURCES} ${HEADERS})
+endif(WIN32)
+
+install(TARGETS HLSL
+ ARCHIVE DESTINATION lib)
diff --git a/hlsl/hlslGrammar.cpp b/hlsl/hlslGrammar.cpp
new file mode 100755
index 0000000..4528a19
--- /dev/null
+++ b/hlsl/hlslGrammar.cpp
@@ -0,0 +1,643 @@
+//
+//Copyright (C) 2016 Google, Inc.
+//
+//All rights reserved.
+//
+//Redistribution and use in source and binary forms, with or without
+//modification, are permitted provided that the following conditions
+//are met:
+//
+// Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//
+// Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+//
+// Neither the name of Google, Inc., nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+//POSSIBILITY OF SUCH DAMAGE.
+//
+
+//
+// This is a set of mutually recursive methods implementing the HLSL grammar.
+// Generally, each returns
+// - through an argument: a type specifically appropriate to which rule it
+// recognized
+// - through the return value: true/false to indicate whether or not it
+// recognized its rule
+//
+// As much as possible, only grammar recognition should happen in this file,
+// with all other work being farmed out to hlslParseHelper.cpp, which in turn
+// will build the AST.
+//
+// The next token, yet to be "accepted" is always sitting in 'token'.
+// When a method says it accepts a rule, that means all tokens involved
+// in the rule will have been consumed, and none left in 'token'.
+//
+
+#include "hlslTokens.h"
+#include "hlslGrammar.h"
+
+namespace glslang {
+
+// Root entry point to this recursive decent parser.
+// Return true if compilation unit was successfully accepted.
+bool HlslGrammar::parse()
+{
+ advanceToken();
+ return acceptCompilationUnit();
+}
+
+void HlslGrammar::expected(const char* syntax)
+{
+ parseContext.error(token.loc, "Expected", syntax, "");
+}
+
+// Load 'token' with the next token in the stream of tokens.
+void HlslGrammar::advanceToken()
+{
+ scanner.tokenize(token);
+}
+
+// Return true and advance to the next token if the current token is the
+// expected (passed in) token class.
+bool HlslGrammar::acceptTokenClass(EHlslTokenClass tokenClass)
+{
+ if (token.tokenClass == tokenClass) {
+ advanceToken();
+ return true;
+ }
+
+ return false;
+}
+
+// Return true, without advancing to the next token, if the current token is
+// the expected (passed in) token class.
+bool HlslGrammar::peekTokenClass(EHlslTokenClass tokenClass)
+{
+ return token.tokenClass == tokenClass;
+}
+
+// Only process the next token if it is an identifier.
+// Return true if it was an identifier.
+bool HlslGrammar::acceptIdentifier(HlslToken& idToken)
+{
+ if (peekTokenClass(EHTokIdentifier)) {
+ idToken = token;
+ advanceToken();
+ return true;
+ }
+
+ return false;
+}
+
+// compilationUnit
+// : list of externalDeclaration
+//
+bool HlslGrammar::acceptCompilationUnit()
+{
+ TIntermNode* unitNode = nullptr;
+
+ while (token.tokenClass != EHTokNone) {
+ // externalDeclaration
+ TIntermNode* declarationNode;
+ if (! acceptDeclaration(declarationNode))
+ return false;
+
+ // hook it up
+ unitNode = intermediate.growAggregate(unitNode, declarationNode);
+ }
+
+ // set root of AST
+ intermediate.setTreeRoot(unitNode);
+
+ return true;
+}
+
+// declaration
+// : SEMICOLON
+// : fully_specified_type SEMICOLON
+// | fully_specified_type identifier SEMICOLON
+// | fully_specified_type identifier = expression SEMICOLON
+// | fully_specified_type identifier function_parameters SEMICOLON // function prototype
+// | fully_specified_type identifier function_parameters COLON semantic compound_statement // function definition
+//
+// 'node' could get created if the declaration creates code, like an initializer
+// or a function body.
+//
+bool HlslGrammar::acceptDeclaration(TIntermNode*& node)
+{
+ node = nullptr;
+
+ // fully_specified_type
+ TType type;
+ if (! acceptFullySpecifiedType(type))
+ return false;
+
+ // identifier
+ HlslToken idToken;
+ if (acceptIdentifier(idToken)) {
+ // = expression
+ TIntermTyped* expressionNode = nullptr;
+ if (acceptTokenClass(EHTokEqual)) {
+ if (! acceptExpression(expressionNode)) {
+ expected("initializer");
+ return false;
+ }
+ }
+
+ // SEMICOLON
+ if (acceptTokenClass(EHTokSemicolon)) {
+ node = parseContext.declareVariable(idToken.loc, *idToken.string, type, 0, expressionNode);
+ return true;
+ }
+
+ // function_parameters
+ TFunction* function = new TFunction(idToken.string, type);
+ if (acceptFunctionParameters(*function)) {
+ // COLON semantic
+ acceptSemantic();
+
+ // compound_statement
+ if (peekTokenClass(EHTokLeftBrace))
+ return acceptFunctionDefinition(*function, node);
+
+ // SEMICOLON
+ if (acceptTokenClass(EHTokSemicolon))
+ return true;
+
+ return false;
+ }
+ }
+
+ // SEMICOLON
+ if (acceptTokenClass(EHTokSemicolon))
+ return true;
+
+ return true;
+}
+
+// fully_specified_type
+// : type_specifier
+// | type_qualifier type_specifier
+//
+bool HlslGrammar::acceptFullySpecifiedType(TType& type)
+{
+ // type_qualifier
+ TQualifier qualifier;
+ qualifier.clear();
+ acceptQualifier(qualifier);
+
+ // type_specifier
+ if (! acceptType(type))
+ return false;
+ type.getQualifier() = qualifier;
+
+ return true;
+}
+
+// If token is a qualifier, return its token class and advance to the next
+// qualifier. Otherwise, return false, and don't advance.
+void HlslGrammar::acceptQualifier(TQualifier& qualifier)
+{
+ switch (token.tokenClass) {
+ case EHTokUniform:
+ qualifier.storage = EvqUniform;
+ break;
+ case EHTokConst:
+ qualifier.storage = EvqConst;
+ break;
+ default:
+ return;
+ }
+
+ advanceToken();
+}
+
+// If token is for a type, update 'type' with the type information,
+// and return true and advance.
+// Otherwise, return false, and don't advance
+bool HlslGrammar::acceptType(TType& type)
+{
+ if (! token.isType)
+ return false;
+
+ switch (token.tokenClass) {
+ case EHTokInt:
+ case EHTokInt1:
+ case EHTokDword:
+ new(&type) TType(EbtInt);
+ break;
+ case EHTokFloat:
+ case EHTokFloat1:
+ new(&type) TType(EbtFloat);
+ break;
+
+ case EHTokFloat2:
+ new(&type) TType(EbtFloat, EvqTemporary, 2);
+ break;
+ case EHTokFloat3:
+ new(&type) TType(EbtFloat, EvqTemporary, 3);
+ break;
+ case EHTokFloat4:
+ new(&type) TType(EbtFloat, EvqTemporary, 4);
+ break;
+
+ case EHTokInt2:
+ new(&type) TType(EbtInt, EvqTemporary, 2);
+ break;
+ case EHTokInt3:
+ new(&type) TType(EbtInt, EvqTemporary, 3);
+ break;
+ case EHTokInt4:
+ new(&type) TType(EbtInt, EvqTemporary, 4);
+ break;
+
+ case EHTokBool2:
+ new(&type) TType(EbtBool, EvqTemporary, 2);
+ break;
+ case EHTokBool3:
+ new(&type) TType(EbtBool, EvqTemporary, 3);
+ break;
+ case EHTokBool4:
+ new(&type) TType(EbtBool, EvqTemporary, 4);
+ break;
+
+ case EHTokFloat2x2:
+ new(&type) TType(EbtFloat, EvqTemporary, 0, 2, 2);
+ break;
+ case EHTokFloat2x3:
+ new(&type) TType(EbtFloat, EvqTemporary, 0, 3, 2);
+ break;
+ case EHTokFloat2x4:
+ new(&type) TType(EbtFloat, EvqTemporary, 0, 4, 2);
+ break;
+ case EHTokFloat3x2:
+ new(&type) TType(EbtFloat, EvqTemporary, 0, 2, 3);
+ break;
+ case EHTokFloat3x3:
+ new(&type) TType(EbtFloat, EvqTemporary, 0, 3, 3);
+ break;
+ case EHTokFloat3x4:
+ new(&type) TType(EbtFloat, EvqTemporary, 0, 4, 3);
+ break;
+ case EHTokFloat4x2:
+ new(&type) TType(EbtFloat, EvqTemporary, 0, 2, 4);
+ break;
+ case EHTokFloat4x3:
+ new(&type) TType(EbtFloat, EvqTemporary, 0, 3, 4);
+ break;
+ case EHTokFloat4x4:
+ new(&type) TType(EbtFloat, EvqTemporary, 0, 4, 4);
+ break;
+
+ default:
+ return false;
+ }
+
+ advanceToken();
+
+ return true;
+}
+
+// function_parameters
+// : LEFT_PAREN parameter_declaration COMMA parameter_declaration ... RIGHT_PAREN
+//
+bool HlslGrammar::acceptFunctionParameters(TFunction& function)
+{
+ // LEFT_PAREN
+ if (! acceptTokenClass(EHTokLeftParen))
+ return false;
+
+ do {
+ // parameter_declaration
+ if (! acceptParameterDeclaration(function))
+ break;
+
+ // COMMA
+ if (! acceptTokenClass(EHTokComma))
+ break;
+ } while (true);
+
+ // RIGHT_PAREN
+ if (! acceptTokenClass(EHTokRightParen)) {
+ expected("right parenthesis");
+ return false;
+ }
+
+ return true;
+}
+
+// parameter_declaration
+// : fully_specified_type
+// | fully_specified_type identifier
+//
+bool HlslGrammar::acceptParameterDeclaration(TFunction& function)
+{
+ // fully_specified_type
+ TType* type = new TType;
+ if (! acceptFullySpecifiedType(*type))
+ return false;
+
+ // identifier
+ HlslToken idToken;
+ acceptIdentifier(idToken);
+
+ TParameter param = { idToken.string, type };
+ function.addParameter(param);
+
+ return true;
+}
+
+// Do the work to create the function definition in addition to
+// parsing the body (compound_statement).
+bool HlslGrammar::acceptFunctionDefinition(TFunction& function, TIntermNode*& node)
+{
+ TFunction* functionDeclarator = parseContext.handleFunctionDeclarator(token.loc, function, false /* not prototype */);
+
+ // This does a symbol table push
+ node = parseContext.handleFunctionDefinition(token.loc, *functionDeclarator);
+
+ // compound_statement
+ TIntermAggregate* functionBody = nullptr;
+ if (acceptCompoundStatement(functionBody)) {
+ node = intermediate.growAggregate(node, functionBody);
+ intermediate.setAggregateOperator(node, EOpFunction, functionDeclarator->getType(), token.loc);
+ node->getAsAggregate()->setName(functionDeclarator->getMangledName().c_str());
+ parseContext.symbolTable.pop(nullptr);
+
+ return true;
+ }
+
+ return false;
+}
+
+// expression
+// : identifier
+// | identifier operator identifier // todo: generalize to all expressions
+// | LEFT_PAREN expression RIGHT_PAREN
+// | constructor
+// | literal
+//
+bool HlslGrammar::acceptExpression(TIntermTyped*& node)
+{
+ // identifier
+ HlslToken idToken;
+ if (acceptIdentifier(idToken)) {
+ TIntermTyped* left = parseContext.handleVariable(idToken.loc, idToken.symbol, token.string);
+
+ // operator?
+ TOperator op;
+ if (! acceptOperator(op))
+ return true;
+ TSourceLoc loc = token.loc;
+
+ // identifier
+ if (acceptIdentifier(idToken)) {
+ TIntermTyped* right = parseContext.handleVariable(idToken.loc, idToken.symbol, token.string);
+ node = intermediate.addBinaryMath(op, left, right, loc);
+ return true;
+ }
+
+ return false;
+ }
+
+ // LEFT_PAREN expression RIGHT_PAREN
+ if (acceptTokenClass(EHTokLeftParen)) {
+ if (! acceptExpression(node)) {
+ expected("expression");
+ return false;
+ }
+ if (! acceptTokenClass(EHTokRightParen)) {
+ expected("right parenthesis");
+ return false;
+ }
+
+ return true;
+ }
+
+ // literal
+ if (acceptLiteral(node))
+ return true;
+
+ // constructor
+ if (acceptConstructor(node))
+ return true;
+
+ return false;
+}
+
+// constructor
+// : type argument_list
+//
+bool HlslGrammar::acceptConstructor(TIntermTyped*& node)
+{
+ // type
+ TType type;
+ if (acceptType(type)) {
+ TFunction* constructorFunction = parseContext.handleConstructorCall(token.loc, type);
+ if (constructorFunction == nullptr)
+ return false;
+
+ // arguments
+ TIntermAggregate* arguments = nullptr;
+ if (! acceptArguments(constructorFunction, arguments)) {
+ expected("constructor arguments");
+ return false;
+ }
+
+ // hook it up
+ node = parseContext.handleFunctionCall(arguments->getLoc(), constructorFunction, arguments);
+
+ return true;
+ }
+
+ return false;
+}
+
+// arguments
+// : LEFT_PAREN expression COMMA expression COMMA ... RIGHT_PAREN
+//
+// The arguments are pushed onto the 'function' argument list and
+// onto the 'arguments' aggregate.
+//
+bool HlslGrammar::acceptArguments(TFunction* function, TIntermAggregate*& arguments)
+{
+ // LEFT_PAREN
+ if (! acceptTokenClass(EHTokLeftParen))
+ return false;
+
+ do {
+ // expression
+ TIntermTyped* arg;
+ if (! acceptExpression(arg))
+ break;
+
+ // hook it up
+ parseContext.handleFunctionArgument(function, arguments, arg);
+
+ // COMMA
+ if (! acceptTokenClass(EHTokComma))
+ break;
+ } while (true);
+
+ // RIGHT_PAREN
+ if (! acceptTokenClass(EHTokRightParen)) {
+ expected("right parenthesis");
+ return false;
+ }
+
+ return true;
+}
+
+bool HlslGrammar::acceptLiteral(TIntermTyped*& node)
+{
+ switch (token.tokenClass) {
+ case EHTokIntConstant:
+ node = intermediate.addConstantUnion(token.i, token.loc, true);
+ break;
+ case EHTokFloatConstant:
+ node = intermediate.addConstantUnion(token.d, EbtFloat, token.loc, true);
+ break;
+ case EHTokDoubleConstant:
+ node = intermediate.addConstantUnion(token.d, EbtDouble, token.loc, true);
+ break;
+ case EHTokBoolConstant:
+ node = intermediate.addConstantUnion(token.b, token.loc, true);
+ break;
+
+ default:
+ return false;
+ }
+
+ advanceToken();
+
+ return true;
+}
+
+// operator
+// : PLUS | DASH | STAR | SLASH | ...
+bool HlslGrammar::acceptOperator(TOperator& op)
+{
+ switch (token.tokenClass) {
+ case EHTokEqual:
+ op = EOpAssign;
+ break;
+ case EHTokPlus:
+ op = EOpAdd;
+ break;
+ case EHTokDash:
+ op = EOpSub;
+ break;
+ case EHTokStar:
+ op = EOpMul;
+ break;
+ case EHTokSlash:
+ op = EOpDiv;
+ break;
+ default:
+ return false;
+ }
+
+ advanceToken();
+
+ return true;
+}
+
+// compound_statement
+// : { statement statement ... }
+//
+bool HlslGrammar::acceptCompoundStatement(TIntermAggregate*& compoundStatement)
+{
+ // {
+ if (! acceptTokenClass(EHTokLeftBrace))
+ return false;
+
+ // statement statement ...
+ TIntermNode* statement = nullptr;
+ while (acceptStatement(statement)) {
+ // hook it up
+ compoundStatement = intermediate.growAggregate(compoundStatement, statement);
+ }
+ compoundStatement->setOperator(EOpSequence);
+
+ // }
+ return acceptTokenClass(EHTokRightBrace);
+}
+
+// statement
+// : compound_statement
+// | return SEMICOLON
+// | return expression SEMICOLON
+// | expression SEMICOLON
+//
+bool HlslGrammar::acceptStatement(TIntermNode*& statement)
+{
+ // compound_statement
+ TIntermAggregate* compoundStatement = nullptr;
+ if (acceptCompoundStatement(compoundStatement)) {
+ statement = compoundStatement;
+ return true;
+ }
+
+ // RETURN
+ if (acceptTokenClass(EHTokReturn)) {
+ // expression
+ TIntermTyped* node;
+ if (acceptExpression(node)) {
+ // hook it up
+ statement = intermediate.addBranch(EOpReturn, node, token.loc);
+ } else
+ statement = intermediate.addBranch(EOpReturn, token.loc);
+
+ // SEMICOLON
+ if (! acceptTokenClass(EHTokSemicolon))
+ return false;
+
+ return true;
+ }
+
+ // expression
+ TIntermTyped* node;
+ if (acceptExpression(node))
+ statement = node;
+
+ // SEMICOLON
+ if (! acceptTokenClass(EHTokSemicolon))
+ return false;
+
+ return true;
+}
+
+// COLON semantic
+bool HlslGrammar::acceptSemantic()
+{
+ // COLON
+ if (acceptTokenClass(EHTokColon)) {
+ // semantic
+ HlslToken idToken;
+ if (! acceptIdentifier(idToken)) {
+ expected("semantic");
+ return false;
+ }
+ }
+
+ return true;
+}
+
+} // end namespace glslang
diff --git a/hlsl/hlslGrammar.h b/hlsl/hlslGrammar.h
new file mode 100755
index 0000000..902ba22
--- /dev/null
+++ b/hlsl/hlslGrammar.h
@@ -0,0 +1,88 @@
+//
+//Copyright (C) 2016 Google, Inc.
+//
+//All rights reserved.
+//
+//Redistribution and use in source and binary forms, with or without
+//modification, are permitted provided that the following conditions
+//are met:
+//
+// Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//
+// Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+//
+// Neither the name of Google, Inc., nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+//POSSIBILITY OF SUCH DAMAGE.
+//
+
+#ifndef HLSLGRAMMAR_H_
+#define HLSLGRAMMAR_H_
+
+#include "hlslScanContext.h"
+#include "hlslParseHelper.h"
+
+namespace glslang {
+
+ // Should just be the grammar aspect of HLSL.
+ // Described in more detail in hlslGrammar.cpp.
+
+ class HlslGrammar {
+ public:
+ HlslGrammar(HlslScanContext& scanner, HlslParseContext& parseContext)
+ : scanner(scanner), parseContext(parseContext), intermediate(parseContext.intermediate) { }
+ virtual ~HlslGrammar() { }
+
+ bool parse();
+
+ protected:
+ void expected(const char*);
+ void advanceToken();
+ bool acceptTokenClass(EHlslTokenClass);
+ bool peekTokenClass(EHlslTokenClass);
+ bool acceptIdentifier(HlslToken&);
+
+ bool acceptCompilationUnit();
+ bool acceptDeclaration(TIntermNode*& node);
+ bool acceptFullySpecifiedType(TType&);
+ void acceptQualifier(TQualifier&);
+ bool acceptType(TType&);
+ bool acceptFunctionParameters(TFunction&);
+ bool acceptParameterDeclaration(TFunction&);
+ bool acceptFunctionDefinition(TFunction&, TIntermNode*&);
+ bool acceptExpression(TIntermTyped*&);
+ bool acceptConstructor(TIntermTyped*&);
+ bool acceptArguments(TFunction*, TIntermAggregate*&);
+ bool acceptLiteral(TIntermTyped*&);
+ bool acceptOperator(TOperator& op);
+ bool acceptCompoundStatement(TIntermAggregate*&);
+ bool acceptStatement(TIntermNode*&);
+ bool acceptSemantic();
+
+ HlslScanContext& scanner; // lexical scanner, to get next token
+ HlslParseContext& parseContext; // state of parsing and helper functions for building the intermediate
+ TIntermediate& intermediate; // the final product, the intermediate representation, includes the AST
+
+ HlslToken token; // the current token we are processing
+ };
+
+} // end namespace glslang
+
+#endif // HLSLGRAMMAR_H_
diff --git a/hlsl/hlslParseHelper.cpp b/hlsl/hlslParseHelper.cpp
new file mode 100755
index 0000000..e05f01f
--- /dev/null
+++ b/hlsl/hlslParseHelper.cpp
@@ -0,0 +1,3581 @@
+//
+//Copyright (C) 2016 Google, Inc.
+//
+//All rights reserved.
+//
+//Redistribution and use in source and binary forms, with or without
+//modification, are permitted provided that the following conditions
+//are met:
+//
+// Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//
+// Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+//
+// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+//POSSIBILITY OF SUCH DAMAGE.
+//
+
+#include "hlslParseHelper.h"
+#include "hlslScanContext.h"
+#include "hlslGrammar.h"
+
+#include "../glslang/MachineIndependent/Scan.h"
+#include "../glslang/MachineIndependent/preprocessor/PpContext.h"
+
+#include "../glslang/OSDependent/osinclude.h"
+
+#include <stdarg.h>
+#include <algorithm>
+
+namespace glslang {
+
+HlslParseContext::HlslParseContext(TSymbolTable& symbolTable, TIntermediate& interm, bool /*parsingBuiltins*/,
+ int version, EProfile profile, int spv, int vulkan, EShLanguage language, TInfoSink& infoSink,
+ bool forwardCompatible, EShMessages messages) :
+ TParseContextBase(symbolTable, interm, version, profile, spv, vulkan, language, infoSink, forwardCompatible, messages),
+ contextPragma(true, false), loopNestingLevel(0), structNestingLevel(0), controlFlowNestingLevel(0), statementNestingLevel(0),
+ postMainReturn(false),
+ limits(resources.limits),
+ afterEOF(false)
+{
+ // ensure we always have a linkage node, even if empty, to simplify tree topology algorithms
+ linkage = new TIntermAggregate;
+
+ globalUniformDefaults.clear();
+ globalUniformDefaults.layoutMatrix = ElmColumnMajor;
+ globalUniformDefaults.layoutPacking = vulkan > 0 ? ElpStd140 : ElpShared;
+
+ globalBufferDefaults.clear();
+ globalBufferDefaults.layoutMatrix = ElmColumnMajor;
+ globalBufferDefaults.layoutPacking = vulkan > 0 ? ElpStd430 : ElpShared;
+
+ globalInputDefaults.clear();
+ globalOutputDefaults.clear();
+
+ // "Shaders in the transform
+ // feedback capturing mode have an initial global default of
+ // layout(xfb_buffer = 0) out;"
+ if (language == EShLangVertex ||
+ language == EShLangTessControl ||
+ language == EShLangTessEvaluation ||
+ language == EShLangGeometry)
+ globalOutputDefaults.layoutXfbBuffer = 0;
+
+ if (language == EShLangGeometry)
+ globalOutputDefaults.layoutStream = 0;
+}
+
+HlslParseContext::~HlslParseContext()
+{
+}
+
+void HlslParseContext::setLimits(const TBuiltInResource& r)
+{
+ resources = r;
+ intermediate.setLimits(resources);
+}
+
+//
+// Parse an array of strings using the parser in HlslRules.
+//
+// Returns true for successful acceptance of the shader, false if any errors.
+//
+bool HlslParseContext::parseShaderStrings(TPpContext& ppContext, TInputScanner& input, bool versionWillBeError)
+{
+ currentScanner = &input;
+ ppContext.setInput(input, versionWillBeError);
+
+ HlslScanContext::fillInKeywordMap(); // TODO: right place, and include the delete too
+
+ HlslScanContext scanContext(*this, ppContext);
+ HlslGrammar grammar(scanContext, *this);
+ if (! grammar.parse())
+ printf("HLSL translation failed.\n");
+
+ return numErrors == 0;
+}
+
+void HlslParseContext::handlePragma(const TSourceLoc& loc, const TVector<TString>& tokens)
+{
+ if (pragmaCallback)
+ pragmaCallback(loc.line, tokens);
+
+ if (tokens.size() == 0)
+ return;
+}
+
+//
+// Look at a '.' field selector string and change it into offsets
+// for a vector or scalar
+//
+// Returns true if there is no error.
+//
+bool HlslParseContext::parseVectorFields(const TSourceLoc& loc, const TString& compString, int vecSize, TVectorFields& fields)
+{
+ fields.num = (int)compString.size();
+ if (fields.num > 4) {
+ error(loc, "illegal vector field selection", compString.c_str(), "");
+ return false;
+ }
+
+ enum {
+ exyzw,
+ ergba,
+ estpq,
+ } fieldSet[4];
+
+ for (int i = 0; i < fields.num; ++i) {
+ switch (compString[i]) {
+ case 'x':
+ fields.offsets[i] = 0;
+ fieldSet[i] = exyzw;
+ break;
+ case 'r':
+ fields.offsets[i] = 0;
+ fieldSet[i] = ergba;
+ break;
+ case 's':
+ fields.offsets[i] = 0;
+ fieldSet[i] = estpq;
+ break;
+ case 'y':
+ fields.offsets[i] = 1;
+ fieldSet[i] = exyzw;
+ break;
+ case 'g':
+ fields.offsets[i] = 1;
+ fieldSet[i] = ergba;
+ break;
+ case 't':
+ fields.offsets[i] = 1;
+ fieldSet[i] = estpq;
+ break;
+ case 'z':
+ fields.offsets[i] = 2;
+ fieldSet[i] = exyzw;
+ break;
+ case 'b':
+ fields.offsets[i] = 2;
+ fieldSet[i] = ergba;
+ break;
+ case 'p':
+ fields.offsets[i] = 2;
+ fieldSet[i] = estpq;
+ break;
+
+ case 'w':
+ fields.offsets[i] = 3;
+ fieldSet[i] = exyzw;
+ break;
+ case 'a':
+ fields.offsets[i] = 3;
+ fieldSet[i] = ergba;
+ break;
+ case 'q':
+ fields.offsets[i] = 3;
+ fieldSet[i] = estpq;
+ break;
+ default:
+ error(loc, "illegal vector field selection", compString.c_str(), "");
+ return false;
+ }
+ }
+
+ for (int i = 0; i < fields.num; ++i) {
+ if (fields.offsets[i] >= vecSize) {
+ error(loc, "vector field selection out of range", compString.c_str(), "");
+ return false;
+ }
+
+ if (i > 0) {
+ if (fieldSet[i] != fieldSet[i - 1]) {
+ error(loc, "illegal - vector component fields not from the same set", compString.c_str(), "");
+ return false;
+ }
+ }
+ }
+
+ return true;
+}
+
+//
+// Used to output syntax, parsing, and semantic errors.
+//
+
+void HlslParseContext::outputMessage(const TSourceLoc& loc, const char* szReason,
+ const char* szToken,
+ const char* szExtraInfoFormat,
+ TPrefixType prefix, va_list args)
+{
+ const int maxSize = MaxTokenLength + 200;
+ char szExtraInfo[maxSize];
+
+ safe_vsprintf(szExtraInfo, maxSize, szExtraInfoFormat, args);
+
+ infoSink.info.prefix(prefix);
+ infoSink.info.location(loc);
+ infoSink.info << "'" << szToken << "' : " << szReason << " " << szExtraInfo << "\n";
+
+ if (prefix == EPrefixError) {
+ ++numErrors;
+ }
+}
+
+void C_DECL HlslParseContext::error(const TSourceLoc& loc, const char* szReason, const char* szToken,
+ const char* szExtraInfoFormat, ...)
+{
+ if (messages & EShMsgOnlyPreprocessor)
+ return;
+ va_list args;
+ va_start(args, szExtraInfoFormat);
+ outputMessage(loc, szReason, szToken, szExtraInfoFormat, EPrefixError, args);
+ va_end(args);
+}
+
+void C_DECL HlslParseContext::warn(const TSourceLoc& loc, const char* szReason, const char* szToken,
+ const char* szExtraInfoFormat, ...)
+{
+ if (suppressWarnings())
+ return;
+ va_list args;
+ va_start(args, szExtraInfoFormat);
+ outputMessage(loc, szReason, szToken, szExtraInfoFormat, EPrefixWarning, args);
+ va_end(args);
+}
+
+void C_DECL HlslParseContext::ppError(const TSourceLoc& loc, const char* szReason, const char* szToken,
+ const char* szExtraInfoFormat, ...)
+{
+ va_list args;
+ va_start(args, szExtraInfoFormat);
+ outputMessage(loc, szReason, szToken, szExtraInfoFormat, EPrefixError, args);
+ va_end(args);
+}
+
+void C_DECL HlslParseContext::ppWarn(const TSourceLoc& loc, const char* szReason, const char* szToken,
+ const char* szExtraInfoFormat, ...)
+{
+ va_list args;
+ va_start(args, szExtraInfoFormat);
+ outputMessage(loc, szReason, szToken, szExtraInfoFormat, EPrefixWarning, args);
+ va_end(args);
+}
+
+//
+// Handle seeing a variable identifier in the grammar.
+//
+TIntermTyped* HlslParseContext::handleVariable(const TSourceLoc& loc, TSymbol* symbol, const TString* string)
+{
+ TIntermTyped* node = nullptr;
+
+ // Error check for requiring specific extensions present.
+ if (symbol && symbol->getNumExtensions())
+ requireExtensions(loc, symbol->getNumExtensions(), symbol->getExtensions(), symbol->getName().c_str());
+
+ if (symbol && symbol->isReadOnly()) {
+ // All shared things containing an implicitly sized array must be copied up
+ // on first use, so that all future references will share its array structure,
+ // so that editing the implicit size will effect all nodes consuming it,
+ // and so that editing the implicit size won't change the shared one.
+ //
+ // If this is a variable or a block, check it and all it contains, but if this
+ // is a member of an anonymous block, check the whole block, as the whole block
+ // will need to be copied up if it contains an implicitly-sized array.
+ if (symbol->getType().containsImplicitlySizedArray() || (symbol->getAsAnonMember() && symbol->getAsAnonMember()->getAnonContainer().getType().containsImplicitlySizedArray()))
+ makeEditable(symbol);
+ }
+
+ const TVariable* variable;
+ const TAnonMember* anon = symbol ? symbol->getAsAnonMember() : nullptr;
+ if (anon) {
+ // It was a member of an anonymous container.
+
+ // Create a subtree for its dereference.
+ variable = anon->getAnonContainer().getAsVariable();
+ TIntermTyped* container = intermediate.addSymbol(*variable, loc);
+ TIntermTyped* constNode = intermediate.addConstantUnion(anon->getMemberNumber(), loc);
+ node = intermediate.addIndex(EOpIndexDirectStruct, container, constNode, loc);
+
+ node->setType(*(*variable->getType().getStruct())[anon->getMemberNumber()].type);
+ if (node->getType().hiddenMember())
+ error(loc, "member of nameless block was not redeclared", string->c_str(), "");
+ } else {
+ // Not a member of an anonymous container.
+
+ // The symbol table search was done in the lexical phase.
+ // See if it was a variable.
+ variable = symbol ? symbol->getAsVariable() : nullptr;
+ if (variable) {
+ if ((variable->getType().getBasicType() == EbtBlock ||
+ variable->getType().getBasicType() == EbtStruct) && variable->getType().getStruct() == nullptr) {
+ error(loc, "cannot be used (maybe an instance name is needed)", string->c_str(), "");
+ variable = nullptr;
+ }
+ } else {
+ if (symbol)
+ error(loc, "variable name expected", string->c_str(), "");
+ }
+
+ // Recovery, if it wasn't found or was not a variable.
+ if (! variable)
+ variable = new TVariable(string, TType(EbtVoid));
+
+ if (variable->getType().getQualifier().isFrontEndConstant())
+ node = intermediate.addConstantUnion(variable->getConstArray(), variable->getType(), loc);
+ else
+ node = intermediate.addSymbol(*variable, loc);
+ }
+
+ if (variable->getType().getQualifier().isIo())
+ intermediate.addIoAccessed(*string);
+
+ return node;
+}
+
+//
+// Handle seeing a base[index] dereference in the grammar.
+//
+TIntermTyped* HlslParseContext::handleBracketDereference(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
+{
+ TIntermTyped* result = nullptr;
+
+ int indexValue = 0;
+ if (index->getQualifier().storage == EvqConst) {
+ indexValue = index->getAsConstantUnion()->getConstArray()[0].getIConst();
+ checkIndex(loc, base->getType(), indexValue);
+ }
+
+ variableCheck(base);
+ if (! base->isArray() && ! base->isMatrix() && ! base->isVector()) {
+ if (base->getAsSymbolNode())
+ error(loc, " left of '[' is not of type array, matrix, or vector ", base->getAsSymbolNode()->getName().c_str(), "");
+ else
+ error(loc, " left of '[' is not of type array, matrix, or vector ", "expression", "");
+ } else if (base->getType().getQualifier().storage == EvqConst && index->getQualifier().storage == EvqConst)
+ return intermediate.foldDereference(base, indexValue, loc);
+ else {
+ // at least one of base and index is variable...
+
+ if (base->getAsSymbolNode() && isIoResizeArray(base->getType()))
+ handleIoResizeArrayAccess(loc, base);
+
+ if (index->getQualifier().storage == EvqConst) {
+ if (base->getType().isImplicitlySizedArray())
+ updateImplicitArraySize(loc, base, indexValue);
+ result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
+ } else {
+ result = intermediate.addIndex(EOpIndexIndirect, base, index, loc);
+ }
+ }
+
+ if (result == nullptr) {
+ // Insert dummy error-recovery result
+ result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
+ } else {
+ // Insert valid dereferenced result
+ TType newType(base->getType(), 0); // dereferenced type
+ if (base->getType().getQualifier().storage == EvqConst && index->getQualifier().storage == EvqConst)
+ newType.getQualifier().storage = EvqConst;
+ else
+ newType.getQualifier().storage = EvqTemporary;
+ result->setType(newType);
+ }
+
+ return result;
+}
+
+void HlslParseContext::checkIndex(const TSourceLoc& loc, const TType& type, int& index)
+{
+ // HLSL todo: any rules for index fixups?
+}
+
+// Make a shared symbol have a non-shared version that can be edited by the current
+// compile, such that editing its type will not change the shared version and will
+// effect all nodes sharing it.
+void HlslParseContext::makeEditable(TSymbol*& symbol)
+{
+ // copyUp() does a deep copy of the type.
+ symbol = symbolTable.copyUp(symbol);
+
+ // Also, see if it's tied to IO resizing
+ if (isIoResizeArray(symbol->getType()))
+ ioArraySymbolResizeList.push_back(symbol);
+
+ // Also, save it in the AST for linker use.
+ intermediate.addSymbolLinkageNode(linkage, *symbol);
+}
+
+TVariable* HlslParseContext::getEditableVariable(const char* name)
+{
+ bool builtIn;
+ TSymbol* symbol = symbolTable.find(name, &builtIn);
+ if (builtIn)
+ makeEditable(symbol);
+
+ return symbol->getAsVariable();
+}
+
+// Return true if this is a geometry shader input array or tessellation control output array.
+bool HlslParseContext::isIoResizeArray(const TType& type) const
+{
+ return type.isArray() &&
+ ((language == EShLangGeometry && type.getQualifier().storage == EvqVaryingIn) ||
+ (language == EShLangTessControl && type.getQualifier().storage == EvqVaryingOut && ! type.getQualifier().patch));
+}
+
+// If an array is not isIoResizeArray() but is an io array, make sure it has the right size
+void HlslParseContext::fixIoArraySize(const TSourceLoc& loc, TType& type)
+{
+ if (! type.isArray() || type.getQualifier().patch || symbolTable.atBuiltInLevel())
+ return;
+
+ assert(! isIoResizeArray(type));
+
+ if (type.getQualifier().storage != EvqVaryingIn || type.getQualifier().patch)
+ return;
+
+ if (language == EShLangTessControl || language == EShLangTessEvaluation) {
+ if (type.getOuterArraySize() != resources.maxPatchVertices) {
+ if (type.isExplicitlySizedArray())
+ error(loc, "tessellation input array size must be gl_MaxPatchVertices or implicitly sized", "[]", "");
+ type.changeOuterArraySize(resources.maxPatchVertices);
+ }
+ }
+}
+
+// Handle a dereference of a geometry shader input array or tessellation control output array.
+// See ioArraySymbolResizeList comment in ParseHelper.h.
+//
+void HlslParseContext::handleIoResizeArrayAccess(const TSourceLoc& /*loc*/, TIntermTyped* base)
+{
+ TIntermSymbol* symbolNode = base->getAsSymbolNode();
+ assert(symbolNode);
+ if (! symbolNode)
+ return;
+
+ // fix array size, if it can be fixed and needs to be fixed (will allow variable indexing)
+ if (symbolNode->getType().isImplicitlySizedArray()) {
+ int newSize = getIoArrayImplicitSize();
+ if (newSize > 0)
+ symbolNode->getWritableType().changeOuterArraySize(newSize);
+ }
+}
+
+// If there has been an input primitive declaration (geometry shader) or an output
+// number of vertices declaration(tessellation shader), make sure all input array types
+// match it in size. Types come either from nodes in the AST or symbols in the
+// symbol table.
+//
+// Types without an array size will be given one.
+// Types already having a size that is wrong will get an error.
+//
+void HlslParseContext::checkIoArraysConsistency(const TSourceLoc& loc, bool tailOnly)
+{
+ int requiredSize = getIoArrayImplicitSize();
+ if (requiredSize == 0)
+ return;
+
+ const char* feature;
+ if (language == EShLangGeometry)
+ feature = TQualifier::getGeometryString(intermediate.getInputPrimitive());
+ else if (language == EShLangTessControl)
+ feature = "vertices";
+ else
+ feature = "unknown";
+
+ if (tailOnly) {
+ checkIoArrayConsistency(loc, requiredSize, feature, ioArraySymbolResizeList.back()->getWritableType(), ioArraySymbolResizeList.back()->getName());
+ return;
+ }
+
+ for (size_t i = 0; i < ioArraySymbolResizeList.size(); ++i)
+ checkIoArrayConsistency(loc, requiredSize, feature, ioArraySymbolResizeList[i]->getWritableType(), ioArraySymbolResizeList[i]->getName());
+}
+
+int HlslParseContext::getIoArrayImplicitSize() const
+{
+ if (language == EShLangGeometry)
+ return TQualifier::mapGeometryToSize(intermediate.getInputPrimitive());
+ else if (language == EShLangTessControl)
+ return intermediate.getVertices() != TQualifier::layoutNotSet ? intermediate.getVertices() : 0;
+ else
+ return 0;
+}
+
+void HlslParseContext::checkIoArrayConsistency(const TSourceLoc& loc, int requiredSize, const char* feature, TType& type, const TString& name)
+{
+ if (type.isImplicitlySizedArray())
+ type.changeOuterArraySize(requiredSize);
+}
+
+// Handle seeing a binary node with a math operation.
+TIntermTyped* HlslParseContext::handleBinaryMath(const TSourceLoc& loc, const char* str, TOperator op, TIntermTyped* left, TIntermTyped* right)
+{
+ TIntermTyped* result = intermediate.addBinaryMath(op, left, right, loc);
+ if (! result)
+ binaryOpError(loc, str, left->getCompleteString(), right->getCompleteString());
+
+ return result;
+}
+
+// Handle seeing a unary node with a math operation.
+TIntermTyped* HlslParseContext::handleUnaryMath(const TSourceLoc& loc, const char* str, TOperator op, TIntermTyped* childNode)
+{
+ TIntermTyped* result = intermediate.addUnaryMath(op, childNode, loc);
+
+ if (result)
+ return result;
+ else
+ unaryOpError(loc, str, childNode->getCompleteString());
+
+ return childNode;
+}
+
+//
+// Handle seeing a base.field dereference in the grammar.
+//
+TIntermTyped* HlslParseContext::handleDotDereference(const TSourceLoc& loc, TIntermTyped* base, const TString& field)
+{
+ variableCheck(base);
+
+ //
+ // .length() can't be resolved until we later see the function-calling syntax.
+ // Save away the name in the AST for now. Processing is completed in
+ // handleLengthMethod().
+ //
+ if (field == "length") {
+ return intermediate.addMethod(base, TType(EbtInt), &field, loc);
+ }
+
+ // It's not .length() if we get to here.
+
+ if (base->isArray()) {
+ error(loc, "cannot apply to an array:", ".", field.c_str());
+
+ return base;
+ }
+
+ // It's neither an array nor .length() if we get here,
+ // leaving swizzles and struct/block dereferences.
+
+ TIntermTyped* result = base;
+ if (base->isVector() || base->isScalar()) {
+ TVectorFields fields;
+ if (! parseVectorFields(loc, field, base->getVectorSize(), fields)) {
+ fields.num = 1;
+ fields.offsets[0] = 0;
+ }
+
+ if (base->isScalar()) {
+ if (fields.num == 1)
+ return result;
+ else {
+ TType type(base->getBasicType(), EvqTemporary, fields.num);
+ return addConstructor(loc, base, type, mapTypeToConstructorOp(type));
+ }
+ }
+
+ if (base->getType().getQualifier().isFrontEndConstant())
+ result = intermediate.foldSwizzle(base, fields, loc);
+ else {
+ if (fields.num == 1) {
+ TIntermTyped* index = intermediate.addConstantUnion(fields.offsets[0], loc);
+ result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
+ result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision));
+ } else {
+ TString vectorString = field;
+ TIntermTyped* index = intermediate.addSwizzle(fields, loc);
+ result = intermediate.addIndex(EOpVectorSwizzle, base, index, loc);
+ result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision, (int)vectorString.size()));
+ }
+ }
+ } else if (base->getBasicType() == EbtStruct || base->getBasicType() == EbtBlock) {
+ const TTypeList* fields = base->getType().getStruct();
+ bool fieldFound = false;
+ int member;
+ for (member = 0; member < (int)fields->size(); ++member) {
+ if ((*fields)[member].type->getFieldName() == field) {
+ fieldFound = true;
+ break;
+ }
+ }
+ if (fieldFound) {
+ if (base->getType().getQualifier().storage == EvqConst)
+ result = intermediate.foldDereference(base, member, loc);
+ else {
+ TIntermTyped* index = intermediate.addConstantUnion(member, loc);
+ result = intermediate.addIndex(EOpIndexDirectStruct, base, index, loc);
+ result->setType(*(*fields)[member].type);
+ }
+ } else
+ error(loc, "no such field in structure", field.c_str(), "");
+ } else
+ error(loc, "does not apply to this type:", field.c_str(), base->getType().getCompleteString().c_str());
+
+ return result;
+}
+
+//
+// Handle seeing a function declarator in the grammar. This is the precursor
+// to recognizing a function prototype or function definition.
+//
+TFunction* HlslParseContext::handleFunctionDeclarator(const TSourceLoc& loc, TFunction& function, bool prototype)
+{
+ //
+ // Multiple declarations of the same function name are allowed.
+ //
+ // If this is a definition, the definition production code will check for redefinitions
+ // (we don't know at this point if it's a definition or not).
+ //
+ // Redeclarations (full signature match) are allowed. But, return types and parameter qualifiers must also match.
+ // - except ES 100, which only allows a single prototype
+ //
+ // ES 100 does not allow redefining, but does allow overloading of built-in functions.
+ // ES 300 does not allow redefining or overloading of built-in functions.
+ //
+ bool builtIn;
+ TSymbol* symbol = symbolTable.find(function.getMangledName(), &builtIn);
+ const TFunction* prevDec = symbol ? symbol->getAsFunction() : 0;
+
+ if (prototype) {
+ // All built-in functions are defined, even though they don't have a body.
+ // Count their prototype as a definition instead.
+ if (symbolTable.atBuiltInLevel())
+ function.setDefined();
+ else {
+ if (prevDec && ! builtIn)
+ symbol->getAsFunction()->setPrototyped(); // need a writable one, but like having prevDec as a const
+ function.setPrototyped();
+ }
+ }
+
+ // This insert won't actually insert it if it's a duplicate signature, but it will still check for
+ // other forms of name collisions.
+ if (! symbolTable.insert(function))
+ error(loc, "function name is redeclaration of existing name", function.getName().c_str(), "");
+
+ //
+ // If this is a redeclaration, it could also be a definition,
+ // in which case, we need to use the parameter names from this one, and not the one that's
+ // being redeclared. So, pass back this declaration, not the one in the symbol table.
+ //
+ return &function;
+}
+
+//
+// Handle seeing the function prototype in front of a function definition in the grammar.
+// The body is handled after this function returns.
+//
+TIntermAggregate* HlslParseContext::handleFunctionDefinition(const TSourceLoc& loc, TFunction& function)
+{
+ currentCaller = function.getMangledName();
+ TSymbol* symbol = symbolTable.find(function.getMangledName());
+ TFunction* prevDec = symbol ? symbol->getAsFunction() : nullptr;
+
+ if (! prevDec)
+ error(loc, "can't find function", function.getName().c_str(), "");
+ // Note: 'prevDec' could be 'function' if this is the first time we've seen function
+ // as it would have just been put in the symbol table. Otherwise, we're looking up
+ // an earlier occurrence.
+
+ if (prevDec && prevDec->isDefined()) {
+ // Then this function already has a body.
+ error(loc, "function already has a body", function.getName().c_str(), "");
+ }
+ if (prevDec && ! prevDec->isDefined()) {
+ prevDec->setDefined();
+
+ // Remember the return type for later checking for RETURN statements.
+ currentFunctionType = &(prevDec->getType());
+ } else
+ currentFunctionType = new TType(EbtVoid);
+ functionReturnsValue = false;
+
+ inEntrypoint = (function.getName() == intermediate.getEntryPoint().c_str());
+
+ //
+ // New symbol table scope for body of function plus its arguments
+ //
+ symbolTable.push();
+
+ //
+ // Insert parameters into the symbol table.
+ // If the parameter has no name, it's not an error, just don't insert it
+ // (could be used for unused args).
+ //
+ // Also, accumulate the list of parameters into the HIL, so lower level code
+ // knows where to find parameters.
+ //
+ TIntermAggregate* paramNodes = new TIntermAggregate;
+ for (int i = 0; i < function.getParamCount(); i++) {
+ TParameter& param = function[i];
+ if (param.name != nullptr) {
+ TVariable *variable = new TVariable(param.name, *param.type);
+
+ // Insert the parameters with name in the symbol table.
+ if (! symbolTable.insert(*variable))
+ error(loc, "redefinition", variable->getName().c_str(), "");
+ else {
+ // Transfer ownership of name pointer to symbol table.
+ param.name = nullptr;
+
+ // Add the parameter to the HIL
+ paramNodes = intermediate.growAggregate(paramNodes,
+ intermediate.addSymbol(*variable, loc),
+ loc);
+ }
+ } else
+ paramNodes = intermediate.growAggregate(paramNodes, intermediate.addSymbol(*param.type, loc), loc);
+ }
+ intermediate.setAggregateOperator(paramNodes, EOpParameters, TType(EbtVoid), loc);
+ loopNestingLevel = 0;
+ statementNestingLevel = 0;
+ controlFlowNestingLevel = 0;
+ postMainReturn = false;
+
+ return paramNodes;
+}
+
+void HlslParseContext::handleFunctionArgument(TFunction* function, TIntermAggregate*& arguments, TIntermTyped* arg)
+{
+ TParameter param = { 0, new TType };
+ param.type->shallowCopy(arg->getType());
+ function->addParameter(param);
+ arguments = intermediate.growAggregate(arguments, arg);
+}
+
+//
+// Handle seeing function call syntax in the grammar, which could be any of
+// - .length() method
+// - constructor
+// - a call to a built-in function mapped to an operator
+// - a call to a built-in function that will remain a function call (e.g., texturing)
+// - user function
+// - subroutine call (not implemented yet)
+//
+TIntermTyped* HlslParseContext::handleFunctionCall(const TSourceLoc& loc, TFunction* function, TIntermNode* arguments)
+{
+ TIntermTyped* result = nullptr;
+
+ TOperator op = function->getBuiltInOp();
+ if (op == EOpArrayLength)
+ result = handleLengthMethod(loc, function, arguments);
+ else if (op != EOpNull) {
+ //
+ // Then this should be a constructor.
+ // Don't go through the symbol table for constructors.
+ // Their parameters will be verified algorithmically.
+ //
+ TType type(EbtVoid); // use this to get the type back
+ if (! constructorError(loc, arguments, *function, op, type)) {
+ //
+ // It's a constructor, of type 'type'.
+ //
+ result = addConstructor(loc, arguments, type, op);
+ if (result == nullptr)
+ error(loc, "cannot construct with these arguments", type.getCompleteString().c_str(), "");
+ }
+ } else {
+ //
+ // Find it in the symbol table.
+ //
+ const TFunction* fnCandidate;
+ bool builtIn;
+ fnCandidate = findFunction(loc, *function, builtIn);
+ if (fnCandidate) {
+ // This is a declared function that might map to
+ // - a built-in operator,
+ // - a built-in function not mapped to an operator, or
+ // - a user function.
+
+ // Error check for a function requiring specific extensions present.
+ if (builtIn && fnCandidate->getNumExtensions())
+ requireExtensions(loc, fnCandidate->getNumExtensions(), fnCandidate->getExtensions(), fnCandidate->getName().c_str());
+
+ if (arguments) {
+ // Make sure qualifications work for these arguments.
+ TIntermAggregate* aggregate = arguments->getAsAggregate();
+ for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
+ // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
+ // is the single argument itself or its children are the arguments. Only one argument
+ // means take 'arguments' itself as the one argument.
+ TIntermNode* arg = fnCandidate->getParamCount() == 1 ? arguments : (aggregate ? aggregate->getSequence()[i] : arguments);
+ TQualifier& formalQualifier = (*fnCandidate)[i].type->getQualifier();
+ TQualifier& argQualifier = arg->getAsTyped()->getQualifier();
+ }
+
+ // Convert 'in' arguments
+ addInputArgumentConversions(*fnCandidate, arguments); // arguments may be modified if it's just a single argument node
+ }
+
+ op = fnCandidate->getBuiltInOp();
+ if (builtIn && op != EOpNull) {
+ // A function call mapped to a built-in operation.
+ result = intermediate.addBuiltInFunctionCall(loc, op, fnCandidate->getParamCount() == 1, arguments, fnCandidate->getType());
+ if (result == nullptr) {
+ error(arguments->getLoc(), " wrong operand type", "Internal Error",
+ "built in unary operator function. Type: %s",
+ static_cast<TIntermTyped*>(arguments)->getCompleteString().c_str());
+ } else if (result->getAsOperator()) {
+ builtInOpCheck(loc, *fnCandidate, *result->getAsOperator());
+ }
+ } else {
+ // This is a function call not mapped to built-in operator.
+ // It could still be a built-in function, but only if PureOperatorBuiltins == false.
+ result = intermediate.setAggregateOperator(arguments, EOpFunctionCall, fnCandidate->getType(), loc);
+ TIntermAggregate* call = result->getAsAggregate();
+ call->setName(fnCandidate->getMangledName());
+
+ // this is how we know whether the given function is a built-in function or a user-defined function
+ // if builtIn == false, it's a userDefined -> could be an overloaded built-in function also
+ // if builtIn == true, it's definitely a built-in function with EOpNull
+ if (! builtIn) {
+ call->setUserDefined();
+ intermediate.addToCallGraph(infoSink, currentCaller, fnCandidate->getMangledName());
+ }
+ }
+
+ // Convert 'out' arguments. If it was a constant folded built-in, it won't be an aggregate anymore.
+ // Built-ins with a single argument aren't called with an aggregate, but they also don't have an output.
+ // Also, build the qualifier list for user function calls, which are always called with an aggregate.
+ if (result->getAsAggregate()) {
+ TQualifierList& qualifierList = result->getAsAggregate()->getQualifierList();
+ for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
+ TStorageQualifier qual = (*fnCandidate)[i].type->getQualifier().storage;
+ qualifierList.push_back(qual);
+ }
+ result = addOutputArgumentConversions(*fnCandidate, *result->getAsAggregate());
+ }
+ }
+ }
+
+ // generic error recovery
+ // TODO: simplification: localize all the error recoveries that look like this, and taking type into account to reduce cascades
+ if (result == nullptr)
+ result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
+
+ return result;
+}
+
+// Finish processing object.length(). This started earlier in handleDotDereference(), where
+// the ".length" part was recognized and semantically checked, and finished here where the
+// function syntax "()" is recognized.
+//
+// Return resulting tree node.
+TIntermTyped* HlslParseContext::handleLengthMethod(const TSourceLoc& loc, TFunction* function, TIntermNode* intermNode)
+{
+ int length = 0;
+
+ if (function->getParamCount() > 0)
+ error(loc, "method does not accept any arguments", function->getName().c_str(), "");
+ else {
+ const TType& type = intermNode->getAsTyped()->getType();
+ if (type.isArray()) {
+ if (type.isRuntimeSizedArray()) {
+ // Create a unary op and let the back end handle it
+ return intermediate.addBuiltInFunctionCall(loc, EOpArrayLength, true, intermNode, TType(EbtInt));
+ } else if (type.isImplicitlySizedArray()) {
+ if (intermNode->getAsSymbolNode() && isIoResizeArray(type)) {
+ // We could be between a layout declaration that gives a built-in io array implicit size and
+ // a user redeclaration of that array, meaning we have to substitute its implicit size here
+ // without actually redeclaring the array. (It is an error to use a member before the
+ // redeclaration, but not an error to use the array name itself.)
+ const TString& name = intermNode->getAsSymbolNode()->getName();
+ if (name == "gl_in" || name == "gl_out")
+ length = getIoArrayImplicitSize();
+ }
+ if (length == 0) {
+ if (intermNode->getAsSymbolNode() && isIoResizeArray(type))
+ error(loc, "", function->getName().c_str(), "array must first be sized by a redeclaration or layout qualifier");
+ else
+ error(loc, "", function->getName().c_str(), "array must be declared with a size before using this method");
+ }
+ } else
+ length = type.getOuterArraySize();
+ } else if (type.isMatrix())
+ length = type.getMatrixCols();
+ else if (type.isVector())
+ length = type.getVectorSize();
+ else {
+ // we should not get here, because earlier semantic checking should have prevented this path
+ error(loc, ".length()", "unexpected use of .length()", "");
+ }
+ }
+
+ if (length == 0)
+ length = 1;
+
+ return intermediate.addConstantUnion(length, loc);
+}
+
+//
+// Add any needed implicit conversions for function-call arguments to input parameters.
+//
+void HlslParseContext::addInputArgumentConversions(const TFunction& function, TIntermNode*& arguments) const
+{
+ TIntermAggregate* aggregate = arguments->getAsAggregate();
+
+ // Process each argument's conversion
+ for (int i = 0; i < function.getParamCount(); ++i) {
+ // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
+ // is the single argument itself or its children are the arguments. Only one argument
+ // means take 'arguments' itself as the one argument.
+ TIntermTyped* arg = function.getParamCount() == 1 ? arguments->getAsTyped() : (aggregate ? aggregate->getSequence()[i]->getAsTyped() : arguments->getAsTyped());
+ if (*function[i].type != arg->getType()) {
+ if (function[i].type->getQualifier().isParamInput()) {
+ // In-qualified arguments just need an extra node added above the argument to
+ // convert to the correct type.
+ arg = intermediate.addConversion(EOpFunctionCall, *function[i].type, arg);
+ if (arg) {
+ if (function.getParamCount() == 1)
+ arguments = arg;
+ else {
+ if (aggregate)
+ aggregate->getSequence()[i] = arg;
+ else
+ arguments = arg;
+ }
+ }
+ }
+ }
+ }
+}
+
+//
+// Add any needed implicit output conversions for function-call arguments. This
+// can require a new tree topology, complicated further by whether the function
+// has a return value.
+//
+// Returns a node of a subtree that evaluates to the return value of the function.
+//
+TIntermTyped* HlslParseContext::addOutputArgumentConversions(const TFunction& function, TIntermAggregate& intermNode) const
+{
+ TIntermSequence& arguments = intermNode.getSequence();
+
+ // Will there be any output conversions?
+ bool outputConversions = false;
+ for (int i = 0; i < function.getParamCount(); ++i) {
+ if (*function[i].type != arguments[i]->getAsTyped()->getType() && function[i].type->getQualifier().storage == EvqOut) {
+ outputConversions = true;
+ break;
+ }
+ }
+
+ if (! outputConversions)
+ return &intermNode;
+
+ // Setup for the new tree, if needed:
+ //
+ // Output conversions need a different tree topology.
+ // Out-qualified arguments need a temporary of the correct type, with the call
+ // followed by an assignment of the temporary to the original argument:
+ // void: function(arg, ...) -> ( function(tempArg, ...), arg = tempArg, ...)
+ // ret = function(arg, ...) -> ret = (tempRet = function(tempArg, ...), arg = tempArg, ..., tempRet)
+ // Where the "tempArg" type needs no conversion as an argument, but will convert on assignment.
+ TIntermTyped* conversionTree = nullptr;
+ TVariable* tempRet = nullptr;
+ if (intermNode.getBasicType() != EbtVoid) {
+ // do the "tempRet = function(...), " bit from above
+ tempRet = makeInternalVariable("tempReturn", intermNode.getType());
+ TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, intermNode.getLoc());
+ conversionTree = intermediate.addAssign(EOpAssign, tempRetNode, &intermNode, intermNode.getLoc());
+ } else
+ conversionTree = &intermNode;
+
+ conversionTree = intermediate.makeAggregate(conversionTree);
+
+ // Process each argument's conversion
+ for (int i = 0; i < function.getParamCount(); ++i) {
+ if (*function[i].type != arguments[i]->getAsTyped()->getType()) {
+ if (function[i].type->getQualifier().isParamOutput()) {
+ // Out-qualified arguments need to use the topology set up above.
+ // do the " ...(tempArg, ...), arg = tempArg" bit from above
+ TVariable* tempArg = makeInternalVariable("tempArg", *function[i].type);
+ tempArg->getWritableType().getQualifier().makeTemporary();
+ TIntermSymbol* tempArgNode = intermediate.addSymbol(*tempArg, intermNode.getLoc());
+ TIntermTyped* tempAssign = intermediate.addAssign(EOpAssign, arguments[i]->getAsTyped(), tempArgNode, arguments[i]->getLoc());
+ conversionTree = intermediate.growAggregate(conversionTree, tempAssign, arguments[i]->getLoc());
+ // replace the argument with another node for the same tempArg variable
+ arguments[i] = intermediate.addSymbol(*tempArg, intermNode.getLoc());
+ }
+ }
+ }
+
+ // Finalize the tree topology (see bigger comment above).
+ if (tempRet) {
+ // do the "..., tempRet" bit from above
+ TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, intermNode.getLoc());
+ conversionTree = intermediate.growAggregate(conversionTree, tempRetNode, intermNode.getLoc());
+ }
+ conversionTree = intermediate.setAggregateOperator(conversionTree, EOpComma, intermNode.getType(), intermNode.getLoc());
+
+ return conversionTree;
+}
+
+//
+// Do additional checking of built-in function calls that is not caught
+// by normal semantic checks on argument type, extension tagging, etc.
+//
+// Assumes there has been a semantically correct match to a built-in function prototype.
+//
+void HlslParseContext::builtInOpCheck(const TSourceLoc& loc, const TFunction& fnCandidate, TIntermOperator& callNode)
+{
+ // Set up convenience accessors to the argument(s). There is almost always
+ // multiple arguments for the cases below, but when there might be one,
+ // check the unaryArg first.
+ const TIntermSequence* argp = nullptr; // confusing to use [] syntax on a pointer, so this is to help get a reference
+ const TIntermTyped* unaryArg = nullptr;
+ const TIntermTyped* arg0 = nullptr;
+ if (callNode.getAsAggregate()) {
+ argp = &callNode.getAsAggregate()->getSequence();
+ if (argp->size() > 0)
+ arg0 = (*argp)[0]->getAsTyped();
+ } else {
+ assert(callNode.getAsUnaryNode());
+ unaryArg = callNode.getAsUnaryNode()->getOperand();
+ arg0 = unaryArg;
+ }
+ const TIntermSequence& aggArgs = *argp; // only valid when unaryArg is nullptr
+
+ // built-in texturing functions get their return value precision from the precision of the sampler
+ if (fnCandidate.getType().getQualifier().precision == EpqNone &&
+ fnCandidate.getParamCount() > 0 && fnCandidate[0].type->getBasicType() == EbtSampler)
+ callNode.getQualifier().precision = arg0->getQualifier().precision;
+
+ switch (callNode.getOp()) {
+ case EOpTextureGather:
+ case EOpTextureGatherOffset:
+ case EOpTextureGatherOffsets:
+ {
+ // Figure out which variants are allowed by what extensions,
+ // and what arguments must be constant for which situations.
+
+ TString featureString = fnCandidate.getName() + "(...)";
+ const char* feature = featureString.c_str();
+ int compArg = -1; // track which argument, if any, is the constant component argument
+ switch (callNode.getOp()) {
+ case EOpTextureGather:
+ // More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5,
+ // otherwise, need GL_ARB_texture_gather.
+ if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect || fnCandidate[0].type->getSampler().shadow) {
+ if (! fnCandidate[0].type->getSampler().shadow)
+ compArg = 2;
+ }
+ break;
+ case EOpTextureGatherOffset:
+ // GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument
+ if (! fnCandidate[0].type->getSampler().shadow)
+ compArg = 3;
+ break;
+ case EOpTextureGatherOffsets:
+ if (! fnCandidate[0].type->getSampler().shadow)
+ compArg = 3;
+ break;
+ default:
+ break;
+ }
+
+ if (compArg > 0 && compArg < fnCandidate.getParamCount()) {
+ if (aggArgs[compArg]->getAsConstantUnion()) {
+ int value = aggArgs[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst();
+ if (value < 0 || value > 3)
+ error(loc, "must be 0, 1, 2, or 3:", feature, "component argument");
+ } else
+ error(loc, "must be a compile-time constant:", feature, "component argument");
+ }
+
+ break;
+ }
+
+ case EOpTextureOffset:
+ case EOpTextureFetchOffset:
+ case EOpTextureProjOffset:
+ case EOpTextureLodOffset:
+ case EOpTextureProjLodOffset:
+ case EOpTextureGradOffset:
+ case EOpTextureProjGradOffset:
+ {
+ // Handle texture-offset limits checking
+ // Pick which argument has to hold constant offsets
+ int arg = -1;
+ switch (callNode.getOp()) {
+ case EOpTextureOffset: arg = 2; break;
+ case EOpTextureFetchOffset: arg = (arg0->getType().getSampler().dim != EsdRect) ? 3 : 2; break;
+ case EOpTextureProjOffset: arg = 2; break;
+ case EOpTextureLodOffset: arg = 3; break;
+ case EOpTextureProjLodOffset: arg = 3; break;
+ case EOpTextureGradOffset: arg = 4; break;
+ case EOpTextureProjGradOffset: arg = 4; break;
+ default:
+ assert(0);
+ break;
+ }
+
+ if (arg > 0) {
+ if (! aggArgs[arg]->getAsConstantUnion())
+ error(loc, "argument must be compile-time constant", "texel offset", "");
+ else {
+ const TType& type = aggArgs[arg]->getAsTyped()->getType();
+ for (int c = 0; c < type.getVectorSize(); ++c) {
+ int offset = aggArgs[arg]->getAsConstantUnion()->getConstArray()[c].getIConst();
+ if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset)
+ error(loc, "value is out of range:", "texel offset", "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]");
+ }
+ }
+ }
+
+ break;
+ }
+
+ case EOpTextureQuerySamples:
+ case EOpImageQuerySamples:
+ break;
+
+ case EOpImageAtomicAdd:
+ case EOpImageAtomicMin:
+ case EOpImageAtomicMax:
+ case EOpImageAtomicAnd:
+ case EOpImageAtomicOr:
+ case EOpImageAtomicXor:
+ case EOpImageAtomicExchange:
+ case EOpImageAtomicCompSwap:
+ break;
+
+ case EOpInterpolateAtCentroid:
+ case EOpInterpolateAtSample:
+ case EOpInterpolateAtOffset:
+ // "For the interpolateAt* functions, the call will return a precision
+ // qualification matching the precision of the 'interpolant' argument to
+ // the function call."
+ callNode.getQualifier().precision = arg0->getQualifier().precision;
+
+ // Make sure the first argument is an interpolant, or an array element of an interpolant
+ if (arg0->getType().getQualifier().storage != EvqVaryingIn) {
+ // It might still be an array element.
+ //
+ // We could check more, but the semantics of the first argument are already met; the
+ // only way to turn an array into a float/vec* is array dereference and swizzle.
+ //
+ // ES and desktop 4.3 and earlier: swizzles may not be used
+ // desktop 4.4 and later: swizzles may be used
+ const TIntermTyped* base = TIntermediate::findLValueBase(arg0, true);
+ if (base == nullptr || base->getType().getQualifier().storage != EvqVaryingIn)
+ error(loc, "first argument must be an interpolant, or interpolant-array element", fnCandidate.getName().c_str(), "");
+ }
+ break;
+
+ default:
+ break;
+ }
+}
+
+//
+// Handle seeing a built-in constructor in a grammar production.
+//
+TFunction* HlslParseContext::handleConstructorCall(const TSourceLoc& loc, const TType& type)
+{
+ TOperator op = mapTypeToConstructorOp(type);
+
+ if (op == EOpNull) {
+ error(loc, "cannot construct this type", type.getBasicString(), "");
+ return nullptr;
+ }
+
+ TString empty("");
+
+ return new TFunction(&empty, type, op);
+}
+
+//
+// Given a type, find what operation would fully construct it.
+//
+TOperator HlslParseContext::mapTypeToConstructorOp(const TType& type) const
+{
+ TOperator op = EOpNull;
+
+ switch (type.getBasicType()) {
+ case EbtStruct:
+ op = EOpConstructStruct;
+ break;
+ case EbtSampler:
+ if (type.getSampler().combined)
+ op = EOpConstructTextureSampler;
+ break;
+ case EbtFloat:
+ if (type.isMatrix()) {
+ switch (type.getMatrixCols()) {
+ case 2:
+ switch (type.getMatrixRows()) {
+ case 2: op = EOpConstructMat2x2; break;
+ case 3: op = EOpConstructMat2x3; break;
+ case 4: op = EOpConstructMat2x4; break;
+ default: break; // some compilers want this
+ }
+ break;
+ case 3:
+ switch (type.getMatrixRows()) {
+ case 2: op = EOpConstructMat3x2; break;
+ case 3: op = EOpConstructMat3x3; break;
+ case 4: op = EOpConstructMat3x4; break;
+ default: break; // some compilers want this
+ }
+ break;
+ case 4:
+ switch (type.getMatrixRows()) {
+ case 2: op = EOpConstructMat4x2; break;
+ case 3: op = EOpConstructMat4x3; break;
+ case 4: op = EOpConstructMat4x4; break;
+ default: break; // some compilers want this
+ }
+ break;
+ default: break; // some compilers want this
+ }
+ } else {
+ switch (type.getVectorSize()) {
+ case 1: op = EOpConstructFloat; break;
+ case 2: op = EOpConstructVec2; break;
+ case 3: op = EOpConstructVec3; break;
+ case 4: op = EOpConstructVec4; break;
+ default: break; // some compilers want this
+ }
+ }
+ break;
+ case EbtDouble:
+ if (type.getMatrixCols()) {
+ switch (type.getMatrixCols()) {
+ case 2:
+ switch (type.getMatrixRows()) {
+ case 2: op = EOpConstructDMat2x2; break;
+ case 3: op = EOpConstructDMat2x3; break;
+ case 4: op = EOpConstructDMat2x4; break;
+ default: break; // some compilers want this
+ }
+ break;
+ case 3:
+ switch (type.getMatrixRows()) {
+ case 2: op = EOpConstructDMat3x2; break;
+ case 3: op = EOpConstructDMat3x3; break;
+ case 4: op = EOpConstructDMat3x4; break;
+ default: break; // some compilers want this
+ }
+ break;
+ case 4:
+ switch (type.getMatrixRows()) {
+ case 2: op = EOpConstructDMat4x2; break;
+ case 3: op = EOpConstructDMat4x3; break;
+ case 4: op = EOpConstructDMat4x4; break;
+ default: break; // some compilers want this
+ }
+ break;
+ }
+ } else {
+ switch (type.getVectorSize()) {
+ case 1: op = EOpConstructDouble; break;
+ case 2: op = EOpConstructDVec2; break;
+ case 3: op = EOpConstructDVec3; break;
+ case 4: op = EOpConstructDVec4; break;
+ default: break; // some compilers want this
+ }
+ }
+ break;
+ case EbtInt:
+ switch (type.getVectorSize()) {
+ case 1: op = EOpConstructInt; break;
+ case 2: op = EOpConstructIVec2; break;
+ case 3: op = EOpConstructIVec3; break;
+ case 4: op = EOpConstructIVec4; break;
+ default: break; // some compilers want this
+ }
+ break;
+ case EbtUint:
+ switch (type.getVectorSize()) {
+ case 1: op = EOpConstructUint; break;
+ case 2: op = EOpConstructUVec2; break;
+ case 3: op = EOpConstructUVec3; break;
+ case 4: op = EOpConstructUVec4; break;
+ default: break; // some compilers want this
+ }
+ break;
+ case EbtBool:
+ switch (type.getVectorSize()) {
+ case 1: op = EOpConstructBool; break;
+ case 2: op = EOpConstructBVec2; break;
+ case 3: op = EOpConstructBVec3; break;
+ case 4: op = EOpConstructBVec4; break;
+ default: break; // some compilers want this
+ }
+ break;
+ default:
+ break;
+ }
+
+ return op;
+}
+
+//
+// Same error message for all places assignments don't work.
+//
+void HlslParseContext::assignError(const TSourceLoc& loc, const char* op, TString left, TString right)
+{
+ error(loc, "", op, "cannot convert from '%s' to '%s'",
+ right.c_str(), left.c_str());
+}
+
+//
+// Same error message for all places unary operations don't work.
+//
+void HlslParseContext::unaryOpError(const TSourceLoc& loc, const char* op, TString operand)
+{
+ error(loc, " wrong operand type", op,
+ "no operation '%s' exists that takes an operand of type %s (or there is no acceptable conversion)",
+ op, operand.c_str());
+}
+
+//
+// Same error message for all binary operations don't work.
+//
+void HlslParseContext::binaryOpError(const TSourceLoc& loc, const char* op, TString left, TString right)
+{
+ error(loc, " wrong operand types:", op,
+ "no operation '%s' exists that takes a left-hand operand of type '%s' and "
+ "a right operand of type '%s' (or there is no acceptable conversion)",
+ op, left.c_str(), right.c_str());
+}
+
+//
+// A basic type of EbtVoid is a key that the name string was seen in the source, but
+// it was not found as a variable in the symbol table. If so, give the error
+// message and insert a dummy variable in the symbol table to prevent future errors.
+//
+void HlslParseContext::variableCheck(TIntermTyped*& nodePtr)
+{
+ TIntermSymbol* symbol = nodePtr->getAsSymbolNode();
+ if (! symbol)
+ return;
+
+ if (symbol->getType().getBasicType() == EbtVoid) {
+ error(symbol->getLoc(), "undeclared identifier", symbol->getName().c_str(), "");
+
+ // Add to symbol table to prevent future error messages on the same name
+ if (symbol->getName().size() > 0) {
+ TVariable* fakeVariable = new TVariable(&symbol->getName(), TType(EbtFloat));
+ symbolTable.insert(*fakeVariable);
+
+ // substitute a symbol node for this new variable
+ nodePtr = intermediate.addSymbol(*fakeVariable, symbol->getLoc());
+ }
+ }
+}
+
+//
+// Both test, and if necessary spit out an error, to see if the node is really
+// a constant.
+//
+void HlslParseContext::constantValueCheck(TIntermTyped* node, const char* token)
+{
+ if (node->getQualifier().storage != EvqConst)
+ error(node->getLoc(), "constant expression required", token, "");
+}
+
+//
+// Both test, and if necessary spit out an error, to see if the node is really
+// an integer.
+//
+void HlslParseContext::integerCheck(const TIntermTyped* node, const char* token)
+{
+ if ((node->getBasicType() == EbtInt || node->getBasicType() == EbtUint) && node->isScalar())
+ return;
+
+ error(node->getLoc(), "scalar integer expression required", token, "");
+}
+
+//
+// Both test, and if necessary spit out an error, to see if we are currently
+// globally scoped.
+//
+void HlslParseContext::globalCheck(const TSourceLoc& loc, const char* token)
+{
+ if (! symbolTable.atGlobalLevel())
+ error(loc, "not allowed in nested scope", token, "");
+}
+
+
+bool HlslParseContext::builtInName(const TString& identifier)
+{
+ return false;
+}
+
+//
+// Make sure there is enough data and not too many arguments provided to the
+// constructor to build something of the type of the constructor. Also returns
+// the type of the constructor.
+//
+// Returns true if there was an error in construction.
+//
+bool HlslParseContext::constructorError(const TSourceLoc& loc, TIntermNode* node, TFunction& function, TOperator op, TType& type)
+{
+ type.shallowCopy(function.getType());
+
+ bool constructingMatrix = false;
+ switch (op) {
+ case EOpConstructTextureSampler:
+ return constructorTextureSamplerError(loc, function);
+ case EOpConstructMat2x2:
+ case EOpConstructMat2x3:
+ case EOpConstructMat2x4:
+ case EOpConstructMat3x2:
+ case EOpConstructMat3x3:
+ case EOpConstructMat3x4:
+ case EOpConstructMat4x2:
+ case EOpConstructMat4x3:
+ case EOpConstructMat4x4:
+ case EOpConstructDMat2x2:
+ case EOpConstructDMat2x3:
+ case EOpConstructDMat2x4:
+ case EOpConstructDMat3x2:
+ case EOpConstructDMat3x3:
+ case EOpConstructDMat3x4:
+ case EOpConstructDMat4x2:
+ case EOpConstructDMat4x3:
+ case EOpConstructDMat4x4:
+ constructingMatrix = true;
+ break;
+ default:
+ break;
+ }
+
+ //
+ // Walk the arguments for first-pass checks and collection of information.
+ //
+
+ int size = 0;
+ bool constType = true;
+ bool full = false;
+ bool overFull = false;
+ bool matrixInMatrix = false;
+ bool arrayArg = false;
+ for (int arg = 0; arg < function.getParamCount(); ++arg) {
+ if (function[arg].type->isArray()) {
+ if (! function[arg].type->isExplicitlySizedArray()) {
+ // Can't construct from an unsized array.
+ error(loc, "array argument must be sized", "constructor", "");
+ return true;
+ }
+ arrayArg = true;
+ }
+ if (constructingMatrix && function[arg].type->isMatrix())
+ matrixInMatrix = true;
+
+ // 'full' will go to true when enough args have been seen. If we loop
+ // again, there is an extra argument.
+ if (full) {
+ // For vectors and matrices, it's okay to have too many components
+ // available, but not okay to have unused arguments.
+ overFull = true;
+ }
+
+ size += function[arg].type->computeNumComponents();
+ if (op != EOpConstructStruct && ! type.isArray() && size >= type.computeNumComponents())
+ full = true;
+
+ if (function[arg].type->getQualifier().storage != EvqConst)
+ constType = false;
+ }
+
+ if (constType)
+ type.getQualifier().storage = EvqConst;
+
+ if (type.isArray()) {
+ if (function.getParamCount() == 0) {
+ error(loc, "array constructor must have at least one argument", "constructor", "");
+ return true;
+ }
+
+ if (type.isImplicitlySizedArray()) {
+ // auto adapt the constructor type to the number of arguments
+ type.changeOuterArraySize(function.getParamCount());
+ } else if (type.getOuterArraySize() != function.getParamCount()) {
+ error(loc, "array constructor needs one argument per array element", "constructor", "");
+ return true;
+ }
+
+ if (type.isArrayOfArrays()) {
+ // Types have to match, but we're still making the type.
+ // Finish making the type, and the comparison is done later
+ // when checking for conversion.
+ TArraySizes& arraySizes = type.getArraySizes();
+
+ // At least the dimensionalities have to match.
+ if (! function[0].type->isArray() || arraySizes.getNumDims() != function[0].type->getArraySizes().getNumDims() + 1) {
+ error(loc, "array constructor argument not correct type to construct array element", "constructior", "");
+ return true;
+ }
+
+ if (arraySizes.isInnerImplicit()) {
+ // "Arrays of arrays ..., and the size for any dimension is optional"
+ // That means we need to adopt (from the first argument) the other array sizes into the type.
+ for (int d = 1; d < arraySizes.getNumDims(); ++d) {
+ if (arraySizes.getDimSize(d) == UnsizedArraySize) {
+ arraySizes.setDimSize(d, function[0].type->getArraySizes().getDimSize(d - 1));
+ }
+ }
+ }
+ }
+ }
+
+ if (arrayArg && op != EOpConstructStruct && ! type.isArrayOfArrays()) {
+ error(loc, "constructing non-array constituent from array argument", "constructor", "");
+ return true;
+ }
+
+ if (matrixInMatrix && ! type.isArray()) {
+ return false;
+ }
+
+ if (overFull) {
+ error(loc, "too many arguments", "constructor", "");
+ return true;
+ }
+
+ if (op == EOpConstructStruct && ! type.isArray() && (int)type.getStruct()->size() != function.getParamCount()) {
+ error(loc, "Number of constructor parameters does not match the number of structure fields", "constructor", "");
+ return true;
+ }
+
+ if ((op != EOpConstructStruct && size != 1 && size < type.computeNumComponents()) ||
+ (op == EOpConstructStruct && size < type.computeNumComponents())) {
+ error(loc, "not enough data provided for construction", "constructor", "");
+ return true;
+ }
+
+ TIntermTyped* typed = node->getAsTyped();
+
+ return false;
+}
+
+// Verify all the correct semantics for constructing a combined texture/sampler.
+// Return true if the semantics are incorrect.
+bool HlslParseContext::constructorTextureSamplerError(const TSourceLoc& loc, const TFunction& function)
+{
+ TString constructorName = function.getType().getBasicTypeString(); // TODO: performance: should not be making copy; interface needs to change
+ const char* token = constructorName.c_str();
+
+ // exactly two arguments needed
+ if (function.getParamCount() != 2) {
+ error(loc, "sampler-constructor requires two arguments", token, "");
+ return true;
+ }
+
+ // For now, not allowing arrayed constructors, the rest of this function
+ // is set up to allow them, if this test is removed:
+ if (function.getType().isArray()) {
+ error(loc, "sampler-constructor cannot make an array of samplers", token, "");
+ return true;
+ }
+
+ // first argument
+ // * the constructor's first argument must be a texture type
+ // * the dimensionality (1D, 2D, 3D, Cube, Rect, Buffer, MS, and Array)
+ // of the texture type must match that of the constructed sampler type
+ // (that is, the suffixes of the type of the first argument and the
+ // type of the constructor will be spelled the same way)
+ if (function[0].type->getBasicType() != EbtSampler ||
+ ! function[0].type->getSampler().isTexture() ||
+ function[0].type->isArray()) {
+ error(loc, "sampler-constructor first argument must be a scalar textureXXX type", token, "");
+ return true;
+ }
+ // simulate the first argument's impact on the result type, so it can be compared with the encapsulated operator!=()
+ TSampler texture = function.getType().getSampler();
+ texture.combined = false;
+ texture.shadow = false;
+ if (texture != function[0].type->getSampler()) {
+ error(loc, "sampler-constructor first argument must match type and dimensionality of constructor type", token, "");
+ return true;
+ }
+
+ // second argument
+ // * the constructor's second argument must be a scalar of type
+ // *sampler* or *samplerShadow*
+ // * the presence or absence of depth comparison (Shadow) must match
+ // between the constructed sampler type and the type of the second argument
+ if (function[1].type->getBasicType() != EbtSampler ||
+ ! function[1].type->getSampler().isPureSampler() ||
+ function[1].type->isArray()) {
+ error(loc, "sampler-constructor second argument must be a scalar type 'sampler'", token, "");
+ return true;
+ }
+ if (function.getType().getSampler().shadow != function[1].type->getSampler().shadow) {
+ error(loc, "sampler-constructor second argument presence of shadow must match constructor presence of shadow", token, "");
+ return true;
+ }
+
+ return false;
+}
+
+// Checks to see if a void variable has been declared and raise an error message for such a case
+//
+// returns true in case of an error
+//
+bool HlslParseContext::voidErrorCheck(const TSourceLoc& loc, const TString& identifier, const TBasicType basicType)
+{
+ if (basicType == EbtVoid) {
+ error(loc, "illegal use of type 'void'", identifier.c_str(), "");
+ return true;
+ }
+
+ return false;
+}
+
+// Checks to see if the node (for the expression) contains a scalar boolean expression or not
+void HlslParseContext::boolCheck(const TSourceLoc& loc, const TIntermTyped* type)
+{
+ if (type->getBasicType() != EbtBool || type->isArray() || type->isMatrix() || type->isVector())
+ error(loc, "boolean expression expected", "", "");
+}
+
+// This function checks to see if the node (for the expression) contains a scalar boolean expression or not
+void HlslParseContext::boolCheck(const TSourceLoc& loc, const TPublicType& pType)
+{
+ if (pType.basicType != EbtBool || pType.arraySizes || pType.matrixCols > 1 || (pType.vectorSize > 1))
+ error(loc, "boolean expression expected", "", "");
+}
+
+//
+// Fix just a full qualifier (no variables or types yet, but qualifier is complete) at global level.
+//
+void HlslParseContext::globalQualifierFix(const TSourceLoc& loc, TQualifier& qualifier)
+{
+ // move from parameter/unknown qualifiers to pipeline in/out qualifiers
+ switch (qualifier.storage) {
+ case EvqIn:
+ qualifier.storage = EvqVaryingIn;
+ break;
+ case EvqOut:
+ qualifier.storage = EvqVaryingOut;
+ break;
+ default:
+ break;
+ }
+}
+
+//
+// Merge characteristics of the 'src' qualifier into the 'dst'.
+// If there is duplication, issue error messages, unless 'force'
+// is specified, which means to just override default settings.
+//
+// Also, when force is false, it will be assumed that 'src' follows
+// 'dst', for the purpose of error checking order for versions
+// that require specific orderings of qualifiers.
+//
+void HlslParseContext::mergeQualifiers(const TSourceLoc& loc, TQualifier& dst, const TQualifier& src, bool force)
+{
+ // Storage qualification
+ if (dst.storage == EvqTemporary || dst.storage == EvqGlobal)
+ dst.storage = src.storage;
+ else if ((dst.storage == EvqIn && src.storage == EvqOut) ||
+ (dst.storage == EvqOut && src.storage == EvqIn))
+ dst.storage = EvqInOut;
+ else if ((dst.storage == EvqIn && src.storage == EvqConst) ||
+ (dst.storage == EvqConst && src.storage == EvqIn))
+ dst.storage = EvqConstReadOnly;
+ else if (src.storage != EvqTemporary && src.storage != EvqGlobal)
+ error(loc, "too many storage qualifiers", GetStorageQualifierString(src.storage), "");
+
+ // Precision qualifiers
+ if (dst.precision == EpqNone || (force && src.precision != EpqNone))
+ dst.precision = src.precision;
+
+ // Layout qualifiers
+ mergeObjectLayoutQualifiers(dst, src, false);
+
+ // individual qualifiers
+ bool repeated = false;
+#define MERGE_SINGLETON(field) repeated |= dst.field && src.field; dst.field |= src.field;
+ MERGE_SINGLETON(invariant);
+ MERGE_SINGLETON(centroid);
+ MERGE_SINGLETON(smooth);
+ MERGE_SINGLETON(flat);
+ MERGE_SINGLETON(nopersp);
+ MERGE_SINGLETON(patch);
+ MERGE_SINGLETON(sample);
+ MERGE_SINGLETON(coherent);
+ MERGE_SINGLETON(volatil);
+ MERGE_SINGLETON(restrict);
+ MERGE_SINGLETON(readonly);
+ MERGE_SINGLETON(writeonly);
+ MERGE_SINGLETON(specConstant);
+}
+
+// used to flatten the sampler type space into a single dimension
+// correlates with the declaration of defaultSamplerPrecision[]
+int HlslParseContext::computeSamplerTypeIndex(TSampler& sampler)
+{
+ int arrayIndex = sampler.arrayed ? 1 : 0;
+ int shadowIndex = sampler.shadow ? 1 : 0;
+ int externalIndex = sampler.external ? 1 : 0;
+
+ return EsdNumDims * (EbtNumTypes * (2 * (2 * arrayIndex + shadowIndex) + externalIndex) + sampler.type) + sampler.dim;
+}
+
+//
+// Do size checking for an array type's size.
+//
+void HlslParseContext::arraySizeCheck(const TSourceLoc& loc, TIntermTyped* expr, TArraySize& sizePair)
+{
+ bool isConst = false;
+ sizePair.size = 1;
+ sizePair.node = nullptr;
+
+ TIntermConstantUnion* constant = expr->getAsConstantUnion();
+ if (constant) {
+ // handle true (non-specialization) constant
+ sizePair.size = constant->getConstArray()[0].getIConst();
+ isConst = true;
+ } else {
+ // see if it's a specialization constant instead
+ if (expr->getQualifier().isSpecConstant()) {
+ isConst = true;
+ sizePair.node = expr;
+ TIntermSymbol* symbol = expr->getAsSymbolNode();
+ if (symbol && symbol->getConstArray().size() > 0)
+ sizePair.size = symbol->getConstArray()[0].getIConst();
+ }
+ }
+
+ if (! isConst || (expr->getBasicType() != EbtInt && expr->getBasicType() != EbtUint)) {
+ error(loc, "array size must be a constant integer expression", "", "");
+ return;
+ }
+
+ if (sizePair.size <= 0) {
+ error(loc, "array size must be a positive integer", "", "");
+ return;
+ }
+}
+
+//
+// Require array to be completely sized
+//
+void HlslParseContext::arraySizeRequiredCheck(const TSourceLoc& loc, const TArraySizes& arraySizes)
+{
+ if (arraySizes.isImplicit())
+ error(loc, "array size required", "", "");
+}
+
+void HlslParseContext::structArrayCheck(const TSourceLoc& /*loc*/, const TType& type)
+{
+ const TTypeList& structure = *type.getStruct();
+ for (int m = 0; m < (int)structure.size(); ++m) {
+ const TType& member = *structure[m].type;
+ if (member.isArray())
+ arraySizeRequiredCheck(structure[m].loc, *member.getArraySizes());
+ }
+}
+
+// Merge array dimensions listed in 'sizes' onto the type's array dimensions.
+//
+// From the spec: "vec4[2] a[3]; // size-3 array of size-2 array of vec4"
+//
+// That means, the 'sizes' go in front of the 'type' as outermost sizes.
+// 'type' is the type part of the declaration (to the left)
+// 'sizes' is the arrayness tagged on the identifier (to the right)
+//
+void HlslParseContext::arrayDimMerge(TType& type, const TArraySizes* sizes)
+{
+ if (sizes)
+ type.addArrayOuterSizes(*sizes);
+}
+
+//
+// Do all the semantic checking for declaring or redeclaring an array, with and
+// without a size, and make the right changes to the symbol table.
+//
+void HlslParseContext::declareArray(const TSourceLoc& loc, TString& identifier, const TType& type, TSymbol*& symbol, bool& newDeclaration)
+{
+ if (! symbol) {
+ bool currentScope;
+ symbol = symbolTable.find(identifier, nullptr, ¤tScope);
+
+ if (symbol && builtInName(identifier) && ! symbolTable.atBuiltInLevel()) {
+ // bad shader (errors already reported) trying to redeclare a built-in name as an array
+ return;
+ }
+ if (symbol == nullptr || ! currentScope) {
+ //
+ // Successfully process a new definition.
+ // (Redeclarations have to take place at the same scope; otherwise they are hiding declarations)
+ //
+ symbol = new TVariable(&identifier, type);
+ symbolTable.insert(*symbol);
+ newDeclaration = true;
+
+ if (! symbolTable.atBuiltInLevel()) {
+ if (isIoResizeArray(type)) {
+ ioArraySymbolResizeList.push_back(symbol);
+ checkIoArraysConsistency(loc, true);
+ } else
+ fixIoArraySize(loc, symbol->getWritableType());
+ }
+
+ return;
+ }
+ if (symbol->getAsAnonMember()) {
+ error(loc, "cannot redeclare a user-block member array", identifier.c_str(), "");
+ symbol = nullptr;
+ return;
+ }
+ }
+
+ //
+ // Process a redeclaration.
+ //
+
+ if (! symbol) {
+ error(loc, "array variable name expected", identifier.c_str(), "");
+ return;
+ }
+
+ // redeclareBuiltinVariable() should have already done the copyUp()
+ TType& existingType = symbol->getWritableType();
+
+
+ if (existingType.isExplicitlySizedArray()) {
+ // be more lenient for input arrays to geometry shaders and tessellation control outputs, where the redeclaration is the same size
+ if (! (isIoResizeArray(type) && existingType.getOuterArraySize() == type.getOuterArraySize()))
+ error(loc, "redeclaration of array with size", identifier.c_str(), "");
+ return;
+ }
+
+ existingType.updateArraySizes(type);
+
+ if (isIoResizeArray(type))
+ checkIoArraysConsistency(loc);
+}
+
+void HlslParseContext::updateImplicitArraySize(const TSourceLoc& loc, TIntermNode *node, int index)
+{
+ // maybe there is nothing to do...
+ TIntermTyped* typedNode = node->getAsTyped();
+ if (typedNode->getType().getImplicitArraySize() > index)
+ return;
+
+ // something to do...
+
+ // Figure out what symbol to lookup, as we will use its type to edit for the size change,
+ // as that type will be shared through shallow copies for future references.
+ TSymbol* symbol = nullptr;
+ int blockIndex = -1;
+ const TString* lookupName = nullptr;
+ if (node->getAsSymbolNode())
+ lookupName = &node->getAsSymbolNode()->getName();
+ else if (node->getAsBinaryNode()) {
+ const TIntermBinary* deref = node->getAsBinaryNode();
+ // This has to be the result of a block dereference, unless it's bad shader code
+ // If it's a uniform block, then an error will be issued elsewhere, but
+ // return early now to avoid crashing later in this function.
+ if (! deref->getLeft()->getAsSymbolNode() || deref->getLeft()->getBasicType() != EbtBlock ||
+ deref->getLeft()->getType().getQualifier().storage == EvqUniform ||
+ deref->getRight()->getAsConstantUnion() == nullptr)
+ return;
+
+ blockIndex = deref->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
+
+ lookupName = &deref->getLeft()->getAsSymbolNode()->getName();
+ if (IsAnonymous(*lookupName))
+ lookupName = &(*deref->getLeft()->getType().getStruct())[blockIndex].type->getFieldName();
+ }
+
+ // Lookup the symbol, should only fail if shader code is incorrect
+ symbol = symbolTable.find(*lookupName);
+ if (symbol == nullptr)
+ return;
+
+ if (symbol->getAsFunction()) {
+ error(loc, "array variable name expected", symbol->getName().c_str(), "");
+ return;
+ }
+
+ symbol->getWritableType().setImplicitArraySize(index + 1);
+}
+
+//
+// See if the identifier is a built-in symbol that can be redeclared, and if so,
+// copy the symbol table's read-only built-in variable to the current
+// global level, where it can be modified based on the passed in type.
+//
+// Returns nullptr if no redeclaration took place; meaning a normal declaration still
+// needs to occur for it, not necessarily an error.
+//
+// Returns a redeclared and type-modified variable if a redeclared occurred.
+//
+TSymbol* HlslParseContext::redeclareBuiltinVariable(const TSourceLoc& loc, const TString& identifier, const TQualifier& qualifier, const TShaderQualifiers& publicType, bool& newDeclaration)
+{
+ if (! builtInName(identifier) || symbolTable.atBuiltInLevel() || ! symbolTable.atGlobalLevel())
+ return nullptr;
+
+ return nullptr;
+}
+
+//
+// Either redeclare the requested block, or give an error message why it can't be done.
+//
+// TODO: functionality: explicitly sizing members of redeclared blocks is not giving them an explicit size
+void HlslParseContext::redeclareBuiltinBlock(const TSourceLoc& loc, TTypeList& newTypeList, const TString& blockName, const TString* instanceName, TArraySizes* arraySizes)
+{
+ // Redeclaring a built-in block...
+
+ // Blocks with instance names are easy to find, lookup the instance name,
+ // Anonymous blocks need to be found via a member.
+ bool builtIn;
+ TSymbol* block;
+ if (instanceName)
+ block = symbolTable.find(*instanceName, &builtIn);
+ else
+ block = symbolTable.find(newTypeList.front().type->getFieldName(), &builtIn);
+
+ // If the block was not found, this must be a version/profile/stage
+ // that doesn't have it, or the instance name is wrong.
+ const char* errorName = instanceName ? instanceName->c_str() : newTypeList.front().type->getFieldName().c_str();
+ if (! block) {
+ error(loc, "no declaration found for redeclaration", errorName, "");
+ return;
+ }
+ // Built-in blocks cannot be redeclared more than once, which if happened,
+ // we'd be finding the already redeclared one here, rather than the built in.
+ if (! builtIn) {
+ error(loc, "can only redeclare a built-in block once, and before any use", blockName.c_str(), "");
+ return;
+ }
+
+ // Copy the block to make a writable version, to insert into the block table after editing.
+ block = symbolTable.copyUpDeferredInsert(block);
+
+ if (block->getType().getBasicType() != EbtBlock) {
+ error(loc, "cannot redeclare a non block as a block", errorName, "");
+ return;
+ }
+
+ // Edit and error check the container against the redeclaration
+ // - remove unused members
+ // - ensure remaining qualifiers/types match
+ TType& type = block->getWritableType();
+ TTypeList::iterator member = type.getWritableStruct()->begin();
+ size_t numOriginalMembersFound = 0;
+ while (member != type.getStruct()->end()) {
+ // look for match
+ bool found = false;
+ TTypeList::const_iterator newMember;
+ TSourceLoc memberLoc;
+ memberLoc.init();
+ for (newMember = newTypeList.begin(); newMember != newTypeList.end(); ++newMember) {
+ if (member->type->getFieldName() == newMember->type->getFieldName()) {
+ found = true;
+ memberLoc = newMember->loc;
+ break;
+ }
+ }
+
+ if (found) {
+ ++numOriginalMembersFound;
+ // - ensure match between redeclared members' types
+ // - check for things that can't be changed
+ // - update things that can be changed
+ TType& oldType = *member->type;
+ const TType& newType = *newMember->type;
+ if (! newType.sameElementType(oldType))
+ error(memberLoc, "cannot redeclare block member with a different type", member->type->getFieldName().c_str(), "");
+ if (oldType.isArray() != newType.isArray())
+ error(memberLoc, "cannot change arrayness of redeclared block member", member->type->getFieldName().c_str(), "");
+ else if (! oldType.sameArrayness(newType) && oldType.isExplicitlySizedArray())
+ error(memberLoc, "cannot change array size of redeclared block member", member->type->getFieldName().c_str(), "");
+ if (newType.getQualifier().isMemory())
+ error(memberLoc, "cannot add memory qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
+ if (newType.getQualifier().hasLayout())
+ error(memberLoc, "cannot add layout to redeclared block member", member->type->getFieldName().c_str(), "");
+ if (newType.getQualifier().patch)
+ error(memberLoc, "cannot add patch to redeclared block member", member->type->getFieldName().c_str(), "");
+ oldType.getQualifier().centroid = newType.getQualifier().centroid;
+ oldType.getQualifier().sample = newType.getQualifier().sample;
+ oldType.getQualifier().invariant = newType.getQualifier().invariant;
+ oldType.getQualifier().smooth = newType.getQualifier().smooth;
+ oldType.getQualifier().flat = newType.getQualifier().flat;
+ oldType.getQualifier().nopersp = newType.getQualifier().nopersp;
+
+ // go to next member
+ ++member;
+ } else {
+ // For missing members of anonymous blocks that have been redeclared,
+ // hide the original (shared) declaration.
+ // Instance-named blocks can just have the member removed.
+ if (instanceName)
+ member = type.getWritableStruct()->erase(member);
+ else {
+ member->type->hideMember();
+ ++member;
+ }
+ }
+ }
+
+ if (numOriginalMembersFound < newTypeList.size())
+ error(loc, "block redeclaration has extra members", blockName.c_str(), "");
+ if (type.isArray() != (arraySizes != nullptr))
+ error(loc, "cannot change arrayness of redeclared block", blockName.c_str(), "");
+ else if (type.isArray()) {
+ if (type.isExplicitlySizedArray() && arraySizes->getOuterSize() == UnsizedArraySize)
+ error(loc, "block already declared with size, can't redeclare as implicitly-sized", blockName.c_str(), "");
+ else if (type.isExplicitlySizedArray() && type.getArraySizes() != *arraySizes)
+ error(loc, "cannot change array size of redeclared block", blockName.c_str(), "");
+ else if (type.isImplicitlySizedArray() && arraySizes->getOuterSize() != UnsizedArraySize)
+ type.changeOuterArraySize(arraySizes->getOuterSize());
+ }
+
+ symbolTable.insert(*block);
+
+ // Tracking for implicit sizing of array
+ if (isIoResizeArray(block->getType())) {
+ ioArraySymbolResizeList.push_back(block);
+ checkIoArraysConsistency(loc, true);
+ } else if (block->getType().isArray())
+ fixIoArraySize(loc, block->getWritableType());
+
+ // Save it in the AST for linker use.
+ intermediate.addSymbolLinkageNode(linkage, *block);
+}
+
+void HlslParseContext::paramCheckFix(const TSourceLoc& loc, const TStorageQualifier& qualifier, TType& type)
+{
+ switch (qualifier) {
+ case EvqConst:
+ case EvqConstReadOnly:
+ type.getQualifier().storage = EvqConstReadOnly;
+ break;
+ case EvqIn:
+ case EvqOut:
+ case EvqInOut:
+ type.getQualifier().storage = qualifier;
+ break;
+ case EvqGlobal:
+ case EvqTemporary:
+ type.getQualifier().storage = EvqIn;
+ break;
+ default:
+ type.getQualifier().storage = EvqIn;
+ error(loc, "storage qualifier not allowed on function parameter", GetStorageQualifierString(qualifier), "");
+ break;
+ }
+}
+
+void HlslParseContext::paramCheckFix(const TSourceLoc& loc, const TQualifier& qualifier, TType& type)
+{
+ if (qualifier.isMemory()) {
+ type.getQualifier().volatil = qualifier.volatil;
+ type.getQualifier().coherent = qualifier.coherent;
+ type.getQualifier().readonly = qualifier.readonly;
+ type.getQualifier().writeonly = qualifier.writeonly;
+ type.getQualifier().restrict = qualifier.restrict;
+ }
+
+ paramCheckFix(loc, qualifier.storage, type);
+}
+
+void HlslParseContext::specializationCheck(const TSourceLoc& loc, const TType& type, const char* op)
+{
+ if (type.containsSpecializationSize())
+ error(loc, "can't use with types containing arrays sized with a specialization constant", op, "");
+}
+
+//
+// Layout qualifier stuff.
+//
+
+// Put the id's layout qualification into the public type, for qualifiers not having a number set.
+// This is before we know any type information for error checking.
+void HlslParseContext::setLayoutQualifier(const TSourceLoc& loc, TPublicType& publicType, TString& id)
+{
+ std::transform(id.begin(), id.end(), id.begin(), ::tolower);
+
+ if (id == TQualifier::getLayoutMatrixString(ElmColumnMajor)) {
+ publicType.qualifier.layoutMatrix = ElmColumnMajor;
+ return;
+ }
+ if (id == TQualifier::getLayoutMatrixString(ElmRowMajor)) {
+ publicType.qualifier.layoutMatrix = ElmRowMajor;
+ return;
+ }
+ if (id == TQualifier::getLayoutPackingString(ElpPacked)) {
+ if (vulkan > 0)
+ vulkanRemoved(loc, "packed");
+ publicType.qualifier.layoutPacking = ElpPacked;
+ return;
+ }
+ if (id == TQualifier::getLayoutPackingString(ElpShared)) {
+ if (vulkan > 0)
+ vulkanRemoved(loc, "shared");
+ publicType.qualifier.layoutPacking = ElpShared;
+ return;
+ }
+ if (id == "push_constant") {
+ requireVulkan(loc, "push_constant");
+ publicType.qualifier.layoutPushConstant = true;
+ return;
+ }
+ if (language == EShLangGeometry || language == EShLangTessEvaluation) {
+ if (id == TQualifier::getGeometryString(ElgTriangles)) {
+ publicType.shaderQualifiers.geometry = ElgTriangles;
+ return;
+ }
+ if (language == EShLangGeometry) {
+ if (id == TQualifier::getGeometryString(ElgPoints)) {
+ publicType.shaderQualifiers.geometry = ElgPoints;
+ return;
+ }
+ if (id == TQualifier::getGeometryString(ElgLineStrip)) {
+ publicType.shaderQualifiers.geometry = ElgLineStrip;
+ return;
+ }
+ if (id == TQualifier::getGeometryString(ElgLines)) {
+ publicType.shaderQualifiers.geometry = ElgLines;
+ return;
+ }
+ if (id == TQualifier::getGeometryString(ElgLinesAdjacency)) {
+ publicType.shaderQualifiers.geometry = ElgLinesAdjacency;
+ return;
+ }
+ if (id == TQualifier::getGeometryString(ElgTrianglesAdjacency)) {
+ publicType.shaderQualifiers.geometry = ElgTrianglesAdjacency;
+ return;
+ }
+ if (id == TQualifier::getGeometryString(ElgTriangleStrip)) {
+ publicType.shaderQualifiers.geometry = ElgTriangleStrip;
+ return;
+ }
+ } else {
+ assert(language == EShLangTessEvaluation);
+
+ // input primitive
+ if (id == TQualifier::getGeometryString(ElgTriangles)) {
+ publicType.shaderQualifiers.geometry = ElgTriangles;
+ return;
+ }
+ if (id == TQualifier::getGeometryString(ElgQuads)) {
+ publicType.shaderQualifiers.geometry = ElgQuads;
+ return;
+ }
+ if (id == TQualifier::getGeometryString(ElgIsolines)) {
+ publicType.shaderQualifiers.geometry = ElgIsolines;
+ return;
+ }
+
+ // vertex spacing
+ if (id == TQualifier::getVertexSpacingString(EvsEqual)) {
+ publicType.shaderQualifiers.spacing = EvsEqual;
+ return;
+ }
+ if (id == TQualifier::getVertexSpacingString(EvsFractionalEven)) {
+ publicType.shaderQualifiers.spacing = EvsFractionalEven;
+ return;
+ }
+ if (id == TQualifier::getVertexSpacingString(EvsFractionalOdd)) {
+ publicType.shaderQualifiers.spacing = EvsFractionalOdd;
+ return;
+ }
+
+ // triangle order
+ if (id == TQualifier::getVertexOrderString(EvoCw)) {
+ publicType.shaderQualifiers.order = EvoCw;
+ return;
+ }
+ if (id == TQualifier::getVertexOrderString(EvoCcw)) {
+ publicType.shaderQualifiers.order = EvoCcw;
+ return;
+ }
+
+ // point mode
+ if (id == "point_mode") {
+ publicType.shaderQualifiers.pointMode = true;
+ return;
+ }
+ }
+ }
+ if (language == EShLangFragment) {
+ if (id == "origin_upper_left") {
+ publicType.shaderQualifiers.originUpperLeft = true;
+ return;
+ }
+ if (id == "pixel_center_integer") {
+ publicType.shaderQualifiers.pixelCenterInteger = true;
+ return;
+ }
+ if (id == "early_fragment_tests") {
+ publicType.shaderQualifiers.earlyFragmentTests = true;
+ return;
+ }
+ for (TLayoutDepth depth = (TLayoutDepth)(EldNone + 1); depth < EldCount; depth = (TLayoutDepth)(depth + 1)) {
+ if (id == TQualifier::getLayoutDepthString(depth)) {
+ publicType.shaderQualifiers.layoutDepth = depth;
+ return;
+ }
+ }
+ if (id.compare(0, 13, "blend_support") == 0) {
+ bool found = false;
+ for (TBlendEquationShift be = (TBlendEquationShift)0; be < EBlendCount; be = (TBlendEquationShift)(be + 1)) {
+ if (id == TQualifier::getBlendEquationString(be)) {
+ requireExtensions(loc, 1, &E_GL_KHR_blend_equation_advanced, "blend equation");
+ intermediate.addBlendEquation(be);
+ publicType.shaderQualifiers.blendEquation = true;
+ found = true;
+ break;
+ }
+ }
+ if (! found)
+ error(loc, "unknown blend equation", "blend_support", "");
+ return;
+ }
+ }
+ error(loc, "unrecognized layout identifier, or qualifier requires assignment (e.g., binding = 4)", id.c_str(), "");
+}
+
+// Put the id's layout qualifier value into the public type, for qualifiers having a number set.
+// This is before we know any type information for error checking.
+void HlslParseContext::setLayoutQualifier(const TSourceLoc& loc, TPublicType& publicType, TString& id, const TIntermTyped* node)
+{
+ const char* feature = "layout-id value";
+ const char* nonLiteralFeature = "non-literal layout-id value";
+
+ integerCheck(node, feature);
+ const TIntermConstantUnion* constUnion = node->getAsConstantUnion();
+ int value = 0;
+ if (constUnion) {
+ value = constUnion->getConstArray()[0].getIConst();
+ }
+
+ std::transform(id.begin(), id.end(), id.begin(), ::tolower);
+
+ if (id == "offset") {
+ publicType.qualifier.layoutOffset = value;
+ return;
+ } else if (id == "align") {
+ // "The specified alignment must be a power of 2, or a compile-time error results."
+ if (! IsPow2(value))
+ error(loc, "must be a power of 2", "align", "");
+ else
+ publicType.qualifier.layoutAlign = value;
+ return;
+ } else if (id == "location") {
+ if ((unsigned int)value >= TQualifier::layoutLocationEnd)
+ error(loc, "location is too large", id.c_str(), "");
+ else
+ publicType.qualifier.layoutLocation = value;
+ return;
+ } else if (id == "set") {
+ if ((unsigned int)value >= TQualifier::layoutSetEnd)
+ error(loc, "set is too large", id.c_str(), "");
+ else
+ publicType.qualifier.layoutSet = value;
+ return;
+ } else if (id == "binding") {
+ if ((unsigned int)value >= TQualifier::layoutBindingEnd)
+ error(loc, "binding is too large", id.c_str(), "");
+ else
+ publicType.qualifier.layoutBinding = value;
+ return;
+ } else if (id == "component") {
+ if ((unsigned)value >= TQualifier::layoutComponentEnd)
+ error(loc, "component is too large", id.c_str(), "");
+ else
+ publicType.qualifier.layoutComponent = value;
+ return;
+ } else if (id.compare(0, 4, "xfb_") == 0) {
+ // "Any shader making any static use (after preprocessing) of any of these
+ // *xfb_* qualifiers will cause the shader to be in a transform feedback
+ // capturing mode and hence responsible for describing the transform feedback
+ // setup."
+ intermediate.setXfbMode();
+ if (id == "xfb_buffer") {
+ // "It is a compile-time error to specify an *xfb_buffer* that is greater than
+ // the implementation-dependent constant gl_MaxTransformFeedbackBuffers."
+ if (value >= resources.maxTransformFeedbackBuffers)
+ error(loc, "buffer is too large:", id.c_str(), "gl_MaxTransformFeedbackBuffers is %d", resources.maxTransformFeedbackBuffers);
+ if (value >= (int)TQualifier::layoutXfbBufferEnd)
+ error(loc, "buffer is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbBufferEnd - 1);
+ else
+ publicType.qualifier.layoutXfbBuffer = value;
+ return;
+ } else if (id == "xfb_offset") {
+ if (value >= (int)TQualifier::layoutXfbOffsetEnd)
+ error(loc, "offset is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbOffsetEnd - 1);
+ else
+ publicType.qualifier.layoutXfbOffset = value;
+ return;
+ } else if (id == "xfb_stride") {
+ // "The resulting stride (implicit or explicit), when divided by 4, must be less than or equal to the
+ // implementation-dependent constant gl_MaxTransformFeedbackInterleavedComponents."
+ if (value > 4 * resources.maxTransformFeedbackInterleavedComponents)
+ error(loc, "1/4 stride is too large:", id.c_str(), "gl_MaxTransformFeedbackInterleavedComponents is %d", resources.maxTransformFeedbackInterleavedComponents);
+ else if (value >= (int)TQualifier::layoutXfbStrideEnd)
+ error(loc, "stride is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbStrideEnd - 1);
+ if (value < (int)TQualifier::layoutXfbStrideEnd)
+ publicType.qualifier.layoutXfbStride = value;
+ return;
+ }
+ }
+
+ if (id == "input_attachment_index") {
+ requireVulkan(loc, "input_attachment_index");
+ if (value >= (int)TQualifier::layoutAttachmentEnd)
+ error(loc, "attachment index is too large", id.c_str(), "");
+ else
+ publicType.qualifier.layoutAttachment = value;
+ return;
+ }
+ if (id == "constant_id") {
+ requireSpv(loc, "constant_id");
+ if (value >= (int)TQualifier::layoutSpecConstantIdEnd) {
+ error(loc, "specialization-constant id is too large", id.c_str(), "");
+ } else {
+ publicType.qualifier.layoutSpecConstantId = value;
+ publicType.qualifier.specConstant = true;
+ if (! intermediate.addUsedConstantId(value))
+ error(loc, "specialization-constant id already used", id.c_str(), "");
+ }
+ return;
+ }
+
+ switch (language) {
+ case EShLangVertex:
+ break;
+
+ case EShLangTessControl:
+ if (id == "vertices") {
+ if (value == 0)
+ error(loc, "must be greater than 0", "vertices", "");
+ else
+ publicType.shaderQualifiers.vertices = value;
+ return;
+ }
+ break;
+
+ case EShLangTessEvaluation:
+ break;
+
+ case EShLangGeometry:
+ if (id == "invocations") {
+ if (value == 0)
+ error(loc, "must be at least 1", "invocations", "");
+ else
+ publicType.shaderQualifiers.invocations = value;
+ return;
+ }
+ if (id == "max_vertices") {
+ publicType.shaderQualifiers.vertices = value;
+ if (value > resources.maxGeometryOutputVertices)
+ error(loc, "too large, must be less than gl_MaxGeometryOutputVertices", "max_vertices", "");
+ return;
+ }
+ if (id == "stream") {
+ publicType.qualifier.layoutStream = value;
+ return;
+ }
+ break;
+
+ case EShLangFragment:
+ if (id == "index") {
+ const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location };
+ publicType.qualifier.layoutIndex = value;
+ return;
+ }
+ break;
+
+ case EShLangCompute:
+ if (id.compare(0, 11, "local_size_") == 0) {
+ if (id == "local_size_x") {
+ publicType.shaderQualifiers.localSize[0] = value;
+ return;
+ }
+ if (id == "local_size_y") {
+ publicType.shaderQualifiers.localSize[1] = value;
+ return;
+ }
+ if (id == "local_size_z") {
+ publicType.shaderQualifiers.localSize[2] = value;
+ return;
+ }
+ if (spv > 0) {
+ if (id == "local_size_x_id") {
+ publicType.shaderQualifiers.localSizeSpecId[0] = value;
+ return;
+ }
+ if (id == "local_size_y_id") {
+ publicType.shaderQualifiers.localSizeSpecId[1] = value;
+ return;
+ }
+ if (id == "local_size_z_id") {
+ publicType.shaderQualifiers.localSizeSpecId[2] = value;
+ return;
+ }
+ }
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ error(loc, "there is no such layout identifier for this stage taking an assigned value", id.c_str(), "");
+}
+
+// Merge any layout qualifier information from src into dst, leaving everything else in dst alone
+//
+// "More than one layout qualifier may appear in a single declaration.
+// Additionally, the same layout-qualifier-name can occur multiple times
+// within a layout qualifier or across multiple layout qualifiers in the
+// same declaration. When the same layout-qualifier-name occurs
+// multiple times, in a single declaration, the last occurrence overrides
+// the former occurrence(s). Further, if such a layout-qualifier-name
+// will effect subsequent declarations or other observable behavior, it
+// is only the last occurrence that will have any effect, behaving as if
+// the earlier occurrence(s) within the declaration are not present.
+// This is also true for overriding layout-qualifier-names, where one
+// overrides the other (e.g., row_major vs. column_major); only the last
+// occurrence has any effect."
+//
+void HlslParseContext::mergeObjectLayoutQualifiers(TQualifier& dst, const TQualifier& src, bool inheritOnly)
+{
+ if (src.hasMatrix())
+ dst.layoutMatrix = src.layoutMatrix;
+ if (src.hasPacking())
+ dst.layoutPacking = src.layoutPacking;
+
+ if (src.hasStream())
+ dst.layoutStream = src.layoutStream;
+
+ if (src.hasFormat())
+ dst.layoutFormat = src.layoutFormat;
+
+ if (src.hasXfbBuffer())
+ dst.layoutXfbBuffer = src.layoutXfbBuffer;
+
+ if (src.hasAlign())
+ dst.layoutAlign = src.layoutAlign;
+
+ if (! inheritOnly) {
+ if (src.hasLocation())
+ dst.layoutLocation = src.layoutLocation;
+ if (src.hasComponent())
+ dst.layoutComponent = src.layoutComponent;
+ if (src.hasIndex())
+ dst.layoutIndex = src.layoutIndex;
+
+ if (src.hasOffset())
+ dst.layoutOffset = src.layoutOffset;
+
+ if (src.hasSet())
+ dst.layoutSet = src.layoutSet;
+ if (src.layoutBinding != TQualifier::layoutBindingEnd)
+ dst.layoutBinding = src.layoutBinding;
+
+ if (src.hasXfbStride())
+ dst.layoutXfbStride = src.layoutXfbStride;
+ if (src.hasXfbOffset())
+ dst.layoutXfbOffset = src.layoutXfbOffset;
+ if (src.hasAttachment())
+ dst.layoutAttachment = src.layoutAttachment;
+ if (src.hasSpecConstantId())
+ dst.layoutSpecConstantId = src.layoutSpecConstantId;
+
+ if (src.layoutPushConstant)
+ dst.layoutPushConstant = true;
+ }
+}
+
+//
+// Look up a function name in the symbol table, and make sure it is a function.
+//
+// Return the function symbol if found, otherwise nullptr.
+//
+const TFunction* HlslParseContext::findFunction(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
+{
+ const TFunction* function = nullptr;
+
+ if (symbolTable.isFunctionNameVariable(call.getName())) {
+ error(loc, "can't use function syntax on variable", call.getName().c_str(), "");
+ return nullptr;
+ }
+
+ // first, look for an exact match
+ TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
+ if (symbol)
+ return symbol->getAsFunction();
+
+ // exact match not found, look through a list of overloaded functions of the same name
+
+ const TFunction* candidate = nullptr;
+ TVector<TFunction*> candidateList;
+ symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
+
+ for (TVector<TFunction*>::const_iterator it = candidateList.begin(); it != candidateList.end(); ++it) {
+ const TFunction& function = *(*it);
+
+ // to even be a potential match, number of arguments has to match
+ if (call.getParamCount() != function.getParamCount())
+ continue;
+
+ bool possibleMatch = true;
+ for (int i = 0; i < function.getParamCount(); ++i) {
+ // same types is easy
+ if (*function[i].type == *call[i].type)
+ continue;
+
+ // We have a mismatch in type, see if it is implicitly convertible
+
+ if (function[i].type->isArray() || call[i].type->isArray() ||
+ ! function[i].type->sameElementShape(*call[i].type))
+ possibleMatch = false;
+ else {
+ // do direction-specific checks for conversion of basic type
+ if (function[i].type->getQualifier().isParamInput()) {
+ if (! intermediate.canImplicitlyPromote(call[i].type->getBasicType(), function[i].type->getBasicType()))
+ possibleMatch = false;
+ }
+ if (function[i].type->getQualifier().isParamOutput()) {
+ if (! intermediate.canImplicitlyPromote(function[i].type->getBasicType(), call[i].type->getBasicType()))
+ possibleMatch = false;
+ }
+ }
+ if (! possibleMatch)
+ break;
+ }
+ if (possibleMatch) {
+ if (candidate) {
+ // our second match, meaning ambiguity
+ error(loc, "ambiguous function signature match: multiple signatures match under implicit type conversion", call.getName().c_str(), "");
+ } else
+ candidate = &function;
+ }
+ }
+
+ if (candidate == nullptr)
+ error(loc, "no matching overloaded function found", call.getName().c_str(), "");
+
+ return candidate;
+}
+
+//
+// Do everything necessary to handle a variable (non-block) declaration.
+// Either redeclaring a variable, or making a new one, updating the symbol
+// table, and all error checking.
+//
+// Returns a subtree node that computes an initializer, if needed.
+// Returns nullptr if there is no code to execute for initialization.
+//
+// 'publicType' is the type part of the declaration (to the left)
+// 'arraySizes' is the arrayness tagged on the identifier (to the right)
+//
+TIntermNode* HlslParseContext::declareVariable(const TSourceLoc& loc, TString& identifier, const TType& parseType, TArraySizes* arraySizes, TIntermTyped* initializer)
+{
+ TType type;
+ type.shallowCopy(parseType);
+ if (type.isImplicitlySizedArray()) {
+ // Because "int[] a = int[2](...), b = int[3](...)" makes two arrays a and b
+ // of different sizes, for this case sharing the shallow copy of arrayness
+ // with the publicType oversubscribes it, so get a deep copy of the arrayness.
+ type.newArraySizes(*parseType.getArraySizes());
+ }
+
+ if (voidErrorCheck(loc, identifier, type.getBasicType()))
+ return nullptr;
+
+ // Check for redeclaration of built-ins and/or attempting to declare a reserved name
+ bool newDeclaration = false; // true if a new entry gets added to the symbol table
+ TSymbol* symbol = nullptr; // = redeclareBuiltinVariable(loc, identifier, type.getQualifier(), publicType.shaderQualifiers, newDeclaration);
+
+ inheritGlobalDefaults(type.getQualifier());
+
+ // Declare the variable
+ if (arraySizes || type.isArray()) {
+ // Arrayness is potentially coming both from the type and from the
+ // variable: "int[] a[];" or just one or the other.
+ // Merge it all to the type, so all arrayness is part of the type.
+ arrayDimMerge(type, arraySizes);
+ declareArray(loc, identifier, type, symbol, newDeclaration);
+ } else {
+ // non-array case
+ if (! symbol)
+ symbol = declareNonArray(loc, identifier, type, newDeclaration);
+ else if (type != symbol->getType())
+ error(loc, "cannot change the type of", "redeclaration", symbol->getName().c_str());
+ }
+
+ if (! symbol)
+ return nullptr;
+
+ // Deal with initializer
+ TIntermNode* initNode = nullptr;
+ if (symbol && initializer) {
+ TVariable* variable = symbol->getAsVariable();
+ if (! variable) {
+ error(loc, "initializer requires a variable, not a member", identifier.c_str(), "");
+ return nullptr;
+ }
+ initNode = executeInitializer(loc, initializer, variable);
+ }
+
+ // see if it's a linker-level object to track
+ if (newDeclaration && symbolTable.atGlobalLevel())
+ intermediate.addSymbolLinkageNode(linkage, *symbol);
+
+ return initNode;
+}
+
+// Pick up global defaults from the provide global defaults into dst.
+void HlslParseContext::inheritGlobalDefaults(TQualifier& dst) const
+{
+ if (dst.storage == EvqVaryingOut) {
+ if (! dst.hasStream() && language == EShLangGeometry)
+ dst.layoutStream = globalOutputDefaults.layoutStream;
+ if (! dst.hasXfbBuffer())
+ dst.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
+ }
+}
+
+//
+// Make an internal-only variable whose name is for debug purposes only
+// and won't be searched for. Callers will only use the return value to use
+// the variable, not the name to look it up. It is okay if the name
+// is the same as other names; there won't be any conflict.
+//
+TVariable* HlslParseContext::makeInternalVariable(const char* name, const TType& type) const
+{
+ TString* nameString = new TString(name);
+ TVariable* variable = new TVariable(nameString, type);
+ symbolTable.makeInternalVariable(*variable);
+
+ return variable;
+}
+
+//
+// Declare a non-array variable, the main point being there is no redeclaration
+// for resizing allowed.
+//
+// Return the successfully declared variable.
+//
+TVariable* HlslParseContext::declareNonArray(const TSourceLoc& loc, TString& identifier, TType& type, bool& newDeclaration)
+{
+ // make a new variable
+ TVariable* variable = new TVariable(&identifier, type);
+
+ // add variable to symbol table
+ if (! symbolTable.insert(*variable)) {
+ error(loc, "redefinition", variable->getName().c_str(), "");
+ return nullptr;
+ } else {
+ newDeclaration = true;
+ return variable;
+ }
+}
+
+//
+// Handle all types of initializers from the grammar.
+//
+// Returning nullptr just means there is no code to execute to handle the
+// initializer, which will, for example, be the case for constant initializers.
+//
+TIntermNode* HlslParseContext::executeInitializer(const TSourceLoc& loc, TIntermTyped* initializer, TVariable* variable)
+{
+ //
+ // Identifier must be of type constant, a global, or a temporary, and
+ // starting at version 120, desktop allows uniforms to have initializers.
+ //
+ TStorageQualifier qualifier = variable->getType().getQualifier().storage;
+
+ //
+ // If the initializer was from braces { ... }, we convert the whole subtree to a
+ // constructor-style subtree, allowing the rest of the code to operate
+ // identically for both kinds of initializers.
+ //
+ initializer = convertInitializerList(loc, variable->getType(), initializer);
+ if (! initializer) {
+ // error recovery; don't leave const without constant values
+ if (qualifier == EvqConst)
+ variable->getWritableType().getQualifier().storage = EvqTemporary;
+ return nullptr;
+ }
+
+ // Fix outer arrayness if variable is unsized, getting size from the initializer
+ if (initializer->getType().isExplicitlySizedArray() &&
+ variable->getType().isImplicitlySizedArray())
+ variable->getWritableType().changeOuterArraySize(initializer->getType().getOuterArraySize());
+
+ // Inner arrayness can also get set by an initializer
+ if (initializer->getType().isArrayOfArrays() && variable->getType().isArrayOfArrays() &&
+ initializer->getType().getArraySizes()->getNumDims() ==
+ variable->getType().getArraySizes()->getNumDims()) {
+ // adopt unsized sizes from the initializer's sizes
+ for (int d = 1; d < variable->getType().getArraySizes()->getNumDims(); ++d) {
+ if (variable->getType().getArraySizes()->getDimSize(d) == UnsizedArraySize)
+ variable->getWritableType().getArraySizes().setDimSize(d, initializer->getType().getArraySizes()->getDimSize(d));
+ }
+ }
+
+ // Uniform and global consts require a constant initializer
+ if (qualifier == EvqUniform && initializer->getType().getQualifier().storage != EvqConst) {
+ error(loc, "uniform initializers must be constant", "=", "'%s'", variable->getType().getCompleteString().c_str());
+ variable->getWritableType().getQualifier().storage = EvqTemporary;
+ return nullptr;
+ }
+ if (qualifier == EvqConst && symbolTable.atGlobalLevel() && initializer->getType().getQualifier().storage != EvqConst) {
+ error(loc, "global const initializers must be constant", "=", "'%s'", variable->getType().getCompleteString().c_str());
+ variable->getWritableType().getQualifier().storage = EvqTemporary;
+ return nullptr;
+ }
+
+ // Const variables require a constant initializer, depending on version
+ if (qualifier == EvqConst) {
+ if (initializer->getType().getQualifier().storage != EvqConst) {
+ variable->getWritableType().getQualifier().storage = EvqConstReadOnly;
+ qualifier = EvqConstReadOnly;
+ }
+ }
+
+ if (qualifier == EvqConst || qualifier == EvqUniform) {
+ // Compile-time tagging of the variable with its constant value...
+
+ initializer = intermediate.addConversion(EOpAssign, variable->getType(), initializer);
+ if (! initializer || ! initializer->getAsConstantUnion() || variable->getType() != initializer->getType()) {
+ error(loc, "non-matching or non-convertible constant type for const initializer",
+ variable->getType().getStorageQualifierString(), "");
+ variable->getWritableType().getQualifier().storage = EvqTemporary;
+ return nullptr;
+ }
+
+ variable->setConstArray(initializer->getAsConstantUnion()->getConstArray());
+ } else {
+ // normal assigning of a value to a variable...
+ specializationCheck(loc, initializer->getType(), "initializer");
+ TIntermSymbol* intermSymbol = intermediate.addSymbol(*variable, loc);
+ TIntermNode* initNode = intermediate.addAssign(EOpAssign, intermSymbol, initializer, loc);
+ if (! initNode)
+ assignError(loc, "=", intermSymbol->getCompleteString(), initializer->getCompleteString());
+
+ return initNode;
+ }
+
+ return nullptr;
+}
+
+//
+// Reprocess any initializer-list { ... } parts of the initializer.
+// Need to hierarchically assign correct types and implicit
+// conversions. Will do this mimicking the same process used for
+// creating a constructor-style initializer, ensuring we get the
+// same form.
+//
+TIntermTyped* HlslParseContext::convertInitializerList(const TSourceLoc& loc, const TType& type, TIntermTyped* initializer)
+{
+ // Will operate recursively. Once a subtree is found that is constructor style,
+ // everything below it is already good: Only the "top part" of the initializer
+ // can be an initializer list, where "top part" can extend for several (or all) levels.
+
+ // see if we have bottomed out in the tree within the initializer-list part
+ TIntermAggregate* initList = initializer->getAsAggregate();
+ if (! initList || initList->getOp() != EOpNull)
+ return initializer;
+
+ // Of the initializer-list set of nodes, need to process bottom up,
+ // so recurse deep, then process on the way up.
+
+ // Go down the tree here...
+ if (type.isArray()) {
+ // The type's array might be unsized, which could be okay, so base sizes on the size of the aggregate.
+ // Later on, initializer execution code will deal with array size logic.
+ TType arrayType;
+ arrayType.shallowCopy(type); // sharing struct stuff is fine
+ arrayType.newArraySizes(*type.getArraySizes()); // but get a fresh copy of the array information, to edit below
+
+ // edit array sizes to fill in unsized dimensions
+ arrayType.changeOuterArraySize((int)initList->getSequence().size());
+ TIntermTyped* firstInit = initList->getSequence()[0]->getAsTyped();
+ if (arrayType.isArrayOfArrays() && firstInit->getType().isArray() &&
+ arrayType.getArraySizes().getNumDims() == firstInit->getType().getArraySizes()->getNumDims() + 1) {
+ for (int d = 1; d < arrayType.getArraySizes().getNumDims(); ++d) {
+ if (arrayType.getArraySizes().getDimSize(d) == UnsizedArraySize)
+ arrayType.getArraySizes().setDimSize(d, firstInit->getType().getArraySizes()->getDimSize(d - 1));
+ }
+ }
+
+ TType elementType(arrayType, 0); // dereferenced type
+ for (size_t i = 0; i < initList->getSequence().size(); ++i) {
+ initList->getSequence()[i] = convertInitializerList(loc, elementType, initList->getSequence()[i]->getAsTyped());
+ if (initList->getSequence()[i] == nullptr)
+ return nullptr;
+ }
+
+ return addConstructor(loc, initList, arrayType, mapTypeToConstructorOp(arrayType));
+ } else if (type.isStruct()) {
+ if (type.getStruct()->size() != initList->getSequence().size()) {
+ error(loc, "wrong number of structure members", "initializer list", "");
+ return nullptr;
+ }
+ for (size_t i = 0; i < type.getStruct()->size(); ++i) {
+ initList->getSequence()[i] = convertInitializerList(loc, *(*type.getStruct())[i].type, initList->getSequence()[i]->getAsTyped());
+ if (initList->getSequence()[i] == nullptr)
+ return nullptr;
+ }
+ } else if (type.isMatrix()) {
+ if (type.getMatrixCols() != (int)initList->getSequence().size()) {
+ error(loc, "wrong number of matrix columns:", "initializer list", type.getCompleteString().c_str());
+ return nullptr;
+ }
+ TType vectorType(type, 0); // dereferenced type
+ for (int i = 0; i < type.getMatrixCols(); ++i) {
+ initList->getSequence()[i] = convertInitializerList(loc, vectorType, initList->getSequence()[i]->getAsTyped());
+ if (initList->getSequence()[i] == nullptr)
+ return nullptr;
+ }
+ } else if (type.isVector()) {
+ if (type.getVectorSize() != (int)initList->getSequence().size()) {
+ error(loc, "wrong vector size (or rows in a matrix column):", "initializer list", type.getCompleteString().c_str());
+ return nullptr;
+ }
+ } else {
+ error(loc, "unexpected initializer-list type:", "initializer list", type.getCompleteString().c_str());
+ return nullptr;
+ }
+
+ // now that the subtree is processed, process this node
+ return addConstructor(loc, initList, type, mapTypeToConstructorOp(type));
+}
+
+//
+// Test for the correctness of the parameters passed to various constructor functions
+// and also convert them to the right data type, if allowed and required.
+//
+// Returns nullptr for an error or the constructed node (aggregate or typed) for no error.
+//
+TIntermTyped* HlslParseContext::addConstructor(const TSourceLoc& loc, TIntermNode* node, const TType& type, TOperator op)
+{
+ if (node == nullptr || node->getAsTyped() == nullptr)
+ return nullptr;
+
+ TIntermAggregate* aggrNode = node->getAsAggregate();
+
+ // Combined texture-sampler constructors are completely semantic checked
+ // in constructorTextureSamplerError()
+ if (op == EOpConstructTextureSampler)
+ return intermediate.setAggregateOperator(aggrNode, op, type, loc);
+
+ TTypeList::const_iterator memberTypes;
+ if (op == EOpConstructStruct)
+ memberTypes = type.getStruct()->begin();
+
+ TType elementType;
+ if (type.isArray()) {
+ TType dereferenced(type, 0);
+ elementType.shallowCopy(dereferenced);
+ } else
+ elementType.shallowCopy(type);
+
+ bool singleArg;
+ if (aggrNode) {
+ if (aggrNode->getOp() != EOpNull || aggrNode->getSequence().size() == 1)
+ singleArg = true;
+ else
+ singleArg = false;
+ } else
+ singleArg = true;
+
+ TIntermTyped *newNode;
+ if (singleArg) {
+ // If structure constructor or array constructor is being called
+ // for only one parameter inside the structure, we need to call constructAggregate function once.
+ if (type.isArray())
+ newNode = constructAggregate(node, elementType, 1, node->getLoc());
+ else if (op == EOpConstructStruct)
+ newNode = constructAggregate(node, *(*memberTypes).type, 1, node->getLoc());
+ else
+ newNode = constructBuiltIn(type, op, node->getAsTyped(), node->getLoc(), false);
+
+ if (newNode && (type.isArray() || op == EOpConstructStruct))
+ newNode = intermediate.setAggregateOperator(newNode, EOpConstructStruct, type, loc);
+
+ return newNode;
+ }
+
+ //
+ // Handle list of arguments.
+ //
+ TIntermSequence &sequenceVector = aggrNode->getSequence(); // Stores the information about the parameter to the constructor
+ // if the structure constructor contains more than one parameter, then construct
+ // each parameter
+
+ int paramCount = 0; // keeps a track of the constructor parameter number being checked
+
+ // for each parameter to the constructor call, check to see if the right type is passed or convert them
+ // to the right type if possible (and allowed).
+ // for structure constructors, just check if the right type is passed, no conversion is allowed.
+
+ for (TIntermSequence::iterator p = sequenceVector.begin();
+ p != sequenceVector.end(); p++, paramCount++) {
+ if (type.isArray())
+ newNode = constructAggregate(*p, elementType, paramCount + 1, node->getLoc());
+ else if (op == EOpConstructStruct)
+ newNode = constructAggregate(*p, *(memberTypes[paramCount]).type, paramCount + 1, node->getLoc());
+ else
+ newNode = constructBuiltIn(type, op, (*p)->getAsTyped(), node->getLoc(), true);
+
+ if (newNode)
+ *p = newNode;
+ else
+ return nullptr;
+ }
+
+ TIntermTyped* constructor = intermediate.setAggregateOperator(aggrNode, op, type, loc);
+
+ return constructor;
+}
+
+// Function for constructor implementation. Calls addUnaryMath with appropriate EOp value
+// for the parameter to the constructor (passed to this function). Essentially, it converts
+// the parameter types correctly. If a constructor expects an int (like ivec2) and is passed a
+// float, then float is converted to int.
+//
+// Returns nullptr for an error or the constructed node.
+//
+TIntermTyped* HlslParseContext::constructBuiltIn(const TType& type, TOperator op, TIntermTyped* node, const TSourceLoc& loc, bool subset)
+{
+ TIntermTyped* newNode;
+ TOperator basicOp;
+
+ //
+ // First, convert types as needed.
+ //
+ switch (op) {
+ case EOpConstructVec2:
+ case EOpConstructVec3:
+ case EOpConstructVec4:
+ case EOpConstructMat2x2:
+ case EOpConstructMat2x3:
+ case EOpConstructMat2x4:
+ case EOpConstructMat3x2:
+ case EOpConstructMat3x3:
+ case EOpConstructMat3x4:
+ case EOpConstructMat4x2:
+ case EOpConstructMat4x3:
+ case EOpConstructMat4x4:
+ case EOpConstructFloat:
+ basicOp = EOpConstructFloat;
+ break;
+
+ case EOpConstructDVec2:
+ case EOpConstructDVec3:
+ case EOpConstructDVec4:
+ case EOpConstructDMat2x2:
+ case EOpConstructDMat2x3:
+ case EOpConstructDMat2x4:
+ case EOpConstructDMat3x2:
+ case EOpConstructDMat3x3:
+ case EOpConstructDMat3x4:
+ case EOpConstructDMat4x2:
+ case EOpConstructDMat4x3:
+ case EOpConstructDMat4x4:
+ case EOpConstructDouble:
+ basicOp = EOpConstructDouble;
+ break;
+
+ case EOpConstructIVec2:
+ case EOpConstructIVec3:
+ case EOpConstructIVec4:
+ case EOpConstructInt:
+ basicOp = EOpConstructInt;
+ break;
+
+ case EOpConstructUVec2:
+ case EOpConstructUVec3:
+ case EOpConstructUVec4:
+ case EOpConstructUint:
+ basicOp = EOpConstructUint;
+ break;
+
+ case EOpConstructBVec2:
+ case EOpConstructBVec3:
+ case EOpConstructBVec4:
+ case EOpConstructBool:
+ basicOp = EOpConstructBool;
+ break;
+
+ default:
+ error(loc, "unsupported construction", "", "");
+
+ return nullptr;
+ }
+ newNode = intermediate.addUnaryMath(basicOp, node, node->getLoc());
+ if (newNode == nullptr) {
+ error(loc, "can't convert", "constructor", "");
+ return nullptr;
+ }
+
+ //
+ // Now, if there still isn't an operation to do the construction, and we need one, add one.
+ //
+
+ // Otherwise, skip out early.
+ if (subset || (newNode != node && newNode->getType() == type))
+ return newNode;
+
+ // setAggregateOperator will insert a new node for the constructor, as needed.
+ return intermediate.setAggregateOperator(newNode, op, type, loc);
+}
+
+// This function tests for the type of the parameters to the structure or array constructor. Raises
+// an error message if the expected type does not match the parameter passed to the constructor.
+//
+// Returns nullptr for an error or the input node itself if the expected and the given parameter types match.
+//
+TIntermTyped* HlslParseContext::constructAggregate(TIntermNode* node, const TType& type, int paramCount, const TSourceLoc& loc)
+{
+ TIntermTyped* converted = intermediate.addConversion(EOpConstructStruct, type, node->getAsTyped());
+ if (! converted || converted->getType() != type) {
+ error(loc, "", "constructor", "cannot convert parameter %d from '%s' to '%s'", paramCount,
+ node->getAsTyped()->getType().getCompleteString().c_str(), type.getCompleteString().c_str());
+
+ return nullptr;
+ }
+
+ return converted;
+}
+
+//
+// Do everything needed to add an interface block.
+//
+void HlslParseContext::declareBlock(const TSourceLoc& loc, TTypeList& typeList, const TString* instanceName, TArraySizes* arraySizes)
+{
+ // fix and check for member storage qualifiers and types that don't belong within a block
+ for (unsigned int member = 0; member < typeList.size(); ++member) {
+ TType& memberType = *typeList[member].type;
+ TQualifier& memberQualifier = memberType.getQualifier();
+ const TSourceLoc& memberLoc = typeList[member].loc;
+ globalQualifierFix(memberLoc, memberQualifier);
+ memberQualifier.storage = currentBlockQualifier.storage;
+ }
+
+ // This might be a redeclaration of a built-in block. If so, redeclareBuiltinBlock() will
+ // do all the rest.
+ if (! symbolTable.atBuiltInLevel() && builtInName(*blockName)) {
+ redeclareBuiltinBlock(loc, typeList, *blockName, instanceName, arraySizes);
+ return;
+ }
+
+ // Make default block qualification, and adjust the member qualifications
+
+ TQualifier defaultQualification;
+ switch (currentBlockQualifier.storage) {
+ case EvqUniform: defaultQualification = globalUniformDefaults; break;
+ case EvqBuffer: defaultQualification = globalBufferDefaults; break;
+ case EvqVaryingIn: defaultQualification = globalInputDefaults; break;
+ case EvqVaryingOut: defaultQualification = globalOutputDefaults; break;
+ default: defaultQualification.clear(); break;
+ }
+
+ // Special case for "push_constant uniform", which has a default of std430,
+ // contrary to normal uniform defaults, and can't have a default tracked for it.
+ if (currentBlockQualifier.layoutPushConstant && ! currentBlockQualifier.hasPacking())
+ currentBlockQualifier.layoutPacking = ElpStd430;
+
+ // fix and check for member layout qualifiers
+
+ mergeObjectLayoutQualifiers(defaultQualification, currentBlockQualifier, true);
+
+ bool memberWithLocation = false;
+ bool memberWithoutLocation = false;
+ for (unsigned int member = 0; member < typeList.size(); ++member) {
+ TQualifier& memberQualifier = typeList[member].type->getQualifier();
+ const TSourceLoc& memberLoc = typeList[member].loc;
+ if (memberQualifier.hasStream()) {
+ if (defaultQualification.layoutStream != memberQualifier.layoutStream)
+ error(memberLoc, "member cannot contradict block", "stream", "");
+ }
+
+ // "This includes a block's inheritance of the
+ // current global default buffer, a block member's inheritance of the block's
+ // buffer, and the requirement that any *xfb_buffer* declared on a block
+ // member must match the buffer inherited from the block."
+ if (memberQualifier.hasXfbBuffer()) {
+ if (defaultQualification.layoutXfbBuffer != memberQualifier.layoutXfbBuffer)
+ error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_buffer", "");
+ }
+
+ if (memberQualifier.hasPacking())
+ error(memberLoc, "member of block cannot have a packing layout qualifier", typeList[member].type->getFieldName().c_str(), "");
+ if (memberQualifier.hasLocation()) {
+ switch (currentBlockQualifier.storage) {
+ case EvqVaryingIn:
+ case EvqVaryingOut:
+ memberWithLocation = true;
+ break;
+ default:
+ break;
+ }
+ } else
+ memberWithoutLocation = true;
+ if (memberQualifier.hasAlign()) {
+ if (defaultQualification.layoutPacking != ElpStd140 && defaultQualification.layoutPacking != ElpStd430)
+ error(memberLoc, "can only be used with std140 or std430 layout packing", "align", "");
+ }
+
+ TQualifier newMemberQualification = defaultQualification;
+ mergeQualifiers(memberLoc, newMemberQualification, memberQualifier, false);
+ memberQualifier = newMemberQualification;
+ }
+
+ // Process the members
+ fixBlockLocations(loc, currentBlockQualifier, typeList, memberWithLocation, memberWithoutLocation);
+ fixBlockXfbOffsets(currentBlockQualifier, typeList);
+ fixBlockUniformOffsets(currentBlockQualifier, typeList);
+
+ // reverse merge, so that currentBlockQualifier now has all layout information
+ // (can't use defaultQualification directly, it's missing other non-layout-default-class qualifiers)
+ mergeObjectLayoutQualifiers(currentBlockQualifier, defaultQualification, true);
+
+ //
+ // Build and add the interface block as a new type named 'blockName'
+ //
+
+ TType blockType(&typeList, *blockName, currentBlockQualifier);
+ if (arraySizes)
+ blockType.newArraySizes(*arraySizes);
+
+ //
+ // Don't make a user-defined type out of block name; that will cause an error
+ // if the same block name gets reused in a different interface.
+ //
+ // "Block names have no other use within a shader
+ // beyond interface matching; it is a compile-time error to use a block name at global scope for anything
+ // other than as a block name (e.g., use of a block name for a global variable name or function name is
+ // currently reserved)."
+ //
+ // Use the symbol table to prevent normal reuse of the block's name, as a variable entry,
+ // whose type is EbtBlock, but without all the structure; that will come from the type
+ // the instances point to.
+ //
+ TType blockNameType(EbtBlock, blockType.getQualifier().storage);
+ TVariable* blockNameVar = new TVariable(blockName, blockNameType);
+ if (! symbolTable.insert(*blockNameVar)) {
+ TSymbol* existingName = symbolTable.find(*blockName);
+ if (existingName->getType().getBasicType() == EbtBlock) {
+ if (existingName->getType().getQualifier().storage == blockType.getQualifier().storage) {
+ error(loc, "Cannot reuse block name within the same interface:", blockName->c_str(), blockType.getStorageQualifierString());
+ return;
+ }
+ } else {
+ error(loc, "block name cannot redefine a non-block name", blockName->c_str(), "");
+ return;
+ }
+ }
+
+ // Add the variable, as anonymous or named instanceName.
+ // Make an anonymous variable if no name was provided.
+ if (! instanceName)
+ instanceName = NewPoolTString("");
+
+ TVariable& variable = *new TVariable(instanceName, blockType);
+ if (! symbolTable.insert(variable)) {
+ if (*instanceName == "")
+ error(loc, "nameless block contains a member that already has a name at global scope", blockName->c_str(), "");
+ else
+ error(loc, "block instance name redefinition", variable.getName().c_str(), "");
+
+ return;
+ }
+
+ if (isIoResizeArray(blockType)) {
+ ioArraySymbolResizeList.push_back(&variable);
+ checkIoArraysConsistency(loc, true);
+ } else
+ fixIoArraySize(loc, variable.getWritableType());
+
+ // Save it in the AST for linker use.
+ intermediate.addSymbolLinkageNode(linkage, variable);
+}
+
+//
+// "For a block, this process applies to the entire block, or until the first member
+// is reached that has a location layout qualifier. When a block member is declared with a location
+// qualifier, its location comes from that qualifier: The member's location qualifier overrides the block-level
+// declaration. Subsequent members are again assigned consecutive locations, based on the newest location,
+// until the next member declared with a location qualifier. The values used for locations do not have to be
+// declared in increasing order."
+void HlslParseContext::fixBlockLocations(const TSourceLoc& loc, TQualifier& qualifier, TTypeList& typeList, bool memberWithLocation, bool memberWithoutLocation)
+{
+ // "If a block has no block-level location layout qualifier, it is required that either all or none of its members
+ // have a location layout qualifier, or a compile-time error results."
+ if (! qualifier.hasLocation() && memberWithLocation && memberWithoutLocation)
+ error(loc, "either the block needs a location, or all members need a location, or no members have a location", "location", "");
+ else {
+ if (memberWithLocation) {
+ // remove any block-level location and make it per *every* member
+ int nextLocation = 0; // by the rule above, initial value is not relevant
+ if (qualifier.hasAnyLocation()) {
+ nextLocation = qualifier.layoutLocation;
+ qualifier.layoutLocation = TQualifier::layoutLocationEnd;
+ if (qualifier.hasComponent()) {
+ // "It is a compile-time error to apply the *component* qualifier to a ... block"
+ error(loc, "cannot apply to a block", "component", "");
+ }
+ if (qualifier.hasIndex()) {
+ error(loc, "cannot apply to a block", "index", "");
+ }
+ }
+ for (unsigned int member = 0; member < typeList.size(); ++member) {
+ TQualifier& memberQualifier = typeList[member].type->getQualifier();
+ const TSourceLoc& memberLoc = typeList[member].loc;
+ if (! memberQualifier.hasLocation()) {
+ if (nextLocation >= (int)TQualifier::layoutLocationEnd)
+ error(memberLoc, "location is too large", "location", "");
+ memberQualifier.layoutLocation = nextLocation;
+ memberQualifier.layoutComponent = 0;
+ }
+ nextLocation = memberQualifier.layoutLocation + intermediate.computeTypeLocationSize(*typeList[member].type);
+ }
+ }
+ }
+}
+
+void HlslParseContext::fixBlockXfbOffsets(TQualifier& qualifier, TTypeList& typeList)
+{
+ // "If a block is qualified with xfb_offset, all its
+ // members are assigned transform feedback buffer offsets. If a block is not qualified with xfb_offset, any
+ // members of that block not qualified with an xfb_offset will not be assigned transform feedback buffer
+ // offsets."
+
+ if (! qualifier.hasXfbBuffer() || ! qualifier.hasXfbOffset())
+ return;
+
+ int nextOffset = qualifier.layoutXfbOffset;
+ for (unsigned int member = 0; member < typeList.size(); ++member) {
+ TQualifier& memberQualifier = typeList[member].type->getQualifier();
+ bool containsDouble = false;
+ int memberSize = intermediate.computeTypeXfbSize(*typeList[member].type, containsDouble);
+ // see if we need to auto-assign an offset to this member
+ if (! memberQualifier.hasXfbOffset()) {
+ // "if applied to an aggregate containing a double, the offset must also be a multiple of 8"
+ if (containsDouble)
+ RoundToPow2(nextOffset, 8);
+ memberQualifier.layoutXfbOffset = nextOffset;
+ } else
+ nextOffset = memberQualifier.layoutXfbOffset;
+ nextOffset += memberSize;
+ }
+
+ // The above gave all block members an offset, so we can take it off the block now,
+ // which will avoid double counting the offset usage.
+ qualifier.layoutXfbOffset = TQualifier::layoutXfbOffsetEnd;
+}
+
+// Calculate and save the offset of each block member, using the recursively
+// defined block offset rules and the user-provided offset and align.
+//
+// Also, compute and save the total size of the block. For the block's size, arrayness
+// is not taken into account, as each element is backed by a separate buffer.
+//
+void HlslParseContext::fixBlockUniformOffsets(TQualifier& qualifier, TTypeList& typeList)
+{
+ if (! qualifier.isUniformOrBuffer())
+ return;
+ if (qualifier.layoutPacking != ElpStd140 && qualifier.layoutPacking != ElpStd430)
+ return;
+
+ int offset = 0;
+ int memberSize;
+ for (unsigned int member = 0; member < typeList.size(); ++member) {
+ TQualifier& memberQualifier = typeList[member].type->getQualifier();
+ const TSourceLoc& memberLoc = typeList[member].loc;
+
+ // "When align is applied to an array, it effects only the start of the array, not the array's internal stride."
+
+ // modify just the children's view of matrix layout, if there is one for this member
+ TLayoutMatrix subMatrixLayout = typeList[member].type->getQualifier().layoutMatrix;
+ int dummyStride;
+ int memberAlignment = intermediate.getBaseAlignment(*typeList[member].type, memberSize, dummyStride, qualifier.layoutPacking == ElpStd140,
+ subMatrixLayout != ElmNone ? subMatrixLayout == ElmRowMajor : qualifier.layoutMatrix == ElmRowMajor);
+ if (memberQualifier.hasOffset()) {
+ // "The specified offset must be a multiple
+ // of the base alignment of the type of the block member it qualifies, or a compile-time error results."
+ if (! IsMultipleOfPow2(memberQualifier.layoutOffset, memberAlignment))
+ error(memberLoc, "must be a multiple of the member's alignment", "offset", "");
+
+ // "It is a compile-time error to specify an offset that is smaller than the offset of the previous
+ // member in the block or that lies within the previous member of the block"
+ if (memberQualifier.layoutOffset < offset)
+ error(memberLoc, "cannot lie in previous members", "offset", "");
+
+ // "The offset qualifier forces the qualified member to start at or after the specified
+ // integral-constant expression, which will be its byte offset from the beginning of the buffer.
+ // "The actual offset of a member is computed as
+ // follows: If offset was declared, start with that offset, otherwise start with the next available offset."
+ offset = std::max(offset, memberQualifier.layoutOffset);
+ }
+
+ // "The actual alignment of a member will be the greater of the specified align alignment and the standard
+ // (e.g., std140) base alignment for the member's type."
+ if (memberQualifier.hasAlign())
+ memberAlignment = std::max(memberAlignment, memberQualifier.layoutAlign);
+
+ // "If the resulting offset is not a multiple of the actual alignment,
+ // increase it to the first offset that is a multiple of
+ // the actual alignment."
+ RoundToPow2(offset, memberAlignment);
+ typeList[member].type->getQualifier().layoutOffset = offset;
+ offset += memberSize;
+ }
+}
+
+// For an identifier that is already declared, add more qualification to it.
+void HlslParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, const TString& identifier)
+{
+ TSymbol* symbol = symbolTable.find(identifier);
+ if (! symbol) {
+ error(loc, "identifier not previously declared", identifier.c_str(), "");
+ return;
+ }
+ if (symbol->getAsFunction()) {
+ error(loc, "cannot re-qualify a function name", identifier.c_str(), "");
+ return;
+ }
+
+ if (qualifier.isAuxiliary() ||
+ qualifier.isMemory() ||
+ qualifier.isInterpolation() ||
+ qualifier.hasLayout() ||
+ qualifier.storage != EvqTemporary ||
+ qualifier.precision != EpqNone) {
+ error(loc, "cannot add storage, auxiliary, memory, interpolation, layout, or precision qualifier to an existing variable", identifier.c_str(), "");
+ return;
+ }
+
+ // For read-only built-ins, add a new symbol for holding the modified qualifier.
+ // This will bring up an entire block, if a block type has to be modified (e.g., gl_Position inside a block)
+ if (symbol->isReadOnly())
+ symbol = symbolTable.copyUp(symbol);
+
+ if (qualifier.invariant) {
+ if (intermediate.inIoAccessed(identifier))
+ error(loc, "cannot change qualification after use", "invariant", "");
+ symbol->getWritableType().getQualifier().invariant = true;
+ } else
+ warn(loc, "unknown requalification", "", "");
+}
+
+void HlslParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, TIdentifierList& identifiers)
+{
+ for (unsigned int i = 0; i < identifiers.size(); ++i)
+ addQualifierToExisting(loc, qualifier, *identifiers[i]);
+}
+
+//
+// Updating default qualifier for the case of a declaration with just a qualifier,
+// no type, block, or identifier.
+//
+void HlslParseContext::updateStandaloneQualifierDefaults(const TSourceLoc& loc, const TPublicType& publicType)
+{
+ if (publicType.shaderQualifiers.vertices != TQualifier::layoutNotSet) {
+ assert(language == EShLangTessControl || language == EShLangGeometry);
+ const char* id = (language == EShLangTessControl) ? "vertices" : "max_vertices";
+
+ if (language == EShLangTessControl)
+ checkIoArraysConsistency(loc);
+ }
+ if (publicType.shaderQualifiers.invocations != TQualifier::layoutNotSet) {
+ if (! intermediate.setInvocations(publicType.shaderQualifiers.invocations))
+ error(loc, "cannot change previously set layout value", "invocations", "");
+ }
+ if (publicType.shaderQualifiers.geometry != ElgNone) {
+ if (publicType.qualifier.storage == EvqVaryingIn) {
+ switch (publicType.shaderQualifiers.geometry) {
+ case ElgPoints:
+ case ElgLines:
+ case ElgLinesAdjacency:
+ case ElgTriangles:
+ case ElgTrianglesAdjacency:
+ case ElgQuads:
+ case ElgIsolines:
+ if (intermediate.setInputPrimitive(publicType.shaderQualifiers.geometry)) {
+ if (language == EShLangGeometry)
+ checkIoArraysConsistency(loc);
+ } else
+ error(loc, "cannot change previously set input primitive", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
+ break;
+ default:
+ error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
+ }
+ } else if (publicType.qualifier.storage == EvqVaryingOut) {
+ switch (publicType.shaderQualifiers.geometry) {
+ case ElgPoints:
+ case ElgLineStrip:
+ case ElgTriangleStrip:
+ if (! intermediate.setOutputPrimitive(publicType.shaderQualifiers.geometry))
+ error(loc, "cannot change previously set output primitive", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
+ break;
+ default:
+ error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
+ }
+ } else
+ error(loc, "cannot apply to:", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), GetStorageQualifierString(publicType.qualifier.storage));
+ }
+ if (publicType.shaderQualifiers.spacing != EvsNone)
+ intermediate.setVertexSpacing(publicType.shaderQualifiers.spacing);
+ if (publicType.shaderQualifiers.order != EvoNone)
+ intermediate.setVertexOrder(publicType.shaderQualifiers.order);
+ if (publicType.shaderQualifiers.pointMode)
+ intermediate.setPointMode();
+ for (int i = 0; i < 3; ++i) {
+ if (publicType.shaderQualifiers.localSize[i] > 1) {
+ int max = 0;
+ switch (i) {
+ case 0: max = resources.maxComputeWorkGroupSizeX; break;
+ case 1: max = resources.maxComputeWorkGroupSizeY; break;
+ case 2: max = resources.maxComputeWorkGroupSizeZ; break;
+ default: break;
+ }
+ if (intermediate.getLocalSize(i) > (unsigned int)max)
+ error(loc, "too large; see gl_MaxComputeWorkGroupSize", "local_size", "");
+
+ // Fix the existing constant gl_WorkGroupSize with this new information.
+ TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
+ workGroupSize->getWritableConstArray()[i].setUConst(intermediate.getLocalSize(i));
+ }
+ if (publicType.shaderQualifiers.localSizeSpecId[i] != TQualifier::layoutNotSet) {
+ intermediate.setLocalSizeSpecId(i, publicType.shaderQualifiers.localSizeSpecId[i]);
+ // Set the workgroup built-in variable as a specialization constant
+ TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
+ workGroupSize->getWritableType().getQualifier().specConstant = true;
+ }
+ }
+ if (publicType.shaderQualifiers.earlyFragmentTests)
+ intermediate.setEarlyFragmentTests();
+
+ const TQualifier& qualifier = publicType.qualifier;
+
+ switch (qualifier.storage) {
+ case EvqUniform:
+ if (qualifier.hasMatrix())
+ globalUniformDefaults.layoutMatrix = qualifier.layoutMatrix;
+ if (qualifier.hasPacking())
+ globalUniformDefaults.layoutPacking = qualifier.layoutPacking;
+ break;
+ case EvqBuffer:
+ if (qualifier.hasMatrix())
+ globalBufferDefaults.layoutMatrix = qualifier.layoutMatrix;
+ if (qualifier.hasPacking())
+ globalBufferDefaults.layoutPacking = qualifier.layoutPacking;
+ break;
+ case EvqVaryingIn:
+ break;
+ case EvqVaryingOut:
+ if (qualifier.hasStream())
+ globalOutputDefaults.layoutStream = qualifier.layoutStream;
+ if (qualifier.hasXfbBuffer())
+ globalOutputDefaults.layoutXfbBuffer = qualifier.layoutXfbBuffer;
+ if (globalOutputDefaults.hasXfbBuffer() && qualifier.hasXfbStride()) {
+ if (! intermediate.setXfbBufferStride(globalOutputDefaults.layoutXfbBuffer, qualifier.layoutXfbStride))
+ error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d", qualifier.layoutXfbBuffer);
+ }
+ break;
+ default:
+ error(loc, "default qualifier requires 'uniform', 'buffer', 'in', or 'out' storage qualification", "", "");
+ return;
+ }
+}
+
+//
+// Take the sequence of statements that has been built up since the last case/default,
+// put it on the list of top-level nodes for the current (inner-most) switch statement,
+// and follow that by the case/default we are on now. (See switch topology comment on
+// TIntermSwitch.)
+//
+void HlslParseContext::wrapupSwitchSubsequence(TIntermAggregate* statements, TIntermNode* branchNode)
+{
+ TIntermSequence* switchSequence = switchSequenceStack.back();
+
+ if (statements) {
+ if (switchSequence->size() == 0)
+ error(statements->getLoc(), "cannot have statements before first case/default label", "switch", "");
+ statements->setOperator(EOpSequence);
+ switchSequence->push_back(statements);
+ }
+ if (branchNode) {
+ // check all previous cases for the same label (or both are 'default')
+ for (unsigned int s = 0; s < switchSequence->size(); ++s) {
+ TIntermBranch* prevBranch = (*switchSequence)[s]->getAsBranchNode();
+ if (prevBranch) {
+ TIntermTyped* prevExpression = prevBranch->getExpression();
+ TIntermTyped* newExpression = branchNode->getAsBranchNode()->getExpression();
+ if (prevExpression == nullptr && newExpression == nullptr)
+ error(branchNode->getLoc(), "duplicate label", "default", "");
+ else if (prevExpression != nullptr &&
+ newExpression != nullptr &&
+ prevExpression->getAsConstantUnion() &&
+ newExpression->getAsConstantUnion() &&
+ prevExpression->getAsConstantUnion()->getConstArray()[0].getIConst() ==
+ newExpression->getAsConstantUnion()->getConstArray()[0].getIConst())
+ error(branchNode->getLoc(), "duplicated value", "case", "");
+ }
+ }
+ switchSequence->push_back(branchNode);
+ }
+}
+
+//
+// Turn the top-level node sequence built up of wrapupSwitchSubsequence
+// into a switch node.
+//
+TIntermNode* HlslParseContext::addSwitch(const TSourceLoc& loc, TIntermTyped* expression, TIntermAggregate* lastStatements)
+{
+ wrapupSwitchSubsequence(lastStatements, nullptr);
+
+ if (expression == nullptr ||
+ (expression->getBasicType() != EbtInt && expression->getBasicType() != EbtUint) ||
+ expression->getType().isArray() || expression->getType().isMatrix() || expression->getType().isVector())
+ error(loc, "condition must be a scalar integer expression", "switch", "");
+
+ // If there is nothing to do, drop the switch but still execute the expression
+ TIntermSequence* switchSequence = switchSequenceStack.back();
+ if (switchSequence->size() == 0)
+ return expression;
+
+ if (lastStatements == nullptr) {
+ // emulate a break for error recovery
+ lastStatements = intermediate.makeAggregate(intermediate.addBranch(EOpBreak, loc));
+ lastStatements->setOperator(EOpSequence);
+ switchSequence->push_back(lastStatements);
+ }
+
+ TIntermAggregate* body = new TIntermAggregate(EOpSequence);
+ body->getSequence() = *switchSequenceStack.back();
+ body->setLoc(loc);
+
+ TIntermSwitch* switchNode = new TIntermSwitch(expression, body);
+ switchNode->setLoc(loc);
+
+ return switchNode;
+}
+
+} // end namespace glslang
diff --git a/hlsl/hlslParseHelper.h b/hlsl/hlslParseHelper.h
new file mode 100755
index 0000000..88a3fe2
--- /dev/null
+++ b/hlsl/hlslParseHelper.h
@@ -0,0 +1,223 @@
+//
+//Copyright (C) 2016 Google, Inc.
+//
+//All rights reserved.
+//
+//Redistribution and use in source and binary forms, with or without
+//modification, are permitted provided that the following conditions
+//are met:
+//
+// Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//
+// Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+//
+// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+//POSSIBILITY OF SUCH DAMAGE.
+//
+#ifndef HLSL_PARSE_INCLUDED_
+#define HLSL_PARSE_INCLUDED_
+
+#include "../glslang/MachineIndependent/parseVersions.h"
+#include "../glslang/MachineIndependent/ParseHelper.h"
+
+namespace glslang {
+
+class HlslParseContext : public TParseContextBase {
+public:
+ HlslParseContext(TSymbolTable&, TIntermediate&, bool parsingBuiltins,
+ int version, EProfile, int spv, int vulkan, EShLanguage, TInfoSink&,
+ bool forwardCompatible = false, EShMessages messages = EShMsgDefault);
+ virtual ~HlslParseContext();
+ void setLimits(const TBuiltInResource&);
+ bool parseShaderStrings(TPpContext&, TInputScanner& input, bool versionWillBeError = false);
+ const char* getPreamble();
+
+ void C_DECL error(const TSourceLoc&, const char* szReason, const char* szToken,
+ const char* szExtraInfoFormat, ...);
+ void C_DECL warn(const TSourceLoc&, const char* szReason, const char* szToken,
+ const char* szExtraInfoFormat, ...);
+ void C_DECL ppError(const TSourceLoc&, const char* szReason, const char* szToken,
+ const char* szExtraInfoFormat, ...);
+ void C_DECL ppWarn(const TSourceLoc&, const char* szReason, const char* szToken,
+ const char* szExtraInfoFormat, ...);
+
+ void reservedPpErrorCheck(const TSourceLoc&, const char* name, const char* op) { }
+ bool lineContinuationCheck(const TSourceLoc&, bool endOfComment) { return true; }
+ bool lineDirectiveShouldSetNextLine() const { return true; }
+ bool builtInName(const TString&);
+
+ void handlePragma(const TSourceLoc&, const TVector<TString>&);
+ TIntermTyped* handleVariable(const TSourceLoc&, TSymbol* symbol, const TString* string);
+ TIntermTyped* handleBracketDereference(const TSourceLoc&, TIntermTyped* base, TIntermTyped* index);
+ void checkIndex(const TSourceLoc&, const TType&, int& index);
+
+ void makeEditable(TSymbol*&);
+ TVariable* getEditableVariable(const char* name);
+ bool isIoResizeArray(const TType&) const;
+ void fixIoArraySize(const TSourceLoc&, TType&);
+ void handleIoResizeArrayAccess(const TSourceLoc&, TIntermTyped* base);
+ void checkIoArraysConsistency(const TSourceLoc&, bool tailOnly = false);
+ int getIoArrayImplicitSize() const;
+ void checkIoArrayConsistency(const TSourceLoc&, int requiredSize, const char* feature, TType&, const TString&);
+
+ TIntermTyped* handleBinaryMath(const TSourceLoc&, const char* str, TOperator op, TIntermTyped* left, TIntermTyped* right);
+ TIntermTyped* handleUnaryMath(const TSourceLoc&, const char* str, TOperator op, TIntermTyped* childNode);
+ TIntermTyped* handleDotDereference(const TSourceLoc&, TIntermTyped* base, const TString& field);
+ TFunction* handleFunctionDeclarator(const TSourceLoc&, TFunction& function, bool prototype);
+ TIntermAggregate* handleFunctionDefinition(const TSourceLoc&, TFunction&);
+ void handleFunctionArgument(TFunction*, TIntermAggregate*&, TIntermTyped*);
+ TIntermTyped* handleFunctionCall(const TSourceLoc&, TFunction*, TIntermNode*);
+ TIntermTyped* handleLengthMethod(const TSourceLoc&, TFunction*, TIntermNode*);
+ void addInputArgumentConversions(const TFunction&, TIntermNode*&) const;
+ TIntermTyped* addOutputArgumentConversions(const TFunction&, TIntermAggregate&) const;
+ void builtInOpCheck(const TSourceLoc&, const TFunction&, TIntermOperator&);
+ TFunction* handleConstructorCall(const TSourceLoc&, const TType&);
+
+ bool parseVectorFields(const TSourceLoc&, const TString&, int vecSize, TVectorFields&);
+ void assignError(const TSourceLoc&, const char* op, TString left, TString right);
+ void unaryOpError(const TSourceLoc&, const char* op, TString operand);
+ void binaryOpError(const TSourceLoc&, const char* op, TString left, TString right);
+ void variableCheck(TIntermTyped*& nodePtr);
+ void constantValueCheck(TIntermTyped* node, const char* token);
+ void integerCheck(const TIntermTyped* node, const char* token);
+ void globalCheck(const TSourceLoc&, const char* token);
+ bool constructorError(const TSourceLoc&, TIntermNode*, TFunction&, TOperator, TType&);
+ bool constructorTextureSamplerError(const TSourceLoc&, const TFunction&);
+ void arraySizeCheck(const TSourceLoc&, TIntermTyped* expr, TArraySize&);
+ void arraySizeRequiredCheck(const TSourceLoc&, const TArraySizes&);
+ void structArrayCheck(const TSourceLoc&, const TType& structure);
+ void arrayDimMerge(TType& type, const TArraySizes* sizes);
+ bool voidErrorCheck(const TSourceLoc&, const TString&, TBasicType);
+ void boolCheck(const TSourceLoc&, const TIntermTyped*);
+ void boolCheck(const TSourceLoc&, const TPublicType&);
+ void globalQualifierFix(const TSourceLoc&, TQualifier&);
+ bool structQualifierErrorCheck(const TSourceLoc&, const TPublicType& pType);
+ void mergeQualifiers(const TSourceLoc&, TQualifier& dst, const TQualifier& src, bool force);
+ int computeSamplerTypeIndex(TSampler&);
+ TSymbol* redeclareBuiltinVariable(const TSourceLoc&, const TString&, const TQualifier&, const TShaderQualifiers&, bool& newDeclaration);
+ void redeclareBuiltinBlock(const TSourceLoc&, TTypeList& typeList, const TString& blockName, const TString* instanceName, TArraySizes* arraySizes);
+ void paramCheckFix(const TSourceLoc&, const TStorageQualifier&, TType& type);
+ void paramCheckFix(const TSourceLoc&, const TQualifier&, TType& type);
+ void specializationCheck(const TSourceLoc&, const TType&, const char* op);
+
+ void setLayoutQualifier(const TSourceLoc&, TPublicType&, TString&);
+ void setLayoutQualifier(const TSourceLoc&, TPublicType&, TString&, const TIntermTyped*);
+ void mergeObjectLayoutQualifiers(TQualifier& dest, const TQualifier& src, bool inheritOnly);
+ void checkNoShaderLayouts(const TSourceLoc&, const TShaderQualifiers&);
+
+ const TFunction* findFunction(const TSourceLoc& loc, const TFunction& call, bool& builtIn);
+ TIntermNode* declareVariable(const TSourceLoc&, TString& identifier, const TType&, TArraySizes* typeArray = 0, TIntermTyped* initializer = 0);
+ TIntermTyped* addConstructor(const TSourceLoc&, TIntermNode*, const TType&, TOperator);
+ TIntermTyped* constructAggregate(TIntermNode*, const TType&, int, const TSourceLoc&);
+ TIntermTyped* constructBuiltIn(const TType&, TOperator, TIntermTyped*, const TSourceLoc&, bool subset);
+ void declareBlock(const TSourceLoc&, TTypeList& typeList, const TString* instanceName = 0, TArraySizes* arraySizes = 0);
+ void fixBlockLocations(const TSourceLoc&, TQualifier&, TTypeList&, bool memberWithLocation, bool memberWithoutLocation);
+ void fixBlockXfbOffsets(TQualifier&, TTypeList&);
+ void fixBlockUniformOffsets(TQualifier&, TTypeList&);
+ void addQualifierToExisting(const TSourceLoc&, TQualifier, const TString& identifier);
+ void addQualifierToExisting(const TSourceLoc&, TQualifier, TIdentifierList&);
+ void updateStandaloneQualifierDefaults(const TSourceLoc&, const TPublicType&);
+ void wrapupSwitchSubsequence(TIntermAggregate* statements, TIntermNode* branchNode);
+ TIntermNode* addSwitch(const TSourceLoc&, TIntermTyped* expression, TIntermAggregate* body);
+
+ void updateImplicitArraySize(const TSourceLoc&, TIntermNode*, int index);
+
+protected:
+ void inheritGlobalDefaults(TQualifier& dst) const;
+ TVariable* makeInternalVariable(const char* name, const TType&) const;
+ TVariable* declareNonArray(const TSourceLoc&, TString& identifier, TType&, bool& newDeclaration);
+ void declareArray(const TSourceLoc&, TString& identifier, const TType&, TSymbol*&, bool& newDeclaration);
+ TIntermNode* executeInitializer(const TSourceLoc&, TIntermTyped* initializer, TVariable* variable);
+ TIntermTyped* convertInitializerList(const TSourceLoc&, const TType&, TIntermTyped* initializer);
+ TOperator mapTypeToConstructorOp(const TType&) const;
+ void outputMessage(const TSourceLoc&, const char* szReason, const char* szToken,
+ const char* szExtraInfoFormat, TPrefixType prefix,
+ va_list args);
+
+ // Current state of parsing
+ struct TPragma contextPragma;
+ int loopNestingLevel; // 0 if outside all loops
+ int structNestingLevel; // 0 if outside blocks and structures
+ int controlFlowNestingLevel; // 0 if outside all flow control
+ int statementNestingLevel; // 0 if outside all flow control or compound statements
+ TList<TIntermSequence*> switchSequenceStack; // case, node, case, case, node, ...; ensure only one node between cases; stack of them for nesting
+ TList<int> switchLevel; // the statementNestingLevel the current switch statement is at, which must match the level of its case statements
+ bool inEntrypoint; // if inside a function, true if the function is the entry point
+ bool postMainReturn; // if inside a function, true if the function is the entry point and this is after a return statement
+ const TType* currentFunctionType; // the return type of the function that's currently being parsed
+ bool functionReturnsValue; // true if a non-void function has a return
+ const TString* blockName;
+ TQualifier currentBlockQualifier;
+ TBuiltInResource resources;
+ TLimits& limits;
+
+ HlslParseContext(HlslParseContext&);
+ HlslParseContext& operator=(HlslParseContext&);
+
+ TMap<TString, TExtensionBehavior> extensionBehavior; // for each extension string, what its current behavior is set to
+ static const int maxSamplerIndex = EsdNumDims * (EbtNumTypes * (2 * 2 * 2)); // see computeSamplerTypeIndex()
+ bool afterEOF;
+ TQualifier globalBufferDefaults;
+ TQualifier globalUniformDefaults;
+ TQualifier globalInputDefaults;
+ TQualifier globalOutputDefaults;
+ TString currentCaller; // name of last function body entered (not valid when at global scope)
+ TIdSetType inductiveLoopIds;
+ TVector<TIntermTyped*> needsIndexLimitationChecking;
+
+ //
+ // Geometry shader input arrays:
+ // - array sizing is based on input primitive and/or explicit size
+ //
+ // Tessellation control output arrays:
+ // - array sizing is based on output layout(vertices=...) and/or explicit size
+ //
+ // Both:
+ // - array sizing is retroactive
+ // - built-in block redeclarations interact with this
+ //
+ // Design:
+ // - use a per-context "resize-list", a list of symbols whose array sizes
+ // can be fixed
+ //
+ // - the resize-list starts empty at beginning of user-shader compilation, it does
+ // not have built-ins in it
+ //
+ // - on built-in array use: copyUp() symbol and add it to the resize-list
+ //
+ // - on user array declaration: add it to the resize-list
+ //
+ // - on block redeclaration: copyUp() symbol and add it to the resize-list
+ // * note, that appropriately gives an error if redeclaring a block that
+ // was already used and hence already copied-up
+ //
+ // - on seeing a layout declaration that sizes the array, fix everything in the
+ // resize-list, giving errors for mismatch
+ //
+ // - on seeing an array size declaration, give errors on mismatch between it and previous
+ // array-sizing declarations
+ //
+ TVector<TSymbol*> ioArraySymbolResizeList;
+};
+
+} // end namespace glslang
+
+#endif // HLSL_PARSE_INCLUDED_
diff --git a/hlsl/hlslScanContext.cpp b/hlsl/hlslScanContext.cpp
new file mode 100755
index 0000000..50277cf
--- /dev/null
+++ b/hlsl/hlslScanContext.cpp
@@ -0,0 +1,621 @@
+//
+//Copyright (C) 2016 Google, Inc.
+//
+//All rights reserved.
+//
+//Redistribution and use in source and binary forms, with or without
+//modification, are permitted provided that the following conditions
+//are met:
+//
+// Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//
+// Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+//
+// Neither the name of Google, Inc., nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+//POSSIBILITY OF SUCH DAMAGE.
+//
+
+//
+// HLSL scanning, leveraging the scanning done by the preprocessor.
+//
+
+#include <string.h>
+#include <unordered_map>
+#include <unordered_set>
+
+#include "../glslang/Include/Types.h"
+#include "../glslang/MachineIndependent/SymbolTable.h"
+#include "../glslang/MachineIndependent/ParseHelper.h"
+#include "hlslScanContext.h"
+#include "hlslTokens.h"
+//#include "Scan.h"
+
+// preprocessor includes
+#include "../glslang/MachineIndependent/preprocessor/PpContext.h"
+#include "../glslang/MachineIndependent/preprocessor/PpTokens.h"
+
+namespace {
+
+struct str_eq
+{
+ bool operator()(const char* lhs, const char* rhs) const
+ {
+ return strcmp(lhs, rhs) == 0;
+ }
+};
+
+struct str_hash
+{
+ size_t operator()(const char* str) const
+ {
+ // djb2
+ unsigned long hash = 5381;
+ int c;
+
+ while ((c = *str++) != 0)
+ hash = ((hash << 5) + hash) + c;
+
+ return hash;
+ }
+};
+
+// A single global usable by all threads, by all versions, by all languages.
+// After a single process-level initialization, this is read only and thread safe
+std::unordered_map<const char*, glslang::EHlslTokenClass, str_hash, str_eq>* KeywordMap = nullptr;
+std::unordered_set<const char*, str_hash, str_eq>* ReservedSet = nullptr;
+
+};
+
+namespace glslang {
+
+void HlslScanContext::fillInKeywordMap()
+{
+ if (KeywordMap != nullptr) {
+ // this is really an error, as this should called only once per process
+ // but, the only risk is if two threads called simultaneously
+ return;
+ }
+ KeywordMap = new std::unordered_map<const char*, EHlslTokenClass, str_hash, str_eq>;
+
+ (*KeywordMap)["static"] = EHTokStatic;
+ (*KeywordMap)["const"] = EHTokConst;
+ (*KeywordMap)["unorm"] = EHTokUnorm;
+ (*KeywordMap)["snorm"] = EHTokSNorm;
+ (*KeywordMap)["extern"] = EHTokExtern;
+ (*KeywordMap)["uniform"] = EHTokUniform;
+ (*KeywordMap)["volatile"] = EHTokVolatile;
+ (*KeywordMap)["shared"] = EHTokShared;
+ (*KeywordMap)["groupshared"] = EHTokGroupShared;
+ (*KeywordMap)["linear"] = EHTokLinear;
+ (*KeywordMap)["centroid"] = EHTokCentroid;
+ (*KeywordMap)["nointerpolation"] = EHTokNointerpolation;
+ (*KeywordMap)["noperspective"] = EHTokNoperspective;
+ (*KeywordMap)["sample"] = EHTokSample;
+ (*KeywordMap)["row_major"] = EHTokRowMajor;
+ (*KeywordMap)["column_major"] = EHTokColumnMajor;
+ (*KeywordMap)["packoffset"] = EHTokPackOffset;
+
+ (*KeywordMap)["Buffer"] = EHTokBuffer;
+ (*KeywordMap)["vector"] = EHTokVector;
+ (*KeywordMap)["matrix"] = EHTokMatrix;
+
+ (*KeywordMap)["void"] = EHTokVoid;
+ (*KeywordMap)["bool"] = EHTokBool;
+ (*KeywordMap)["int"] = EHTokInt;
+ (*KeywordMap)["uint"] = EHTokUint;
+ (*KeywordMap)["dword"] = EHTokDword;
+ (*KeywordMap)["half"] = EHTokHalf;
+ (*KeywordMap)["float"] = EHTokFloat;
+ (*KeywordMap)["double"] = EHTokDouble;
+ (*KeywordMap)["min16float"] = EHTokMin16float;
+ (*KeywordMap)["min10float"] = EHTokMin10float;
+ (*KeywordMap)["min16int"] = EHTokMin16int;
+ (*KeywordMap)["min12int"] = EHTokMin12int;
+ (*KeywordMap)["min16uint"] = EHTokMin16int;
+
+ (*KeywordMap)["bool1"] = EHTokBool1;
+ (*KeywordMap)["bool2"] = EHTokBool2;
+ (*KeywordMap)["bool3"] = EHTokBool3;
+ (*KeywordMap)["bool4"] = EHTokBool4;
+ (*KeywordMap)["float1"] = EHTokFloat1;
+ (*KeywordMap)["float2"] = EHTokFloat2;
+ (*KeywordMap)["float3"] = EHTokFloat3;
+ (*KeywordMap)["float4"] = EHTokFloat4;
+ (*KeywordMap)["int1"] = EHTokInt1;
+ (*KeywordMap)["int2"] = EHTokInt2;
+ (*KeywordMap)["int3"] = EHTokInt3;
+ (*KeywordMap)["int4"] = EHTokInt4;
+ (*KeywordMap)["double1"] = EHTokDouble1;
+ (*KeywordMap)["double2"] = EHTokDouble2;
+ (*KeywordMap)["double3"] = EHTokDouble3;
+ (*KeywordMap)["double4"] = EHTokDouble4;
+ (*KeywordMap)["uint1"] = EHTokUint1;
+ (*KeywordMap)["uint2"] = EHTokUint2;
+ (*KeywordMap)["uint3"] = EHTokUint3;
+ (*KeywordMap)["uint4"] = EHTokUint4;
+
+ (*KeywordMap)["int1x1"] = EHTokInt1x1;
+ (*KeywordMap)["int1x2"] = EHTokInt1x2;
+ (*KeywordMap)["int1x3"] = EHTokInt1x3;
+ (*KeywordMap)["int1x4"] = EHTokInt1x4;
+ (*KeywordMap)["int2x1"] = EHTokInt2x1;
+ (*KeywordMap)["int2x2"] = EHTokInt2x2;
+ (*KeywordMap)["int2x3"] = EHTokInt2x3;
+ (*KeywordMap)["int2x4"] = EHTokInt2x4;
+ (*KeywordMap)["int3x1"] = EHTokInt3x1;
+ (*KeywordMap)["int3x2"] = EHTokInt3x2;
+ (*KeywordMap)["int3x3"] = EHTokInt3x3;
+ (*KeywordMap)["int3x4"] = EHTokInt3x4;
+ (*KeywordMap)["int4x1"] = EHTokInt4x1;
+ (*KeywordMap)["int4x2"] = EHTokInt4x2;
+ (*KeywordMap)["int4x3"] = EHTokInt4x3;
+ (*KeywordMap)["int4x4"] = EHTokInt4x4;
+ (*KeywordMap)["float1x1"] = EHTokFloat1x1;
+ (*KeywordMap)["float1x2"] = EHTokFloat1x2;
+ (*KeywordMap)["float1x3"] = EHTokFloat1x3;
+ (*KeywordMap)["float1x4"] = EHTokFloat1x4;
+ (*KeywordMap)["float2x1"] = EHTokFloat2x1;
+ (*KeywordMap)["float2x2"] = EHTokFloat2x2;
+ (*KeywordMap)["float2x3"] = EHTokFloat2x3;
+ (*KeywordMap)["float2x4"] = EHTokFloat2x4;
+ (*KeywordMap)["float3x1"] = EHTokFloat3x1;
+ (*KeywordMap)["float3x2"] = EHTokFloat3x2;
+ (*KeywordMap)["float3x3"] = EHTokFloat3x3;
+ (*KeywordMap)["float3x4"] = EHTokFloat3x4;
+ (*KeywordMap)["float4x1"] = EHTokFloat4x1;
+ (*KeywordMap)["float4x2"] = EHTokFloat4x2;
+ (*KeywordMap)["float4x3"] = EHTokFloat4x3;
+ (*KeywordMap)["float4x4"] = EHTokFloat4x4;
+ (*KeywordMap)["double1x1"] = EHTokDouble1x1;
+ (*KeywordMap)["double1x2"] = EHTokDouble1x2;
+ (*KeywordMap)["double1x3"] = EHTokDouble1x3;
+ (*KeywordMap)["double1x4"] = EHTokDouble1x4;
+ (*KeywordMap)["double2x1"] = EHTokDouble2x1;
+ (*KeywordMap)["double2x2"] = EHTokDouble2x2;
+ (*KeywordMap)["double2x3"] = EHTokDouble2x3;
+ (*KeywordMap)["double2x4"] = EHTokDouble2x4;
+ (*KeywordMap)["double3x1"] = EHTokDouble3x1;
+ (*KeywordMap)["double3x2"] = EHTokDouble3x2;
+ (*KeywordMap)["double3x3"] = EHTokDouble3x3;
+ (*KeywordMap)["double3x4"] = EHTokDouble3x4;
+ (*KeywordMap)["double4x1"] = EHTokDouble4x1;
+ (*KeywordMap)["double4x2"] = EHTokDouble4x2;
+ (*KeywordMap)["double4x3"] = EHTokDouble4x3;
+ (*KeywordMap)["double4x4"] = EHTokDouble4x4;
+
+ (*KeywordMap)["sampler"] = EHTokSampler;
+ (*KeywordMap)["sampler1D"] = EHTokSampler1d;
+ (*KeywordMap)["sampler2D"] = EHTokSampler2d;
+ (*KeywordMap)["sampler3D"] = EHTokSampler3d;
+ (*KeywordMap)["samplerCube"] = EHTokSamplerCube;
+ (*KeywordMap)["sampler_state"] = EHTokSamplerState;
+ (*KeywordMap)["SamplerState"] = EHTokSamplerState;
+ (*KeywordMap)["SamplerComparisonState"] = EHTokSamplerComparisonState;
+ (*KeywordMap)["texture"] = EHTokTexture;
+ (*KeywordMap)["Texture1D"] = EHTokTexture1d;
+ (*KeywordMap)["Texture1DArray"] = EHTokTexture1darray;
+ (*KeywordMap)["Texture2D"] = EHTokTexture2d;
+ (*KeywordMap)["Texture2DArray"] = EHTokTexture2darray;
+ (*KeywordMap)["Texture3D"] = EHTokTexture3d;
+ (*KeywordMap)["TextureCube"] = EHTokTextureCube;
+
+ (*KeywordMap)["struct"] = EHTokStruct;
+ (*KeywordMap)["typedef"] = EHTokTypedef;
+
+ (*KeywordMap)["true"] = EHTokBoolConstant;
+ (*KeywordMap)["false"] = EHTokBoolConstant;
+
+ (*KeywordMap)["for"] = EHTokFor;
+ (*KeywordMap)["do"] = EHTokDo;
+ (*KeywordMap)["while"] = EHTokWhile;
+ (*KeywordMap)["break"] = EHTokBreak;
+ (*KeywordMap)["continue"] = EHTokContinue;
+ (*KeywordMap)["if"] = EHTokIf;
+ (*KeywordMap)["else"] = EHTokElse;
+ (*KeywordMap)["discard"] = EHTokDiscard;
+ (*KeywordMap)["return"] = EHTokReturn;
+ (*KeywordMap)["switch"] = EHTokSwitch;
+ (*KeywordMap)["case"] = EHTokCase;
+ (*KeywordMap)["default"] = EHTokDefault;
+
+ // TODO: get correct set here
+ ReservedSet = new std::unordered_set<const char*, str_hash, str_eq>;
+
+ ReservedSet->insert("auto");
+ ReservedSet->insert("catch");
+ ReservedSet->insert("char");
+ ReservedSet->insert("class");
+ ReservedSet->insert("const_cast");
+ ReservedSet->insert("enum");
+ ReservedSet->insert("explicit");
+ ReservedSet->insert("friend");
+ ReservedSet->insert("goto");
+ ReservedSet->insert("long");
+ ReservedSet->insert("mutable");
+ ReservedSet->insert("new");
+ ReservedSet->insert("operator");
+ ReservedSet->insert("private");
+ ReservedSet->insert("protected");
+ ReservedSet->insert("public");
+ ReservedSet->insert("reinterpret_cast");
+ ReservedSet->insert("short");
+ ReservedSet->insert("signed");
+ ReservedSet->insert("sizeof");
+ ReservedSet->insert("static_cast");
+ ReservedSet->insert("template");
+ ReservedSet->insert("this");
+ ReservedSet->insert("throw");
+ ReservedSet->insert("try");
+ ReservedSet->insert("typename");
+ ReservedSet->insert("union");
+ ReservedSet->insert("unsigned");
+ ReservedSet->insert("using");
+ ReservedSet->insert("virtual");
+}
+
+void HlslScanContext::deleteKeywordMap()
+{
+ delete KeywordMap;
+ KeywordMap = nullptr;
+ delete ReservedSet;
+ ReservedSet = nullptr;
+}
+
+// Wrapper for tokenizeClass()"] = to get everything inside the token.
+void HlslScanContext::tokenize(HlslToken& token)
+{
+ token.isType = false;
+ EHlslTokenClass tokenClass = tokenizeClass(token);
+ token.tokenClass = tokenClass;
+ if (token.isType)
+ afterType = true;
+}
+
+//
+// Fill in token information for the next token, except for the token class.
+// Returns the enum value of the token class of the next token found.
+// Return 0 (EndOfTokens) on end of input.
+//
+EHlslTokenClass HlslScanContext::tokenizeClass(HlslToken& token)
+{
+ do {
+ parserToken = &token;
+ TPpToken ppToken;
+ tokenText = ppContext.tokenize(&ppToken);
+ if (tokenText == nullptr)
+ return EHTokNone;
+
+ loc = ppToken.loc;
+ parserToken->loc = loc;
+ switch (ppToken.token) {
+ case ';': afterType = false; return EHTokSemicolon;
+ case ',': afterType = false; return EHTokComma;
+ case ':': return EHTokColon;
+ case '=': afterType = false; return EHTokEqual;
+ case '(': afterType = false; return EHTokLeftParen;
+ case ')': afterType = false; return EHTokRightParen;
+ case '.': field = true; return EHTokDot;
+ case '!': return EHTokBang;
+ case '-': return EHTokDash;
+ case '~': return EHTokTilde;
+ case '+': return EHTokPlus;
+ case '*': return EHTokStar;
+ case '/': return EHTokSlash;
+ case '%': return EHTokPercent;
+ case '<': return EHTokLeftAngle;
+ case '>': return EHTokRightAngle;
+ case '|': return EHTokVerticalBar;
+ case '^': return EHTokCaret;
+ case '&': return EHTokAmpersand;
+ case '?': return EHTokQuestion;
+ case '[': return EHTokLeftBracket;
+ case ']': return EHTokRightBracket;
+ case '{': return EHTokLeftBrace;
+ case '}': return EHTokRightBrace;
+ case '\\':
+ parseContext.error(loc, "illegal use of escape character", "\\", "");
+ break;
+
+ case PpAtomAdd: return EHTokAddAssign;
+ case PpAtomSub: return EHTokSubAssign;
+ case PpAtomMul: return EHTokMulAssign;
+ case PpAtomDiv: return EHTokDivAssign;
+ case PpAtomMod: return EHTokModAssign;
+
+ case PpAtomRight: return EHTokRightOp;
+ case PpAtomLeft: return EHTokLeftOp;
+
+ case PpAtomRightAssign: return EHTokRightAssign;
+ case PpAtomLeftAssign: return EHTokLeftAssign;
+ case PpAtomAndAssign: return EHTokAndAssign;
+ case PpAtomOrAssign: return EHTokOrAssign;
+ case PpAtomXorAssign: return EHTokXorAssign;
+
+ case PpAtomAnd: return EHTokAndOp;
+ case PpAtomOr: return EHTokOrOp;
+ case PpAtomXor: return EHTokXorOp;
+
+ case PpAtomEQ: return EHTokEqOp;
+ case PpAtomGE: return EHTokGeOp;
+ case PpAtomNE: return EHTokNeOp;
+ case PpAtomLE: return EHTokLeOp;
+
+ case PpAtomDecrement: return EHTokDecOp;
+ case PpAtomIncrement: return EHTokIncOp;
+
+ case PpAtomConstInt: parserToken->i = ppToken.ival; return EHTokIntConstant;
+ case PpAtomConstUint: parserToken->i = ppToken.ival; return EHTokUintConstant;
+ case PpAtomConstFloat: parserToken->d = ppToken.dval; return EHTokFloatConstant;
+ case PpAtomConstDouble: parserToken->d = ppToken.dval; return EHTokDoubleConstant;
+ case PpAtomIdentifier:
+ {
+ EHlslTokenClass token = tokenizeIdentifier();
+ field = false;
+ return token;
+ }
+
+ case EndOfInput: return EHTokNone;
+
+ default:
+ char buf[2];
+ buf[0] = (char)ppToken.token;
+ buf[1] = 0;
+ parseContext.error(loc, "unexpected token", buf, "");
+ break;
+ }
+ } while (true);
+}
+
+EHlslTokenClass HlslScanContext::tokenizeIdentifier()
+{
+ if (ReservedSet->find(tokenText) != ReservedSet->end())
+ return reservedWord();
+
+ auto it = KeywordMap->find(tokenText);
+ if (it == KeywordMap->end()) {
+ // Should have an identifier of some sort
+ return identifierOrType();
+ }
+ keyword = it->second;
+
+ switch (keyword) {
+
+ // qualifiers
+ case EHTokStatic:
+ case EHTokConst:
+ case EHTokSNorm:
+ case EHTokUnorm:
+ case EHTokExtern:
+ case EHTokUniform:
+ case EHTokVolatile:
+ case EHTokShared:
+ case EHTokGroupShared:
+ case EHTokLinear:
+ case EHTokCentroid:
+ case EHTokNointerpolation:
+ case EHTokNoperspective:
+ case EHTokSample:
+ case EHTokRowMajor:
+ case EHTokColumnMajor:
+ case EHTokPackOffset:
+ return keyword;
+
+ // template types
+ case EHTokBuffer:
+ case EHTokVector:
+ case EHTokMatrix:
+ return keyword;
+
+ // scalar types
+ case EHTokVoid:
+ case EHTokBool:
+ case EHTokInt:
+ case EHTokUint:
+ case EHTokDword:
+ case EHTokHalf:
+ case EHTokFloat:
+ case EHTokDouble:
+ case EHTokMin16float:
+ case EHTokMin10float:
+ case EHTokMin16int:
+ case EHTokMin12int:
+ case EHTokMin16uint:
+
+ // vector types
+ case EHTokBool1:
+ case EHTokBool2:
+ case EHTokBool3:
+ case EHTokBool4:
+ case EHTokFloat1:
+ case EHTokFloat2:
+ case EHTokFloat3:
+ case EHTokFloat4:
+ case EHTokInt1:
+ case EHTokInt2:
+ case EHTokInt3:
+ case EHTokInt4:
+ case EHTokDouble1:
+ case EHTokDouble2:
+ case EHTokDouble3:
+ case EHTokDouble4:
+ case EHTokUint1:
+ case EHTokUint2:
+ case EHTokUint3:
+ case EHTokUint4:
+
+ // matrix types
+ case EHTokInt1x1:
+ case EHTokInt1x2:
+ case EHTokInt1x3:
+ case EHTokInt1x4:
+ case EHTokInt2x1:
+ case EHTokInt2x2:
+ case EHTokInt2x3:
+ case EHTokInt2x4:
+ case EHTokInt3x1:
+ case EHTokInt3x2:
+ case EHTokInt3x3:
+ case EHTokInt3x4:
+ case EHTokInt4x1:
+ case EHTokInt4x2:
+ case EHTokInt4x3:
+ case EHTokInt4x4:
+ case EHTokFloat1x1:
+ case EHTokFloat1x2:
+ case EHTokFloat1x3:
+ case EHTokFloat1x4:
+ case EHTokFloat2x1:
+ case EHTokFloat2x2:
+ case EHTokFloat2x3:
+ case EHTokFloat2x4:
+ case EHTokFloat3x1:
+ case EHTokFloat3x2:
+ case EHTokFloat3x3:
+ case EHTokFloat3x4:
+ case EHTokFloat4x1:
+ case EHTokFloat4x2:
+ case EHTokFloat4x3:
+ case EHTokFloat4x4:
+ case EHTokDouble1x1:
+ case EHTokDouble1x2:
+ case EHTokDouble1x3:
+ case EHTokDouble1x4:
+ case EHTokDouble2x1:
+ case EHTokDouble2x2:
+ case EHTokDouble2x3:
+ case EHTokDouble2x4:
+ case EHTokDouble3x1:
+ case EHTokDouble3x2:
+ case EHTokDouble3x3:
+ case EHTokDouble3x4:
+ case EHTokDouble4x1:
+ case EHTokDouble4x2:
+ case EHTokDouble4x3:
+ case EHTokDouble4x4:
+ parserToken->isType = true;
+ return keyword;
+
+ // texturing types
+ case EHTokSampler:
+ case EHTokSampler1d:
+ case EHTokSampler2d:
+ case EHTokSampler3d:
+ case EHTokSamplerCube:
+ case EHTokSamplerState:
+ case EHTokSamplerComparisonState:
+ case EHTokTexture:
+ case EHTokTexture1d:
+ case EHTokTexture1darray:
+ case EHTokTexture2d:
+ case EHTokTexture2darray:
+ case EHTokTexture3d:
+ case EHTokTextureCube:
+ parserToken->isType = true;
+ return keyword;
+
+ // variable, user type, ...
+ case EHTokStruct:
+ case EHTokTypedef:
+
+ case EHTokBoolConstant:
+ if (strcmp("true", tokenText) == 0)
+ parserToken->b = true;
+ else
+ parserToken->b = false;
+ return keyword;
+
+ // control flow
+ case EHTokFor:
+ case EHTokDo:
+ case EHTokWhile:
+ case EHTokBreak:
+ case EHTokContinue:
+ case EHTokIf:
+ case EHTokElse:
+ case EHTokDiscard:
+ case EHTokReturn:
+ case EHTokCase:
+ case EHTokSwitch:
+ case EHTokDefault:
+ return keyword;
+
+ default:
+ parseContext.infoSink.info.message(EPrefixInternalError, "Unknown glslang keyword", loc);
+ return EHTokNone;
+ }
+}
+
+EHlslTokenClass HlslScanContext::identifierOrType()
+{
+ parserToken->string = NewPoolTString(tokenText);
+ if (field)
+ return EHTokIdentifier;
+
+ parserToken->symbol = parseContext.symbolTable.find(*parserToken->string);
+ if (afterType == false && parserToken->symbol) {
+ if (const TVariable* variable = parserToken->symbol->getAsVariable()) {
+ if (variable->isUserType()) {
+ afterType = true;
+
+ return EHTokTypeName;
+ }
+ }
+ }
+
+ return EHTokIdentifier;
+}
+
+// Give an error for use of a reserved symbol.
+// However, allow built-in declarations to use reserved words, to allow
+// extension support before the extension is enabled.
+EHlslTokenClass HlslScanContext::reservedWord()
+{
+ if (! parseContext.symbolTable.atBuiltInLevel())
+ parseContext.error(loc, "Reserved word.", tokenText, "", "");
+
+ return EHTokNone;
+}
+
+EHlslTokenClass HlslScanContext::identifierOrReserved(bool reserved)
+{
+ if (reserved) {
+ reservedWord();
+
+ return EHTokNone;
+ }
+
+ if (parseContext.forwardCompatible)
+ parseContext.warn(loc, "using future reserved keyword", tokenText, "");
+
+ return identifierOrType();
+}
+
+// For a keyword that was never reserved, until it suddenly
+// showed up.
+EHlslTokenClass HlslScanContext::nonreservedKeyword(int version)
+{
+ if (parseContext.version < version)
+ return identifierOrType();
+
+ return keyword;
+}
+
+} // end namespace glslang
diff --git a/hlsl/hlslScanContext.h b/hlsl/hlslScanContext.h
new file mode 100755
index 0000000..04f2438
--- /dev/null
+++ b/hlsl/hlslScanContext.h
@@ -0,0 +1,112 @@
+//
+//Copyright (C) 2016 Google, Inc.
+//
+//All rights reserved.
+//
+//Redistribution and use in source and binary forms, with or without
+//modification, are permitted provided that the following conditions
+//are met:
+//
+// Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//
+// Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+//
+// Neither the name of Google, Inc., nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+//POSSIBILITY OF SUCH DAMAGE.
+//
+
+//
+// This holds context specific to the HLSL scanner, which
+// sits between the preprocessor scanner and HLSL parser.
+//
+
+#ifndef HLSLSCANCONTEXT_H_
+#define HLSLSCANCONTEXT_H_
+
+#include "../glslang/MachineIndependent/ParseHelper.h"
+#include "hlslTokens.h"
+
+namespace glslang {
+
+class TPpContext;
+class TPpToken;
+
+
+//
+// Everything needed to fully describe a token.
+//
+struct HlslToken {
+ HlslToken() : isType(false), string(nullptr), symbol(nullptr) { loc.init(); }
+ TSourceLoc loc; // location of token in the source
+ EHlslTokenClass tokenClass; // what kind of token it is
+ bool isType; // true if the token represents a user type
+ union { // what data the token holds
+ glslang::TString *string; // for identifiers
+ int i; // for literals
+ unsigned int u;
+ bool b;
+ double d;
+ };
+ glslang::TSymbol* symbol; // if a symbol table lookup was done already, this is the result
+};
+
+//
+// The state of scanning and translating raw tokens to slightly richer
+// semantics, like knowing if an identifier is an existing symbol, or
+// user-defined type.
+//
+class HlslScanContext {
+public:
+ HlslScanContext(TParseContextBase& parseContext, TPpContext& ppContext)
+ : parseContext(parseContext), ppContext(ppContext), afterType(false), field(false) { }
+ virtual ~HlslScanContext() { }
+
+ static void fillInKeywordMap();
+ static void deleteKeywordMap();
+
+ void tokenize(HlslToken&);
+
+protected:
+ HlslScanContext(HlslScanContext&);
+ HlslScanContext& operator=(HlslScanContext&);
+
+ EHlslTokenClass tokenizeClass(HlslToken&);
+ EHlslTokenClass tokenizeIdentifier();
+ EHlslTokenClass identifierOrType();
+ EHlslTokenClass reservedWord();
+ EHlslTokenClass identifierOrReserved(bool reserved);
+ EHlslTokenClass nonreservedKeyword(int version);
+
+ TParseContextBase& parseContext;
+ TPpContext& ppContext;
+ bool afterType; // true if we've recognized a type, so can only be looking for an identifier
+ bool field; // true if we're on a field, right after a '.'
+ TSourceLoc loc;
+ TPpToken* ppToken;
+ HlslToken* parserToken;
+
+ const char* tokenText;
+ EHlslTokenClass keyword;
+};
+
+} // end namespace glslang
+
+#endif // HLSLSCANCONTEXT_H_
diff --git a/hlsl/hlslTokens.h b/hlsl/hlslTokens.h
new file mode 100755
index 0000000..b118f2e
--- /dev/null
+++ b/hlsl/hlslTokens.h
@@ -0,0 +1,248 @@
+//
+//Copyright (C) 2016 Google, Inc.
+//
+//All rights reserved.
+//
+//Redistribution and use in source and binary forms, with or without
+//modification, are permitted provided that the following conditions
+//are met:
+//
+// Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//
+// Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+//
+// Neither the name of Google, Inc., nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+//POSSIBILITY OF SUCH DAMAGE.
+//
+
+#ifndef EHLSLTOKENS_H_
+#define EHLSLTOKENS_H_
+
+namespace glslang {
+
+enum EHlslTokenClass {
+ EHTokNone = 0,
+
+ // qualifiers
+ EHTokStatic,
+ EHTokConst,
+ EHTokSNorm,
+ EHTokUnorm,
+ EHTokExtern,
+ EHTokUniform,
+ EHTokVolatile,
+ EHTokShared,
+ EHTokGroupShared,
+ EHTokLinear,
+ EHTokCentroid,
+ EHTokNointerpolation,
+ EHTokNoperspective,
+ EHTokSample,
+ EHTokRowMajor,
+ EHTokColumnMajor,
+ EHTokPackOffset,
+
+ // template types
+ EHTokBuffer,
+ EHTokVector,
+ EHTokMatrix,
+
+ // scalar types
+ EHTokVoid,
+ EHTokBool,
+ EHTokInt,
+ EHTokUint,
+ EHTokDword,
+ EHTokHalf,
+ EHTokFloat,
+ EHTokDouble,
+ EHTokMin16float,
+ EHTokMin10float,
+ EHTokMin16int,
+ EHTokMin12int,
+ EHTokMin16uint,
+
+ // vector types
+ EHTokBool1,
+ EHTokBool2,
+ EHTokBool3,
+ EHTokBool4,
+ EHTokFloat1,
+ EHTokFloat2,
+ EHTokFloat3,
+ EHTokFloat4,
+ EHTokInt1,
+ EHTokInt2,
+ EHTokInt3,
+ EHTokInt4,
+ EHTokDouble1,
+ EHTokDouble2,
+ EHTokDouble3,
+ EHTokDouble4,
+ EHTokUint1,
+ EHTokUint2,
+ EHTokUint3,
+ EHTokUint4,
+
+ // matrix types
+ EHTokInt1x1,
+ EHTokInt1x2,
+ EHTokInt1x3,
+ EHTokInt1x4,
+ EHTokInt2x1,
+ EHTokInt2x2,
+ EHTokInt2x3,
+ EHTokInt2x4,
+ EHTokInt3x1,
+ EHTokInt3x2,
+ EHTokInt3x3,
+ EHTokInt3x4,
+ EHTokInt4x1,
+ EHTokInt4x2,
+ EHTokInt4x3,
+ EHTokInt4x4,
+ EHTokFloat1x1,
+ EHTokFloat1x2,
+ EHTokFloat1x3,
+ EHTokFloat1x4,
+ EHTokFloat2x1,
+ EHTokFloat2x2,
+ EHTokFloat2x3,
+ EHTokFloat2x4,
+ EHTokFloat3x1,
+ EHTokFloat3x2,
+ EHTokFloat3x3,
+ EHTokFloat3x4,
+ EHTokFloat4x1,
+ EHTokFloat4x2,
+ EHTokFloat4x3,
+ EHTokFloat4x4,
+ EHTokDouble1x1,
+ EHTokDouble1x2,
+ EHTokDouble1x3,
+ EHTokDouble1x4,
+ EHTokDouble2x1,
+ EHTokDouble2x2,
+ EHTokDouble2x3,
+ EHTokDouble2x4,
+ EHTokDouble3x1,
+ EHTokDouble3x2,
+ EHTokDouble3x3,
+ EHTokDouble3x4,
+ EHTokDouble4x1,
+ EHTokDouble4x2,
+ EHTokDouble4x3,
+ EHTokDouble4x4,
+
+ // texturing types
+ EHTokSampler,
+ EHTokSampler1d,
+ EHTokSampler2d,
+ EHTokSampler3d,
+ EHTokSamplerCube,
+ EHTokSamplerState,
+ EHTokSamplerComparisonState,
+ EHTokTexture,
+ EHTokTexture1d,
+ EHTokTexture1darray,
+ EHTokTexture2d,
+ EHTokTexture2darray,
+ EHTokTexture3d,
+ EHTokTextureCube,
+
+ // variable, user type, ...
+ EHTokIdentifier,
+ EHTokTypeName,
+ EHTokStruct,
+ EHTokTypedef,
+
+ // constant
+ EHTokFloatConstant,
+ EHTokDoubleConstant,
+ EHTokIntConstant,
+ EHTokUintConstant,
+ EHTokBoolConstant,
+
+ // control flow
+ EHTokFor,
+ EHTokDo,
+ EHTokWhile,
+ EHTokBreak,
+ EHTokContinue,
+ EHTokIf,
+ EHTokElse,
+ EHTokDiscard,
+ EHTokReturn,
+ EHTokSwitch,
+ EHTokCase,
+ EHTokDefault,
+
+ // expressions
+ EHTokLeftOp,
+ EHTokRightOp,
+ EHTokIncOp,
+ EHTokDecOp,
+ EHTokLeOp,
+ EHTokGeOp,
+ EHTokEqOp,
+ EHTokNeOp,
+ EHTokAndOp,
+ EHTokOrOp,
+ EHTokXorOp,
+ EHTokMulAssign,
+ EHTokDivAssign,
+ EHTokAddAssign,
+ EHTokModAssign,
+ EHTokLeftAssign,
+ EHTokRightAssign,
+ EHTokAndAssign,
+ EHTokXorAssign,
+ EHTokOrAssign,
+ EHTokSubAssign,
+ EHTokLeftParen,
+ EHTokRightParen,
+ EHTokLeftBracket,
+ EHTokRightBracket,
+ EHTokLeftBrace,
+ EHTokRightBrace,
+ EHTokDot,
+ EHTokComma,
+ EHTokColon,
+ EHTokEqual,
+ EHTokSemicolon,
+ EHTokBang,
+ EHTokDash,
+ EHTokTilde,
+ EHTokPlus,
+ EHTokStar,
+ EHTokSlash,
+ EHTokPercent,
+ EHTokLeftAngle,
+ EHTokRightAngle,
+ EHTokVerticalBar,
+ EHTokCaret,
+ EHTokAmpersand,
+ EHTokQuestion,
+};
+
+} // end namespace glslang
+
+#endif // EHLSLTOKENS_H_
\ No newline at end of file